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
iopipe/iopipe-js-trace
src/shimmerHttp.js
extendedCallback
function extendedCallback(res) { timeline.mark(`end:${id}`); // add full response data moduleData[id].response = getResDataObject(res); // flatten object for easy transformation/filtering later moduleData[id] = flatten(moduleData[id], { maxDepth: 5 }); moduleData[id] = filterData(config, moduleData[id]); // if filter function returns falsey value, drop all data completely if (typeof moduleData[id] !== 'object') { timeline.data = timeline.data.filter( d => !new RegExp(id).test(d.name) ); delete moduleData[id]; } if (typeof originalCallback === 'function') { return originalCallback.apply(this, [res]); } return true; }
javascript
function extendedCallback(res) { timeline.mark(`end:${id}`); // add full response data moduleData[id].response = getResDataObject(res); // flatten object for easy transformation/filtering later moduleData[id] = flatten(moduleData[id], { maxDepth: 5 }); moduleData[id] = filterData(config, moduleData[id]); // if filter function returns falsey value, drop all data completely if (typeof moduleData[id] !== 'object') { timeline.data = timeline.data.filter( d => !new RegExp(id).test(d.name) ); delete moduleData[id]; } if (typeof originalCallback === 'function') { return originalCallback.apply(this, [res]); } return true; }
[ "function", "extendedCallback", "(", "res", ")", "{", "timeline", ".", "mark", "(", "`", "${", "id", "}", "`", ")", ";", "moduleData", "[", "id", "]", ".", "response", "=", "getResDataObject", "(", "res", ")", ";", "moduleData", "[", "id", "]", "=", "flatten", "(", "moduleData", "[", "id", "]", ",", "{", "maxDepth", ":", "5", "}", ")", ";", "moduleData", "[", "id", "]", "=", "filterData", "(", "config", ",", "moduleData", "[", "id", "]", ")", ";", "if", "(", "typeof", "moduleData", "[", "id", "]", "!==", "'object'", ")", "{", "timeline", ".", "data", "=", "timeline", ".", "data", ".", "filter", "(", "d", "=>", "!", "new", "RegExp", "(", "id", ")", ".", "test", "(", "d", ".", "name", ")", ")", ";", "delete", "moduleData", "[", "id", "]", ";", "}", "if", "(", "typeof", "originalCallback", "===", "'function'", ")", "{", "return", "originalCallback", ".", "apply", "(", "this", ",", "[", "res", "]", ")", ";", "}", "return", "true", ";", "}" ]
the func to execute at the end of the http call
[ "the", "func", "to", "execute", "at", "the", "end", "of", "the", "http", "call" ]
20783f04fcfce6f374f7e5699101ae138499adb9
https://github.com/iopipe/iopipe-js-trace/blob/20783f04fcfce6f374f7e5699101ae138499adb9/src/shimmerHttp.js#L156-L176
train
kayahr/console-shim
console-shim.js
function(func, scope, args) { var fixedArgs = Array.prototype.slice.call(arguments, 2); return function() { var args = fixedArgs.concat(Array.prototype.slice.call(arguments, 0)); (/** @type {Function} */ func).apply(scope, args); }; }
javascript
function(func, scope, args) { var fixedArgs = Array.prototype.slice.call(arguments, 2); return function() { var args = fixedArgs.concat(Array.prototype.slice.call(arguments, 0)); (/** @type {Function} */ func).apply(scope, args); }; }
[ "function", "(", "func", ",", "scope", ",", "args", ")", "{", "var", "fixedArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ";", "return", "function", "(", ")", "{", "var", "args", "=", "fixedArgs", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ")", ";", "(", "func", ")", ".", "apply", "(", "scope", ",", "args", ")", ";", "}", ";", "}" ]
Returns a function which calls the specified function in the specified scope. @param {Function} func The function to call. @param {Object} scope The scope to call the function in. @param {...*} args Additional arguments to pass to the bound function. @returns {function(...[*]): undefined} The bound function.
[ "Returns", "a", "function", "which", "calls", "the", "specified", "function", "in", "the", "specified", "scope", "." ]
2c18ef22194222ad0e21cd48dad073c086f9253d
https://github.com/kayahr/console-shim/blob/2c18ef22194222ad0e21cd48dad073c086f9253d/console-shim.js#L26-L34
train
kayahr/console-shim
console-shim.js
function(args) { var i, max, match, log; // Convert argument list to real array args = Array.prototype.slice.call(arguments, 0); // First argument is the log method to call log = args.shift(); max = args.length; if (max > 1 && window["__consoleShimTest__"] !== false) { // When first parameter is not a string then add a format string to // the argument list so we are able to modify it in the next stop if (typeof(args[0]) != "string") { args.unshift("%o"); max += 1; } // For each additional parameter which has no placeholder in the // format string we add another placeholder separated with a // space character. match = args[0].match(/%[a-z]/g); for (i = match ? match.length + 1 : 1; i < max; i += 1) { args[0] += " %o"; } } Function.apply.call(log, console, args); }
javascript
function(args) { var i, max, match, log; // Convert argument list to real array args = Array.prototype.slice.call(arguments, 0); // First argument is the log method to call log = args.shift(); max = args.length; if (max > 1 && window["__consoleShimTest__"] !== false) { // When first parameter is not a string then add a format string to // the argument list so we are able to modify it in the next stop if (typeof(args[0]) != "string") { args.unshift("%o"); max += 1; } // For each additional parameter which has no placeholder in the // format string we add another placeholder separated with a // space character. match = args[0].match(/%[a-z]/g); for (i = match ? match.length + 1 : 1; i < max; i += 1) { args[0] += " %o"; } } Function.apply.call(log, console, args); }
[ "function", "(", "args", ")", "{", "var", "i", ",", "max", ",", "match", ",", "log", ";", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "log", "=", "args", ".", "shift", "(", ")", ";", "max", "=", "args", ".", "length", ";", "if", "(", "max", ">", "1", "&&", "window", "[", "\"__consoleShimTest__\"", "]", "!==", "false", ")", "{", "if", "(", "typeof", "(", "args", "[", "0", "]", ")", "!=", "\"string\"", ")", "{", "args", ".", "unshift", "(", "\"%o\"", ")", ";", "max", "+=", "1", ";", "}", "match", "=", "args", "[", "0", "]", ".", "match", "(", "/", "%[a-z]", "/", "g", ")", ";", "for", "(", "i", "=", "match", "?", "match", ".", "length", "+", "1", ":", "1", ";", "i", "<", "max", ";", "i", "+=", "1", ")", "{", "args", "[", "0", "]", "+=", "\" %o\"", ";", "}", "}", "Function", ".", "apply", ".", "call", "(", "log", ",", "console", ",", "args", ")", ";", "}" ]
Wraps the call to a real IE logging method. Modifies the arguments so parameters which are not represented by a placeholder are properly printed with a space character as separator. @param {...*} args The function arguments. First argument is the log function to call, the other arguments are the log arguments.
[ "Wraps", "the", "call", "to", "a", "real", "IE", "logging", "method", ".", "Modifies", "the", "arguments", "so", "parameters", "which", "are", "not", "represented", "by", "a", "placeholder", "are", "properly", "printed", "with", "a", "space", "character", "as", "separator", "." ]
2c18ef22194222ad0e21cd48dad073c086f9253d
https://github.com/kayahr/console-shim/blob/2c18ef22194222ad0e21cd48dad073c086f9253d/console-shim.js#L82-L113
train
stldo/url-slug
src/index.js
parseOptions
function parseOptions(options) { let separator let transformer if (2 === options.length) { [separator, transformer] = options if (defaultTransformers[transformer]) { transformer = defaultTransformers[transformer] /* Don't validate */ validate({ separator }) } else { validate({ separator, transformer }) } } else if (1 === options.length) { const option = options[0] if (false === option || 'function' === typeof option) { transformer = option /* Don't validate */ } else if (defaultTransformers[option]) { transformer = defaultTransformers[option] /* Don't validate */ } else { separator = option validate({ separator }) } } return { separator, transformer } }
javascript
function parseOptions(options) { let separator let transformer if (2 === options.length) { [separator, transformer] = options if (defaultTransformers[transformer]) { transformer = defaultTransformers[transformer] /* Don't validate */ validate({ separator }) } else { validate({ separator, transformer }) } } else if (1 === options.length) { const option = options[0] if (false === option || 'function' === typeof option) { transformer = option /* Don't validate */ } else if (defaultTransformers[option]) { transformer = defaultTransformers[option] /* Don't validate */ } else { separator = option validate({ separator }) } } return { separator, transformer } }
[ "function", "parseOptions", "(", "options", ")", "{", "let", "separator", "let", "transformer", "if", "(", "2", "===", "options", ".", "length", ")", "{", "[", "separator", ",", "transformer", "]", "=", "options", "if", "(", "defaultTransformers", "[", "transformer", "]", ")", "{", "transformer", "=", "defaultTransformers", "[", "transformer", "]", "validate", "(", "{", "separator", "}", ")", "}", "else", "{", "validate", "(", "{", "separator", ",", "transformer", "}", ")", "}", "}", "else", "if", "(", "1", "===", "options", ".", "length", ")", "{", "const", "option", "=", "options", "[", "0", "]", "if", "(", "false", "===", "option", "||", "'function'", "===", "typeof", "option", ")", "{", "transformer", "=", "option", "}", "else", "if", "(", "defaultTransformers", "[", "option", "]", ")", "{", "transformer", "=", "defaultTransformers", "[", "option", "]", "}", "else", "{", "separator", "=", "option", "validate", "(", "{", "separator", "}", ")", "}", "}", "return", "{", "separator", ",", "transformer", "}", "}" ]
Check and return validated options
[ "Check", "and", "return", "validated", "options" ]
4e124d7c5d4ffeef25c3eb4df1bb659771095056
https://github.com/stldo/url-slug/blob/4e124d7c5d4ffeef25c3eb4df1bb659771095056/src/index.js#L34-L59
train
uber-workflow/probot-app-release-notes
generate-changelog.js
getWeight
function getWeight(labels, labelWeight) { const places = labels.map(label => labelWeight.indexOf(label.name)); let binary = ''; for (let i = 0; i < labelWeight.length; i++) { binary += places.includes(i) ? '1' : '0'; } return parseInt(binary, 2); }
javascript
function getWeight(labels, labelWeight) { const places = labels.map(label => labelWeight.indexOf(label.name)); let binary = ''; for (let i = 0; i < labelWeight.length; i++) { binary += places.includes(i) ? '1' : '0'; } return parseInt(binary, 2); }
[ "function", "getWeight", "(", "labels", ",", "labelWeight", ")", "{", "const", "places", "=", "labels", ".", "map", "(", "label", "=>", "labelWeight", ".", "indexOf", "(", "label", ".", "name", ")", ")", ";", "let", "binary", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "labelWeight", ".", "length", ";", "i", "++", ")", "{", "binary", "+=", "places", ".", "includes", "(", "i", ")", "?", "'1'", ":", "'0'", ";", "}", "return", "parseInt", "(", "binary", ",", "2", ")", ";", "}" ]
Calculates the weight of a given array of labels
[ "Calculates", "the", "weight", "of", "a", "given", "array", "of", "labels" ]
a3321d07ad091516dce5d3c973fd963d67bcc364
https://github.com/uber-workflow/probot-app-release-notes/blob/a3321d07ad091516dce5d3c973fd963d67bcc364/generate-changelog.js#L58-L65
train
uber-workflow/probot-app-release-notes
index.js
getReleaseInfo
async function getReleaseInfo(context, childTags) { const tagShas = []; const releasesBySha = await fetchAllReleases(context, release => { if (childTags.has(release.tag_name)) { // put in reverse order // later releases come first, // but we want to iterate beginning oldest releases first tagShas.unshift(release.target_commitish); // tagSha.push(release.target_commitish); } }); return {releasesBySha, tagShas}; }
javascript
async function getReleaseInfo(context, childTags) { const tagShas = []; const releasesBySha = await fetchAllReleases(context, release => { if (childTags.has(release.tag_name)) { // put in reverse order // later releases come first, // but we want to iterate beginning oldest releases first tagShas.unshift(release.target_commitish); // tagSha.push(release.target_commitish); } }); return {releasesBySha, tagShas}; }
[ "async", "function", "getReleaseInfo", "(", "context", ",", "childTags", ")", "{", "const", "tagShas", "=", "[", "]", ";", "const", "releasesBySha", "=", "await", "fetchAllReleases", "(", "context", ",", "release", "=>", "{", "if", "(", "childTags", ".", "has", "(", "release", ".", "tag_name", ")", ")", "{", "tagShas", ".", "unshift", "(", "release", ".", "target_commitish", ")", ";", "}", "}", ")", ";", "return", "{", "releasesBySha", ",", "tagShas", "}", ";", "}" ]
fetches all releases also finds releases corresponding to provided tags
[ "fetches", "all", "releases", "also", "finds", "releases", "corresponding", "to", "provided", "tags" ]
a3321d07ad091516dce5d3c973fd963d67bcc364
https://github.com/uber-workflow/probot-app-release-notes/blob/a3321d07ad091516dce5d3c973fd963d67bcc364/index.js#L79-L93
train
litixsoft/lx-valid
lx-valid.js
getType
function getType(value) { // inspired by http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/ // handle null in old IE if (value === null) { return 'null'; } // handle DOM elements if (value && (value.nodeType === 1 || value.nodeType === 9)) { return 'element'; } var s = Object.prototype.toString.call(value); var type = s.match(/\[object (.*?)\]/)[1].toLowerCase(); // handle NaN and Infinity if (type === 'number') { if (isNaN(value)) { return 'nan'; } if (!isFinite(value)) { return 'infinity'; } } return type; }
javascript
function getType(value) { // inspired by http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/ // handle null in old IE if (value === null) { return 'null'; } // handle DOM elements if (value && (value.nodeType === 1 || value.nodeType === 9)) { return 'element'; } var s = Object.prototype.toString.call(value); var type = s.match(/\[object (.*?)\]/)[1].toLowerCase(); // handle NaN and Infinity if (type === 'number') { if (isNaN(value)) { return 'nan'; } if (!isFinite(value)) { return 'infinity'; } } return type; }
[ "function", "getType", "(", "value", ")", "{", "if", "(", "value", "===", "null", ")", "{", "return", "'null'", ";", "}", "if", "(", "value", "&&", "(", "value", ".", "nodeType", "===", "1", "||", "value", ".", "nodeType", "===", "9", ")", ")", "{", "return", "'element'", ";", "}", "var", "s", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ";", "var", "type", "=", "s", ".", "match", "(", "/", "\\[object (.*?)\\]", "/", ")", "[", "1", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "type", "===", "'number'", ")", "{", "if", "(", "isNaN", "(", "value", ")", ")", "{", "return", "'nan'", ";", "}", "if", "(", "!", "isFinite", "(", "value", ")", ")", "{", "return", "'infinity'", ";", "}", "}", "return", "type", ";", "}" ]
Gets the type of the value in lower case. @param {*} value The value to test. @returns {string}
[ "Gets", "the", "type", "of", "the", "value", "in", "lower", "case", "." ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L18-L45
train
litixsoft/lx-valid
lx-valid.js
extendFormatExtensions
function extendFormatExtensions (extensionName, extensionValue) { if (typeof extensionName !== 'string' || !(extensionValue instanceof RegExp)) { throw new Error('extensionName or extensionValue undefined or not correct type'); } if (revalidator.validate.formats.hasOwnProperty(extensionName) || revalidator.validate.formats.hasOwnProperty(extensionName)) { var msg = 'extensionName: ' + extensionName + ' already exists in formatExtensions.'; throw new Error(msg); } revalidator.validate.formatExtensions[extensionName] = extensionValue; }
javascript
function extendFormatExtensions (extensionName, extensionValue) { if (typeof extensionName !== 'string' || !(extensionValue instanceof RegExp)) { throw new Error('extensionName or extensionValue undefined or not correct type'); } if (revalidator.validate.formats.hasOwnProperty(extensionName) || revalidator.validate.formats.hasOwnProperty(extensionName)) { var msg = 'extensionName: ' + extensionName + ' already exists in formatExtensions.'; throw new Error(msg); } revalidator.validate.formatExtensions[extensionName] = extensionValue; }
[ "function", "extendFormatExtensions", "(", "extensionName", ",", "extensionValue", ")", "{", "if", "(", "typeof", "extensionName", "!==", "'string'", "||", "!", "(", "extensionValue", "instanceof", "RegExp", ")", ")", "{", "throw", "new", "Error", "(", "'extensionName or extensionValue undefined or not correct type'", ")", ";", "}", "if", "(", "revalidator", ".", "validate", ".", "formats", ".", "hasOwnProperty", "(", "extensionName", ")", "||", "revalidator", ".", "validate", ".", "formats", ".", "hasOwnProperty", "(", "extensionName", ")", ")", "{", "var", "msg", "=", "'extensionName: '", "+", "extensionName", "+", "' already exists in formatExtensions.'", ";", "throw", "new", "Error", "(", "msg", ")", ";", "}", "revalidator", ".", "validate", ".", "formatExtensions", "[", "extensionName", "]", "=", "extensionValue", ";", "}" ]
Extend revalidator format extensions @param extensionName @param extensionValue
[ "Extend", "revalidator", "format", "extensions" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L819-L831
train
litixsoft/lx-valid
lx-valid.js
getError
function getError (type, expected, actual) { return { attribute: type, expected: expected, actual: actual, message: getMsg(type, expected) }; }
javascript
function getError (type, expected, actual) { return { attribute: type, expected: expected, actual: actual, message: getMsg(type, expected) }; }
[ "function", "getError", "(", "type", ",", "expected", ",", "actual", ")", "{", "return", "{", "attribute", ":", "type", ",", "expected", ":", "expected", ",", "actual", ":", "actual", ",", "message", ":", "getMsg", "(", "type", ",", "expected", ")", "}", ";", "}" ]
Get an error object @param type @param expected @param actual @return {Object}
[ "Get", "an", "error", "object" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L850-L857
train
litixsoft/lx-valid
lx-valid.js
getResult
function getResult (err) { var res = { valid: true, errors: [] }; if (err !== null) { res.valid = false; res.errors.push(err); } return res; }
javascript
function getResult (err) { var res = { valid: true, errors: [] }; if (err !== null) { res.valid = false; res.errors.push(err); } return res; }
[ "function", "getResult", "(", "err", ")", "{", "var", "res", "=", "{", "valid", ":", "true", ",", "errors", ":", "[", "]", "}", ";", "if", "(", "err", "!==", "null", ")", "{", "res", ".", "valid", "=", "false", ";", "res", ".", "errors", ".", "push", "(", "err", ")", ";", "}", "return", "res", ";", "}" ]
Get an validation result @param err @return {object}
[ "Get", "an", "validation", "result" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L864-L876
train
litixsoft/lx-valid
lx-valid.js
uniqueArrayHelper
function uniqueArrayHelper (val) { var h = {}; for (var i = 0, l = val.length; i < l; i++) { var key = JSON.stringify(val[i]); if (h[key]) { return false; } h[key] = true; } return true; }
javascript
function uniqueArrayHelper (val) { var h = {}; for (var i = 0, l = val.length; i < l; i++) { var key = JSON.stringify(val[i]); if (h[key]) { return false; } h[key] = true; } return true; }
[ "function", "uniqueArrayHelper", "(", "val", ")", "{", "var", "h", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "val", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "key", "=", "JSON", ".", "stringify", "(", "val", "[", "i", "]", ")", ";", "if", "(", "h", "[", "key", "]", ")", "{", "return", "false", ";", "}", "h", "[", "key", "]", "=", "true", ";", "}", "return", "true", ";", "}" ]
Check if array is unique @param val @return {Boolean}
[ "Check", "if", "array", "is", "unique" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L883-L895
train
litixsoft/lx-valid
lx-valid.js
getValidationFunction
function getValidationFunction (validationOptions) { validationOptions = validationOptions || {}; return function (doc, schema, options) { doc = doc || {}; options = options || {}; options.isUpdate = options.isUpdate || false; // check is update if (options.isUpdate) { var i, keys = Object.keys(schema.properties), length = keys.length; for (i = 0; i < length; i++) { if (!doc.hasOwnProperty(keys[i])) { // set property required to false schema.properties[keys[i]].required = false; // remove property from required array if (Array.isArray(schema.required) && schema.required.indexOf(keys[i]) > -1) { schema.required.splice(schema.required.indexOf(keys[i]), 1); } } } } // add default validation options to options object for (var key in validationOptions) { // only add options, do not override if (validationOptions.hasOwnProperty(key) && !options.hasOwnProperty(key)) { options[key] = validationOptions[key]; } } // json schema validate return exports.validate(doc, schema, options); }; }
javascript
function getValidationFunction (validationOptions) { validationOptions = validationOptions || {}; return function (doc, schema, options) { doc = doc || {}; options = options || {}; options.isUpdate = options.isUpdate || false; // check is update if (options.isUpdate) { var i, keys = Object.keys(schema.properties), length = keys.length; for (i = 0; i < length; i++) { if (!doc.hasOwnProperty(keys[i])) { // set property required to false schema.properties[keys[i]].required = false; // remove property from required array if (Array.isArray(schema.required) && schema.required.indexOf(keys[i]) > -1) { schema.required.splice(schema.required.indexOf(keys[i]), 1); } } } } // add default validation options to options object for (var key in validationOptions) { // only add options, do not override if (validationOptions.hasOwnProperty(key) && !options.hasOwnProperty(key)) { options[key] = validationOptions[key]; } } // json schema validate return exports.validate(doc, schema, options); }; }
[ "function", "getValidationFunction", "(", "validationOptions", ")", "{", "validationOptions", "=", "validationOptions", "||", "{", "}", ";", "return", "function", "(", "doc", ",", "schema", ",", "options", ")", "{", "doc", "=", "doc", "||", "{", "}", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "isUpdate", "=", "options", ".", "isUpdate", "||", "false", ";", "if", "(", "options", ".", "isUpdate", ")", "{", "var", "i", ",", "keys", "=", "Object", ".", "keys", "(", "schema", ".", "properties", ")", ",", "length", "=", "keys", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "!", "doc", ".", "hasOwnProperty", "(", "keys", "[", "i", "]", ")", ")", "{", "schema", ".", "properties", "[", "keys", "[", "i", "]", "]", ".", "required", "=", "false", ";", "if", "(", "Array", ".", "isArray", "(", "schema", ".", "required", ")", "&&", "schema", ".", "required", ".", "indexOf", "(", "keys", "[", "i", "]", ")", ">", "-", "1", ")", "{", "schema", ".", "required", ".", "splice", "(", "schema", ".", "required", ".", "indexOf", "(", "keys", "[", "i", "]", ")", ",", "1", ")", ";", "}", "}", "}", "}", "for", "(", "var", "key", "in", "validationOptions", ")", "{", "if", "(", "validationOptions", ".", "hasOwnProperty", "(", "key", ")", "&&", "!", "options", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "options", "[", "key", "]", "=", "validationOptions", "[", "key", "]", ";", "}", "}", "return", "exports", ".", "validate", "(", "doc", ",", "schema", ",", "options", ")", ";", "}", ";", "}" ]
Gets the validate function and encapsulates some param checks @param {object=} validationOptions The validation options for revalidator. @return {function(doc, schema, options)}
[ "Gets", "the", "validate", "function", "and", "encapsulates", "some", "param", "checks" ]
ae879336d2fdea69afa86dc6d1332587fda7bc18
https://github.com/litixsoft/lx-valid/blob/ae879336d2fdea69afa86dc6d1332587fda7bc18/lx-valid.js#L1244-L1282
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
componentExists
function componentExists(componentPath) { const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath)); const existsInWidgets = fs.existsSync(path.resolve(themes.getPath(), 'widgets', componentPath)); return !(!existsInExtensions && !existsInWidgets); }
javascript
function componentExists(componentPath) { const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath)); const existsInWidgets = fs.existsSync(path.resolve(themes.getPath(), 'widgets', componentPath)); return !(!existsInExtensions && !existsInWidgets); }
[ "function", "componentExists", "(", "componentPath", ")", "{", "const", "existsInExtensions", "=", "fs", ".", "existsSync", "(", "path", ".", "resolve", "(", "EXTENSIONS_PATH", ",", "componentPath", ")", ")", ";", "const", "existsInWidgets", "=", "fs", ".", "existsSync", "(", "path", ".", "resolve", "(", "themes", ".", "getPath", "(", ")", ",", "'widgets'", ",", "componentPath", ")", ")", ";", "return", "!", "(", "!", "existsInExtensions", "&&", "!", "existsInWidgets", ")", ";", "}" ]
Checks if the component exists. @param {string} componentPath The component path. @return {boolean}
[ "Checks", "if", "the", "component", "exists", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L37-L42
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
readConfig
function readConfig(options) { return new Promise((resolve, reject) => { const { type, config, importsStart = null, importsEnd = null, exportsStart = 'export default {', exportsEnd = '};', isArray = false, } = options; if (!config || !isPlainObject(config)) { return reject(new TypeError(t('SUPPLIED_CONFIG_IS_NOT_AN_OBJECT', { typeofConfig: typeof config, }))); } const imports = importsStart ? [importsStart] : []; // Holds the import strings. const exports = [exportsStart]; // Holds the export strings. // eslint-disable-next-line global-require, import/no-dynamic-require const themePackage = require(`${themes.getPath()}/package.json`); if ( (type === TYPE_PORTALS || type === TYPE_WIDGETS) && has(themePackage.dependencies, 'react-loadable') ) { imports.push('import Loadable from \'react-loadable\';'); imports.push('import Loading from \'@shopgate/pwa-common/components/Loading\';'); imports.push(''); } try { Object.keys(config).forEach((id) => { const component = config[id]; const componentPath = isDev ? component.path.replace('/dist/', '/src/') : component.path; if (!componentExists(componentPath)) { return; } const variableName = getVariableName(id); const isPortalsOrWidgets = ( (type === TYPE_PORTALS && component.target !== 'app.routes') || type === TYPE_WIDGETS ); if (isPortalsOrWidgets && has(themePackage.dependencies, 'react-loadable')) { imports.push(`const ${variableName} = Loadable({\n loader: () => import('${componentPath}'),\n loading: Loading,\n});\n`); } else { imports.push(`import ${variableName} from '${componentPath}';`); } if (isArray) { exports.push(` ${variableName},`); return; } exports.push(` '${id}': ${variableName},`); }); } catch (e) { return reject(e); } if (importsEnd) { imports.push(importsEnd); } exports.push(exportsEnd); return resolve({ imports, exports, }); }); }
javascript
function readConfig(options) { return new Promise((resolve, reject) => { const { type, config, importsStart = null, importsEnd = null, exportsStart = 'export default {', exportsEnd = '};', isArray = false, } = options; if (!config || !isPlainObject(config)) { return reject(new TypeError(t('SUPPLIED_CONFIG_IS_NOT_AN_OBJECT', { typeofConfig: typeof config, }))); } const imports = importsStart ? [importsStart] : []; // Holds the import strings. const exports = [exportsStart]; // Holds the export strings. // eslint-disable-next-line global-require, import/no-dynamic-require const themePackage = require(`${themes.getPath()}/package.json`); if ( (type === TYPE_PORTALS || type === TYPE_WIDGETS) && has(themePackage.dependencies, 'react-loadable') ) { imports.push('import Loadable from \'react-loadable\';'); imports.push('import Loading from \'@shopgate/pwa-common/components/Loading\';'); imports.push(''); } try { Object.keys(config).forEach((id) => { const component = config[id]; const componentPath = isDev ? component.path.replace('/dist/', '/src/') : component.path; if (!componentExists(componentPath)) { return; } const variableName = getVariableName(id); const isPortalsOrWidgets = ( (type === TYPE_PORTALS && component.target !== 'app.routes') || type === TYPE_WIDGETS ); if (isPortalsOrWidgets && has(themePackage.dependencies, 'react-loadable')) { imports.push(`const ${variableName} = Loadable({\n loader: () => import('${componentPath}'),\n loading: Loading,\n});\n`); } else { imports.push(`import ${variableName} from '${componentPath}';`); } if (isArray) { exports.push(` ${variableName},`); return; } exports.push(` '${id}': ${variableName},`); }); } catch (e) { return reject(e); } if (importsEnd) { imports.push(importsEnd); } exports.push(exportsEnd); return resolve({ imports, exports, }); }); }
[ "function", "readConfig", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "{", "type", ",", "config", ",", "importsStart", "=", "null", ",", "importsEnd", "=", "null", ",", "exportsStart", "=", "'export default {'", ",", "exportsEnd", "=", "'};'", ",", "isArray", "=", "false", ",", "}", "=", "options", ";", "if", "(", "!", "config", "||", "!", "isPlainObject", "(", "config", ")", ")", "{", "return", "reject", "(", "new", "TypeError", "(", "t", "(", "'SUPPLIED_CONFIG_IS_NOT_AN_OBJECT'", ",", "{", "typeofConfig", ":", "typeof", "config", ",", "}", ")", ")", ")", ";", "}", "const", "imports", "=", "importsStart", "?", "[", "importsStart", "]", ":", "[", "]", ";", "const", "exports", "=", "[", "exportsStart", "]", ";", "const", "themePackage", "=", "require", "(", "`", "${", "themes", ".", "getPath", "(", ")", "}", "`", ")", ";", "if", "(", "(", "type", "===", "TYPE_PORTALS", "||", "type", "===", "TYPE_WIDGETS", ")", "&&", "has", "(", "themePackage", ".", "dependencies", ",", "'react-loadable'", ")", ")", "{", "imports", ".", "push", "(", "'import Loadable from \\'react-loadable\\';'", ")", ";", "\\'", "\\'", "}", "imports", ".", "push", "(", "'import Loading from \\'@shopgate/pwa-common/components/Loading\\';'", ")", ";", "\\'", "\\'", "imports", ".", "push", "(", "''", ")", ";", "}", ")", ";", "}" ]
Reads the components config and creates import and export variables. @param {Object} options The read config options. @return {Promise}
[ "Reads", "the", "components", "config", "and", "creates", "import", "and", "export", "variables", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L58-L135
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
getIndexLogTranslations
function getIndexLogTranslations(type = TYPE_WIDGETS) { const params = { type: t(`TYPE_${type}`) }; return { logStart: ` ${t('INDEXING_TYPE', params)}`, logEnd: ` ${t('INDEXED_TYPE', params)}`, logNotFound: ` ${t('NO_EXTENSIONS_FOUND_FOR_TYPE', params)}`, }; }
javascript
function getIndexLogTranslations(type = TYPE_WIDGETS) { const params = { type: t(`TYPE_${type}`) }; return { logStart: ` ${t('INDEXING_TYPE', params)}`, logEnd: ` ${t('INDEXED_TYPE', params)}`, logNotFound: ` ${t('NO_EXTENSIONS_FOUND_FOR_TYPE', params)}`, }; }
[ "function", "getIndexLogTranslations", "(", "type", "=", "TYPE_WIDGETS", ")", "{", "const", "params", "=", "{", "type", ":", "t", "(", "`", "${", "type", "}", "`", ")", "}", ";", "return", "{", "logStart", ":", "`", "${", "t", "(", "'INDEXING_TYPE'", ",", "params", ")", "}", "`", ",", "logEnd", ":", "`", "${", "t", "(", "'INDEXED_TYPE'", ",", "params", ")", "}", "`", ",", "logNotFound", ":", "`", "${", "t", "(", "'NO_EXTENSIONS_FOUND_FOR_TYPE'", ",", "params", ")", "}", "`", ",", "}", ";", "}" ]
Creates translations for the extension indexing log. @param {string} type The indexed type. @returns {Object}
[ "Creates", "translations", "for", "the", "extension", "indexing", "log", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L142-L150
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
validateExtensions
function validateExtensions(input) { return new Promise((resolve, reject) => { try { const extensionPath = getExtensionsPath(); if (!fs.existsSync(extensionPath)) { fs.mkdirSync(extensionPath); } if (!input.imports.length) { return resolve(null); } return resolve(input); } catch (e) { return reject(new Error(t('EXTENSION_COULD_NOT_BE_VALIDATED'))); } }); }
javascript
function validateExtensions(input) { return new Promise((resolve, reject) => { try { const extensionPath = getExtensionsPath(); if (!fs.existsSync(extensionPath)) { fs.mkdirSync(extensionPath); } if (!input.imports.length) { return resolve(null); } return resolve(input); } catch (e) { return reject(new Error(t('EXTENSION_COULD_NOT_BE_VALIDATED'))); } }); }
[ "function", "validateExtensions", "(", "input", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "const", "extensionPath", "=", "getExtensionsPath", "(", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "extensionPath", ")", ")", "{", "fs", ".", "mkdirSync", "(", "extensionPath", ")", ";", "}", "if", "(", "!", "input", ".", "imports", ".", "length", ")", "{", "return", "resolve", "(", "null", ")", ";", "}", "return", "resolve", "(", "input", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "reject", "(", "new", "Error", "(", "t", "(", "'EXTENSION_COULD_NOT_BE_VALIDATED'", ")", ")", ")", ";", "}", "}", ")", ";", "}" ]
Validates the extensions input. @param {Object} input The input. @return {Promise}
[ "Validates", "the", "extensions", "input", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L157-L175
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
createStrings
function createStrings(input) { return new Promise((resolve, reject) => { try { if (!input) { return resolve(null); } const importsString = input.imports.length ? `${input.imports.join('\n')}\n\n` : ''; const exportsString = input.exports.length ? `${input.exports.join('\n')}\n` : ''; const indexString = `${importsString}${exportsString}`.replace('\n\n\n', '\n\n'); return resolve(indexString.length ? indexString : null); } catch (e) { return reject(new Error(t('STRINGS_COULD_NOT_BE_CREATED'))); } }); }
javascript
function createStrings(input) { return new Promise((resolve, reject) => { try { if (!input) { return resolve(null); } const importsString = input.imports.length ? `${input.imports.join('\n')}\n\n` : ''; const exportsString = input.exports.length ? `${input.exports.join('\n')}\n` : ''; const indexString = `${importsString}${exportsString}`.replace('\n\n\n', '\n\n'); return resolve(indexString.length ? indexString : null); } catch (e) { return reject(new Error(t('STRINGS_COULD_NOT_BE_CREATED'))); } }); }
[ "function", "createStrings", "(", "input", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "if", "(", "!", "input", ")", "{", "return", "resolve", "(", "null", ")", ";", "}", "const", "importsString", "=", "input", ".", "imports", ".", "length", "?", "`", "${", "input", ".", "imports", ".", "join", "(", "'\\n'", ")", "}", "\\n", "\\n", "`", ":", "\\n", ";", "''", "const", "exportsString", "=", "input", ".", "exports", ".", "length", "?", "`", "${", "input", ".", "exports", ".", "join", "(", "'\\n'", ")", "}", "\\n", "`", ":", "\\n", ";", "''", "}", "const", "indexString", "=", "`", "${", "importsString", "}", "${", "exportsString", "}", "`", ".", "replace", "(", "'\\n\\n\\n'", ",", "\\n", ")", ";", "}", ")", ";", "}" ]
Creates the string that is written into the appropriate file. @param {Object} input The input object. @return {string}
[ "Creates", "the", "string", "that", "is", "written", "into", "the", "appropriate", "file", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L182-L198
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
writeExtensionFile
function writeExtensionFile(options) { return new Promise((resolve, reject) => { try { const { file, input, defaultContent, logNotFound, logEnd, } = options; const filePath = path.resolve(getExtensionsPath(), file); if (!input) { logger.warn(logNotFound); fs.writeFileSync(filePath, defaultContent, { flag: 'w+' }); return resolve(); } fs.writeFileSync(filePath, input, { flag: 'w+' }); logger.log(logEnd); return resolve(); } catch (e) { return reject(e); } }); }
javascript
function writeExtensionFile(options) { return new Promise((resolve, reject) => { try { const { file, input, defaultContent, logNotFound, logEnd, } = options; const filePath = path.resolve(getExtensionsPath(), file); if (!input) { logger.warn(logNotFound); fs.writeFileSync(filePath, defaultContent, { flag: 'w+' }); return resolve(); } fs.writeFileSync(filePath, input, { flag: 'w+' }); logger.log(logEnd); return resolve(); } catch (e) { return reject(e); } }); }
[ "function", "writeExtensionFile", "(", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "const", "{", "file", ",", "input", ",", "defaultContent", ",", "logNotFound", ",", "logEnd", ",", "}", "=", "options", ";", "const", "filePath", "=", "path", ".", "resolve", "(", "getExtensionsPath", "(", ")", ",", "file", ")", ";", "if", "(", "!", "input", ")", "{", "logger", ".", "warn", "(", "logNotFound", ")", ";", "fs", ".", "writeFileSync", "(", "filePath", ",", "defaultContent", ",", "{", "flag", ":", "'w+'", "}", ")", ";", "return", "resolve", "(", ")", ";", "}", "fs", ".", "writeFileSync", "(", "filePath", ",", "input", ",", "{", "flag", ":", "'w+'", "}", ")", ";", "logger", ".", "log", "(", "logEnd", ")", ";", "return", "resolve", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
Writes to extension file. @param {Object} options The action object. @return {Promise}
[ "Writes", "to", "extension", "file", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L205-L231
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
index
function index(options) { const { file, config, logStart, logNotFound, logEnd, defaultContent = defaultFileContent, } = options; logger.log(logStart); return readConfig(config) .then(input => validateExtensions(input)) .then(input => createStrings(input)) .then(input => writeExtensionFile({ input, file, defaultContent, logNotFound, logEnd, })); }
javascript
function index(options) { const { file, config, logStart, logNotFound, logEnd, defaultContent = defaultFileContent, } = options; logger.log(logStart); return readConfig(config) .then(input => validateExtensions(input)) .then(input => createStrings(input)) .then(input => writeExtensionFile({ input, file, defaultContent, logNotFound, logEnd, })); }
[ "function", "index", "(", "options", ")", "{", "const", "{", "file", ",", "config", ",", "logStart", ",", "logNotFound", ",", "logEnd", ",", "defaultContent", "=", "defaultFileContent", ",", "}", "=", "options", ";", "logger", ".", "log", "(", "logStart", ")", ";", "return", "readConfig", "(", "config", ")", ".", "then", "(", "input", "=>", "validateExtensions", "(", "input", ")", ")", ".", "then", "(", "input", "=>", "createStrings", "(", "input", ")", ")", ".", "then", "(", "input", "=>", "writeExtensionFile", "(", "{", "input", ",", "file", ",", "defaultContent", ",", "logNotFound", ",", "logEnd", ",", "}", ")", ")", ";", "}" ]
Creates an index. @param {Object} options The indexing options, @return {Promise}
[ "Creates", "an", "index", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L238-L260
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexWidgets
function indexWidgets() { const { widgets = {} } = getComponentsSettings(); return index({ file: 'widgets.js', config: { type: TYPE_WIDGETS, config: widgets, }, ...getIndexLogTranslations(TYPE_WIDGETS), }); }
javascript
function indexWidgets() { const { widgets = {} } = getComponentsSettings(); return index({ file: 'widgets.js', config: { type: TYPE_WIDGETS, config: widgets, }, ...getIndexLogTranslations(TYPE_WIDGETS), }); }
[ "function", "indexWidgets", "(", ")", "{", "const", "{", "widgets", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'widgets.js'", ",", "config", ":", "{", "type", ":", "TYPE_WIDGETS", ",", "config", ":", "widgets", ",", "}", ",", "...", "getIndexLogTranslations", "(", "TYPE_WIDGETS", ")", ",", "}", ")", ";", "}" ]
Indexes the widgets. @return {Promise}
[ "Indexes", "the", "widgets", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L266-L277
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexTracking
function indexTracking() { const { tracking = {} } = getComponentsSettings(); return index({ file: 'tracking.js', config: { type: TYPE_TRACKERS, config: tracking, }, ...getIndexLogTranslations(TYPE_TRACKERS), }); }
javascript
function indexTracking() { const { tracking = {} } = getComponentsSettings(); return index({ file: 'tracking.js', config: { type: TYPE_TRACKERS, config: tracking, }, ...getIndexLogTranslations(TYPE_TRACKERS), }); }
[ "function", "indexTracking", "(", ")", "{", "const", "{", "tracking", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'tracking.js'", ",", "config", ":", "{", "type", ":", "TYPE_TRACKERS", ",", "config", ":", "tracking", ",", "}", ",", "...", "getIndexLogTranslations", "(", "TYPE_TRACKERS", ")", ",", "}", ")", ";", "}" ]
Indexes the tracking. @return {Promise}
[ "Indexes", "the", "tracking", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L283-L294
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexPortals
function indexPortals() { const { portals = {} } = getComponentsSettings(); return index({ file: 'portals.js', config: { type: TYPE_PORTALS, config: portals, importsStart: 'import portalCollection from \'@shopgate/pwa-common/helpers/portals/portalCollection\';', exportsStart: 'portalCollection.registerPortals({', exportsEnd: '});', }, ...getIndexLogTranslations(TYPE_PORTALS), }); }
javascript
function indexPortals() { const { portals = {} } = getComponentsSettings(); return index({ file: 'portals.js', config: { type: TYPE_PORTALS, config: portals, importsStart: 'import portalCollection from \'@shopgate/pwa-common/helpers/portals/portalCollection\';', exportsStart: 'portalCollection.registerPortals({', exportsEnd: '});', }, ...getIndexLogTranslations(TYPE_PORTALS), }); }
[ "function", "indexPortals", "(", ")", "{", "const", "{", "portals", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'portals.js'", ",", "config", ":", "{", "type", ":", "TYPE_PORTALS", ",", "config", ":", "portals", ",", "importsStart", ":", "'import portalCollection from \\'@shopgate/pwa-common/helpers/portals/portalCollection\\';'", ",", "\\'", ",", "\\'", ",", "}", ",", "exportsStart", ":", "'portalCollection.registerPortals({'", ",", "}", ")", ";", "}" ]
Indexes the portals. @return {Promise}
[ "Indexes", "the", "portals", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L300-L314
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexReducers
function indexReducers() { const { reducers = {} } = getComponentsSettings(); return index({ file: 'reducers.js', config: { type: TYPE_REDUCERS, config: reducers, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_REDUCERS), }); }
javascript
function indexReducers() { const { reducers = {} } = getComponentsSettings(); return index({ file: 'reducers.js', config: { type: TYPE_REDUCERS, config: reducers, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_REDUCERS), }); }
[ "function", "indexReducers", "(", ")", "{", "const", "{", "reducers", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'reducers.js'", ",", "config", ":", "{", "type", ":", "TYPE_REDUCERS", ",", "config", ":", "reducers", ",", "}", ",", "defaultContent", ":", "'export default null;\\n'", ",", "\\n", ",", "}", ")", ";", "}" ]
Indexes the reducers from extensions. @return {Promise}
[ "Indexes", "the", "reducers", "from", "extensions", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L320-L332
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexSubscribers
function indexSubscribers() { const { subscribers = {} } = getComponentsSettings(); return index({ file: 'subscribers.js', config: { type: TYPE_SUBSCRIBERS, config: subscribers, exportsStart: 'export default [', exportsEnd: '];', isArray: true, }, defaultContent: 'export default [];\n', ...getIndexLogTranslations(TYPE_SUBSCRIBERS), }); }
javascript
function indexSubscribers() { const { subscribers = {} } = getComponentsSettings(); return index({ file: 'subscribers.js', config: { type: TYPE_SUBSCRIBERS, config: subscribers, exportsStart: 'export default [', exportsEnd: '];', isArray: true, }, defaultContent: 'export default [];\n', ...getIndexLogTranslations(TYPE_SUBSCRIBERS), }); }
[ "function", "indexSubscribers", "(", ")", "{", "const", "{", "subscribers", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'subscribers.js'", ",", "config", ":", "{", "type", ":", "TYPE_SUBSCRIBERS", ",", "config", ":", "subscribers", ",", "exportsStart", ":", "'export default ['", ",", "exportsEnd", ":", "'];'", ",", "isArray", ":", "true", ",", "}", ",", "defaultContent", ":", "'export default [];\\n'", ",", "\\n", ",", "}", ")", ";", "}" ]
Indexes the RxJS subscriptions from extensions. @return {Promise}
[ "Indexes", "the", "RxJS", "subscriptions", "from", "extensions", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L338-L353
train
shopgate/cloud-sdk-webpack
lib/helpers/indexes.js
indexTranslations
function indexTranslations() { const { translations = {} } = getComponentsSettings(); return index({ file: 'translations.js', config: { type: TYPE_TRANSLATIONS, config: translations, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_TRANSLATIONS), }); }
javascript
function indexTranslations() { const { translations = {} } = getComponentsSettings(); return index({ file: 'translations.js', config: { type: TYPE_TRANSLATIONS, config: translations, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_TRANSLATIONS), }); }
[ "function", "indexTranslations", "(", ")", "{", "const", "{", "translations", "=", "{", "}", "}", "=", "getComponentsSettings", "(", ")", ";", "return", "index", "(", "{", "file", ":", "'translations.js'", ",", "config", ":", "{", "type", ":", "TYPE_TRANSLATIONS", ",", "config", ":", "translations", ",", "}", ",", "defaultContent", ":", "'export default null;\\n'", ",", "\\n", ",", "}", ")", ";", "}" ]
Indexes the translations from extensions. @return {Promise}
[ "Indexes", "the", "translations", "from", "extensions", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/indexes.js#L359-L371
train
cheminfo-js/openchemlib-extended
src/db/search.js
search
function search(query, options = {}) { const { format = 'idCode', mode = 'substructure', flattenResult = true, keepMolecule = false, limit = Number.MAX_SAFE_INTEGER } = options; if (typeof query === 'string') { const getMoleculeCreators = require('./moleculeCreators'); const moleculeCreators = getMoleculeCreators(this.OCL.Molecule); query = moleculeCreators.get(format.toLowerCase())(query); } else if (!(query instanceof this.OCL.Molecule)) { throw new TypeError('toSearch must be a Molecule or string'); } let result; switch (mode.toLowerCase()) { case 'exact': result = exactSearch(this.moleculeDB.db, query, limit); break; case 'substructure': result = subStructureSearch(this.moleculeDB, query, limit); break; case 'similarity': result = similaritySearch(this.moleculeDB, this.OCL, query, limit); break; default: throw new Error(`unknown search mode: ${options.mode}`); } return processResult(result, { flattenResult, keepMolecule, limit }); }
javascript
function search(query, options = {}) { const { format = 'idCode', mode = 'substructure', flattenResult = true, keepMolecule = false, limit = Number.MAX_SAFE_INTEGER } = options; if (typeof query === 'string') { const getMoleculeCreators = require('./moleculeCreators'); const moleculeCreators = getMoleculeCreators(this.OCL.Molecule); query = moleculeCreators.get(format.toLowerCase())(query); } else if (!(query instanceof this.OCL.Molecule)) { throw new TypeError('toSearch must be a Molecule or string'); } let result; switch (mode.toLowerCase()) { case 'exact': result = exactSearch(this.moleculeDB.db, query, limit); break; case 'substructure': result = subStructureSearch(this.moleculeDB, query, limit); break; case 'similarity': result = similaritySearch(this.moleculeDB, this.OCL, query, limit); break; default: throw new Error(`unknown search mode: ${options.mode}`); } return processResult(result, { flattenResult, keepMolecule, limit }); }
[ "function", "search", "(", "query", ",", "options", "=", "{", "}", ")", "{", "const", "{", "format", "=", "'idCode'", ",", "mode", "=", "'substructure'", ",", "flattenResult", "=", "true", ",", "keepMolecule", "=", "false", ",", "limit", "=", "Number", ".", "MAX_SAFE_INTEGER", "}", "=", "options", ";", "if", "(", "typeof", "query", "===", "'string'", ")", "{", "const", "getMoleculeCreators", "=", "require", "(", "'./moleculeCreators'", ")", ";", "const", "moleculeCreators", "=", "getMoleculeCreators", "(", "this", ".", "OCL", ".", "Molecule", ")", ";", "query", "=", "moleculeCreators", ".", "get", "(", "format", ".", "toLowerCase", "(", ")", ")", "(", "query", ")", ";", "}", "else", "if", "(", "!", "(", "query", "instanceof", "this", ".", "OCL", ".", "Molecule", ")", ")", "{", "throw", "new", "TypeError", "(", "'toSearch must be a Molecule or string'", ")", ";", "}", "let", "result", ";", "switch", "(", "mode", ".", "toLowerCase", "(", ")", ")", "{", "case", "'exact'", ":", "result", "=", "exactSearch", "(", "this", ".", "moleculeDB", ".", "db", ",", "query", ",", "limit", ")", ";", "break", ";", "case", "'substructure'", ":", "result", "=", "subStructureSearch", "(", "this", ".", "moleculeDB", ",", "query", ",", "limit", ")", ";", "break", ";", "case", "'similarity'", ":", "result", "=", "similaritySearch", "(", "this", ".", "moleculeDB", ",", "this", ".", "OCL", ",", "query", ",", "limit", ")", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "options", ".", "mode", "}", "`", ")", ";", "}", "return", "processResult", "(", "result", ",", "{", "flattenResult", ",", "keepMolecule", ",", "limit", "}", ")", ";", "}" ]
Search in a MoleculeDB Inside the database all the same molecules are group together @memberof DB @instance @param {string|OCL.Molecule} [query] smiles, molfile, oclCode or instance of Molecule to look for @param {object} [options={}] @param {string} [options.format='idCode'] - query is in the format 'smiles', 'oclid' or 'molfile' @param {string} [options.mode='substructure'] - search by 'substructure', 'exact' or 'similarity' @param {boolean} [options.flattenResult=true] - The database group the data for the same product. This allows to flatten the result @param {boolean} [options.keepMolecule=false] - keep the OCL.Molecule object in the result @param {number} [options.limit=Number.MAX_SAFE_INTEGER] - maximal number of result @return {Array} array of object of the type {(molecule), idCode, data, properties}
[ "Search", "in", "a", "MoleculeDB", "Inside", "the", "database", "all", "the", "same", "molecules", "are", "group", "together" ]
45775a97f0ca952ba2aae4e6fe1c35846be4e1f8
https://github.com/cheminfo-js/openchemlib-extended/blob/45775a97f0ca952ba2aae4e6fe1c35846be4e1f8/src/db/search.js#L17-L49
train
ipfs-shipyard/ipfs-redux-bundle
src/js-ipfs-api/index.js
maybeApi
async function maybeApi ({ apiAddress, apiOpts, ipfsConnectionTest, IpfsApi }) { try { const ipfs = new IpfsApi(apiAddress, apiOpts) await ipfsConnectionTest(ipfs) return { ipfs, provider, apiAddress } } catch (error) { console.log('Failed to connect to ipfs-api', apiAddress) } }
javascript
async function maybeApi ({ apiAddress, apiOpts, ipfsConnectionTest, IpfsApi }) { try { const ipfs = new IpfsApi(apiAddress, apiOpts) await ipfsConnectionTest(ipfs) return { ipfs, provider, apiAddress } } catch (error) { console.log('Failed to connect to ipfs-api', apiAddress) } }
[ "async", "function", "maybeApi", "(", "{", "apiAddress", ",", "apiOpts", ",", "ipfsConnectionTest", ",", "IpfsApi", "}", ")", "{", "try", "{", "const", "ipfs", "=", "new", "IpfsApi", "(", "apiAddress", ",", "apiOpts", ")", "await", "ipfsConnectionTest", "(", "ipfs", ")", "return", "{", "ipfs", ",", "provider", ",", "apiAddress", "}", "}", "catch", "(", "error", ")", "{", "console", ".", "log", "(", "'Failed to connect to ipfs-api'", ",", "apiAddress", ")", "}", "}" ]
Helper to construct and test an api client. Returns an js-ipfs-api instance or null
[ "Helper", "to", "construct", "and", "test", "an", "api", "client", ".", "Returns", "an", "js", "-", "ipfs", "-", "api", "instance", "or", "null" ]
c53610427538d321d6f7614b402fabd5d469e6de
https://github.com/ipfs-shipyard/ipfs-redux-bundle/blob/c53610427538d321d6f7614b402fabd5d469e6de/src/js-ipfs-api/index.js#L43-L51
train
cheminfo-js/openchemlib-extended
src/extend/diastereotopic/migrated/DiastereotopicAtomID.js
addMissingChirality
function addMissingChirality(molecule, esrType = Molecule.cESRTypeAnd) { for (let iAtom = 0; iAtom < molecule.getAllAtoms(); iAtom++) { let tempMolecule = molecule.getCompactCopy(); changeAtomForStereo(tempMolecule, iAtom); // After copy, helpers must be recalculated tempMolecule.ensureHelperArrays(Molecule.cHelperParities); // We need to have >0 and not >1 because there could be unspecified chirality in racemate for (let i = 0; i < tempMolecule.getAtoms(); i++) { // changed from from handling below; TLS 9.Nov.2015 if ( tempMolecule.isAtomStereoCenter(i) && tempMolecule.getStereoBond(i) === -1 ) { let stereoBond = tempMolecule.getAtomPreferredStereoBond(i); if (stereoBond !== -1) { molecule.setBondType(stereoBond, Molecule.cBondTypeUp); if (molecule.getBondAtom(1, stereoBond) === i) { let connAtom = molecule.getBondAtom(0, stereoBond); molecule.setBondAtom(0, stereoBond, i); molecule.setBondAtom(1, stereoBond, connAtom); } // To me it seems that we have to add all stereo centers into AND group 0. TLS 9.Nov.2015 molecule.setAtomESR(i, esrType, 0); } } } } }
javascript
function addMissingChirality(molecule, esrType = Molecule.cESRTypeAnd) { for (let iAtom = 0; iAtom < molecule.getAllAtoms(); iAtom++) { let tempMolecule = molecule.getCompactCopy(); changeAtomForStereo(tempMolecule, iAtom); // After copy, helpers must be recalculated tempMolecule.ensureHelperArrays(Molecule.cHelperParities); // We need to have >0 and not >1 because there could be unspecified chirality in racemate for (let i = 0; i < tempMolecule.getAtoms(); i++) { // changed from from handling below; TLS 9.Nov.2015 if ( tempMolecule.isAtomStereoCenter(i) && tempMolecule.getStereoBond(i) === -1 ) { let stereoBond = tempMolecule.getAtomPreferredStereoBond(i); if (stereoBond !== -1) { molecule.setBondType(stereoBond, Molecule.cBondTypeUp); if (molecule.getBondAtom(1, stereoBond) === i) { let connAtom = molecule.getBondAtom(0, stereoBond); molecule.setBondAtom(0, stereoBond, i); molecule.setBondAtom(1, stereoBond, connAtom); } // To me it seems that we have to add all stereo centers into AND group 0. TLS 9.Nov.2015 molecule.setAtomESR(i, esrType, 0); } } } } }
[ "function", "addMissingChirality", "(", "molecule", ",", "esrType", "=", "Molecule", ".", "cESRTypeAnd", ")", "{", "for", "(", "let", "iAtom", "=", "0", ";", "iAtom", "<", "molecule", ".", "getAllAtoms", "(", ")", ";", "iAtom", "++", ")", "{", "let", "tempMolecule", "=", "molecule", ".", "getCompactCopy", "(", ")", ";", "changeAtomForStereo", "(", "tempMolecule", ",", "iAtom", ")", ";", "tempMolecule", ".", "ensureHelperArrays", "(", "Molecule", ".", "cHelperParities", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tempMolecule", ".", "getAtoms", "(", ")", ";", "i", "++", ")", "{", "if", "(", "tempMolecule", ".", "isAtomStereoCenter", "(", "i", ")", "&&", "tempMolecule", ".", "getStereoBond", "(", "i", ")", "===", "-", "1", ")", "{", "let", "stereoBond", "=", "tempMolecule", ".", "getAtomPreferredStereoBond", "(", "i", ")", ";", "if", "(", "stereoBond", "!==", "-", "1", ")", "{", "molecule", ".", "setBondType", "(", "stereoBond", ",", "Molecule", ".", "cBondTypeUp", ")", ";", "if", "(", "molecule", ".", "getBondAtom", "(", "1", ",", "stereoBond", ")", "===", "i", ")", "{", "let", "connAtom", "=", "molecule", ".", "getBondAtom", "(", "0", ",", "stereoBond", ")", ";", "molecule", ".", "setBondAtom", "(", "0", ",", "stereoBond", ",", "i", ")", ";", "molecule", ".", "setBondAtom", "(", "1", ",", "stereoBond", ",", "connAtom", ")", ";", "}", "molecule", ".", "setAtomESR", "(", "i", ",", "esrType", ",", "0", ")", ";", "}", "}", "}", "}", "}" ]
The problem is that sometimes we need to add chiral bond that was not planned because it is the same group This is the case for example for the valine where the 2 C of the methyl groups are diastereotopic @param molecule
[ "The", "problem", "is", "that", "sometimes", "we", "need", "to", "add", "chiral", "bond", "that", "was", "not", "planned", "because", "it", "is", "the", "same", "group", "This", "is", "the", "case", "for", "example", "for", "the", "valine", "where", "the", "2", "C", "of", "the", "methyl", "groups", "are", "diastereotopic" ]
45775a97f0ca952ba2aae4e6fe1c35846be4e1f8
https://github.com/cheminfo-js/openchemlib-extended/blob/45775a97f0ca952ba2aae4e6fe1c35846be4e1f8/src/extend/diastereotopic/migrated/DiastereotopicAtomID.js#L33-L60
train
cheminfo-js/openchemlib-extended
src/extend/diastereotopic/migrated/DiastereotopicAtomID.js
markDiastereotopicAtoms
function markDiastereotopicAtoms(molecule) { // changed from markDiastereo(); TLS 9.Nov.2015 let ids = getAtomIDs(molecule); let analyzed = {}; let group = 0; for (let id of ids) { console.log(`${id} - ${group}`); if (!analyzed.contains(id)) { analyzed[id] = true; for (let iAtom = 0; iAtom < ids.length; iAtom++) { if (id.equals(ids[iAtom])) { molecule.setAtomCustomLabel(iAtom, group); } } group++; } } }
javascript
function markDiastereotopicAtoms(molecule) { // changed from markDiastereo(); TLS 9.Nov.2015 let ids = getAtomIDs(molecule); let analyzed = {}; let group = 0; for (let id of ids) { console.log(`${id} - ${group}`); if (!analyzed.contains(id)) { analyzed[id] = true; for (let iAtom = 0; iAtom < ids.length; iAtom++) { if (id.equals(ids[iAtom])) { molecule.setAtomCustomLabel(iAtom, group); } } group++; } } }
[ "function", "markDiastereotopicAtoms", "(", "molecule", ")", "{", "let", "ids", "=", "getAtomIDs", "(", "molecule", ")", ";", "let", "analyzed", "=", "{", "}", ";", "let", "group", "=", "0", ";", "for", "(", "let", "id", "of", "ids", ")", "{", "console", ".", "log", "(", "`", "${", "id", "}", "${", "group", "}", "`", ")", ";", "if", "(", "!", "analyzed", ".", "contains", "(", "id", ")", ")", "{", "analyzed", "[", "id", "]", "=", "true", ";", "for", "(", "let", "iAtom", "=", "0", ";", "iAtom", "<", "ids", ".", "length", ";", "iAtom", "++", ")", "{", "if", "(", "id", ".", "equals", "(", "ids", "[", "iAtom", "]", ")", ")", "{", "molecule", ".", "setAtomCustomLabel", "(", "iAtom", ",", "group", ")", ";", "}", "}", "group", "++", ";", "}", "}", "}" ]
In order to debug we could number the group of diastereotopic atoms @param molecule
[ "In", "order", "to", "debug", "we", "could", "number", "the", "group", "of", "diastereotopic", "atoms" ]
45775a97f0ca952ba2aae4e6fe1c35846be4e1f8
https://github.com/cheminfo-js/openchemlib-extended/blob/45775a97f0ca952ba2aae4e6fe1c35846be4e1f8/src/extend/diastereotopic/migrated/DiastereotopicAtomID.js#L83-L100
train
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
getContrastColor
function getContrastColor(bgColor, colors) { // We set a rather high cutoff to prefer light text if possible. const cutoff = 0.74; // Calculate the perceived luminosity (relative brightness) of the color. const perceivedLuminosity = Color(bgColor).luminosity(); return perceivedLuminosity >= cutoff ? colors.dark : colors.light; }
javascript
function getContrastColor(bgColor, colors) { // We set a rather high cutoff to prefer light text if possible. const cutoff = 0.74; // Calculate the perceived luminosity (relative brightness) of the color. const perceivedLuminosity = Color(bgColor).luminosity(); return perceivedLuminosity >= cutoff ? colors.dark : colors.light; }
[ "function", "getContrastColor", "(", "bgColor", ",", "colors", ")", "{", "const", "cutoff", "=", "0.74", ";", "const", "perceivedLuminosity", "=", "Color", "(", "bgColor", ")", ".", "luminosity", "(", ")", ";", "return", "perceivedLuminosity", ">=", "cutoff", "?", "colors", ".", "dark", ":", "colors", ".", "light", ";", "}" ]
Calculates a contrast color for a given background color. The color will either be black or white depending on the perceived luminosity of the background color. @param {string} bgColor The background color. @param {Object} colors The full color variables. @returns {string} The contrast color.
[ "Calculates", "a", "contrast", "color", "for", "a", "given", "background", "color", ".", "The", "color", "will", "either", "be", "black", "or", "white", "depending", "on", "the", "perceived", "luminosity", "of", "the", "background", "color", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L14-L22
train
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
getFocusColor
function getFocusColor(colors) { if (Color(colors.primary).luminosity() >= 0.8) { return colors.accent; } return colors.primary; }
javascript
function getFocusColor(colors) { if (Color(colors.primary).luminosity() >= 0.8) { return colors.accent; } return colors.primary; }
[ "function", "getFocusColor", "(", "colors", ")", "{", "if", "(", "Color", "(", "colors", ".", "primary", ")", ".", "luminosity", "(", ")", ">=", "0.8", ")", "{", "return", "colors", ".", "accent", ";", "}", "return", "colors", ".", "primary", ";", "}" ]
Gets the default focus color. This usually is the themes primary color. However, if this color is too bright, the result of ths method will fall back to the accent color. @param {Object} colors The full color variables. @return {string} The color.
[ "Gets", "the", "default", "focus", "color", ".", "This", "usually", "is", "the", "themes", "primary", "color", ".", "However", "if", "this", "color", "is", "too", "bright", "the", "result", "of", "ths", "method", "will", "fall", "back", "to", "the", "accent", "color", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L31-L37
train
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
applyContrastColors
function applyContrastColors(config) { const { colors } = config; return { ...config, colors: { ...colors, primaryContrast: getContrastColor(colors.primary, colors), accentContrast: getContrastColor(colors.accent, colors), focus: getFocusColor(colors), }, }; }
javascript
function applyContrastColors(config) { const { colors } = config; return { ...config, colors: { ...colors, primaryContrast: getContrastColor(colors.primary, colors), accentContrast: getContrastColor(colors.accent, colors), focus: getFocusColor(colors), }, }; }
[ "function", "applyContrastColors", "(", "config", ")", "{", "const", "{", "colors", "}", "=", "config", ";", "return", "{", "...", "config", ",", "colors", ":", "{", "...", "colors", ",", "primaryContrast", ":", "getContrastColor", "(", "colors", ".", "primary", ",", "colors", ")", ",", "accentContrast", ":", "getContrastColor", "(", "colors", ".", "accent", ",", "colors", ")", ",", "focus", ":", "getFocusColor", "(", "colors", ")", ",", "}", ",", "}", ";", "}" ]
Applies the contrast and focus colors to the colors configuration. @param {Object} config The complete theme configuration. @return {Object}
[ "Applies", "the", "contrast", "and", "focus", "colors", "to", "the", "colors", "configuration", "." ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L44-L56
train
shopgate/cloud-sdk-webpack
lib/helpers/getThemeConfig.js
applyCustomColors
function applyCustomColors(config) { const { colors } = getAppSettings(); if (!config.hasOwnProperty('colors')) { return { ...config, colors, }; } return { ...config, colors: { ...config.colors, ...colors, }, }; }
javascript
function applyCustomColors(config) { const { colors } = getAppSettings(); if (!config.hasOwnProperty('colors')) { return { ...config, colors, }; } return { ...config, colors: { ...config.colors, ...colors, }, }; }
[ "function", "applyCustomColors", "(", "config", ")", "{", "const", "{", "colors", "}", "=", "getAppSettings", "(", ")", ";", "if", "(", "!", "config", ".", "hasOwnProperty", "(", "'colors'", ")", ")", "{", "return", "{", "...", "config", ",", "colors", ",", "}", ";", "}", "return", "{", "...", "config", ",", "colors", ":", "{", "...", "config", ".", "colors", ",", "...", "colors", ",", "}", ",", "}", ";", "}" ]
Applies custom colors @param {[type]} config [description] @return {[type]} [description]
[ "Applies", "custom", "colors" ]
9ba5a79a0558e885e275339096eed89eccee0013
https://github.com/shopgate/cloud-sdk-webpack/blob/9ba5a79a0558e885e275339096eed89eccee0013/lib/helpers/getThemeConfig.js#L63-L80
train
Open-Xchange-Frontend/appserver
lib/middleware/appsload.js
module
function module(filename) { return function () { if (verbose.local) console.log(filename); response.write(fs.readFileSync(filename) + '\n/*:oxsep:*/\n'); }; }
javascript
function module(filename) { return function () { if (verbose.local) console.log(filename); response.write(fs.readFileSync(filename) + '\n/*:oxsep:*/\n'); }; }
[ "function", "module", "(", "filename", ")", "{", "return", "function", "(", ")", "{", "if", "(", "verbose", ".", "local", ")", "console", ".", "log", "(", "filename", ")", ";", "response", ".", "write", "(", "fs", ".", "readFileSync", "(", "filename", ")", "+", "'\\n/*:oxsep:*/\\n'", ")", ";", "}", ";", "}" ]
normal RequireJS module
[ "normal", "RequireJS", "module" ]
bcf65b97842c44351464fafaafd20ae45dcd78fa
https://github.com/Open-Xchange-Frontend/appserver/blob/bcf65b97842c44351464fafaafd20ae45dcd78fa/lib/middleware/appsload.js#L89-L94
train
developmentseed/collecticons-processor
src/core/bundle.js
collecticonsBundle
async function collecticonsBundle (params) { const { dirPath, destFile } = params; await validateDirPath(dirPath); const resultFiles = await collecticonsCompile({ dirPath, styleFormats: ['css'], styleDest: './styles', fontDest: './', fontTypes: ['woff', 'woff2'], previewDest: './', noFileOutput: true }); if (resultFiles === null) return; // Create zip. let zip = new JSZip(); // Add generated files. resultFiles.forEach(file => { zip.file(file.path, file.contents); }); // Add the icons. const dir = await fs.readdir(dirPath); const svgs = await Promise.all(dir.map(async file => { return file.endsWith('.svg') ? ( { path: `icons/${file}`, contents: await fs.readFile(path.resolve(dirPath, file)) } ) : null; })); svgs.forEach(file => { zip.file(file.path, file.contents); }); await fs.ensureDir(path.dirname(destFile)); await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary'); }
javascript
async function collecticonsBundle (params) { const { dirPath, destFile } = params; await validateDirPath(dirPath); const resultFiles = await collecticonsCompile({ dirPath, styleFormats: ['css'], styleDest: './styles', fontDest: './', fontTypes: ['woff', 'woff2'], previewDest: './', noFileOutput: true }); if (resultFiles === null) return; // Create zip. let zip = new JSZip(); // Add generated files. resultFiles.forEach(file => { zip.file(file.path, file.contents); }); // Add the icons. const dir = await fs.readdir(dirPath); const svgs = await Promise.all(dir.map(async file => { return file.endsWith('.svg') ? ( { path: `icons/${file}`, contents: await fs.readFile(path.resolve(dirPath, file)) } ) : null; })); svgs.forEach(file => { zip.file(file.path, file.contents); }); await fs.ensureDir(path.dirname(destFile)); await fs.writeFile(destFile, zip.generate({ base64: false, compression: 'DEFLATE' }), 'binary'); }
[ "async", "function", "collecticonsBundle", "(", "params", ")", "{", "const", "{", "dirPath", ",", "destFile", "}", "=", "params", ";", "await", "validateDirPath", "(", "dirPath", ")", ";", "const", "resultFiles", "=", "await", "collecticonsCompile", "(", "{", "dirPath", ",", "styleFormats", ":", "[", "'css'", "]", ",", "styleDest", ":", "'./styles'", ",", "fontDest", ":", "'./'", ",", "fontTypes", ":", "[", "'woff'", ",", "'woff2'", "]", ",", "previewDest", ":", "'./'", ",", "noFileOutput", ":", "true", "}", ")", ";", "if", "(", "resultFiles", "===", "null", ")", "return", ";", "let", "zip", "=", "new", "JSZip", "(", ")", ";", "resultFiles", ".", "forEach", "(", "file", "=>", "{", "zip", ".", "file", "(", "file", ".", "path", ",", "file", ".", "contents", ")", ";", "}", ")", ";", "const", "dir", "=", "await", "fs", ".", "readdir", "(", "dirPath", ")", ";", "const", "svgs", "=", "await", "Promise", ".", "all", "(", "dir", ".", "map", "(", "async", "file", "=>", "{", "return", "file", ".", "endsWith", "(", "'.svg'", ")", "?", "(", "{", "path", ":", "`", "${", "file", "}", "`", ",", "contents", ":", "await", "fs", ".", "readFile", "(", "path", ".", "resolve", "(", "dirPath", ",", "file", ")", ")", "}", ")", ":", "null", ";", "}", ")", ")", ";", "svgs", ".", "forEach", "(", "file", "=>", "{", "zip", ".", "file", "(", "file", ".", "path", ",", "file", ".", "contents", ")", ";", "}", ")", ";", "await", "fs", ".", "ensureDir", "(", "path", ".", "dirname", "(", "destFile", ")", ")", ";", "await", "fs", ".", "writeFile", "(", "destFile", ",", "zip", ".", "generate", "(", "{", "base64", ":", "false", ",", "compression", ":", "'DEFLATE'", "}", ")", ",", "'binary'", ")", ";", "}" ]
Compiles the collecticons font and zips it. Contains all the used icons, the fonts, stylesheet and preview. @param {object} params @param {string} params.dirPath Source path for the svg icons. @param {string} params.destFile Destination of the zip file.
[ "Compiles", "the", "collecticons", "font", "and", "zips", "it", ".", "Contains", "all", "the", "used", "icons", "the", "fonts", "stylesheet", "and", "preview", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/core/bundle.js#L18-L65
train
canjs/can-map-define
can-map-define.js
function(errors) { //!steal-remove-start if (process.env.NODE_ENV !== 'production') { clearTimeout(asyncTimer); } //!steal-remove-end var stub = error && error.call(self, errors); // if 'validations' is on the page it will trigger // the error itself and we dont want to trigger // the event twice. :) if (stub !== false) { mapEventsMixin.dispatch.call(self, 'error', [ prop, errors ], true); } return false; }
javascript
function(errors) { //!steal-remove-start if (process.env.NODE_ENV !== 'production') { clearTimeout(asyncTimer); } //!steal-remove-end var stub = error && error.call(self, errors); // if 'validations' is on the page it will trigger // the error itself and we dont want to trigger // the event twice. :) if (stub !== false) { mapEventsMixin.dispatch.call(self, 'error', [ prop, errors ], true); } return false; }
[ "function", "(", "errors", ")", "{", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "clearTimeout", "(", "asyncTimer", ")", ";", "}", "var", "stub", "=", "error", "&&", "error", ".", "call", "(", "self", ",", "errors", ")", ";", "if", "(", "stub", "!==", "false", ")", "{", "mapEventsMixin", ".", "dispatch", ".", "call", "(", "self", ",", "'error'", ",", "[", "prop", ",", "errors", "]", ",", "true", ")", ";", "}", "return", "false", ";", "}" ]
check if there's a setter
[ "check", "if", "there", "s", "a", "setter" ]
1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d
https://github.com/canjs/can-map-define/blob/1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d/can-map-define.js#L174-L189
train
canjs/can-map-define
can-map-define.js
function(map, attr, val) { var serializer = attr === "*" ? false : getPropDefineBehavior("serialize", attr, map.define); if (serializer === undefined) { return oldSingleSerialize.call(map, attr, val); } else if (serializer !== false) { return typeof serializer === "function" ? serializer.call(map, val, attr) : oldSingleSerialize.call(map, attr, val); } }
javascript
function(map, attr, val) { var serializer = attr === "*" ? false : getPropDefineBehavior("serialize", attr, map.define); if (serializer === undefined) { return oldSingleSerialize.call(map, attr, val); } else if (serializer !== false) { return typeof serializer === "function" ? serializer.call(map, val, attr) : oldSingleSerialize.call(map, attr, val); } }
[ "function", "(", "map", ",", "attr", ",", "val", ")", "{", "var", "serializer", "=", "attr", "===", "\"*\"", "?", "false", ":", "getPropDefineBehavior", "(", "\"serialize\"", ",", "attr", ",", "map", ".", "define", ")", ";", "if", "(", "serializer", "===", "undefined", ")", "{", "return", "oldSingleSerialize", ".", "call", "(", "map", ",", "attr", ",", "val", ")", ";", "}", "else", "if", "(", "serializer", "!==", "false", ")", "{", "return", "typeof", "serializer", "===", "\"function\"", "?", "serializer", ".", "call", "(", "map", ",", "val", ",", "attr", ")", ":", "oldSingleSerialize", ".", "call", "(", "map", ",", "attr", ",", "val", ")", ";", "}", "}" ]
If the map has a define serializer for the given attr, run it.
[ "If", "the", "map", "has", "a", "define", "serializer", "for", "the", "given", "attr", "run", "it", "." ]
1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d
https://github.com/canjs/can-map-define/blob/1327861b2baa1f4dc8b3bc4ef6995ec30bc7e49d/can-map-define.js#L380-L387
train
developmentseed/collecticons-processor
src/font-generator.js
generateFonts
async function generateFonts (options = {}) { if (!options.fontName) throw new TypeError('Missing fontName argument'); if (!options.icons || !Array.isArray(options.icons) || !options.icons.length) { throw new TypeError('Invalid or empty icons argument'); } // Store created tasks to match dependencies. let genTasks = {}; /** * First, creates tasks for dependent font types. * Then creates task for specified font type and chains it to dependencies promises. * If some task already exists, it reuses it. */ const makeGenTask = type => { // If already defined return. if (genTasks[type]) return genTasks[type]; // Get generator function. const gen = generators[type]; // Create dependent functions const depsTasks = (gen.deps || []).map(depType => makeGenTask(depType)); const task = Promise.all(depsTasks).then(results => gen.fn(options, results) ); genTasks[type] = task; return task; }; // Make a gen task for each type. const types = ['svg', 'ttf', 'woff', 'woff2']; const tasks = types.map(type => { return makeGenTask(type); }); const results = await Promise.all(tasks); return zipObject(types, results); }
javascript
async function generateFonts (options = {}) { if (!options.fontName) throw new TypeError('Missing fontName argument'); if (!options.icons || !Array.isArray(options.icons) || !options.icons.length) { throw new TypeError('Invalid or empty icons argument'); } // Store created tasks to match dependencies. let genTasks = {}; /** * First, creates tasks for dependent font types. * Then creates task for specified font type and chains it to dependencies promises. * If some task already exists, it reuses it. */ const makeGenTask = type => { // If already defined return. if (genTasks[type]) return genTasks[type]; // Get generator function. const gen = generators[type]; // Create dependent functions const depsTasks = (gen.deps || []).map(depType => makeGenTask(depType)); const task = Promise.all(depsTasks).then(results => gen.fn(options, results) ); genTasks[type] = task; return task; }; // Make a gen task for each type. const types = ['svg', 'ttf', 'woff', 'woff2']; const tasks = types.map(type => { return makeGenTask(type); }); const results = await Promise.all(tasks); return zipObject(types, results); }
[ "async", "function", "generateFonts", "(", "options", "=", "{", "}", ")", "{", "if", "(", "!", "options", ".", "fontName", ")", "throw", "new", "TypeError", "(", "'Missing fontName argument'", ")", ";", "if", "(", "!", "options", ".", "icons", "||", "!", "Array", ".", "isArray", "(", "options", ".", "icons", ")", "||", "!", "options", ".", "icons", ".", "length", ")", "{", "throw", "new", "TypeError", "(", "'Invalid or empty icons argument'", ")", ";", "}", "let", "genTasks", "=", "{", "}", ";", "const", "makeGenTask", "=", "type", "=>", "{", "if", "(", "genTasks", "[", "type", "]", ")", "return", "genTasks", "[", "type", "]", ";", "const", "gen", "=", "generators", "[", "type", "]", ";", "const", "depsTasks", "=", "(", "gen", ".", "deps", "||", "[", "]", ")", ".", "map", "(", "depType", "=>", "makeGenTask", "(", "depType", ")", ")", ";", "const", "task", "=", "Promise", ".", "all", "(", "depsTasks", ")", ".", "then", "(", "results", "=>", "gen", ".", "fn", "(", "options", ",", "results", ")", ")", ";", "genTasks", "[", "type", "]", "=", "task", ";", "return", "task", ";", "}", ";", "const", "types", "=", "[", "'svg'", ",", "'ttf'", ",", "'woff'", ",", "'woff2'", "]", ";", "const", "tasks", "=", "types", ".", "map", "(", "type", "=>", "{", "return", "makeGenTask", "(", "type", ")", ";", "}", ")", ";", "const", "results", "=", "await", "Promise", ".", "all", "(", "tasks", ")", ";", "return", "zipObject", "(", "types", ",", "results", ")", ";", "}" ]
Generated the svg, ttf, woff, and woff2 fonts. @param {object} options Configuration @param {string} options.fontName Name of the font. @param {array} options.icons List of icons. Each should have a `name` and `codepoint` properties.boolean @param {object} options.formatOptions Configuration for each of the font generation plugins @returns {object} Object keyed with the font type and respective content. All fonts are returned in Buffer format.
[ "Generated", "the", "svg", "ttf", "woff", "and", "woff2", "fonts", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/font-generator.js#L97-L132
train
developmentseed/collecticons-processor
src/renderers/index.js
renderSass
async function renderSass (opts = {}) { const tpl = await fs.readFile(path.resolve(__dirname, 'sass.ejs'), 'utf8'); return ejs.render(tpl, opts); }
javascript
async function renderSass (opts = {}) { const tpl = await fs.readFile(path.resolve(__dirname, 'sass.ejs'), 'utf8'); return ejs.render(tpl, opts); }
[ "async", "function", "renderSass", "(", "opts", "=", "{", "}", ")", "{", "const", "tpl", "=", "await", "fs", ".", "readFile", "(", "path", ".", "resolve", "(", "__dirname", ",", "'sass.ejs'", ")", ",", "'utf8'", ")", ";", "return", "ejs", ".", "render", "(", "tpl", ",", "opts", ")", ";", "}" ]
Renders the sass file using the `sass.ejs` template. @param {object} opts Option for the generation. @param {string} opts.fontName Name of the font to render. @param {string} opts.embed Whether or not to embed the fonts defined in the `fonts` option. @param {object} opts.fonts Fonts to use. Only `woff` and `woff2` are supported. The object key should be the font type and each should have a contents in Buffer format and a path to the font File. The path is not needed if embed is set to `true`. Example: woff: { contents: Buffer path: String } @param {string} opts.authorName Name of the font author. Will go into the style header comment. @param {string} opts.authorUrl Url of the font author. Will go into the style header comment. @param {string} opts.className Class name / sass placeholder to use. @param {array} opts.icons List of icons. Each should have a `name` and `codepoint` properties.boolean @param {boolean} opts.sassPlaceholder Whether or not to use sass placeholders. @param {boolean} opts.cssClass Whether or not to use css classes. @param {string} opts.dateFormatted Generation date. Will go into the style header comment. @returns {string} Rendered data
[ "Renders", "the", "sass", "file", "using", "the", "sass", ".", "ejs", "template", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/renderers/index.js#L67-L70
train
developmentseed/collecticons-processor
src/renderers/index.js
renderCatalog
async function renderCatalog (opts = {}) { if (!opts.fontName) throw new ReferenceError('fontName is undefined'); if (!opts.className) throw new ReferenceError('className is undefined'); if (!opts.icons || !opts.icons.length) throw new ReferenceError('icons is undefined or empty'); const fonts = opts.fonts ? Object.keys(opts.fonts).reduce((acc, name) => { return { ...acc, [name]: opts.fonts[name].contents.toString('base64') }; }, {}) : undefined; return JSON.stringify({ name: opts.fontName, className: opts.className, fonts, icons: opts.icons.map(i => ({ icon: `${opts.className}-${i.name}`, charCode: `${i.codepoint.toString(16).toUpperCase()}` })) }); }
javascript
async function renderCatalog (opts = {}) { if (!opts.fontName) throw new ReferenceError('fontName is undefined'); if (!opts.className) throw new ReferenceError('className is undefined'); if (!opts.icons || !opts.icons.length) throw new ReferenceError('icons is undefined or empty'); const fonts = opts.fonts ? Object.keys(opts.fonts).reduce((acc, name) => { return { ...acc, [name]: opts.fonts[name].contents.toString('base64') }; }, {}) : undefined; return JSON.stringify({ name: opts.fontName, className: opts.className, fonts, icons: opts.icons.map(i => ({ icon: `${opts.className}-${i.name}`, charCode: `${i.codepoint.toString(16).toUpperCase()}` })) }); }
[ "async", "function", "renderCatalog", "(", "opts", "=", "{", "}", ")", "{", "if", "(", "!", "opts", ".", "fontName", ")", "throw", "new", "ReferenceError", "(", "'fontName is undefined'", ")", ";", "if", "(", "!", "opts", ".", "className", ")", "throw", "new", "ReferenceError", "(", "'className is undefined'", ")", ";", "if", "(", "!", "opts", ".", "icons", "||", "!", "opts", ".", "icons", ".", "length", ")", "throw", "new", "ReferenceError", "(", "'icons is undefined or empty'", ")", ";", "const", "fonts", "=", "opts", ".", "fonts", "?", "Object", ".", "keys", "(", "opts", ".", "fonts", ")", ".", "reduce", "(", "(", "acc", ",", "name", ")", "=>", "{", "return", "{", "...", "acc", ",", "[", "name", "]", ":", "opts", ".", "fonts", "[", "name", "]", ".", "contents", ".", "toString", "(", "'base64'", ")", "}", ";", "}", ",", "{", "}", ")", ":", "undefined", ";", "return", "JSON", ".", "stringify", "(", "{", "name", ":", "opts", ".", "fontName", ",", "className", ":", "opts", ".", "className", ",", "fonts", ",", "icons", ":", "opts", ".", "icons", ".", "map", "(", "i", "=>", "(", "{", "icon", ":", "`", "${", "opts", ".", "className", "}", "${", "i", ".", "name", "}", "`", ",", "charCode", ":", "`", "${", "i", ".", "codepoint", ".", "toString", "(", "16", ")", ".", "toUpperCase", "(", ")", "}", "`", "}", ")", ")", "}", ")", ";", "}" ]
Renders the catalog file returning a json string. @param {object} opts Option for the generation. @param {string} opts.fontName Name of the font to render. @param {string} opts.className Class name / sass placeholder to use. @param {object} opts.fonts Fonts to include as base64 strings. Each object key is the font type and its value is the encoded string. @param {array} opts.icons List of icons. Each should have a `name` and `codepoint` properties.boolean @returns {string} Rendered data
[ "Renders", "the", "catalog", "file", "returning", "a", "json", "string", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/renderers/index.js#L103-L126
train
developmentseed/collecticons-processor
src/utils.js
Logger
function Logger () { const levels = [ 'fatal', // 1 'error', // 2 'warn', // 3 'info', // 4 'debug' // 5 ]; let verbosity = 3; levels.forEach((level, idx) => { this[level] = (...params) => { if (idx + 1 <= verbosity) console.log(...params); // eslint-disable-line }; }); this.setLevel = (_) => { verbosity = _; }; return this; }
javascript
function Logger () { const levels = [ 'fatal', // 1 'error', // 2 'warn', // 3 'info', // 4 'debug' // 5 ]; let verbosity = 3; levels.forEach((level, idx) => { this[level] = (...params) => { if (idx + 1 <= verbosity) console.log(...params); // eslint-disable-line }; }); this.setLevel = (_) => { verbosity = _; }; return this; }
[ "function", "Logger", "(", ")", "{", "const", "levels", "=", "[", "'fatal'", ",", "'error'", ",", "'warn'", ",", "'info'", ",", "'debug'", "]", ";", "let", "verbosity", "=", "3", ";", "levels", ".", "forEach", "(", "(", "level", ",", "idx", ")", "=>", "{", "this", "[", "level", "]", "=", "(", "...", "params", ")", "=>", "{", "if", "(", "idx", "+", "1", "<=", "verbosity", ")", "console", ".", "log", "(", "...", "params", ")", ";", "}", ";", "}", ")", ";", "this", ".", "setLevel", "=", "(", "_", ")", "=>", "{", "verbosity", "=", "_", ";", "}", ";", "return", "this", ";", "}" ]
Simple logger with levels. 1 - fatal 2 - error 3 - warn 4 - info 5 - debug Logger level set globally with setLevel(). Logging done using logger.<level>().
[ "Simple", "logger", "with", "levels", ".", "1", "-", "fatal", "2", "-", "error", "3", "-", "warn", "4", "-", "info", "5", "-", "debug" ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L15-L36
train
developmentseed/collecticons-processor
src/utils.js
userError
function userError (details = [], code) { const err = new Error('User error'); err.userError = true; err.code = code; err.details = details; return err; }
javascript
function userError (details = [], code) { const err = new Error('User error'); err.userError = true; err.code = code; err.details = details; return err; }
[ "function", "userError", "(", "details", "=", "[", "]", ",", "code", ")", "{", "const", "err", "=", "new", "Error", "(", "'User error'", ")", ";", "err", ".", "userError", "=", "true", ";", "err", ".", "code", "=", "code", ";", "err", ".", "details", "=", "details", ";", "return", "err", ";", "}" ]
Creates a User Error object. Each error has a details array where each entry is a message line to be printed. The error is supposed to bubble up the chain and print the cli help if the option is enabled. The `userError` property can be used to know if the error is created on purpose rather than thrown by something else. @param {array} details The message lines @returns Error
[ "Creates", "a", "User", "Error", "object", ".", "Each", "error", "has", "a", "details", "array", "where", "each", "entry", "is", "a", "message", "line", "to", "be", "printed", ".", "The", "error", "is", "supposed", "to", "bubble", "up", "the", "chain", "and", "print", "the", "cli", "help", "if", "the", "option", "is", "enabled", ".", "The", "userError", "property", "can", "be", "used", "to", "know", "if", "the", "error", "is", "created", "on", "purpose", "rather", "than", "thrown", "by", "something", "else", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L51-L57
train
developmentseed/collecticons-processor
src/utils.js
time
function time (name) { const t = timers[name]; if (t) { let elapsed = Date.now() - t; if (elapsed < 1000) return `${elapsed}ms`; if (elapsed < 60 * 1000) return `${elapsed / 1000}s`; elapsed /= 1000; const h = Math.floor(elapsed / 3600); const m = Math.floor((elapsed % 3600) / 60); const s = Math.floor((elapsed % 3600) % 60); delete timers[name]; return `${h}h ${m}m ${s}s`; } else { timers[name] = Date.now(); } }
javascript
function time (name) { const t = timers[name]; if (t) { let elapsed = Date.now() - t; if (elapsed < 1000) return `${elapsed}ms`; if (elapsed < 60 * 1000) return `${elapsed / 1000}s`; elapsed /= 1000; const h = Math.floor(elapsed / 3600); const m = Math.floor((elapsed % 3600) / 60); const s = Math.floor((elapsed % 3600) % 60); delete timers[name]; return `${h}h ${m}m ${s}s`; } else { timers[name] = Date.now(); } }
[ "function", "time", "(", "name", ")", "{", "const", "t", "=", "timers", "[", "name", "]", ";", "if", "(", "t", ")", "{", "let", "elapsed", "=", "Date", ".", "now", "(", ")", "-", "t", ";", "if", "(", "elapsed", "<", "1000", ")", "return", "`", "${", "elapsed", "}", "`", ";", "if", "(", "elapsed", "<", "60", "*", "1000", ")", "return", "`", "${", "elapsed", "/", "1000", "}", "`", ";", "elapsed", "/=", "1000", ";", "const", "h", "=", "Math", ".", "floor", "(", "elapsed", "/", "3600", ")", ";", "const", "m", "=", "Math", ".", "floor", "(", "(", "elapsed", "%", "3600", ")", "/", "60", ")", ";", "const", "s", "=", "Math", ".", "floor", "(", "(", "elapsed", "%", "3600", ")", "%", "60", ")", ";", "delete", "timers", "[", "name", "]", ";", "return", "`", "${", "h", "}", "${", "m", "}", "${", "s", "}", "`", ";", "}", "else", "{", "timers", "[", "name", "]", "=", "Date", ".", "now", "(", ")", ";", "}", "}" ]
Like console.time but better. Instead of printing the value returns it. Displays 1h 10m 10s notation for times above 60 seconds. Uses a global timers variable to keep track of timers. On the first call sets the time, on the second returns the value @param {string} name Timer name
[ "Like", "console", ".", "time", "but", "better", ".", "Instead", "of", "printing", "the", "value", "returns", "it", ".", "Displays", "1h", "10m", "10s", "notation", "for", "times", "above", "60", "seconds", ".", "Uses", "a", "global", "timers", "variable", "to", "keep", "track", "of", "timers", ".", "On", "the", "first", "call", "sets", "the", "time", "on", "the", "second", "returns", "the", "value" ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L69-L87
train
developmentseed/collecticons-processor
src/utils.js
validateDirPath
async function validateDirPath (dirPath) { try { const stats = await fs.lstat(dirPath); if (!stats.isDirectory()) { throw userError([ 'Source path must be a directory', '' ]); } } catch (error) { if (error.code === 'ENOENT') { throw userError([ 'No files or directories found at ' + dirPath, '' ]); } throw error; } }
javascript
async function validateDirPath (dirPath) { try { const stats = await fs.lstat(dirPath); if (!stats.isDirectory()) { throw userError([ 'Source path must be a directory', '' ]); } } catch (error) { if (error.code === 'ENOENT') { throw userError([ 'No files or directories found at ' + dirPath, '' ]); } throw error; } }
[ "async", "function", "validateDirPath", "(", "dirPath", ")", "{", "try", "{", "const", "stats", "=", "await", "fs", ".", "lstat", "(", "dirPath", ")", ";", "if", "(", "!", "stats", ".", "isDirectory", "(", ")", ")", "{", "throw", "userError", "(", "[", "'Source path must be a directory'", ",", "''", "]", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "if", "(", "error", ".", "code", "===", "'ENOENT'", ")", "{", "throw", "userError", "(", "[", "'No files or directories found at '", "+", "dirPath", ",", "''", "]", ")", ";", "}", "throw", "error", ";", "}", "}" ]
Validates that the given path is a directory, throwing user errors in other cases. @param {string} dirPath Path to validate @see userError() @throws Error if validation fails
[ "Validates", "that", "the", "given", "path", "is", "a", "directory", "throwing", "user", "errors", "in", "other", "cases", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L98-L117
train
developmentseed/collecticons-processor
src/utils.js
validateDirPathForCLI
async function validateDirPathForCLI (dirPath) { try { await validateDirPath(dirPath); } catch (error) { if (!error.userError) throw error; if (error.details[0].startsWith('Source path must be a directory')) { const args = process.argv.reduce((acc, o, idx) => { // Discard the first 2 arguments. if (idx < 1) return acc; if (o === dirPath) return acc.concat(path.dirname(dirPath)); return acc.concat(o); }, []); throw userError([ 'Source path must be a directory. Try running with the following instead:', '', ` node ${args.join(' ')}`, '' ]); } throw error; } }
javascript
async function validateDirPathForCLI (dirPath) { try { await validateDirPath(dirPath); } catch (error) { if (!error.userError) throw error; if (error.details[0].startsWith('Source path must be a directory')) { const args = process.argv.reduce((acc, o, idx) => { // Discard the first 2 arguments. if (idx < 1) return acc; if (o === dirPath) return acc.concat(path.dirname(dirPath)); return acc.concat(o); }, []); throw userError([ 'Source path must be a directory. Try running with the following instead:', '', ` node ${args.join(' ')}`, '' ]); } throw error; } }
[ "async", "function", "validateDirPathForCLI", "(", "dirPath", ")", "{", "try", "{", "await", "validateDirPath", "(", "dirPath", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "!", "error", ".", "userError", ")", "throw", "error", ";", "if", "(", "error", ".", "details", "[", "0", "]", ".", "startsWith", "(", "'Source path must be a directory'", ")", ")", "{", "const", "args", "=", "process", ".", "argv", ".", "reduce", "(", "(", "acc", ",", "o", ",", "idx", ")", "=>", "{", "if", "(", "idx", "<", "1", ")", "return", "acc", ";", "if", "(", "o", "===", "dirPath", ")", "return", "acc", ".", "concat", "(", "path", ".", "dirname", "(", "dirPath", ")", ")", ";", "return", "acc", ".", "concat", "(", "o", ")", ";", "}", ",", "[", "]", ")", ";", "throw", "userError", "(", "[", "'Source path must be a directory. Try running with the following instead:'", ",", "''", ",", "`", "${", "args", ".", "join", "(", "' '", ")", "}", "`", ",", "''", "]", ")", ";", "}", "throw", "error", ";", "}", "}" ]
Same functionality as validateDirPath but with error messages directed at a CLI tool. Validates that the given path is a directory, throwing user errors in other cases. @param {string} dirPath Path to validate @see validateDirPath() @throws Error if validation fails
[ "Same", "functionality", "as", "validateDirPath", "but", "with", "error", "messages", "directed", "at", "a", "CLI", "tool", ".", "Validates", "that", "the", "given", "path", "is", "a", "directory", "throwing", "user", "errors", "in", "other", "cases", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/src/utils.js#L130-L152
train
developmentseed/collecticons-processor
bin/programs.js
compileProgram
async function compileProgram (dirPath, command) { await validateDirPathForCLI(dirPath); const params = pick(command, [ 'fontName', 'sassPlaceholder', 'cssClass', 'fontTypes', 'styleFormats', 'styleDest', 'styleName', 'fontDest', 'authorName', 'authorUrl', 'className', 'previewDest', 'preview', 'catalogDest', 'experimentalFontOnCatalog', 'experimentalDisableStyles' ]); try { return collecticonsCompile({ dirPath, ...params }); } catch (error) { if (!error.userError) throw error; // Capture some errors and convert to their command line alternative. const code = error.code; if (code === 'PLC_CLASS_EXC') { error.details = ['Error: --no-sass-placeholder and --no-css-class are mutually exclusive']; } else if (code === 'FONT_TYPE') { error.details = ['Error: invalid font type value passed to --font-types']; } else if (code === 'CLASS_CSS_FORMAT') { error.details = ['Error: "--no-css-class" and "--style-formats css" are not compatible']; } else if (code === 'STYLE_TYPE') { error.details = ['Error: invalid style format value passed to --style-format']; } throw error; } }
javascript
async function compileProgram (dirPath, command) { await validateDirPathForCLI(dirPath); const params = pick(command, [ 'fontName', 'sassPlaceholder', 'cssClass', 'fontTypes', 'styleFormats', 'styleDest', 'styleName', 'fontDest', 'authorName', 'authorUrl', 'className', 'previewDest', 'preview', 'catalogDest', 'experimentalFontOnCatalog', 'experimentalDisableStyles' ]); try { return collecticonsCompile({ dirPath, ...params }); } catch (error) { if (!error.userError) throw error; // Capture some errors and convert to their command line alternative. const code = error.code; if (code === 'PLC_CLASS_EXC') { error.details = ['Error: --no-sass-placeholder and --no-css-class are mutually exclusive']; } else if (code === 'FONT_TYPE') { error.details = ['Error: invalid font type value passed to --font-types']; } else if (code === 'CLASS_CSS_FORMAT') { error.details = ['Error: "--no-css-class" and "--style-formats css" are not compatible']; } else if (code === 'STYLE_TYPE') { error.details = ['Error: invalid style format value passed to --style-format']; } throw error; } }
[ "async", "function", "compileProgram", "(", "dirPath", ",", "command", ")", "{", "await", "validateDirPathForCLI", "(", "dirPath", ")", ";", "const", "params", "=", "pick", "(", "command", ",", "[", "'fontName'", ",", "'sassPlaceholder'", ",", "'cssClass'", ",", "'fontTypes'", ",", "'styleFormats'", ",", "'styleDest'", ",", "'styleName'", ",", "'fontDest'", ",", "'authorName'", ",", "'authorUrl'", ",", "'className'", ",", "'previewDest'", ",", "'preview'", ",", "'catalogDest'", ",", "'experimentalFontOnCatalog'", ",", "'experimentalDisableStyles'", "]", ")", ";", "try", "{", "return", "collecticonsCompile", "(", "{", "dirPath", ",", "...", "params", "}", ")", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "!", "error", ".", "userError", ")", "throw", "error", ";", "const", "code", "=", "error", ".", "code", ";", "if", "(", "code", "===", "'PLC_CLASS_EXC'", ")", "{", "error", ".", "details", "=", "[", "'Error: --no-sass-placeholder and --no-css-class are mutually exclusive'", "]", ";", "}", "else", "if", "(", "code", "===", "'FONT_TYPE'", ")", "{", "error", ".", "details", "=", "[", "'Error: invalid font type value passed to --font-types'", "]", ";", "}", "else", "if", "(", "code", "===", "'CLASS_CSS_FORMAT'", ")", "{", "error", ".", "details", "=", "[", "'Error: \"--no-css-class\" and \"--style-formats css\" are not compatible'", "]", ";", "}", "else", "if", "(", "code", "===", "'STYLE_TYPE'", ")", "{", "error", ".", "details", "=", "[", "'Error: invalid style format value passed to --style-format'", "]", ";", "}", "throw", "error", ";", "}", "}" ]
Collecticons compile wrapped for use in the CLI tool.
[ "Collecticons", "compile", "wrapped", "for", "use", "in", "the", "CLI", "tool", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/bin/programs.js#L13-L56
train
developmentseed/collecticons-processor
bin/programs.js
bundleProgram
async function bundleProgram (dirPath, destFile) { await validateDirPathForCLI(dirPath); return collecticonsBundle({ dirPath, destFile }); }
javascript
async function bundleProgram (dirPath, destFile) { await validateDirPathForCLI(dirPath); return collecticonsBundle({ dirPath, destFile }); }
[ "async", "function", "bundleProgram", "(", "dirPath", ",", "destFile", ")", "{", "await", "validateDirPathForCLI", "(", "dirPath", ")", ";", "return", "collecticonsBundle", "(", "{", "dirPath", ",", "destFile", "}", ")", ";", "}" ]
Collecticons bundle wrapped for use in the CLI tool.
[ "Collecticons", "bundle", "wrapped", "for", "use", "in", "the", "CLI", "tool", "." ]
1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9
https://github.com/developmentseed/collecticons-processor/blob/1b3420de13a6a1fdc830e1c81bb97e8bc26e3ed9/bin/programs.js#L61-L67
train
RackHD/on-core
lib/common/connection.js
Connection
function Connection (options, clientOptions, label) { this.options = options; this.clientOptions = clientOptions; this.label = label; this.initialConnection = false; this.initialConnectionRetries = 0; this.maxConnectionRetries = 60; Object.defineProperty(this, 'exchanges', { get: function () { if (this.connection) { return this.connection.exchanges; } } }); Object.defineProperty(this, 'connected', { get: function () { return this.connection !== undefined; } }); }
javascript
function Connection (options, clientOptions, label) { this.options = options; this.clientOptions = clientOptions; this.label = label; this.initialConnection = false; this.initialConnectionRetries = 0; this.maxConnectionRetries = 60; Object.defineProperty(this, 'exchanges', { get: function () { if (this.connection) { return this.connection.exchanges; } } }); Object.defineProperty(this, 'connected', { get: function () { return this.connection !== undefined; } }); }
[ "function", "Connection", "(", "options", ",", "clientOptions", ",", "label", ")", "{", "this", ".", "options", "=", "options", ";", "this", ".", "clientOptions", "=", "clientOptions", ";", "this", ".", "label", "=", "label", ";", "this", ".", "initialConnection", "=", "false", ";", "this", ".", "initialConnectionRetries", "=", "0", ";", "this", ".", "maxConnectionRetries", "=", "60", ";", "Object", ".", "defineProperty", "(", "this", ",", "'exchanges'", ",", "{", "get", ":", "function", "(", ")", "{", "if", "(", "this", ".", "connection", ")", "{", "return", "this", ".", "connection", ".", "exchanges", ";", "}", "}", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'connected'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "this", ".", "connection", "!==", "undefined", ";", "}", "}", ")", ";", "}" ]
Connection provides a wrapper around the AMQP connection logic which presents a simplified interface for using multiple connections in the messenger. @param {Object} options node-amqp createConnection options. @param {type} [clientOptions] node-amqp createConnection client options.
[ "Connection", "provides", "a", "wrapper", "around", "the", "AMQP", "connection", "logic", "which", "presents", "a", "simplified", "interface", "for", "using", "multiple", "connections", "in", "the", "messenger", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/connection.js#L24-L45
train
RackHD/on-core
lib/common/json-schema-validator.js
resolveRef
function resolveRef(schemaObj, resolvedValues) { // the array store referenced value var refVal = schemaObj.refVal; // the map store full ref id and index of the referenced value in refVal // example: { 'test#definitions/option' : 1, 'test#definitions/repo' : 2 } var refs = schemaObj.refs; // the map to store schema value with sub reference var subRefs = {}; _.forEach(refs, function (index, refId) { // if reference id already resolved then continue the loop if (refId in resolvedValues) { return true; // continue } var refValue = refVal[index]; // if no further nested reference, add to resolved map if (_.isEmpty(refValue.refs)) { resolvedValues[refId] = refValue; return true; } // add schema value with sub reference to map to resolve later subRefs[refId] = refValue; }); // resolve sub reference recursively _.forEach(subRefs, function (subRef, refId) { resolvedValues[refId] = 1; resolvedValues[refId] = resolveRef(subRef, resolvedValues); }); return schemaObj.schema; }
javascript
function resolveRef(schemaObj, resolvedValues) { // the array store referenced value var refVal = schemaObj.refVal; // the map store full ref id and index of the referenced value in refVal // example: { 'test#definitions/option' : 1, 'test#definitions/repo' : 2 } var refs = schemaObj.refs; // the map to store schema value with sub reference var subRefs = {}; _.forEach(refs, function (index, refId) { // if reference id already resolved then continue the loop if (refId in resolvedValues) { return true; // continue } var refValue = refVal[index]; // if no further nested reference, add to resolved map if (_.isEmpty(refValue.refs)) { resolvedValues[refId] = refValue; return true; } // add schema value with sub reference to map to resolve later subRefs[refId] = refValue; }); // resolve sub reference recursively _.forEach(subRefs, function (subRef, refId) { resolvedValues[refId] = 1; resolvedValues[refId] = resolveRef(subRef, resolvedValues); }); return schemaObj.schema; }
[ "function", "resolveRef", "(", "schemaObj", ",", "resolvedValues", ")", "{", "var", "refVal", "=", "schemaObj", ".", "refVal", ";", "var", "refs", "=", "schemaObj", ".", "refs", ";", "var", "subRefs", "=", "{", "}", ";", "_", ".", "forEach", "(", "refs", ",", "function", "(", "index", ",", "refId", ")", "{", "if", "(", "refId", "in", "resolvedValues", ")", "{", "return", "true", ";", "}", "var", "refValue", "=", "refVal", "[", "index", "]", ";", "if", "(", "_", ".", "isEmpty", "(", "refValue", ".", "refs", ")", ")", "{", "resolvedValues", "[", "refId", "]", "=", "refValue", ";", "return", "true", ";", "}", "subRefs", "[", "refId", "]", "=", "refValue", ";", "}", ")", ";", "_", ".", "forEach", "(", "subRefs", ",", "function", "(", "subRef", ",", "refId", ")", "{", "resolvedValues", "[", "refId", "]", "=", "1", ";", "resolvedValues", "[", "refId", "]", "=", "resolveRef", "(", "subRef", ",", "resolvedValues", ")", ";", "}", ")", ";", "return", "schemaObj", ".", "schema", ";", "}" ]
resolve reference recursively it search the compiled schema data structure from ajv.getSchema, find out and store referenced value to resolvedValues map
[ "resolve", "reference", "recursively", "it", "search", "the", "compiled", "schema", "data", "structure", "from", "ajv", ".", "getSchema", "find", "out", "and", "store", "referenced", "value", "to", "resolvedValues", "map" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/json-schema-validator.js#L246-L279
train
bminer/node-static-asset
lib/static-asset.js
assetFingerprint
function assetFingerprint(label, fingerprint, cacheInfo) { if(arguments.length > 1) { //Add a label var labelInfo = labels[label] = {"fingerprint": fingerprint}; if(cacheInfo) for(var i in cacheInfo) labelInfo[i] = cacheInfo[i]; } else { //Try to get a fingerprint from a registered label var info = labels[label]; if(info) { fingerprints[info.fingerprint] = info; return info.fingerprint; } else { info = {}; //Try to get a fingerprint using the specified cache strategy var fullPath = path.resolve(rootPath + "/" + (label || this.url) ); //Use the "cache strategy" to get a fingerprint //Prefer the use of etag over lastModified when generating fingerprints if(!fs.existsSync(fullPath) ) return label; if(strategy.lastModified) { var mdate = info.lastModified = strategy.lastModified(fullPath); mdate.setMilliseconds(0); } if(strategy.etag) info.etag = strategy.etag(fullPath); if(strategy.expires) info.expires = strategy.expires(fullPath); if(strategy.fileFingerprint) { var fingerprint = strategy.fileFingerprint(label, fullPath); fingerprints[fingerprint] = info; return fingerprint; } else return label; //Do not generate a fingerprint } } }
javascript
function assetFingerprint(label, fingerprint, cacheInfo) { if(arguments.length > 1) { //Add a label var labelInfo = labels[label] = {"fingerprint": fingerprint}; if(cacheInfo) for(var i in cacheInfo) labelInfo[i] = cacheInfo[i]; } else { //Try to get a fingerprint from a registered label var info = labels[label]; if(info) { fingerprints[info.fingerprint] = info; return info.fingerprint; } else { info = {}; //Try to get a fingerprint using the specified cache strategy var fullPath = path.resolve(rootPath + "/" + (label || this.url) ); //Use the "cache strategy" to get a fingerprint //Prefer the use of etag over lastModified when generating fingerprints if(!fs.existsSync(fullPath) ) return label; if(strategy.lastModified) { var mdate = info.lastModified = strategy.lastModified(fullPath); mdate.setMilliseconds(0); } if(strategy.etag) info.etag = strategy.etag(fullPath); if(strategy.expires) info.expires = strategy.expires(fullPath); if(strategy.fileFingerprint) { var fingerprint = strategy.fileFingerprint(label, fullPath); fingerprints[fingerprint] = info; return fingerprint; } else return label; //Do not generate a fingerprint } } }
[ "function", "assetFingerprint", "(", "label", ",", "fingerprint", ",", "cacheInfo", ")", "{", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "var", "labelInfo", "=", "labels", "[", "label", "]", "=", "{", "\"fingerprint\"", ":", "fingerprint", "}", ";", "if", "(", "cacheInfo", ")", "for", "(", "var", "i", "in", "cacheInfo", ")", "labelInfo", "[", "i", "]", "=", "cacheInfo", "[", "i", "]", ";", "}", "else", "{", "var", "info", "=", "labels", "[", "label", "]", ";", "if", "(", "info", ")", "{", "fingerprints", "[", "info", ".", "fingerprint", "]", "=", "info", ";", "return", "info", ".", "fingerprint", ";", "}", "else", "{", "info", "=", "{", "}", ";", "var", "fullPath", "=", "path", ".", "resolve", "(", "rootPath", "+", "\"/\"", "+", "(", "label", "||", "this", ".", "url", ")", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "fullPath", ")", ")", "return", "label", ";", "if", "(", "strategy", ".", "lastModified", ")", "{", "var", "mdate", "=", "info", ".", "lastModified", "=", "strategy", ".", "lastModified", "(", "fullPath", ")", ";", "mdate", ".", "setMilliseconds", "(", "0", ")", ";", "}", "if", "(", "strategy", ".", "etag", ")", "info", ".", "etag", "=", "strategy", ".", "etag", "(", "fullPath", ")", ";", "if", "(", "strategy", ".", "expires", ")", "info", ".", "expires", "=", "strategy", ".", "expires", "(", "fullPath", ")", ";", "if", "(", "strategy", ".", "fileFingerprint", ")", "{", "var", "fingerprint", "=", "strategy", ".", "fileFingerprint", "(", "label", ",", "fullPath", ")", ";", "fingerprints", "[", "fingerprint", "]", "=", "info", ";", "return", "fingerprint", ";", "}", "else", "return", "label", ";", "}", "}", "}" ]
req.assetFingerprint function
[ "req", ".", "assetFingerprint", "function" ]
cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097
https://github.com/bminer/node-static-asset/blob/cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097/lib/static-asset.js#L72-L118
train
RackHD/on-core
lib/models/node.js
function() { var self = this; return waterline.catalogs.findOne({"node": self.id}) .then(function(catalog) { return !_.isEmpty(catalog); }); }
javascript
function() { var self = this; return waterline.catalogs.findOne({"node": self.id}) .then(function(catalog) { return !_.isEmpty(catalog); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "return", "waterline", ".", "catalogs", ".", "findOne", "(", "{", "\"node\"", ":", "self", ".", "id", "}", ")", ".", "then", "(", "function", "(", "catalog", ")", "{", "return", "!", "_", ".", "isEmpty", "(", "catalog", ")", ";", "}", ")", ";", "}" ]
We only count a node as having been discovered if a node document exists AND it has any catalogs associated with it
[ "We", "only", "count", "a", "node", "as", "having", "been", "discovered", "if", "a", "node", "document", "exists", "AND", "it", "has", "any", "catalogs", "associated", "with", "it" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/models/node.js#L90-L96
train
RackHD/on-core
spec/helper.js
function () { var waterline = this.injector.get('Services.Waterline'); return bluebird.all( _.map(waterline, function (collection) { if (typeof collection.destroy === 'function') { return bluebird.fromNode(collection.destroy.bind(collection)).then(function () { if (collection.adapterDictionary.define !== 'mongo') { return bluebird.fromNode( collection.adapter.define.bind(collection.adapter) ); } }); } }) ); }
javascript
function () { var waterline = this.injector.get('Services.Waterline'); return bluebird.all( _.map(waterline, function (collection) { if (typeof collection.destroy === 'function') { return bluebird.fromNode(collection.destroy.bind(collection)).then(function () { if (collection.adapterDictionary.define !== 'mongo') { return bluebird.fromNode( collection.adapter.define.bind(collection.adapter) ); } }); } }) ); }
[ "function", "(", ")", "{", "var", "waterline", "=", "this", ".", "injector", ".", "get", "(", "'Services.Waterline'", ")", ";", "return", "bluebird", ".", "all", "(", "_", ".", "map", "(", "waterline", ",", "function", "(", "collection", ")", "{", "if", "(", "typeof", "collection", ".", "destroy", "===", "'function'", ")", "{", "return", "bluebird", ".", "fromNode", "(", "collection", ".", "destroy", ".", "bind", "(", "collection", ")", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "collection", ".", "adapterDictionary", ".", "define", "!==", "'mongo'", ")", "{", "return", "bluebird", ".", "fromNode", "(", "collection", ".", "adapter", ".", "define", ".", "bind", "(", "collection", ".", "adapter", ")", ")", ";", "}", "}", ")", ";", "}", "}", ")", ")", ";", "}" ]
maps through all collections loaded into Services.Waterline and destroys them to reset testing state. Usage: beforeEach(function() { this.timeout(5000); // gives the system 5 seconds to do the wiping return waterline.start().then(function() { return helper.reset(); }) }) @returns {Promise}
[ "maps", "through", "all", "collections", "loaded", "into", "Services", ".", "Waterline", "and", "destroys", "them", "to", "reset", "testing", "state", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/spec/helper.js#L198-L214
train
RackHD/on-core
lib/common/child-process.js
ChildProcess
function ChildProcess (command, args, env, code, maxBuffer) { var self = this; assert.string(command); assert.optionalArrayOfNumber(code); self.command = command; self.file = self._parseCommandPath(self.command); self.args = args; self.environment = env || {}; self.exitCode = code || [0]; self.maxBuffer = maxBuffer || Constants.ChildProcess.MaxBuffer; if (!self.file) { throw new Error('Unable to locate command file (' + self.command +').'); } if (!_.isEmpty(self.args)) { try { assert.arrayOfString(self.args, 'ChildProcess command arguments'); } catch (e) { throw new Error('args must be an array of strings'); } } self.hasBeenKilled = false; self.hasBeenCancelled = false; self.spawnInstance = undefined; }
javascript
function ChildProcess (command, args, env, code, maxBuffer) { var self = this; assert.string(command); assert.optionalArrayOfNumber(code); self.command = command; self.file = self._parseCommandPath(self.command); self.args = args; self.environment = env || {}; self.exitCode = code || [0]; self.maxBuffer = maxBuffer || Constants.ChildProcess.MaxBuffer; if (!self.file) { throw new Error('Unable to locate command file (' + self.command +').'); } if (!_.isEmpty(self.args)) { try { assert.arrayOfString(self.args, 'ChildProcess command arguments'); } catch (e) { throw new Error('args must be an array of strings'); } } self.hasBeenKilled = false; self.hasBeenCancelled = false; self.spawnInstance = undefined; }
[ "function", "ChildProcess", "(", "command", ",", "args", ",", "env", ",", "code", ",", "maxBuffer", ")", "{", "var", "self", "=", "this", ";", "assert", ".", "string", "(", "command", ")", ";", "assert", ".", "optionalArrayOfNumber", "(", "code", ")", ";", "self", ".", "command", "=", "command", ";", "self", ".", "file", "=", "self", ".", "_parseCommandPath", "(", "self", ".", "command", ")", ";", "self", ".", "args", "=", "args", ";", "self", ".", "environment", "=", "env", "||", "{", "}", ";", "self", ".", "exitCode", "=", "code", "||", "[", "0", "]", ";", "self", ".", "maxBuffer", "=", "maxBuffer", "||", "Constants", ".", "ChildProcess", ".", "MaxBuffer", ";", "if", "(", "!", "self", ".", "file", ")", "{", "throw", "new", "Error", "(", "'Unable to locate command file ('", "+", "self", ".", "command", "+", "').'", ")", ";", "}", "if", "(", "!", "_", ".", "isEmpty", "(", "self", ".", "args", ")", ")", "{", "try", "{", "assert", ".", "arrayOfString", "(", "self", ".", "args", ",", "'ChildProcess command arguments'", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "'args must be an array of strings'", ")", ";", "}", "}", "self", ".", "hasBeenKilled", "=", "false", ";", "self", ".", "hasBeenCancelled", "=", "false", ";", "self", ".", "spawnInstance", "=", "undefined", ";", "}" ]
ChildProcess provides a promise based mechanism to run shell commands in a fairly secure manner. @constructor
[ "ChildProcess", "provides", "a", "promise", "based", "mechanism", "to", "run", "shell", "commands", "in", "a", "fairly", "secure", "manner", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/child-process.js#L48-L75
train
RackHD/on-core
lib/di.js
provideName
function provideName(obj, token){ if(!isString(token)) { throw new Error('Must provide string as name of module'); } di.annotate(obj, new di.Provide(token)); }
javascript
function provideName(obj, token){ if(!isString(token)) { throw new Error('Must provide string as name of module'); } di.annotate(obj, new di.Provide(token)); }
[ "function", "provideName", "(", "obj", ",", "token", ")", "{", "if", "(", "!", "isString", "(", "token", ")", ")", "{", "throw", "new", "Error", "(", "'Must provide string as name of module'", ")", ";", "}", "di", ".", "annotate", "(", "obj", ",", "new", "di", ".", "Provide", "(", "token", ")", ")", ";", "}" ]
Apply provide annotation to object @private @param {*} obj @param {string} token string to apply as provide annotation
[ "Apply", "provide", "annotation", "to", "object" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L251-L256
train
RackHD/on-core
lib/di.js
providePromise
function providePromise(obj, providePromiseName) { if(!isString(providePromiseName)) { throw new Error('Must provide string as name of promised module'); } di.annotate(obj, new di.ProvidePromise(providePromiseName)); }
javascript
function providePromise(obj, providePromiseName) { if(!isString(providePromiseName)) { throw new Error('Must provide string as name of promised module'); } di.annotate(obj, new di.ProvidePromise(providePromiseName)); }
[ "function", "providePromise", "(", "obj", ",", "providePromiseName", ")", "{", "if", "(", "!", "isString", "(", "providePromiseName", ")", ")", "{", "throw", "new", "Error", "(", "'Must provide string as name of promised module'", ")", ";", "}", "di", ".", "annotate", "(", "obj", ",", "new", "di", ".", "ProvidePromise", "(", "providePromiseName", ")", ")", ";", "}" ]
Apply provide promise annotation to object @private @param {*} obj @param {string} providePromiseName string to apply as provide promise annotation
[ "Apply", "provide", "promise", "annotation", "to", "object" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L263-L268
train
RackHD/on-core
lib/di.js
resolveProvide
function resolveProvide(obj, override) { var provide = override || obj.$provide; if(isString(provide)) { return provideName(obj, provide); } if(isObject(provide)) { if (isString(provide.promise)) { return providePromise(obj, provide.promise); } else if (isString(provide.provide)) { return provideName(obj, provide.provide); } } }
javascript
function resolveProvide(obj, override) { var provide = override || obj.$provide; if(isString(provide)) { return provideName(obj, provide); } if(isObject(provide)) { if (isString(provide.promise)) { return providePromise(obj, provide.promise); } else if (isString(provide.provide)) { return provideName(obj, provide.provide); } } }
[ "function", "resolveProvide", "(", "obj", ",", "override", ")", "{", "var", "provide", "=", "override", "||", "obj", ".", "$provide", ";", "if", "(", "isString", "(", "provide", ")", ")", "{", "return", "provideName", "(", "obj", ",", "provide", ")", ";", "}", "if", "(", "isObject", "(", "provide", ")", ")", "{", "if", "(", "isString", "(", "provide", ".", "promise", ")", ")", "{", "return", "providePromise", "(", "obj", ",", "provide", ".", "promise", ")", ";", "}", "else", "if", "(", "isString", "(", "provide", ".", "provide", ")", ")", "{", "return", "provideName", "(", "obj", ",", "provide", ".", "provide", ")", ";", "}", "}", "}" ]
resolve the type of promise and the name given the underlying object and any overrides @private @param {*} obj @param {string|object} [override] - specify any of the overides
[ "resolve", "the", "type", "of", "promise", "and", "the", "name", "given", "the", "underlying", "object", "and", "any", "overrides" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L276-L290
train
RackHD/on-core
lib/di.js
addInject
function addInject(obj, inject) { if(!exists(inject)) { return; } var injectMe; if (inject === '$injector') { injectMe = new di.Inject(di.Injector); } else if (isObject(inject)) { if(isString(inject.inject)){ injectMe = new di.Inject(inject.inject); } else if(isString(inject.promise)) { injectMe = new di.InjectPromise(inject.promise); } else if(isString(inject.lazy)) { injectMe = new di.InjectLazy(inject.lazy); } } else { injectMe = new di.Inject(inject); } di.annotate(obj, injectMe); }
javascript
function addInject(obj, inject) { if(!exists(inject)) { return; } var injectMe; if (inject === '$injector') { injectMe = new di.Inject(di.Injector); } else if (isObject(inject)) { if(isString(inject.inject)){ injectMe = new di.Inject(inject.inject); } else if(isString(inject.promise)) { injectMe = new di.InjectPromise(inject.promise); } else if(isString(inject.lazy)) { injectMe = new di.InjectLazy(inject.lazy); } } else { injectMe = new di.Inject(inject); } di.annotate(obj, injectMe); }
[ "function", "addInject", "(", "obj", ",", "inject", ")", "{", "if", "(", "!", "exists", "(", "inject", ")", ")", "{", "return", ";", "}", "var", "injectMe", ";", "if", "(", "inject", "===", "'$injector'", ")", "{", "injectMe", "=", "new", "di", ".", "Inject", "(", "di", ".", "Injector", ")", ";", "}", "else", "if", "(", "isObject", "(", "inject", ")", ")", "{", "if", "(", "isString", "(", "inject", ".", "inject", ")", ")", "{", "injectMe", "=", "new", "di", ".", "Inject", "(", "inject", ".", "inject", ")", ";", "}", "else", "if", "(", "isString", "(", "inject", ".", "promise", ")", ")", "{", "injectMe", "=", "new", "di", ".", "InjectPromise", "(", "inject", ".", "promise", ")", ";", "}", "else", "if", "(", "isString", "(", "inject", ".", "lazy", ")", ")", "{", "injectMe", "=", "new", "di", ".", "InjectLazy", "(", "inject", ".", "lazy", ")", ";", "}", "}", "else", "{", "injectMe", "=", "new", "di", ".", "Inject", "(", "inject", ")", ";", "}", "di", ".", "annotate", "(", "obj", ",", "injectMe", ")", ";", "}" ]
Add Inject Annotation @private @param {*} obj @param {string|object} inject
[ "Add", "Inject", "Annotation" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L298-L320
train
RackHD/on-core
lib/di.js
resolveInjects
function resolveInjects(obj, override){ var injects = obj.$inject || override; if (exists(injects)) { if (!Array.isArray(injects)) { injects = [injects]; } injects.forEach(function addInjects(element) { addInject(obj, element); }); } }
javascript
function resolveInjects(obj, override){ var injects = obj.$inject || override; if (exists(injects)) { if (!Array.isArray(injects)) { injects = [injects]; } injects.forEach(function addInjects(element) { addInject(obj, element); }); } }
[ "function", "resolveInjects", "(", "obj", ",", "override", ")", "{", "var", "injects", "=", "obj", ".", "$inject", "||", "override", ";", "if", "(", "exists", "(", "injects", ")", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "injects", ")", ")", "{", "injects", "=", "[", "injects", "]", ";", "}", "injects", ".", "forEach", "(", "function", "addInjects", "(", "element", ")", "{", "addInject", "(", "obj", ",", "element", ")", ";", "}", ")", ";", "}", "}" ]
adds provided annotations to obj @private @param obj @param override
[ "adds", "provided", "annotations", "to", "obj" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L328-L339
train
RackHD/on-core
lib/di.js
injectableWrapper
function injectableWrapper(obj, provide, injects, isTransientScope) { // TODO(@davequick): discuss with @halfspiral whether isTransientScope might just better // be an array of Annotations var wrappedObject = function wrapOrCreateObject() { if(isFunction(obj) && (exists(obj.$provide) || exists(obj.$inject) || provide || injects)){ var instance = Object.create(obj.prototype); return obj.apply(instance,arguments) || instance; } return obj; }; return _wrapper(obj, wrappedObject, provide, injects, isTransientScope); }
javascript
function injectableWrapper(obj, provide, injects, isTransientScope) { // TODO(@davequick): discuss with @halfspiral whether isTransientScope might just better // be an array of Annotations var wrappedObject = function wrapOrCreateObject() { if(isFunction(obj) && (exists(obj.$provide) || exists(obj.$inject) || provide || injects)){ var instance = Object.create(obj.prototype); return obj.apply(instance,arguments) || instance; } return obj; }; return _wrapper(obj, wrappedObject, provide, injects, isTransientScope); }
[ "function", "injectableWrapper", "(", "obj", ",", "provide", ",", "injects", ",", "isTransientScope", ")", "{", "var", "wrappedObject", "=", "function", "wrapOrCreateObject", "(", ")", "{", "if", "(", "isFunction", "(", "obj", ")", "&&", "(", "exists", "(", "obj", ".", "$provide", ")", "||", "exists", "(", "obj", ".", "$inject", ")", "||", "provide", "||", "injects", ")", ")", "{", "var", "instance", "=", "Object", ".", "create", "(", "obj", ".", "prototype", ")", ";", "return", "obj", ".", "apply", "(", "instance", ",", "arguments", ")", "||", "instance", ";", "}", "return", "obj", ";", "}", ";", "return", "_wrapper", "(", "obj", ",", "wrappedObject", ",", "provide", ",", "injects", ",", "isTransientScope", ")", ";", "}" ]
This is meant to be used where you have an injectable that might be an injectable function. if it is we want to actually have the injection happen while it is being returned. @param obj @param provide @param injects @param isTransientScope @returns {*}
[ "This", "is", "meant", "to", "be", "used", "where", "you", "have", "an", "injectable", "that", "might", "be", "an", "injectable", "function", ".", "if", "it", "is", "we", "want", "to", "actually", "have", "the", "injection", "happen", "while", "it", "is", "being", "returned", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L410-L421
train
RackHD/on-core
lib/di.js
_requireFile
function _requireFile(requirable, directory) { var required; try{ var res = resolve.sync(requirable, { basedir: directory}); required = require(res); } catch(err) { required = (void 0); } return required; }
javascript
function _requireFile(requirable, directory) { var required; try{ var res = resolve.sync(requirable, { basedir: directory}); required = require(res); } catch(err) { required = (void 0); } return required; }
[ "function", "_requireFile", "(", "requirable", ",", "directory", ")", "{", "var", "required", ";", "try", "{", "var", "res", "=", "resolve", ".", "sync", "(", "requirable", ",", "{", "basedir", ":", "directory", "}", ")", ";", "required", "=", "require", "(", "res", ")", ";", "}", "catch", "(", "err", ")", "{", "required", "=", "(", "void", "0", ")", ";", "}", "return", "required", ";", "}" ]
Attempt to fetch the supplied filename, no exceptions on fail @private @param {string} requirable to try and require @param {string} [directory] - directory to attempt resolving filename path with @returns {*} the result of the require, undefined if not found
[ "Attempt", "to", "fetch", "the", "supplied", "filename", "no", "exceptions", "on", "fail" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L456-L466
train
RackHD/on-core
lib/di.js
_require
function _require(requireMe, provides, injects, currentDirectory, next) { var requireResult = _requireFile (requireMe, currentDirectory) || _requireFile (requireMe, defaultDirectory) || _requireFile (requireMe, __dirname) || _requireFile (requireMe, process.cwd()) || _requireFile (requireMe, (void 0)); if(!exists(requireResult)) { var directories = 'directories:('; directories += exists(currentDirectory) ? currentDirectory + ', ' : ''; directories += exists(defaultDirectory) ? defaultDirectory + ', ' : ''; directories += __dirname + ')'; throw new Error('dihelper incapable of finding specified file for require filename:' + requireMe + ', ' + directories); } if (typeof provides === 'undefined' && !exists(requireResult.$provide)) { //TODO(@davequick): also look for annotations once ES6, for now can't because you would // receive a different di instance if you did require('di/dist/cjs/annotations') so class // equalities would not work. Once all is ES6, then instanceof for the classes should work // and add it here. For now you have to have a string or object on yourmodule.$provide or // it will be overwritten. provides = requireMe; } return next(requireResult, provides, injects); }
javascript
function _require(requireMe, provides, injects, currentDirectory, next) { var requireResult = _requireFile (requireMe, currentDirectory) || _requireFile (requireMe, defaultDirectory) || _requireFile (requireMe, __dirname) || _requireFile (requireMe, process.cwd()) || _requireFile (requireMe, (void 0)); if(!exists(requireResult)) { var directories = 'directories:('; directories += exists(currentDirectory) ? currentDirectory + ', ' : ''; directories += exists(defaultDirectory) ? defaultDirectory + ', ' : ''; directories += __dirname + ')'; throw new Error('dihelper incapable of finding specified file for require filename:' + requireMe + ', ' + directories); } if (typeof provides === 'undefined' && !exists(requireResult.$provide)) { //TODO(@davequick): also look for annotations once ES6, for now can't because you would // receive a different di instance if you did require('di/dist/cjs/annotations') so class // equalities would not work. Once all is ES6, then instanceof for the classes should work // and add it here. For now you have to have a string or object on yourmodule.$provide or // it will be overwritten. provides = requireMe; } return next(requireResult, provides, injects); }
[ "function", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "currentDirectory", ",", "next", ")", "{", "var", "requireResult", "=", "_requireFile", "(", "requireMe", ",", "currentDirectory", ")", "||", "_requireFile", "(", "requireMe", ",", "defaultDirectory", ")", "||", "_requireFile", "(", "requireMe", ",", "__dirname", ")", "||", "_requireFile", "(", "requireMe", ",", "process", ".", "cwd", "(", ")", ")", "||", "_requireFile", "(", "requireMe", ",", "(", "void", "0", ")", ")", ";", "if", "(", "!", "exists", "(", "requireResult", ")", ")", "{", "var", "directories", "=", "'directories:('", ";", "directories", "+=", "exists", "(", "currentDirectory", ")", "?", "currentDirectory", "+", "', '", ":", "''", ";", "directories", "+=", "exists", "(", "defaultDirectory", ")", "?", "defaultDirectory", "+", "', '", ":", "''", ";", "directories", "+=", "__dirname", "+", "')'", ";", "throw", "new", "Error", "(", "'dihelper incapable of finding specified file for require filename:'", "+", "requireMe", "+", "', '", "+", "directories", ")", ";", "}", "if", "(", "typeof", "provides", "===", "'undefined'", "&&", "!", "exists", "(", "requireResult", ".", "$provide", ")", ")", "{", "provides", "=", "requireMe", ";", "}", "return", "next", "(", "requireResult", ",", "provides", ",", "injects", ")", ";", "}" ]
internal helper for the exposed require helpers to cut down on replication of code. @private @param {string} requireMe is string passed to require() @param {string|object} [provides] - is either an array or string of things this object provides @param {string|string[]|object|objects[]} [injects] - is either a single string or array of strings of module names to be injected @param {string} [currentDirectory] - directory to attempt first require from @param {function} next function (wrap or override) to call with the result of the require @returns {*}
[ "internal", "helper", "for", "the", "exposed", "require", "helpers", "to", "cut", "down", "on", "replication", "of", "code", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L480-L508
train
RackHD/on-core
lib/di.js
requireWrapper
function requireWrapper(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, simpleWrapper); }
javascript
function requireWrapper(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, simpleWrapper); }
[ "function", "requireWrapper", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ")", "{", "return", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ",", "simpleWrapper", ")", ";", "}" ]
this one does the require for you and returns an object that is annotated @param requireMe is string passed to require() @param [provides] - is either an array or string of things this object provides @param [injects] - is either a single string or array of strings of module names to be injected @param [directory] - to attempt first require from @returns {*}
[ "this", "one", "does", "the", "require", "for", "you", "and", "returns", "an", "object", "that", "is", "annotated" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L518-L520
train
RackHD/on-core
lib/di.js
requireGlob
function requireGlob(pattern) { return _.map(glob.sync(pattern), function (file) { var required = require(file); resolveProvide(required); resolveInjects(required); return required; }); }
javascript
function requireGlob(pattern) { return _.map(glob.sync(pattern), function (file) { var required = require(file); resolveProvide(required); resolveInjects(required); return required; }); }
[ "function", "requireGlob", "(", "pattern", ")", "{", "return", "_", ".", "map", "(", "glob", ".", "sync", "(", "pattern", ")", ",", "function", "(", "file", ")", "{", "var", "required", "=", "require", "(", "file", ")", ";", "resolveProvide", "(", "required", ")", ";", "resolveInjects", "(", "required", ")", ";", "return", "required", ";", "}", ")", ";", "}" ]
requireGlob requires all files matching the glob pattern and provides a list of injectables based on that pattern. @param {String} pattern A glob pattern to search for files to require. @return {Array.<Object>} A list of require'd objects to provide to the injector.
[ "requireGlob", "requires", "all", "files", "matching", "the", "glob", "pattern", "and", "provides", "a", "list", "of", "injectables", "based", "on", "that", "pattern", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L528-L537
train
RackHD/on-core
lib/di.js
injectableFromFile
function injectableFromFile(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, injectableWrapper); }
javascript
function injectableFromFile(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, injectableWrapper); }
[ "function", "injectableFromFile", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ")", "{", "return", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ",", "injectableWrapper", ")", ";", "}" ]
expecting an injeciton aware function and the function is called with the injectables on get. @param requireMe is string passed to require() @param [provides] - is either an array or string of things this object provides @param [injects] - is either a single string or array of strings of module names to be injected @param [directory] - to attempt first require from @returns {*}
[ "expecting", "an", "injeciton", "aware", "function", "and", "the", "function", "is", "called", "with", "the", "injectables", "on", "get", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L560-L562
train
RackHD/on-core
lib/di.js
requireOverrideInjection
function requireOverrideInjection(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, overrideInjection); }
javascript
function requireOverrideInjection(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, overrideInjection); }
[ "function", "requireOverrideInjection", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ")", "{", "return", "_require", "(", "requireMe", ",", "provides", ",", "injects", ",", "directory", ",", "overrideInjection", ")", ";", "}" ]
overides the given require with the injectables provided @param requireMe is string passed to require() @param [provides] - is either an array or string of things this object provides @param [injects] - is either a single string or array of strings of module names to be injected @param [directory] - to attempt first require from @returns {*}
[ "overides", "the", "given", "require", "with", "the", "injectables", "provided" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/di.js#L572-L574
train
bigpipe/env-variable
index.js
env
function env(environment) { environment = environment || {}; if ('object' === typeof process && 'object' === typeof process.env) { env.merge(environment, process.env); } if ('undefined' !== typeof window) { if ('string' === window.name && window.name.length) { env.merge(environment, env.parse(window.name)); } if (window.localStorage) { try { env.merge(environment, env.parse(window.localStorage.env || window.localStorage.debug)); } catch (e) {} } if ( 'object' === typeof window.location && 'string' === typeof window.location.hash && window.location.hash.length ) { env.merge(environment, env.parse(window.location.hash.charAt(0) === '#' ? window.location.hash.slice(1) : window.location.hash )); } } // // Also add lower case variants to the object for easy access. // var key, lower; for (key in environment) { lower = key.toLowerCase(); if (!(lower in environment)) { environment[lower] = environment[key]; } } return environment; }
javascript
function env(environment) { environment = environment || {}; if ('object' === typeof process && 'object' === typeof process.env) { env.merge(environment, process.env); } if ('undefined' !== typeof window) { if ('string' === window.name && window.name.length) { env.merge(environment, env.parse(window.name)); } if (window.localStorage) { try { env.merge(environment, env.parse(window.localStorage.env || window.localStorage.debug)); } catch (e) {} } if ( 'object' === typeof window.location && 'string' === typeof window.location.hash && window.location.hash.length ) { env.merge(environment, env.parse(window.location.hash.charAt(0) === '#' ? window.location.hash.slice(1) : window.location.hash )); } } // // Also add lower case variants to the object for easy access. // var key, lower; for (key in environment) { lower = key.toLowerCase(); if (!(lower in environment)) { environment[lower] = environment[key]; } } return environment; }
[ "function", "env", "(", "environment", ")", "{", "environment", "=", "environment", "||", "{", "}", ";", "if", "(", "'object'", "===", "typeof", "process", "&&", "'object'", "===", "typeof", "process", ".", "env", ")", "{", "env", ".", "merge", "(", "environment", ",", "process", ".", "env", ")", ";", "}", "if", "(", "'undefined'", "!==", "typeof", "window", ")", "{", "if", "(", "'string'", "===", "window", ".", "name", "&&", "window", ".", "name", ".", "length", ")", "{", "env", ".", "merge", "(", "environment", ",", "env", ".", "parse", "(", "window", ".", "name", ")", ")", ";", "}", "if", "(", "window", ".", "localStorage", ")", "{", "try", "{", "env", ".", "merge", "(", "environment", ",", "env", ".", "parse", "(", "window", ".", "localStorage", ".", "env", "||", "window", ".", "localStorage", ".", "debug", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "if", "(", "'object'", "===", "typeof", "window", ".", "location", "&&", "'string'", "===", "typeof", "window", ".", "location", ".", "hash", "&&", "window", ".", "location", ".", "hash", ".", "length", ")", "{", "env", ".", "merge", "(", "environment", ",", "env", ".", "parse", "(", "window", ".", "location", ".", "hash", ".", "charAt", "(", "0", ")", "===", "'#'", "?", "window", ".", "location", ".", "hash", ".", "slice", "(", "1", ")", ":", "window", ".", "location", ".", "hash", ")", ")", ";", "}", "}", "var", "key", ",", "lower", ";", "for", "(", "key", "in", "environment", ")", "{", "lower", "=", "key", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "(", "lower", "in", "environment", ")", ")", "{", "environment", "[", "lower", "]", "=", "environment", "[", "key", "]", ";", "}", "}", "return", "environment", ";", "}" ]
Gather environment variables from various locations. @param {Object} environment The default environment variables. @returns {Object} environment. @api public
[ "Gather", "environment", "variables", "from", "various", "locations", "." ]
f663c23ac41beff094378738843584c5754cd6cf
https://github.com/bigpipe/env-variable/blob/f663c23ac41beff094378738843584c5754cd6cf/index.js#L12-L54
train
g13013/broccoli-compass
index.js
moveToDest
function moveToDest(srcDir, destDir) { if (!this.options.cleanOutput) { return srcDir; } var content, cssDir, src; var copiedCache = this.copiedCache || {}; var copied = {}; var options = this.options; var tree = this.walkDir(srcDir, {cache: this.cache}); var cache = tree.paths; var generated = tree.changed; var linkedFiles = []; for (var i = 0; i < generated.length; i += 1) { file = generated[i]; if (cache[file].isDirectory || copiedCache[file] === cache[file].statsHash) { continue; } src = srcDir + '/' + file; if (file.substr(-4) === '.css') { content = fs.readFileSync(src); cssDir = path.dirname(file); while ((linkedFile = urlRe.exec(content))) { linkedFile = (linkedFile[1][0] === '/') ? linkedFile[1].substr(1) : path.normalize(cssDir + '/' + linkedFile[1]); linkedFiles.push(linkedFile); } } mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(src, destDir + '/' + file); copied[file] = cache[file].statsHash; } for (i = 0; i < linkedFiles.length; i += 1) { file = linkedFiles[i]; if (file in copied) { continue; } if (!cache[file] || copiedCache[file] !== cache[file].statsHash) { copied[file] = cache[file] && cache[file].statsHash; mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(srcDir + '/' + file, destDir + '/' + file); } } this.copiedCache = copied; return destDir; }
javascript
function moveToDest(srcDir, destDir) { if (!this.options.cleanOutput) { return srcDir; } var content, cssDir, src; var copiedCache = this.copiedCache || {}; var copied = {}; var options = this.options; var tree = this.walkDir(srcDir, {cache: this.cache}); var cache = tree.paths; var generated = tree.changed; var linkedFiles = []; for (var i = 0; i < generated.length; i += 1) { file = generated[i]; if (cache[file].isDirectory || copiedCache[file] === cache[file].statsHash) { continue; } src = srcDir + '/' + file; if (file.substr(-4) === '.css') { content = fs.readFileSync(src); cssDir = path.dirname(file); while ((linkedFile = urlRe.exec(content))) { linkedFile = (linkedFile[1][0] === '/') ? linkedFile[1].substr(1) : path.normalize(cssDir + '/' + linkedFile[1]); linkedFiles.push(linkedFile); } } mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(src, destDir + '/' + file); copied[file] = cache[file].statsHash; } for (i = 0; i < linkedFiles.length; i += 1) { file = linkedFiles[i]; if (file in copied) { continue; } if (!cache[file] || copiedCache[file] !== cache[file].statsHash) { copied[file] = cache[file] && cache[file].statsHash; mkdirp(destDir + '/' + path.dirname(file)); symlinkOrCopy(srcDir + '/' + file, destDir + '/' + file); } } this.copiedCache = copied; return destDir; }
[ "function", "moveToDest", "(", "srcDir", ",", "destDir", ")", "{", "if", "(", "!", "this", ".", "options", ".", "cleanOutput", ")", "{", "return", "srcDir", ";", "}", "var", "content", ",", "cssDir", ",", "src", ";", "var", "copiedCache", "=", "this", ".", "copiedCache", "||", "{", "}", ";", "var", "copied", "=", "{", "}", ";", "var", "options", "=", "this", ".", "options", ";", "var", "tree", "=", "this", ".", "walkDir", "(", "srcDir", ",", "{", "cache", ":", "this", ".", "cache", "}", ")", ";", "var", "cache", "=", "tree", ".", "paths", ";", "var", "generated", "=", "tree", ".", "changed", ";", "var", "linkedFiles", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "generated", ".", "length", ";", "i", "+=", "1", ")", "{", "file", "=", "generated", "[", "i", "]", ";", "if", "(", "cache", "[", "file", "]", ".", "isDirectory", "||", "copiedCache", "[", "file", "]", "===", "cache", "[", "file", "]", ".", "statsHash", ")", "{", "continue", ";", "}", "src", "=", "srcDir", "+", "'/'", "+", "file", ";", "if", "(", "file", ".", "substr", "(", "-", "4", ")", "===", "'.css'", ")", "{", "content", "=", "fs", ".", "readFileSync", "(", "src", ")", ";", "cssDir", "=", "path", ".", "dirname", "(", "file", ")", ";", "while", "(", "(", "linkedFile", "=", "urlRe", ".", "exec", "(", "content", ")", ")", ")", "{", "linkedFile", "=", "(", "linkedFile", "[", "1", "]", "[", "0", "]", "===", "'/'", ")", "?", "linkedFile", "[", "1", "]", ".", "substr", "(", "1", ")", ":", "path", ".", "normalize", "(", "cssDir", "+", "'/'", "+", "linkedFile", "[", "1", "]", ")", ";", "linkedFiles", ".", "push", "(", "linkedFile", ")", ";", "}", "}", "mkdirp", "(", "destDir", "+", "'/'", "+", "path", ".", "dirname", "(", "file", ")", ")", ";", "symlinkOrCopy", "(", "src", ",", "destDir", "+", "'/'", "+", "file", ")", ";", "copied", "[", "file", "]", "=", "cache", "[", "file", "]", ".", "statsHash", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "linkedFiles", ".", "length", ";", "i", "+=", "1", ")", "{", "file", "=", "linkedFiles", "[", "i", "]", ";", "if", "(", "file", "in", "copied", ")", "{", "continue", ";", "}", "if", "(", "!", "cache", "[", "file", "]", "||", "copiedCache", "[", "file", "]", "!==", "cache", "[", "file", "]", ".", "statsHash", ")", "{", "copied", "[", "file", "]", "=", "cache", "[", "file", "]", "&&", "cache", "[", "file", "]", ".", "statsHash", ";", "mkdirp", "(", "destDir", "+", "'/'", "+", "path", ".", "dirname", "(", "file", ")", ")", ";", "symlinkOrCopy", "(", "srcDir", "+", "'/'", "+", "file", ",", "destDir", "+", "'/'", "+", "file", ")", ";", "}", "}", "this", ".", "copiedCache", "=", "copied", ";", "return", "destDir", ";", "}" ]
Walks the tree and looks for css files under css directory, if `cleanOutput` is TRUE, css content is read to extract images and fonts paths to add them to the queue. Note that this function simply return srcDir if `cleanOutput` is false. @param {String} srcDir Source directory @param {String} destDir Destination
[ "Walks", "the", "tree", "and", "looks", "for", "css", "files", "under", "css", "directory", "if", "cleanOutput", "is", "TRUE", "css", "content", "is", "read", "to", "extract", "images", "and", "fonts", "paths", "to", "add", "them", "to", "the", "queue", ".", "Note", "that", "this", "function", "simply", "return", "srcDir", "if", "cleanOutput", "is", "false", "." ]
d915daa711491f13d6129cdd41c9fce2dbaf2ade
https://github.com/g13013/broccoli-compass/blob/d915daa711491f13d6129cdd41c9fce2dbaf2ade/index.js#L57-L99
train
g13013/broccoli-compass
index.js
CompassCompiler
function CompassCompiler(inputTree, files, options) { options = arguments.length > 2 ? (options || {}) : (files || {}); if (arguments.length > 2) { console.log('[broccoli-compass] DEPRECATION: passing files to broccoli-compass constructor as second parameter is deprecated, ' + 'use options.files instead'); options.files = files; } if (!(this instanceof CompassCompiler)) { return new CompassCompiler(inputTree, options); } if (options.exclude) { console.log('[broccoli-compass] DEPRECATION: The exclude option has been deprecated in favour of the `cleanOutput` option'); } this.options = merge(true, this.defaultOptions); merge(this.options, options); options = this.options; options.files = (options.files instanceof Array) ? options.files : []; this.generateCmdLine(); this.inputTree = inputTree; }
javascript
function CompassCompiler(inputTree, files, options) { options = arguments.length > 2 ? (options || {}) : (files || {}); if (arguments.length > 2) { console.log('[broccoli-compass] DEPRECATION: passing files to broccoli-compass constructor as second parameter is deprecated, ' + 'use options.files instead'); options.files = files; } if (!(this instanceof CompassCompiler)) { return new CompassCompiler(inputTree, options); } if (options.exclude) { console.log('[broccoli-compass] DEPRECATION: The exclude option has been deprecated in favour of the `cleanOutput` option'); } this.options = merge(true, this.defaultOptions); merge(this.options, options); options = this.options; options.files = (options.files instanceof Array) ? options.files : []; this.generateCmdLine(); this.inputTree = inputTree; }
[ "function", "CompassCompiler", "(", "inputTree", ",", "files", ",", "options", ")", "{", "options", "=", "arguments", ".", "length", ">", "2", "?", "(", "options", "||", "{", "}", ")", ":", "(", "files", "||", "{", "}", ")", ";", "if", "(", "arguments", ".", "length", ">", "2", ")", "{", "console", ".", "log", "(", "'[broccoli-compass] DEPRECATION: passing files to broccoli-compass constructor as second parameter is deprecated, '", "+", "'use options.files instead'", ")", ";", "options", ".", "files", "=", "files", ";", "}", "if", "(", "!", "(", "this", "instanceof", "CompassCompiler", ")", ")", "{", "return", "new", "CompassCompiler", "(", "inputTree", ",", "options", ")", ";", "}", "if", "(", "options", ".", "exclude", ")", "{", "console", ".", "log", "(", "'[broccoli-compass] DEPRECATION: The exclude option has been deprecated in favour of the `cleanOutput` option'", ")", ";", "}", "this", ".", "options", "=", "merge", "(", "true", ",", "this", ".", "defaultOptions", ")", ";", "merge", "(", "this", ".", "options", ",", "options", ")", ";", "options", "=", "this", ".", "options", ";", "options", ".", "files", "=", "(", "options", ".", "files", "instanceof", "Array", ")", "?", "options", ".", "files", ":", "[", "]", ";", "this", ".", "generateCmdLine", "(", ")", ";", "this", ".", "inputTree", "=", "inputTree", ";", "}" ]
broccoli-compass Constructor. @param inputTree Any Broccoli tree. @param files [Optional] An array of sass files to compile. @param options The compass options. @returns {CompassCompiler}
[ "broccoli", "-", "compass", "Constructor", "." ]
d915daa711491f13d6129cdd41c9fce2dbaf2ade
https://github.com/g13013/broccoli-compass/blob/d915daa711491f13d6129cdd41c9fce2dbaf2ade/index.js#L145-L167
train
bminer/node-static-asset
lib/cache-strategies/default.js
addToCache
function addToCache(filename, obj) { if(cacheOn) { var x = cache[filename]; if(!x) x = cache[filename] = {}; x.mtime = obj.mtime || x.mtime; x.etag = obj.etag || x.etag; x.size = obj.size || x.size; } }
javascript
function addToCache(filename, obj) { if(cacheOn) { var x = cache[filename]; if(!x) x = cache[filename] = {}; x.mtime = obj.mtime || x.mtime; x.etag = obj.etag || x.etag; x.size = obj.size || x.size; } }
[ "function", "addToCache", "(", "filename", ",", "obj", ")", "{", "if", "(", "cacheOn", ")", "{", "var", "x", "=", "cache", "[", "filename", "]", ";", "if", "(", "!", "x", ")", "x", "=", "cache", "[", "filename", "]", "=", "{", "}", ";", "x", ".", "mtime", "=", "obj", ".", "mtime", "||", "x", ".", "mtime", ";", "x", ".", "etag", "=", "obj", ".", "etag", "||", "x", ".", "etag", ";", "x", ".", "size", "=", "obj", ".", "size", "||", "x", ".", "size", ";", "}", "}" ]
Adds information to the cache
[ "Adds", "information", "to", "the", "cache" ]
cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097
https://github.com/bminer/node-static-asset/blob/cd7bbe1fcbc6d5e2e1738c7f4b9b823471222097/lib/cache-strategies/default.js#L6-L16
train
RackHD/on-core
lib/common/model.js
function () { var self = this; var indexes = self.$indexes || []; return Promise.try (function() { assert.arrayOfObject(indexes, '$indexes should be an array of object'); //validate and assign default arguments before creating indexes //if necessary, convert the indexes format to fit for different database _.forEach(indexes, function(indexItem) { assert.object(indexItem.keys, 'Database index keys should be object'); if (indexItem.options) { assert.object(indexItem.options, 'Database index options should be object'); } else { indexItem.options = {}; } }); return indexes; }) .then(function(indexes) { if (_.isEmpty(indexes)) { return; } switch(self.connection.toString()) { case 'mongo': return Promise.map(indexes, function(indexItem) { return self.createMongoIndexes([indexItem.keys, indexItem.options]); }); default: break; } }); }
javascript
function () { var self = this; var indexes = self.$indexes || []; return Promise.try (function() { assert.arrayOfObject(indexes, '$indexes should be an array of object'); //validate and assign default arguments before creating indexes //if necessary, convert the indexes format to fit for different database _.forEach(indexes, function(indexItem) { assert.object(indexItem.keys, 'Database index keys should be object'); if (indexItem.options) { assert.object(indexItem.options, 'Database index options should be object'); } else { indexItem.options = {}; } }); return indexes; }) .then(function(indexes) { if (_.isEmpty(indexes)) { return; } switch(self.connection.toString()) { case 'mongo': return Promise.map(indexes, function(indexItem) { return self.createMongoIndexes([indexItem.keys, indexItem.options]); }); default: break; } }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "indexes", "=", "self", ".", "$indexes", "||", "[", "]", ";", "return", "Promise", ".", "try", "(", "function", "(", ")", "{", "assert", ".", "arrayOfObject", "(", "indexes", ",", "'$indexes should be an array of object'", ")", ";", "_", ".", "forEach", "(", "indexes", ",", "function", "(", "indexItem", ")", "{", "assert", ".", "object", "(", "indexItem", ".", "keys", ",", "'Database index keys should be object'", ")", ";", "if", "(", "indexItem", ".", "options", ")", "{", "assert", ".", "object", "(", "indexItem", ".", "options", ",", "'Database index options should be object'", ")", ";", "}", "else", "{", "indexItem", ".", "options", "=", "{", "}", ";", "}", "}", ")", ";", "return", "indexes", ";", "}", ")", ".", "then", "(", "function", "(", "indexes", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "indexes", ")", ")", "{", "return", ";", "}", "switch", "(", "self", ".", "connection", ".", "toString", "(", ")", ")", "{", "case", "'mongo'", ":", "return", "Promise", ".", "map", "(", "indexes", ",", "function", "(", "indexItem", ")", "{", "return", "self", ".", "createMongoIndexes", "(", "[", "indexItem", ".", "keys", ",", "indexItem", ".", "options", "]", ")", ";", "}", ")", ";", "default", ":", "break", ";", "}", "}", ")", ";", "}" ]
Create indexes for different database the waterline has bug for index creation and it also doesn't support compound index, this function is to manually create indexes regardless what waterline will do. This function support both single-field and compound index @return {Promise} Resolved if create indexes successfully.
[ "Create", "indexes", "for", "different", "database" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L150-L184
train
RackHD/on-core
lib/common/model.js
function (criteria) { var identity = this.identity; return this.findOne(criteria).then(function (record) { if (!record) { throw new Errors.NotFoundError( 'Could not find %s with criteria %j.'.format( pluralize.singular(identity), criteria ), { criteria: criteria, collection: identity }); } return record; }); }
javascript
function (criteria) { var identity = this.identity; return this.findOne(criteria).then(function (record) { if (!record) { throw new Errors.NotFoundError( 'Could not find %s with criteria %j.'.format( pluralize.singular(identity), criteria ), { criteria: criteria, collection: identity }); } return record; }); }
[ "function", "(", "criteria", ")", "{", "var", "identity", "=", "this", ".", "identity", ";", "return", "this", ".", "findOne", "(", "criteria", ")", ".", "then", "(", "function", "(", "record", ")", "{", "if", "(", "!", "record", ")", "{", "throw", "new", "Errors", ".", "NotFoundError", "(", "'Could not find %s with criteria %j.'", ".", "format", "(", "pluralize", ".", "singular", "(", "identity", ")", ",", "criteria", ")", ",", "{", "criteria", ":", "criteria", ",", "collection", ":", "identity", "}", ")", ";", "}", "return", "record", ";", "}", ")", ";", "}" ]
Find a single document via criteria and resolve it, otherwise reject with a NotFoundError.
[ "Find", "a", "single", "document", "via", "criteria", "and", "resolve", "it", "otherwise", "reject", "with", "a", "NotFoundError", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L586-L603
train
RackHD/on-core
lib/common/model.js
function (criteria, document) { var self = this; return this.needOne(criteria).then(function (target) { return self.update(target.id, document).then(function (documents) { return documents[0]; }); }); }
javascript
function (criteria, document) { var self = this; return this.needOne(criteria).then(function (target) { return self.update(target.id, document).then(function (documents) { return documents[0]; }); }); }
[ "function", "(", "criteria", ",", "document", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "needOne", "(", "criteria", ")", ".", "then", "(", "function", "(", "target", ")", "{", "return", "self", ".", "update", "(", "target", ".", "id", ",", "document", ")", ".", "then", "(", "function", "(", "documents", ")", "{", "return", "documents", "[", "0", "]", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update a single document by criteria and resolve it, otherwise reject with a NotFoundError.
[ "Update", "a", "single", "document", "by", "criteria", "and", "resolve", "it", "otherwise", "reject", "with", "a", "NotFoundError", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L617-L625
train
RackHD/on-core
lib/common/model.js
function (criteria) { var self = this; return this.needOne(criteria).then(function (target) { return self.destroy(target.id).then(function (documents) { return documents[0]; }); }); }
javascript
function (criteria) { var self = this; return this.needOne(criteria).then(function (target) { return self.destroy(target.id).then(function (documents) { return documents[0]; }); }); }
[ "function", "(", "criteria", ")", "{", "var", "self", "=", "this", ";", "return", "this", ".", "needOne", "(", "criteria", ")", ".", "then", "(", "function", "(", "target", ")", "{", "return", "self", ".", "destroy", "(", "target", ".", "id", ")", ".", "then", "(", "function", "(", "documents", ")", "{", "return", "documents", "[", "0", "]", ";", "}", ")", ";", "}", ")", ";", "}" ]
Destroy a single document by criteria and resolve it, otherwies reject with a NotFoundError.
[ "Destroy", "a", "single", "document", "by", "criteria", "and", "resolve", "it", "otherwies", "reject", "with", "a", "NotFoundError", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/model.js#L770-L778
train
RackHD/on-core
lib/common/errors.js
BaseError
function BaseError(message, context) { this.message = message; this.name = this.constructor.name; this.context = context || {}; Error.captureStackTrace(this, BaseError); }
javascript
function BaseError(message, context) { this.message = message; this.name = this.constructor.name; this.context = context || {}; Error.captureStackTrace(this, BaseError); }
[ "function", "BaseError", "(", "message", ",", "context", ")", "{", "this", ".", "message", "=", "message", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "context", "=", "context", "||", "{", "}", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "BaseError", ")", ";", "}" ]
Base error object which should be inherited, not used directly. @constructor @param {string} message Error Message
[ "Base", "error", "object", "which", "should", "be", "inherited", "not", "used", "directly", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/errors.js#L18-L24
train
RackHD/on-core
lib/common/subscription.js
Subscription
function Subscription (queue, options) { assert.object(queue, 'queue'); assert.object(options, 'options'); this.MAX_DISPOSE_RETRIES = 3; this.retryDelay = 1000; this.queue = queue; this.options = options; this._disposed = false; }
javascript
function Subscription (queue, options) { assert.object(queue, 'queue'); assert.object(options, 'options'); this.MAX_DISPOSE_RETRIES = 3; this.retryDelay = 1000; this.queue = queue; this.options = options; this._disposed = false; }
[ "function", "Subscription", "(", "queue", ",", "options", ")", "{", "assert", ".", "object", "(", "queue", ",", "'queue'", ")", ";", "assert", ".", "object", "(", "options", ",", "'options'", ")", ";", "this", ".", "MAX_DISPOSE_RETRIES", "=", "3", ";", "this", ".", "retryDelay", "=", "1000", ";", "this", ".", "queue", "=", "queue", ";", "this", ".", "options", "=", "options", ";", "this", ".", "_disposed", "=", "false", ";", "}" ]
Creates a new subscription to a queue @param queue {string} @constructor
[ "Creates", "a", "new", "subscription", "to", "a", "queue" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/subscription.js#L22-L31
train
choojs/choo-devtools
lib/perf.js
Perf
function Perf (stats, name, filter, rename) { this.stats = stats this.name = name this.filter = filter || function () { return true } this.rename = rename || function (name) { return name } }
javascript
function Perf (stats, name, filter, rename) { this.stats = stats this.name = name this.filter = filter || function () { return true } this.rename = rename || function (name) { return name } }
[ "function", "Perf", "(", "stats", ",", "name", ",", "filter", ",", "rename", ")", "{", "this", ".", "stats", "=", "stats", "this", ".", "name", "=", "name", "this", ".", "filter", "=", "filter", "||", "function", "(", ")", "{", "return", "true", "}", "this", ".", "rename", "=", "rename", "||", "function", "(", "name", ")", "{", "return", "name", "}", "}" ]
Create a new Perf instance by passing it a filter
[ "Create", "a", "new", "Perf", "instance", "by", "passing", "it", "a", "filter" ]
d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9
https://github.com/choojs/choo-devtools/blob/d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9/lib/perf.js#L67-L72
train
choojs/choo-devtools
lib/perf.js
getMedian
function getMedian (args) { if (!args.length) return 0 var numbers = args.slice(0).sort(function (a, b) { return a - b }) var middle = Math.floor(numbers.length / 2) var isEven = numbers.length % 2 === 0 var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle] return Number(res.toFixed(2)) }
javascript
function getMedian (args) { if (!args.length) return 0 var numbers = args.slice(0).sort(function (a, b) { return a - b }) var middle = Math.floor(numbers.length / 2) var isEven = numbers.length % 2 === 0 var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle] return Number(res.toFixed(2)) }
[ "function", "getMedian", "(", "args", ")", "{", "if", "(", "!", "args", ".", "length", ")", "return", "0", "var", "numbers", "=", "args", ".", "slice", "(", "0", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", "}", ")", "var", "middle", "=", "Math", ".", "floor", "(", "numbers", ".", "length", "/", "2", ")", "var", "isEven", "=", "numbers", ".", "length", "%", "2", "===", "0", "var", "res", "=", "isEven", "?", "(", "numbers", "[", "middle", "]", "+", "numbers", "[", "middle", "-", "1", "]", ")", "/", "2", ":", "numbers", "[", "middle", "]", "return", "Number", "(", "res", ".", "toFixed", "(", "2", ")", ")", "}" ]
Get the median from an array of numbers.
[ "Get", "the", "median", "from", "an", "array", "of", "numbers", "." ]
d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9
https://github.com/choojs/choo-devtools/blob/d23bcacbf5d7cc05dc121b9580d33b28a2b2d0f9/lib/perf.js#L129-L136
train
RackHD/on-core
lib/common/message.js
Message
function Message (data, headers, deliveryInfo) { assert.object(data); assert.object(headers); assert.object(deliveryInfo); this.data = Message.factory(data, deliveryInfo.type); this.headers = headers; this.deliveryInfo = deliveryInfo; }
javascript
function Message (data, headers, deliveryInfo) { assert.object(data); assert.object(headers); assert.object(deliveryInfo); this.data = Message.factory(data, deliveryInfo.type); this.headers = headers; this.deliveryInfo = deliveryInfo; }
[ "function", "Message", "(", "data", ",", "headers", ",", "deliveryInfo", ")", "{", "assert", ".", "object", "(", "data", ")", ";", "assert", ".", "object", "(", "headers", ")", ";", "assert", ".", "object", "(", "deliveryInfo", ")", ";", "this", ".", "data", "=", "Message", ".", "factory", "(", "data", ",", "deliveryInfo", ".", "type", ")", ";", "this", ".", "headers", "=", "headers", ";", "this", ".", "deliveryInfo", "=", "deliveryInfo", ";", "}" ]
Constructor for a message @param {*} messenger @param {Object} data @param {*} [options] @constructor
[ "Constructor", "for", "a", "message" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/message.js#L24-L32
train
RackHD/on-core
lib/common/profile.js
profileServiceFactory
function profileServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(ProfileService, DbRenderable); /** * ProfileService is a singleton object which provides key/value store * access to profile files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function ProfileService () { DbRenderable.call(this, { directory: Constants.Profiles.Directory, collectionName: 'profiles' }); } ProfileService.prototype.get = function (name, raw, scope ) { return ProfileService.super_.prototype.get.call(this, name, scope) .then(function(profile) { if (profile && raw) { return profile.contents; } else { return profile; } }); }; return new ProfileService(); }
javascript
function profileServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(ProfileService, DbRenderable); /** * ProfileService is a singleton object which provides key/value store * access to profile files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function ProfileService () { DbRenderable.call(this, { directory: Constants.Profiles.Directory, collectionName: 'profiles' }); } ProfileService.prototype.get = function (name, raw, scope ) { return ProfileService.super_.prototype.get.call(this, name, scope) .then(function(profile) { if (profile && raw) { return profile.contents; } else { return profile; } }); }; return new ProfileService(); }
[ "function", "profileServiceFactory", "(", "Constants", ",", "Promise", ",", "_", ",", "DbRenderable", ",", "Util", ")", "{", "Util", ".", "inherits", "(", "ProfileService", ",", "DbRenderable", ")", ";", "function", "ProfileService", "(", ")", "{", "DbRenderable", ".", "call", "(", "this", ",", "{", "directory", ":", "Constants", ".", "Profiles", ".", "Directory", ",", "collectionName", ":", "'profiles'", "}", ")", ";", "}", "ProfileService", ".", "prototype", ".", "get", "=", "function", "(", "name", ",", "raw", ",", "scope", ")", "{", "return", "ProfileService", ".", "super_", ".", "prototype", ".", "get", ".", "call", "(", "this", ",", "name", ",", "scope", ")", ".", "then", "(", "function", "(", "profile", ")", "{", "if", "(", "profile", "&&", "raw", ")", "{", "return", "profile", ".", "contents", ";", "}", "else", "{", "return", "profile", ";", "}", "}", ")", ";", "}", ";", "return", "new", "ProfileService", "(", ")", ";", "}" ]
profileServiceFactory provides the profile-service singleton object. @private @param {FileLoader} FileLoader A FileLoader class for extension. @param {configuration} configuration An instance of the configuration configuration object. @return {ProfileService} An instance of the ProfileService.
[ "profileServiceFactory", "provides", "the", "profile", "-", "service", "singleton", "object", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/profile.js#L23-L57
train
RackHD/on-core
lib/common/logger.js
loggerFactory
function loggerFactory( events, Constants, assert, _, util, stack, nconf ) { var levels = _.keys(Constants.Logging.Levels); function getCaller (depth) { var current = stack.get()[depth]; var file = current.getFileName().replace( Constants.WorkingDirectory, '' ) + ':' + current.getLineNumber(); return file.replace(/^node_modules/, ''); } function Logger (module) { var provides = util.provides(module); if (provides !== undefined) { this.module = provides; } else { if (_.isFunction(module)) { this.module = module.name; } else { this.module = module || 'No Module'; } } } Logger.prototype.log = function (level, message, context) { assert.isIn(level, levels); assert.string(message, 'message'); // Exit if the log level of this message is less than the minimum log level. var minLogLevel = nconf.get('minLogLevel'); if ((minLogLevel === undefined) || (typeof minLogLevel !== 'number')) { minLogLevel = 0; } if (Constants.Logging.Levels[level] < minLogLevel) { return; } events.log({ name: Constants.Name, host: Constants.Host, module: this.module, level: level, message: message, context: context, timestamp: new Date().toISOString(), caller: getCaller(3), subject: 'Server' }); }; _.forEach(levels, function(level) { Logger.prototype[level] = function (message, context) { this.log(level, message, context); }; }); Logger.prototype.deprecate = function (message, frames) { console.error([ 'DEPRECATION:', this.module, '-', message, getCaller(frames || 2) ].join(' ')); }; Logger.initialize = function (module) { return new Logger(module); }; return Logger; }
javascript
function loggerFactory( events, Constants, assert, _, util, stack, nconf ) { var levels = _.keys(Constants.Logging.Levels); function getCaller (depth) { var current = stack.get()[depth]; var file = current.getFileName().replace( Constants.WorkingDirectory, '' ) + ':' + current.getLineNumber(); return file.replace(/^node_modules/, ''); } function Logger (module) { var provides = util.provides(module); if (provides !== undefined) { this.module = provides; } else { if (_.isFunction(module)) { this.module = module.name; } else { this.module = module || 'No Module'; } } } Logger.prototype.log = function (level, message, context) { assert.isIn(level, levels); assert.string(message, 'message'); // Exit if the log level of this message is less than the minimum log level. var minLogLevel = nconf.get('minLogLevel'); if ((minLogLevel === undefined) || (typeof minLogLevel !== 'number')) { minLogLevel = 0; } if (Constants.Logging.Levels[level] < minLogLevel) { return; } events.log({ name: Constants.Name, host: Constants.Host, module: this.module, level: level, message: message, context: context, timestamp: new Date().toISOString(), caller: getCaller(3), subject: 'Server' }); }; _.forEach(levels, function(level) { Logger.prototype[level] = function (message, context) { this.log(level, message, context); }; }); Logger.prototype.deprecate = function (message, frames) { console.error([ 'DEPRECATION:', this.module, '-', message, getCaller(frames || 2) ].join(' ')); }; Logger.initialize = function (module) { return new Logger(module); }; return Logger; }
[ "function", "loggerFactory", "(", "events", ",", "Constants", ",", "assert", ",", "_", ",", "util", ",", "stack", ",", "nconf", ")", "{", "var", "levels", "=", "_", ".", "keys", "(", "Constants", ".", "Logging", ".", "Levels", ")", ";", "function", "getCaller", "(", "depth", ")", "{", "var", "current", "=", "stack", ".", "get", "(", ")", "[", "depth", "]", ";", "var", "file", "=", "current", ".", "getFileName", "(", ")", ".", "replace", "(", "Constants", ".", "WorkingDirectory", ",", "''", ")", "+", "':'", "+", "current", ".", "getLineNumber", "(", ")", ";", "return", "file", ".", "replace", "(", "/", "^node_modules", "/", ",", "''", ")", ";", "}", "function", "Logger", "(", "module", ")", "{", "var", "provides", "=", "util", ".", "provides", "(", "module", ")", ";", "if", "(", "provides", "!==", "undefined", ")", "{", "this", ".", "module", "=", "provides", ";", "}", "else", "{", "if", "(", "_", ".", "isFunction", "(", "module", ")", ")", "{", "this", ".", "module", "=", "module", ".", "name", ";", "}", "else", "{", "this", ".", "module", "=", "module", "||", "'No Module'", ";", "}", "}", "}", "Logger", ".", "prototype", ".", "log", "=", "function", "(", "level", ",", "message", ",", "context", ")", "{", "assert", ".", "isIn", "(", "level", ",", "levels", ")", ";", "assert", ".", "string", "(", "message", ",", "'message'", ")", ";", "var", "minLogLevel", "=", "nconf", ".", "get", "(", "'minLogLevel'", ")", ";", "if", "(", "(", "minLogLevel", "===", "undefined", ")", "||", "(", "typeof", "minLogLevel", "!==", "'number'", ")", ")", "{", "minLogLevel", "=", "0", ";", "}", "if", "(", "Constants", ".", "Logging", ".", "Levels", "[", "level", "]", "<", "minLogLevel", ")", "{", "return", ";", "}", "events", ".", "log", "(", "{", "name", ":", "Constants", ".", "Name", ",", "host", ":", "Constants", ".", "Host", ",", "module", ":", "this", ".", "module", ",", "level", ":", "level", ",", "message", ":", "message", ",", "context", ":", "context", ",", "timestamp", ":", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "caller", ":", "getCaller", "(", "3", ")", ",", "subject", ":", "'Server'", "}", ")", ";", "}", ";", "_", ".", "forEach", "(", "levels", ",", "function", "(", "level", ")", "{", "Logger", ".", "prototype", "[", "level", "]", "=", "function", "(", "message", ",", "context", ")", "{", "this", ".", "log", "(", "level", ",", "message", ",", "context", ")", ";", "}", ";", "}", ")", ";", "Logger", ".", "prototype", ".", "deprecate", "=", "function", "(", "message", ",", "frames", ")", "{", "console", ".", "error", "(", "[", "'DEPRECATION:'", ",", "this", ".", "module", ",", "'-'", ",", "message", ",", "getCaller", "(", "frames", "||", "2", ")", "]", ".", "join", "(", "' '", ")", ")", ";", "}", ";", "Logger", ".", "initialize", "=", "function", "(", "module", ")", "{", "return", "new", "Logger", "(", "module", ")", ";", "}", ";", "return", "Logger", ";", "}" ]
loggerFactory returns a Logger instance. @private
[ "loggerFactory", "returns", "a", "Logger", "instance", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/logger.js#L22-L105
train
RackHD/on-core
lib/common/graph-progress.js
GraphProgress
function GraphProgress(graph, graphDescription) { assert.object(graph, 'graph'); assert.string(graphDescription, 'graphDescription'); this.graph = graph; this.data = { graphId: graph.instanceId, nodeId: graph.node, graphName: graph.name || 'Not available', status: graph._status, progress: { description: graphDescription || 'Not available', } }; this._calculateGraphProgress(); }
javascript
function GraphProgress(graph, graphDescription) { assert.object(graph, 'graph'); assert.string(graphDescription, 'graphDescription'); this.graph = graph; this.data = { graphId: graph.instanceId, nodeId: graph.node, graphName: graph.name || 'Not available', status: graph._status, progress: { description: graphDescription || 'Not available', } }; this._calculateGraphProgress(); }
[ "function", "GraphProgress", "(", "graph", ",", "graphDescription", ")", "{", "assert", ".", "object", "(", "graph", ",", "'graph'", ")", ";", "assert", ".", "string", "(", "graphDescription", ",", "'graphDescription'", ")", ";", "this", ".", "graph", "=", "graph", ";", "this", ".", "data", "=", "{", "graphId", ":", "graph", ".", "instanceId", ",", "nodeId", ":", "graph", ".", "node", ",", "graphName", ":", "graph", ".", "name", "||", "'Not available'", ",", "status", ":", "graph", ".", "_status", ",", "progress", ":", "{", "description", ":", "graphDescription", "||", "'Not available'", ",", "}", "}", ";", "this", ".", "_calculateGraphProgress", "(", ")", ";", "}" ]
Creates a new GraphProgress and calculate the graph progress @param graph {Object} @param graphDescription {String} @constructor
[ "Creates", "a", "new", "GraphProgress", "and", "calculate", "the", "graph", "progress" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/graph-progress.js#L24-L39
train
RackHD/on-core
lib/common/http-tool.js
HttpTool
function HttpTool(){ this.settings = {}; this.urlObject = {}; this.dataToWrite = ''; // ********** Helper Functions/Members ********** var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH']; /** * Make sure that settings has at least property of url and method. * @return {boolean} whether settings is valid. */ this.isSettingValid = function(settings){ if (_.isEmpty(settings)) { return false; } if ( ! (settings.hasOwnProperty('url') && settings.hasOwnProperty('method'))) { return false; } if (_.isEmpty(settings.url) || _.isEmpty(settings.method)) { return false; } if (_.indexOf(validMethods, settings.method) === -1) { return false; } return true; }; /** * Parse and convert setting into a urlObject that suitable for * http/https module in NodeJs. * @return {object} - the object that suitable for Node http/https module. */ this.setupUrlOptions = function(settings) { var urlTool = require('url'); var urlObject = {}; // Parse the string into url options if (typeof (settings.url) === 'string') { urlObject = urlTool.parse(settings.url); } else { urlObject = settings.url; } // set the REST options urlObject.method = settings.method; // set up the REST headers if (! _.isEmpty(settings.headers)){ urlObject.headers = settings.headers; } else { urlObject.headers = {}; } urlObject.headers['Content-Length'] = 0; if (settings.hasOwnProperty('data')){ switch (typeof settings.data) { case 'object': this.dataToWrite = JSON.stringify(settings.data); urlObject.headers['Content-Type'] = 'application/json'; break; case 'string': this.dataToWrite = settings.data; break; default: throw new TypeError("Data field can only be object or string," + " but got " + (typeof settings.data)); } urlObject.headers['Content-Length'] = Buffer.byteLength(this.dataToWrite); } if (! _.isEmpty(settings.credential)){ if (!_.isEmpty(settings.credential.password) && _.isEmpty(settings.credential.username)) { throw new Error('Please provide username and password '+ 'for basic authentication.'); } else { urlObject.auth = settings.credential.username +':'+ settings.credential.password; } } // set the protolcol paramter if (urlObject.protocol.substr(-1) !== ':') { urlObject.protocol = urlObject.protocol + ':'; } urlObject.rejectUnauthorized = settings.verifySSL || false; urlObject.recvTimeoutMs = settings.recvTimeoutMs; return urlObject; }; }
javascript
function HttpTool(){ this.settings = {}; this.urlObject = {}; this.dataToWrite = ''; // ********** Helper Functions/Members ********** var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH']; /** * Make sure that settings has at least property of url and method. * @return {boolean} whether settings is valid. */ this.isSettingValid = function(settings){ if (_.isEmpty(settings)) { return false; } if ( ! (settings.hasOwnProperty('url') && settings.hasOwnProperty('method'))) { return false; } if (_.isEmpty(settings.url) || _.isEmpty(settings.method)) { return false; } if (_.indexOf(validMethods, settings.method) === -1) { return false; } return true; }; /** * Parse and convert setting into a urlObject that suitable for * http/https module in NodeJs. * @return {object} - the object that suitable for Node http/https module. */ this.setupUrlOptions = function(settings) { var urlTool = require('url'); var urlObject = {}; // Parse the string into url options if (typeof (settings.url) === 'string') { urlObject = urlTool.parse(settings.url); } else { urlObject = settings.url; } // set the REST options urlObject.method = settings.method; // set up the REST headers if (! _.isEmpty(settings.headers)){ urlObject.headers = settings.headers; } else { urlObject.headers = {}; } urlObject.headers['Content-Length'] = 0; if (settings.hasOwnProperty('data')){ switch (typeof settings.data) { case 'object': this.dataToWrite = JSON.stringify(settings.data); urlObject.headers['Content-Type'] = 'application/json'; break; case 'string': this.dataToWrite = settings.data; break; default: throw new TypeError("Data field can only be object or string," + " but got " + (typeof settings.data)); } urlObject.headers['Content-Length'] = Buffer.byteLength(this.dataToWrite); } if (! _.isEmpty(settings.credential)){ if (!_.isEmpty(settings.credential.password) && _.isEmpty(settings.credential.username)) { throw new Error('Please provide username and password '+ 'for basic authentication.'); } else { urlObject.auth = settings.credential.username +':'+ settings.credential.password; } } // set the protolcol paramter if (urlObject.protocol.substr(-1) !== ':') { urlObject.protocol = urlObject.protocol + ':'; } urlObject.rejectUnauthorized = settings.verifySSL || false; urlObject.recvTimeoutMs = settings.recvTimeoutMs; return urlObject; }; }
[ "function", "HttpTool", "(", ")", "{", "this", ".", "settings", "=", "{", "}", ";", "this", ".", "urlObject", "=", "{", "}", ";", "this", ".", "dataToWrite", "=", "''", ";", "var", "validMethods", "=", "[", "'GET'", ",", "'PUT'", ",", "'POST'", ",", "'DELETE'", ",", "'PATCH'", "]", ";", "this", ".", "isSettingValid", "=", "function", "(", "settings", ")", "{", "if", "(", "_", ".", "isEmpty", "(", "settings", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "(", "settings", ".", "hasOwnProperty", "(", "'url'", ")", "&&", "settings", ".", "hasOwnProperty", "(", "'method'", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "_", ".", "isEmpty", "(", "settings", ".", "url", ")", "||", "_", ".", "isEmpty", "(", "settings", ".", "method", ")", ")", "{", "return", "false", ";", "}", "if", "(", "_", ".", "indexOf", "(", "validMethods", ",", "settings", ".", "method", ")", "===", "-", "1", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", ";", "this", ".", "setupUrlOptions", "=", "function", "(", "settings", ")", "{", "var", "urlTool", "=", "require", "(", "'url'", ")", ";", "var", "urlObject", "=", "{", "}", ";", "if", "(", "typeof", "(", "settings", ".", "url", ")", "===", "'string'", ")", "{", "urlObject", "=", "urlTool", ".", "parse", "(", "settings", ".", "url", ")", ";", "}", "else", "{", "urlObject", "=", "settings", ".", "url", ";", "}", "urlObject", ".", "method", "=", "settings", ".", "method", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "settings", ".", "headers", ")", ")", "{", "urlObject", ".", "headers", "=", "settings", ".", "headers", ";", "}", "else", "{", "urlObject", ".", "headers", "=", "{", "}", ";", "}", "urlObject", ".", "headers", "[", "'Content-Length'", "]", "=", "0", ";", "if", "(", "settings", ".", "hasOwnProperty", "(", "'data'", ")", ")", "{", "switch", "(", "typeof", "settings", ".", "data", ")", "{", "case", "'object'", ":", "this", ".", "dataToWrite", "=", "JSON", ".", "stringify", "(", "settings", ".", "data", ")", ";", "urlObject", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", ";", "break", ";", "case", "'string'", ":", "this", ".", "dataToWrite", "=", "settings", ".", "data", ";", "break", ";", "default", ":", "throw", "new", "TypeError", "(", "\"Data field can only be object or string,\"", "+", "\" but got \"", "+", "(", "typeof", "settings", ".", "data", ")", ")", ";", "}", "urlObject", ".", "headers", "[", "'Content-Length'", "]", "=", "Buffer", ".", "byteLength", "(", "this", ".", "dataToWrite", ")", ";", "}", "if", "(", "!", "_", ".", "isEmpty", "(", "settings", ".", "credential", ")", ")", "{", "if", "(", "!", "_", ".", "isEmpty", "(", "settings", ".", "credential", ".", "password", ")", "&&", "_", ".", "isEmpty", "(", "settings", ".", "credential", ".", "username", ")", ")", "{", "throw", "new", "Error", "(", "'Please provide username and password '", "+", "'for basic authentication.'", ")", ";", "}", "else", "{", "urlObject", ".", "auth", "=", "settings", ".", "credential", ".", "username", "+", "':'", "+", "settings", ".", "credential", ".", "password", ";", "}", "}", "if", "(", "urlObject", ".", "protocol", ".", "substr", "(", "-", "1", ")", "!==", "':'", ")", "{", "urlObject", ".", "protocol", "=", "urlObject", ".", "protocol", "+", "':'", ";", "}", "urlObject", ".", "rejectUnauthorized", "=", "settings", ".", "verifySSL", "||", "false", ";", "urlObject", ".", "recvTimeoutMs", "=", "settings", ".", "recvTimeoutMs", ";", "return", "urlObject", ";", "}", ";", "}" ]
Tool class that does HTTP methods @constructor
[ "Tool", "class", "that", "does", "HTTP", "methods" ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/http-tool.js#L25-L121
train
RackHD/on-core
lib/common/template.js
templateServiceFactory
function templateServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(TemplateService, DbRenderable); /** * TemplateService is a singleton object which provides key/value store * access to template files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function TemplateService () { DbRenderable.call(this, { directory: Constants.Templates.Directory, collectionName: 'templates' }); } return new TemplateService(); }
javascript
function templateServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(TemplateService, DbRenderable); /** * TemplateService is a singleton object which provides key/value store * access to template files loaded from disk via FileLoader. * @constructor * @extends {FileLoader} */ function TemplateService () { DbRenderable.call(this, { directory: Constants.Templates.Directory, collectionName: 'templates' }); } return new TemplateService(); }
[ "function", "templateServiceFactory", "(", "Constants", ",", "Promise", ",", "_", ",", "DbRenderable", ",", "Util", ")", "{", "Util", ".", "inherits", "(", "TemplateService", ",", "DbRenderable", ")", ";", "function", "TemplateService", "(", ")", "{", "DbRenderable", ".", "call", "(", "this", ",", "{", "directory", ":", "Constants", ".", "Templates", ".", "Directory", ",", "collectionName", ":", "'templates'", "}", ")", ";", "}", "return", "new", "TemplateService", "(", ")", ";", "}" ]
templateServiceFactory provides the template-service singleton object. @private @param {FileLoader} FileLoader A FileLoader class for extension. @param {configuration} configuration An instance of the configuration configuration object. @return {TemplateService} An instance of the TemplateService.
[ "templateServiceFactory", "provides", "the", "template", "-", "service", "singleton", "object", "." ]
bff135fe26183003892e4fdd0baf42c2a02f5f03
https://github.com/RackHD/on-core/blob/bff135fe26183003892e4fdd0baf42c2a02f5f03/lib/common/template.js#L23-L46
train
tapjs/foreground-child
index.js
normalizeFgArgs
function normalizeFgArgs(fgArgs) { var program, args, cb; var processArgsEnd = fgArgs.length; var lastFgArg = fgArgs[fgArgs.length - 1]; if (typeof lastFgArg === "function") { cb = lastFgArg; processArgsEnd -= 1; } else { cb = function(done) { done(); }; } if (Array.isArray(fgArgs[0])) { program = fgArgs[0][0]; args = fgArgs[0].slice(1); } else { program = fgArgs[0]; args = Array.isArray(fgArgs[1]) ? fgArgs[1] : fgArgs.slice(1, processArgsEnd); } return {program: program, args: args, cb: cb}; }
javascript
function normalizeFgArgs(fgArgs) { var program, args, cb; var processArgsEnd = fgArgs.length; var lastFgArg = fgArgs[fgArgs.length - 1]; if (typeof lastFgArg === "function") { cb = lastFgArg; processArgsEnd -= 1; } else { cb = function(done) { done(); }; } if (Array.isArray(fgArgs[0])) { program = fgArgs[0][0]; args = fgArgs[0].slice(1); } else { program = fgArgs[0]; args = Array.isArray(fgArgs[1]) ? fgArgs[1] : fgArgs.slice(1, processArgsEnd); } return {program: program, args: args, cb: cb}; }
[ "function", "normalizeFgArgs", "(", "fgArgs", ")", "{", "var", "program", ",", "args", ",", "cb", ";", "var", "processArgsEnd", "=", "fgArgs", ".", "length", ";", "var", "lastFgArg", "=", "fgArgs", "[", "fgArgs", ".", "length", "-", "1", "]", ";", "if", "(", "typeof", "lastFgArg", "===", "\"function\"", ")", "{", "cb", "=", "lastFgArg", ";", "processArgsEnd", "-=", "1", ";", "}", "else", "{", "cb", "=", "function", "(", "done", ")", "{", "done", "(", ")", ";", "}", ";", "}", "if", "(", "Array", ".", "isArray", "(", "fgArgs", "[", "0", "]", ")", ")", "{", "program", "=", "fgArgs", "[", "0", "]", "[", "0", "]", ";", "args", "=", "fgArgs", "[", "0", "]", ".", "slice", "(", "1", ")", ";", "}", "else", "{", "program", "=", "fgArgs", "[", "0", "]", ";", "args", "=", "Array", ".", "isArray", "(", "fgArgs", "[", "1", "]", ")", "?", "fgArgs", "[", "1", "]", ":", "fgArgs", ".", "slice", "(", "1", ",", "processArgsEnd", ")", ";", "}", "return", "{", "program", ":", "program", ",", "args", ":", "args", ",", "cb", ":", "cb", "}", ";", "}" ]
Normalizes the arguments passed to `foregroundChild`. See the signature of `foregroundChild` for the supported arguments. @param fgArgs Array of arguments passed to `foregroundChild`. @return Normalized arguments @internal
[ "Normalizes", "the", "arguments", "passed", "to", "foregroundChild", "." ]
df07e2426a4072eca9dd15a52aaf3b6c4b117338
https://github.com/tapjs/foreground-child/blob/df07e2426a4072eca9dd15a52aaf3b6c4b117338/index.js#L16-L36
train
turf-junkyard/turf-isolines
conrec.js
Conrec
function Conrec(drawContour) { if (!drawContour) { var c = this; c.contours = {}; /** * drawContour - interface for implementing the user supplied method to * render the countours. * * Draws a line between the start and end coordinates. * * @param startX - start coordinate for X * @param startY - start coordinate for Y * @param endX - end coordinate for X * @param endY - end coordinate for Y * @param contourLevel - Contour level for line. */ this.drawContour = function(startX, startY, endX, endY, contourLevel, k) { var cb = c.contours[k]; if (!cb) { cb = c.contours[k] = new ContourBuilder(contourLevel); } cb.addSegment({x: startX, y: startY}, {x: endX, y: endY}); } this.contourList = function() { var l = []; var a = c.contours; for (var k in a) { var s = a[k].s; var level = a[k].level; while (s) { var h = s.head; var l2 = []; l2.level = level; l2.k = k; while (h && h.p) { l2.push(h.p); h = h.next; } l.push(l2); s = s.next; } } l.sort(function(a, b) { return a.k - b.k }); return l; } } else { this.drawContour = drawContour; } this.h = new Array(5); this.sh = new Array(5); this.xh = new Array(5); this.yh = new Array(5); }
javascript
function Conrec(drawContour) { if (!drawContour) { var c = this; c.contours = {}; /** * drawContour - interface for implementing the user supplied method to * render the countours. * * Draws a line between the start and end coordinates. * * @param startX - start coordinate for X * @param startY - start coordinate for Y * @param endX - end coordinate for X * @param endY - end coordinate for Y * @param contourLevel - Contour level for line. */ this.drawContour = function(startX, startY, endX, endY, contourLevel, k) { var cb = c.contours[k]; if (!cb) { cb = c.contours[k] = new ContourBuilder(contourLevel); } cb.addSegment({x: startX, y: startY}, {x: endX, y: endY}); } this.contourList = function() { var l = []; var a = c.contours; for (var k in a) { var s = a[k].s; var level = a[k].level; while (s) { var h = s.head; var l2 = []; l2.level = level; l2.k = k; while (h && h.p) { l2.push(h.p); h = h.next; } l.push(l2); s = s.next; } } l.sort(function(a, b) { return a.k - b.k }); return l; } } else { this.drawContour = drawContour; } this.h = new Array(5); this.sh = new Array(5); this.xh = new Array(5); this.yh = new Array(5); }
[ "function", "Conrec", "(", "drawContour", ")", "{", "if", "(", "!", "drawContour", ")", "{", "var", "c", "=", "this", ";", "c", ".", "contours", "=", "{", "}", ";", "this", ".", "drawContour", "=", "function", "(", "startX", ",", "startY", ",", "endX", ",", "endY", ",", "contourLevel", ",", "k", ")", "{", "var", "cb", "=", "c", ".", "contours", "[", "k", "]", ";", "if", "(", "!", "cb", ")", "{", "cb", "=", "c", ".", "contours", "[", "k", "]", "=", "new", "ContourBuilder", "(", "contourLevel", ")", ";", "}", "cb", ".", "addSegment", "(", "{", "x", ":", "startX", ",", "y", ":", "startY", "}", ",", "{", "x", ":", "endX", ",", "y", ":", "endY", "}", ")", ";", "}", "this", ".", "contourList", "=", "function", "(", ")", "{", "var", "l", "=", "[", "]", ";", "var", "a", "=", "c", ".", "contours", ";", "for", "(", "var", "k", "in", "a", ")", "{", "var", "s", "=", "a", "[", "k", "]", ".", "s", ";", "var", "level", "=", "a", "[", "k", "]", ".", "level", ";", "while", "(", "s", ")", "{", "var", "h", "=", "s", ".", "head", ";", "var", "l2", "=", "[", "]", ";", "l2", ".", "level", "=", "level", ";", "l2", ".", "k", "=", "k", ";", "while", "(", "h", "&&", "h", ".", "p", ")", "{", "l2", ".", "push", "(", "h", ".", "p", ")", ";", "h", "=", "h", ".", "next", ";", "}", "l", ".", "push", "(", "l2", ")", ";", "s", "=", "s", ".", "next", ";", "}", "}", "l", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "k", "-", "b", ".", "k", "}", ")", ";", "return", "l", ";", "}", "}", "else", "{", "this", ".", "drawContour", "=", "drawContour", ";", "}", "this", ".", "h", "=", "new", "Array", "(", "5", ")", ";", "this", ".", "sh", "=", "new", "Array", "(", "5", ")", ";", "this", ".", "xh", "=", "new", "Array", "(", "5", ")", ";", "this", ".", "yh", "=", "new", "Array", "(", "5", ")", ";", "}" ]
Implements CONREC. @param {function} drawContour function for drawing contour. Defaults to a custom "contour builder", which populates the contours property.
[ "Implements", "CONREC", "." ]
379514fea9bbd458dd4e5beb32d5051796c2026f
https://github.com/turf-junkyard/turf-isolines/blob/379514fea9bbd458dd4e5beb32d5051796c2026f/conrec.js#L254-L306
train
c9/smith.io
server-plugin/plugin.js
failFirstRequest
function failFirstRequest(server) { var listeners = server.listeners("request"), existingListeners = []; for (var i = 0, l = listeners.length; i < l; i++) { existingListeners[i] = listeners[i]; } server.removeAllListeners("request"); server.on("request", function (req, res) { var fireExisting = true; if (/^\/transport\/server\//.test(req.url)) { fireExisting = onTransportRequest(req, res); } if (fireExisting) { for (var i = 0, l = existingListeners.length; i < l; i++) { existingListeners[i].call(server, req, res); } } }); var count = 0; function onTransportRequest(req, res) { count += 1; console.log("REQUEST", req.url, count); if (count === 1) { console.log(" Fail request"); res.end("<An unparsable response>"); return false; } return true; } }
javascript
function failFirstRequest(server) { var listeners = server.listeners("request"), existingListeners = []; for (var i = 0, l = listeners.length; i < l; i++) { existingListeners[i] = listeners[i]; } server.removeAllListeners("request"); server.on("request", function (req, res) { var fireExisting = true; if (/^\/transport\/server\//.test(req.url)) { fireExisting = onTransportRequest(req, res); } if (fireExisting) { for (var i = 0, l = existingListeners.length; i < l; i++) { existingListeners[i].call(server, req, res); } } }); var count = 0; function onTransportRequest(req, res) { count += 1; console.log("REQUEST", req.url, count); if (count === 1) { console.log(" Fail request"); res.end("<An unparsable response>"); return false; } return true; } }
[ "function", "failFirstRequest", "(", "server", ")", "{", "var", "listeners", "=", "server", ".", "listeners", "(", "\"request\"", ")", ",", "existingListeners", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "listeners", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "existingListeners", "[", "i", "]", "=", "listeners", "[", "i", "]", ";", "}", "server", ".", "removeAllListeners", "(", "\"request\"", ")", ";", "server", ".", "on", "(", "\"request\"", ",", "function", "(", "req", ",", "res", ")", "{", "var", "fireExisting", "=", "true", ";", "if", "(", "/", "^\\/transport\\/server\\/", "/", ".", "test", "(", "req", ".", "url", ")", ")", "{", "fireExisting", "=", "onTransportRequest", "(", "req", ",", "res", ")", ";", "}", "if", "(", "fireExisting", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "existingListeners", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "existingListeners", "[", "i", "]", ".", "call", "(", "server", ",", "req", ",", "res", ")", ";", "}", "}", "}", ")", ";", "var", "count", "=", "0", ";", "function", "onTransportRequest", "(", "req", ",", "res", ")", "{", "count", "+=", "1", ";", "console", ".", "log", "(", "\"REQUEST\"", ",", "req", ".", "url", ",", "count", ")", ";", "if", "(", "count", "===", "1", ")", "{", "console", ".", "log", "(", "\" Fail request\"", ")", ";", "res", ".", "end", "(", "\"<An unparsable response>\"", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}", "}" ]
Used to test re-connect when connect request fails.
[ "Used", "to", "test", "re", "-", "connect", "when", "connect", "request", "fails", "." ]
282ed97e043732ef0785318d597172e57931c55c
https://github.com/c9/smith.io/blob/282ed97e043732ef0785318d597172e57931c55c/server-plugin/plugin.js#L213-L243
train
Instrumental/statsd-instrumental-backend
lib/instrumental.js
instrumental_send
function instrumental_send(payload) { var state = "cold"; var tlsOptionsVariation = selectTlsOptionsVariation(); var client = instrumental_connection(host, port, tlsOptionsVariation, function(_client){ state = "connected"; var cleanString = function(value) { return String(value).replace(/\s+/g, "_"); } // Write the authentication header _client.write( "hello version node/statsd-instrumental-backend/" + cleanString(package.version) + " hostname " + cleanString(hostname) + " pid " + cleanString(process.pid) + " runtime " + cleanString("node/" + process.versions.node) + " platform " + cleanString(process.platform + "-" + process.arch) + "\n" + "authenticate " + key + "\n" ); }); // We need to handle the timeout. I think we should only care about read // timeouts. That is we write out data, if we don't hear back in timeout // seconds then the data probably hasn't reached the server. client.setTimeout(timeout, function() { // ZOMG FAILED WRITING WE ARE BAD AT COMPUTER SCIENCE if(state == "connected") { // We're waiting to hear back from the server and it has timed out. It's // unlikely that the server will suddenly wake up and send us our data so // lets disconnect and go shopping. client.end(); } }); // HOW WE HANDLE ERRORS. We should probably reconnect, maybe retry. client.addListener("error", function(exception){ if(debug) { log("Client error:", exception); } instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000); }); // What do we do when instrumental talks to us var totalBuffer = ""; client.on("data", function(buffer) { totalBuffer = totalBuffer + buffer; if(debug) { log("Received:", buffer); } // Authorization success if(totalBuffer == "ok\nok\n") { error = false; if(debug) { log("Sending:", payload.join("\n")); } client.end(payload.join("\n") + "\n", function() { tlsOptionsVariation.lastSuccessAt = new Date(); if (debug) log("payload sent, tlsOptionsVariation: ", tlsOptionsVariation); state = "sent"; }); instrumentalStats.last_flush = Math.round(new Date().getTime() / 1000); // Authorization failure } else if(totalBuffer.length >= "ok\nok\n".length) { // TODO: Actually do something with this error = true; instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000); } }); }
javascript
function instrumental_send(payload) { var state = "cold"; var tlsOptionsVariation = selectTlsOptionsVariation(); var client = instrumental_connection(host, port, tlsOptionsVariation, function(_client){ state = "connected"; var cleanString = function(value) { return String(value).replace(/\s+/g, "_"); } // Write the authentication header _client.write( "hello version node/statsd-instrumental-backend/" + cleanString(package.version) + " hostname " + cleanString(hostname) + " pid " + cleanString(process.pid) + " runtime " + cleanString("node/" + process.versions.node) + " platform " + cleanString(process.platform + "-" + process.arch) + "\n" + "authenticate " + key + "\n" ); }); // We need to handle the timeout. I think we should only care about read // timeouts. That is we write out data, if we don't hear back in timeout // seconds then the data probably hasn't reached the server. client.setTimeout(timeout, function() { // ZOMG FAILED WRITING WE ARE BAD AT COMPUTER SCIENCE if(state == "connected") { // We're waiting to hear back from the server and it has timed out. It's // unlikely that the server will suddenly wake up and send us our data so // lets disconnect and go shopping. client.end(); } }); // HOW WE HANDLE ERRORS. We should probably reconnect, maybe retry. client.addListener("error", function(exception){ if(debug) { log("Client error:", exception); } instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000); }); // What do we do when instrumental talks to us var totalBuffer = ""; client.on("data", function(buffer) { totalBuffer = totalBuffer + buffer; if(debug) { log("Received:", buffer); } // Authorization success if(totalBuffer == "ok\nok\n") { error = false; if(debug) { log("Sending:", payload.join("\n")); } client.end(payload.join("\n") + "\n", function() { tlsOptionsVariation.lastSuccessAt = new Date(); if (debug) log("payload sent, tlsOptionsVariation: ", tlsOptionsVariation); state = "sent"; }); instrumentalStats.last_flush = Math.round(new Date().getTime() / 1000); // Authorization failure } else if(totalBuffer.length >= "ok\nok\n".length) { // TODO: Actually do something with this error = true; instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000); } }); }
[ "function", "instrumental_send", "(", "payload", ")", "{", "var", "state", "=", "\"cold\"", ";", "var", "tlsOptionsVariation", "=", "selectTlsOptionsVariation", "(", ")", ";", "var", "client", "=", "instrumental_connection", "(", "host", ",", "port", ",", "tlsOptionsVariation", ",", "function", "(", "_client", ")", "{", "state", "=", "\"connected\"", ";", "var", "cleanString", "=", "function", "(", "value", ")", "{", "return", "String", "(", "value", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "\"_\"", ")", ";", "}", "_client", ".", "write", "(", "\"hello version node/statsd-instrumental-backend/\"", "+", "cleanString", "(", "package", ".", "version", ")", "+", "\" hostname \"", "+", "cleanString", "(", "hostname", ")", "+", "\" pid \"", "+", "cleanString", "(", "process", ".", "pid", ")", "+", "\" runtime \"", "+", "cleanString", "(", "\"node/\"", "+", "process", ".", "versions", ".", "node", ")", "+", "\" platform \"", "+", "cleanString", "(", "process", ".", "platform", "+", "\"-\"", "+", "process", ".", "arch", ")", "+", "\"\\n\"", "+", "\\n", "+", "\"authenticate \"", "+", "key", ")", ";", "}", ")", ";", "\"\\n\"", "\\n", "client", ".", "setTimeout", "(", "timeout", ",", "function", "(", ")", "{", "if", "(", "state", "==", "\"connected\"", ")", "{", "client", ".", "end", "(", ")", ";", "}", "}", ")", ";", "client", ".", "addListener", "(", "\"error\"", ",", "function", "(", "exception", ")", "{", "if", "(", "debug", ")", "{", "log", "(", "\"Client error:\"", ",", "exception", ")", ";", "}", "instrumentalStats", ".", "last_exception", "=", "Math", ".", "round", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "/", "1000", ")", ";", "}", ")", ";", "}" ]
Push data to instrumental
[ "Push", "data", "to", "instrumental" ]
e7e32ce75cd770114589447a2caf72eb673b8327
https://github.com/Instrumental/statsd-instrumental-backend/blob/e7e32ce75cd770114589447a2caf72eb673b8327/lib/instrumental.js#L176-L252
train
rekit/rekit-core
plugins/rekit-react/app.js
getRoutes
function getRoutes(feature) { const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js'); if (vio.fileNotExists(targetPath)) return []; const theAst = ast.getAst(targetPath); const arr = []; let rootPath = ''; let indexRoute = null; traverse(theAst, { ObjectExpression(path) { const node = path.node; const props = node.properties; if (!props.length) return; const obj = {}; props.forEach(p => { if (_.has(p, 'key.name') && !p.computed) { obj[p.key.name] = p; } }); if (obj.path && obj.component) { // in a route config, if an object expression has both 'path' and 'component' property, then it's a route config arr.push({ path: _.get(obj.path, 'value.value'), // only string literal supported component: _.get(obj.component, 'value.name'), // only identifier supported isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean node: { start: node.start, end: node.end, }, }); } if (obj.isIndex && obj.component && !indexRoute) { // only find the first index route indexRoute = { component: _.get(obj.component, 'value.name'), }; } if (obj.path && obj.childRoutes && !rootPath) { rootPath = _.get(obj.path, 'value.value'); if (!rootPath) rootPath = '$none'; // only find the first rootPath } }, }); const prjRootPath = getRootRoutePath(); if (rootPath === '$none') rootPath = prjRootPath; else if (!/^\//.test(rootPath)) rootPath = prjRootPath + '/' + rootPath; rootPath = rootPath.replace(/\/+/, '/'); arr.forEach(item => { if (!/^\//.test(item.path)) { item.path = (rootPath + '/' + item.path).replace(/\/+/, '/'); } }); if (indexRoute) { indexRoute.path = rootPath; arr.unshift(indexRoute); } return arr; }
javascript
function getRoutes(feature) { const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js'); if (vio.fileNotExists(targetPath)) return []; const theAst = ast.getAst(targetPath); const arr = []; let rootPath = ''; let indexRoute = null; traverse(theAst, { ObjectExpression(path) { const node = path.node; const props = node.properties; if (!props.length) return; const obj = {}; props.forEach(p => { if (_.has(p, 'key.name') && !p.computed) { obj[p.key.name] = p; } }); if (obj.path && obj.component) { // in a route config, if an object expression has both 'path' and 'component' property, then it's a route config arr.push({ path: _.get(obj.path, 'value.value'), // only string literal supported component: _.get(obj.component, 'value.name'), // only identifier supported isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean node: { start: node.start, end: node.end, }, }); } if (obj.isIndex && obj.component && !indexRoute) { // only find the first index route indexRoute = { component: _.get(obj.component, 'value.name'), }; } if (obj.path && obj.childRoutes && !rootPath) { rootPath = _.get(obj.path, 'value.value'); if (!rootPath) rootPath = '$none'; // only find the first rootPath } }, }); const prjRootPath = getRootRoutePath(); if (rootPath === '$none') rootPath = prjRootPath; else if (!/^\//.test(rootPath)) rootPath = prjRootPath + '/' + rootPath; rootPath = rootPath.replace(/\/+/, '/'); arr.forEach(item => { if (!/^\//.test(item.path)) { item.path = (rootPath + '/' + item.path).replace(/\/+/, '/'); } }); if (indexRoute) { indexRoute.path = rootPath; arr.unshift(indexRoute); } return arr; }
[ "function", "getRoutes", "(", "feature", ")", "{", "const", "targetPath", "=", "`", "${", "feature", "}", "`", ";", "if", "(", "vio", ".", "fileNotExists", "(", "targetPath", ")", ")", "return", "[", "]", ";", "const", "theAst", "=", "ast", ".", "getAst", "(", "targetPath", ")", ";", "const", "arr", "=", "[", "]", ";", "let", "rootPath", "=", "''", ";", "let", "indexRoute", "=", "null", ";", "traverse", "(", "theAst", ",", "{", "ObjectExpression", "(", "path", ")", "{", "const", "node", "=", "path", ".", "node", ";", "const", "props", "=", "node", ".", "properties", ";", "if", "(", "!", "props", ".", "length", ")", "return", ";", "const", "obj", "=", "{", "}", ";", "props", ".", "forEach", "(", "p", "=>", "{", "if", "(", "_", ".", "has", "(", "p", ",", "'key.name'", ")", "&&", "!", "p", ".", "computed", ")", "{", "obj", "[", "p", ".", "key", ".", "name", "]", "=", "p", ";", "}", "}", ")", ";", "if", "(", "obj", ".", "path", "&&", "obj", ".", "component", ")", "{", "arr", ".", "push", "(", "{", "path", ":", "_", ".", "get", "(", "obj", ".", "path", ",", "'value.value'", ")", ",", "component", ":", "_", ".", "get", "(", "obj", ".", "component", ",", "'value.name'", ")", ",", "isIndex", ":", "!", "!", "obj", ".", "isIndex", "&&", "_", ".", "get", "(", "obj", ".", "isIndex", ",", "'value.value'", ")", ",", "node", ":", "{", "start", ":", "node", ".", "start", ",", "end", ":", "node", ".", "end", ",", "}", ",", "}", ")", ";", "}", "if", "(", "obj", ".", "isIndex", "&&", "obj", ".", "component", "&&", "!", "indexRoute", ")", "{", "indexRoute", "=", "{", "component", ":", "_", ".", "get", "(", "obj", ".", "component", ",", "'value.name'", ")", ",", "}", ";", "}", "if", "(", "obj", ".", "path", "&&", "obj", ".", "childRoutes", "&&", "!", "rootPath", ")", "{", "rootPath", "=", "_", ".", "get", "(", "obj", ".", "path", ",", "'value.value'", ")", ";", "if", "(", "!", "rootPath", ")", "rootPath", "=", "'$none'", ";", "}", "}", ",", "}", ")", ";", "const", "prjRootPath", "=", "getRootRoutePath", "(", ")", ";", "if", "(", "rootPath", "===", "'$none'", ")", "rootPath", "=", "prjRootPath", ";", "else", "if", "(", "!", "/", "^\\/", "/", ".", "test", "(", "rootPath", ")", ")", "rootPath", "=", "prjRootPath", "+", "'/'", "+", "rootPath", ";", "rootPath", "=", "rootPath", ".", "replace", "(", "/", "\\/+", "/", ",", "'/'", ")", ";", "arr", ".", "forEach", "(", "item", "=>", "{", "if", "(", "!", "/", "^\\/", "/", ".", "test", "(", "item", ".", "path", ")", ")", "{", "item", ".", "path", "=", "(", "rootPath", "+", "'/'", "+", "item", ".", "path", ")", ".", "replace", "(", "/", "\\/+", "/", ",", "'/'", ")", ";", "}", "}", ")", ";", "if", "(", "indexRoute", ")", "{", "indexRoute", ".", "path", "=", "rootPath", ";", "arr", ".", "unshift", "(", "indexRoute", ")", ";", "}", "return", "arr", ";", "}" ]
Get route rules defined in a feature. @param {string} feature - The feature name.
[ "Get", "route", "rules", "defined", "in", "a", "feature", "." ]
e98ab59da85a517717e1ff4e7c724d4c917a45b8
https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/plugins/rekit-react/app.js#L194-L251
train
jhudson8/react-backbone
react-backbone.js
getKey
function getKey(context) { if (context.getModelKey) { return context.getModelKey(); } return context.props.name || context.props.key || context.props.ref; }
javascript
function getKey(context) { if (context.getModelKey) { return context.getModelKey(); } return context.props.name || context.props.key || context.props.ref; }
[ "function", "getKey", "(", "context", ")", "{", "if", "(", "context", ".", "getModelKey", ")", "{", "return", "context", ".", "getModelKey", "(", ")", ";", "}", "return", "context", ".", "props", ".", "name", "||", "context", ".", "props", ".", "key", "||", "context", ".", "props", ".", "ref", ";", "}" ]
Return a model attribute key used for attribute specific operations
[ "Return", "a", "model", "attribute", "key", "used", "for", "attribute", "specific", "operations" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L131-L136
train
jhudson8/react-backbone
react-backbone.js
modelOrCollectionOnOrOnce
function modelOrCollectionOnOrOnce(modelType, type, args, _this, _modelOrCollection) { var modelEvents = getModelAndCollectionEvents(modelType, _this); var ev = args[0]; var cb = args[1]; var ctx = args[2]; modelEvents[ev] = { type: type, ev: ev, cb: cb, ctx: ctx }; function _on(modelOrCollection) { _this[type === 'on' ? 'listenTo' : 'listenToOnce'](modelOrCollection, ev, cb, ctx); } if (modelEvents.__bound) { if (_modelOrCollection) { _on(_modelOrCollection); } else { getModelOrCollections(modelType, _this, _on); } } }
javascript
function modelOrCollectionOnOrOnce(modelType, type, args, _this, _modelOrCollection) { var modelEvents = getModelAndCollectionEvents(modelType, _this); var ev = args[0]; var cb = args[1]; var ctx = args[2]; modelEvents[ev] = { type: type, ev: ev, cb: cb, ctx: ctx }; function _on(modelOrCollection) { _this[type === 'on' ? 'listenTo' : 'listenToOnce'](modelOrCollection, ev, cb, ctx); } if (modelEvents.__bound) { if (_modelOrCollection) { _on(_modelOrCollection); } else { getModelOrCollections(modelType, _this, _on); } } }
[ "function", "modelOrCollectionOnOrOnce", "(", "modelType", ",", "type", ",", "args", ",", "_this", ",", "_modelOrCollection", ")", "{", "var", "modelEvents", "=", "getModelAndCollectionEvents", "(", "modelType", ",", "_this", ")", ";", "var", "ev", "=", "args", "[", "0", "]", ";", "var", "cb", "=", "args", "[", "1", "]", ";", "var", "ctx", "=", "args", "[", "2", "]", ";", "modelEvents", "[", "ev", "]", "=", "{", "type", ":", "type", ",", "ev", ":", "ev", ",", "cb", ":", "cb", ",", "ctx", ":", "ctx", "}", ";", "function", "_on", "(", "modelOrCollection", ")", "{", "_this", "[", "type", "===", "'on'", "?", "'listenTo'", ":", "'listenToOnce'", "]", "(", "modelOrCollection", ",", "ev", ",", "cb", ",", "ctx", ")", ";", "}", "if", "(", "modelEvents", ".", "__bound", ")", "{", "if", "(", "_modelOrCollection", ")", "{", "_on", "(", "_modelOrCollection", ")", ";", "}", "else", "{", "getModelOrCollections", "(", "modelType", ",", "_this", ",", "_on", ")", ";", "}", "}", "}" ]
Provide modelOn and modelOnce argument with proxied arguments arguments are event, callback, context
[ "Provide", "modelOn", "and", "modelOnce", "argument", "with", "proxied", "arguments", "arguments", "are", "event", "callback", "context" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L214-L236
train
jhudson8/react-backbone
react-backbone.js
getModelAndCollectionEvents
function getModelAndCollectionEvents(type, context) { var key = '__' + type + CAP_EVENTS, modelEvents = getState(key, context); if (!modelEvents) { modelEvents = {}; var stateVar = {}; stateVar[key] = modelEvents; setState(stateVar, context, false); } return modelEvents; }
javascript
function getModelAndCollectionEvents(type, context) { var key = '__' + type + CAP_EVENTS, modelEvents = getState(key, context); if (!modelEvents) { modelEvents = {}; var stateVar = {}; stateVar[key] = modelEvents; setState(stateVar, context, false); } return modelEvents; }
[ "function", "getModelAndCollectionEvents", "(", "type", ",", "context", ")", "{", "var", "key", "=", "'__'", "+", "type", "+", "CAP_EVENTS", ",", "modelEvents", "=", "getState", "(", "key", ",", "context", ")", ";", "if", "(", "!", "modelEvents", ")", "{", "modelEvents", "=", "{", "}", ";", "var", "stateVar", "=", "{", "}", ";", "stateVar", "[", "key", "]", "=", "modelEvents", ";", "setState", "(", "stateVar", ",", "context", ",", "false", ")", ";", "}", "return", "modelEvents", ";", "}" ]
Return all bound model events
[ "Return", "all", "bound", "model", "events" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L282-L292
train
jhudson8/react-backbone
react-backbone.js
pushLoadingState
function pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force) { var currentLoads = getState(stateName, context), currentlyLoading = currentLoads && currentLoads.length; if (!currentLoads) { currentLoads = []; } if (_.isArray(currentLoads)) { if (_.indexOf(currentLoads, xhrEvent) >= 0) { if (!force) { return; } } else { currentLoads.push(xhrEvent); } if (!currentlyLoading) { var toSet = {}; toSet[stateName] = currentLoads; setState(toSet, context); } xhrEvent.on('complete', function() { popLoadingState(xhrEvent, stateName, modelOrCollection, context); }); } }
javascript
function pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force) { var currentLoads = getState(stateName, context), currentlyLoading = currentLoads && currentLoads.length; if (!currentLoads) { currentLoads = []; } if (_.isArray(currentLoads)) { if (_.indexOf(currentLoads, xhrEvent) >= 0) { if (!force) { return; } } else { currentLoads.push(xhrEvent); } if (!currentlyLoading) { var toSet = {}; toSet[stateName] = currentLoads; setState(toSet, context); } xhrEvent.on('complete', function() { popLoadingState(xhrEvent, stateName, modelOrCollection, context); }); } }
[ "function", "pushLoadingState", "(", "xhrEvent", ",", "stateName", ",", "modelOrCollection", ",", "context", ",", "force", ")", "{", "var", "currentLoads", "=", "getState", "(", "stateName", ",", "context", ")", ",", "currentlyLoading", "=", "currentLoads", "&&", "currentLoads", ".", "length", ";", "if", "(", "!", "currentLoads", ")", "{", "currentLoads", "=", "[", "]", ";", "}", "if", "(", "_", ".", "isArray", "(", "currentLoads", ")", ")", "{", "if", "(", "_", ".", "indexOf", "(", "currentLoads", ",", "xhrEvent", ")", ">=", "0", ")", "{", "if", "(", "!", "force", ")", "{", "return", ";", "}", "}", "else", "{", "currentLoads", ".", "push", "(", "xhrEvent", ")", ";", "}", "if", "(", "!", "currentlyLoading", ")", "{", "var", "toSet", "=", "{", "}", ";", "toSet", "[", "stateName", "]", "=", "currentLoads", ";", "setState", "(", "toSet", ",", "context", ")", ";", "}", "xhrEvent", ".", "on", "(", "'complete'", ",", "function", "(", ")", "{", "popLoadingState", "(", "xhrEvent", ",", "stateName", ",", "modelOrCollection", ",", "context", ")", ";", "}", ")", ";", "}", "}" ]
loading state helpers
[ "loading", "state", "helpers" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L295-L321
train
jhudson8/react-backbone
react-backbone.js
popLoadingState
function popLoadingState(xhrEvent, stateName, modelOrCollection, context) { var currentLoads = getState(stateName, context); if (_.isArray(currentLoads)) { var i = currentLoads.indexOf(xhrEvent); while (i >= 0) { currentLoads.splice(i, 1); i = currentLoads.indexOf(xhrEvent); } if (!currentLoads.length) { var toSet = {}; toSet[stateName] = undefined; setState(toSet, context); } } }
javascript
function popLoadingState(xhrEvent, stateName, modelOrCollection, context) { var currentLoads = getState(stateName, context); if (_.isArray(currentLoads)) { var i = currentLoads.indexOf(xhrEvent); while (i >= 0) { currentLoads.splice(i, 1); i = currentLoads.indexOf(xhrEvent); } if (!currentLoads.length) { var toSet = {}; toSet[stateName] = undefined; setState(toSet, context); } } }
[ "function", "popLoadingState", "(", "xhrEvent", ",", "stateName", ",", "modelOrCollection", ",", "context", ")", "{", "var", "currentLoads", "=", "getState", "(", "stateName", ",", "context", ")", ";", "if", "(", "_", ".", "isArray", "(", "currentLoads", ")", ")", "{", "var", "i", "=", "currentLoads", ".", "indexOf", "(", "xhrEvent", ")", ";", "while", "(", "i", ">=", "0", ")", "{", "currentLoads", ".", "splice", "(", "i", ",", "1", ")", ";", "i", "=", "currentLoads", ".", "indexOf", "(", "xhrEvent", ")", ";", "}", "if", "(", "!", "currentLoads", ".", "length", ")", "{", "var", "toSet", "=", "{", "}", ";", "toSet", "[", "stateName", "]", "=", "undefined", ";", "setState", "(", "toSet", ",", "context", ")", ";", "}", "}", "}" ]
remove the xhrEvent from the loading state
[ "remove", "the", "xhrEvent", "from", "the", "loading", "state" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L324-L338
train
jhudson8/react-backbone
react-backbone.js
joinCurrentModelActivity
function joinCurrentModelActivity(method, stateName, modelOrCollection, context, force) { var xhrActivity = modelOrCollection[xhrModelLoadingAttribute]; if (xhrActivity) { _.each(xhrActivity, function(xhrEvent) { if (!method || method === ALL_XHR_ACTIVITY || xhrEvent.method === method) { // this is one that is applicable pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force); } }); } }
javascript
function joinCurrentModelActivity(method, stateName, modelOrCollection, context, force) { var xhrActivity = modelOrCollection[xhrModelLoadingAttribute]; if (xhrActivity) { _.each(xhrActivity, function(xhrEvent) { if (!method || method === ALL_XHR_ACTIVITY || xhrEvent.method === method) { // this is one that is applicable pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force); } }); } }
[ "function", "joinCurrentModelActivity", "(", "method", ",", "stateName", ",", "modelOrCollection", ",", "context", ",", "force", ")", "{", "var", "xhrActivity", "=", "modelOrCollection", "[", "xhrModelLoadingAttribute", "]", ";", "if", "(", "xhrActivity", ")", "{", "_", ".", "each", "(", "xhrActivity", ",", "function", "(", "xhrEvent", ")", "{", "if", "(", "!", "method", "||", "method", "===", "ALL_XHR_ACTIVITY", "||", "xhrEvent", ".", "method", "===", "method", ")", "{", "pushLoadingState", "(", "xhrEvent", ",", "stateName", ",", "modelOrCollection", ",", "context", ",", "force", ")", ";", "}", "}", ")", ";", "}", "}" ]
if there is any current xhrEvent that match the method, add a reference to it with this context
[ "if", "there", "is", "any", "current", "xhrEvent", "that", "match", "the", "method", "add", "a", "reference", "to", "it", "with", "this", "context" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L341-L351
train
jhudson8/react-backbone
react-backbone.js
function() { var keys = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : undefined; return { getInitialState: function() { var self = this; modelOrCollectionEventHandler(typeData.type, keys || 'updateOn', this, '{key}', function() { self.deferUpdate(); }); } }; }
javascript
function() { var keys = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : undefined; return { getInitialState: function() { var self = this; modelOrCollectionEventHandler(typeData.type, keys || 'updateOn', this, '{key}', function() { self.deferUpdate(); }); } }; }
[ "function", "(", ")", "{", "var", "keys", "=", "arguments", ".", "length", ">", "0", "?", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ":", "undefined", ";", "return", "{", "getInitialState", ":", "function", "(", ")", "{", "var", "self", "=", "this", ";", "modelOrCollectionEventHandler", "(", "typeData", ".", "type", ",", "keys", "||", "'updateOn'", ",", "this", ",", "'{key}'", ",", "function", "(", ")", "{", "self", ".", "deferUpdate", "(", ")", ";", "}", ")", ";", "}", "}", ";", "}" ]
Gives any comonent the ability to force an update when an event is fired
[ "Gives", "any", "comonent", "the", "ability", "to", "force", "an", "update", "when", "an", "event", "is", "fired" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L669-L679
train
jhudson8/react-backbone
react-backbone.js
function(type, attributes, isCheckable, classAttributes) { return React.createClass(_.extend({ mixins: ['modelAware'], render: function() { var props = {}; var defaultValue = getModelValue(this); if (isCheckable) { props.defaultChecked = defaultValue; } else { props.defaultValue = defaultValue; } return React.DOM[type](_.extend(props, attributes, this.props, {onChange: twoWayBinding(this)}), this.props.children); }, getValue: function() { if (this.isMounted()) { if (isCheckable) { var el = this.getDOMNode(); return el.checked ? true : false; } else { return getElementValue(this); } } }, getDOMValue: function() { if (this.isMounted()) { return getElementValue(this); } } }, classAttributes)); }
javascript
function(type, attributes, isCheckable, classAttributes) { return React.createClass(_.extend({ mixins: ['modelAware'], render: function() { var props = {}; var defaultValue = getModelValue(this); if (isCheckable) { props.defaultChecked = defaultValue; } else { props.defaultValue = defaultValue; } return React.DOM[type](_.extend(props, attributes, this.props, {onChange: twoWayBinding(this)}), this.props.children); }, getValue: function() { if (this.isMounted()) { if (isCheckable) { var el = this.getDOMNode(); return el.checked ? true : false; } else { return getElementValue(this); } } }, getDOMValue: function() { if (this.isMounted()) { return getElementValue(this); } } }, classAttributes)); }
[ "function", "(", "type", ",", "attributes", ",", "isCheckable", ",", "classAttributes", ")", "{", "return", "React", ".", "createClass", "(", "_", ".", "extend", "(", "{", "mixins", ":", "[", "'modelAware'", "]", ",", "render", ":", "function", "(", ")", "{", "var", "props", "=", "{", "}", ";", "var", "defaultValue", "=", "getModelValue", "(", "this", ")", ";", "if", "(", "isCheckable", ")", "{", "props", ".", "defaultChecked", "=", "defaultValue", ";", "}", "else", "{", "props", ".", "defaultValue", "=", "defaultValue", ";", "}", "return", "React", ".", "DOM", "[", "type", "]", "(", "_", ".", "extend", "(", "props", ",", "attributes", ",", "this", ".", "props", ",", "{", "onChange", ":", "twoWayBinding", "(", "this", ")", "}", ")", ",", "this", ".", "props", ".", "children", ")", ";", "}", ",", "getValue", ":", "function", "(", ")", "{", "if", "(", "this", ".", "isMounted", "(", ")", ")", "{", "if", "(", "isCheckable", ")", "{", "var", "el", "=", "this", ".", "getDOMNode", "(", ")", ";", "return", "el", ".", "checked", "?", "true", ":", "false", ";", "}", "else", "{", "return", "getElementValue", "(", "this", ")", ";", "}", "}", "}", ",", "getDOMValue", ":", "function", "(", ")", "{", "if", "(", "this", ".", "isMounted", "(", ")", ")", "{", "return", "getElementValue", "(", "this", ")", ";", "}", "}", "}", ",", "classAttributes", ")", ")", ";", "}" ]
Standard input components that implement react-backbone model awareness
[ "Standard", "input", "components", "that", "implement", "react", "-", "backbone", "model", "awareness" ]
d9064510ae73f915444a11ec1100b53614bef177
https://github.com/jhudson8/react-backbone/blob/d9064510ae73f915444a11ec1100b53614bef177/react-backbone.js#L942-L972
train
rekit/rekit-core
core/plugin.js
loadPlugin
function loadPlugin(pluginRoot, noUI) { // noUI flag is used for loading dev plugins whose ui is from webpack dev server try { // const pkgJson = require(paths.join(pluginRoot, 'package.json')); const pluginInstance = {}; // Core part const coreIndex = paths.join(pluginRoot, 'core/index.js'); if (fs.existsSync(coreIndex)) { Object.assign(pluginInstance, require(coreIndex)); } // UI part if (!noUI && fs.existsSync(path.join(pluginRoot, 'build/main.js'))) { pluginInstance.ui = { root: path.join(pluginRoot, 'build'), }; } // Plugin meta defined in package.json const pkgJsonPath = path.join(pluginRoot, 'package.json'); let pkgJson = null; if (fs.existsSync(pkgJsonPath)) { pkgJson = fs.readJsonSync(pkgJsonPath); ['appType', 'name', 'featureFiles'].forEach(key => { if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) { if (key === 'name') { let name = pkgJson.name; if (name.startsWith('rekit-plugin')) name = name.replace('rekit-plugin-', ''); pluginInstance.name = name; } else { pluginInstance[key] = pkgJson[key] || null; } } }); if (pkgJson.rekitPlugin) { Object.keys(pkgJson.rekitPlugin).forEach(key => { if (!pluginInstance.hasOwnProperty(key)) { pluginInstance[key] = pkgJson.rekitPlugin[key]; } }); } } return pluginInstance; } catch (e) { logger.warn(`Failed to load plugin: ${pluginRoot}`, e); } return null; }
javascript
function loadPlugin(pluginRoot, noUI) { // noUI flag is used for loading dev plugins whose ui is from webpack dev server try { // const pkgJson = require(paths.join(pluginRoot, 'package.json')); const pluginInstance = {}; // Core part const coreIndex = paths.join(pluginRoot, 'core/index.js'); if (fs.existsSync(coreIndex)) { Object.assign(pluginInstance, require(coreIndex)); } // UI part if (!noUI && fs.existsSync(path.join(pluginRoot, 'build/main.js'))) { pluginInstance.ui = { root: path.join(pluginRoot, 'build'), }; } // Plugin meta defined in package.json const pkgJsonPath = path.join(pluginRoot, 'package.json'); let pkgJson = null; if (fs.existsSync(pkgJsonPath)) { pkgJson = fs.readJsonSync(pkgJsonPath); ['appType', 'name', 'featureFiles'].forEach(key => { if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) { if (key === 'name') { let name = pkgJson.name; if (name.startsWith('rekit-plugin')) name = name.replace('rekit-plugin-', ''); pluginInstance.name = name; } else { pluginInstance[key] = pkgJson[key] || null; } } }); if (pkgJson.rekitPlugin) { Object.keys(pkgJson.rekitPlugin).forEach(key => { if (!pluginInstance.hasOwnProperty(key)) { pluginInstance[key] = pkgJson.rekitPlugin[key]; } }); } } return pluginInstance; } catch (e) { logger.warn(`Failed to load plugin: ${pluginRoot}`, e); } return null; }
[ "function", "loadPlugin", "(", "pluginRoot", ",", "noUI", ")", "{", "try", "{", "const", "pluginInstance", "=", "{", "}", ";", "const", "coreIndex", "=", "paths", ".", "join", "(", "pluginRoot", ",", "'core/index.js'", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "coreIndex", ")", ")", "{", "Object", ".", "assign", "(", "pluginInstance", ",", "require", "(", "coreIndex", ")", ")", ";", "}", "if", "(", "!", "noUI", "&&", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "pluginRoot", ",", "'build/main.js'", ")", ")", ")", "{", "pluginInstance", ".", "ui", "=", "{", "root", ":", "path", ".", "join", "(", "pluginRoot", ",", "'build'", ")", ",", "}", ";", "}", "const", "pkgJsonPath", "=", "path", ".", "join", "(", "pluginRoot", ",", "'package.json'", ")", ";", "let", "pkgJson", "=", "null", ";", "if", "(", "fs", ".", "existsSync", "(", "pkgJsonPath", ")", ")", "{", "pkgJson", "=", "fs", ".", "readJsonSync", "(", "pkgJsonPath", ")", ";", "[", "'appType'", ",", "'name'", ",", "'featureFiles'", "]", ".", "forEach", "(", "key", "=>", "{", "if", "(", "!", "pluginInstance", ".", "hasOwnProperty", "(", "key", ")", "&&", "pkgJson", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "key", "===", "'name'", ")", "{", "let", "name", "=", "pkgJson", ".", "name", ";", "if", "(", "name", ".", "startsWith", "(", "'rekit-plugin'", ")", ")", "name", "=", "name", ".", "replace", "(", "'rekit-plugin-'", ",", "''", ")", ";", "pluginInstance", ".", "name", "=", "name", ";", "}", "else", "{", "pluginInstance", "[", "key", "]", "=", "pkgJson", "[", "key", "]", "||", "null", ";", "}", "}", "}", ")", ";", "if", "(", "pkgJson", ".", "rekitPlugin", ")", "{", "Object", ".", "keys", "(", "pkgJson", ".", "rekitPlugin", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "!", "pluginInstance", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "pluginInstance", "[", "key", "]", "=", "pkgJson", ".", "rekitPlugin", "[", "key", "]", ";", "}", "}", ")", ";", "}", "}", "return", "pluginInstance", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "warn", "(", "`", "${", "pluginRoot", "}", "`", ",", "e", ")", ";", "}", "return", "null", ";", "}" ]
Load plugin instance, plugin depends on project config
[ "Load", "plugin", "instance", "plugin", "depends", "on", "project", "config" ]
e98ab59da85a517717e1ff4e7c724d4c917a45b8
https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/plugin.js#L112-L160
train
rekit/rekit-core
core/plugin.js
addPlugin
function addPlugin(plugin) { if (!plugin) { return; } if (!needFilterPlugin) { console.warn('You are adding a plugin after getPlugins is called.'); } needFilterPlugin = true; if (!plugin.name) { console.log('plugin: ', plugin); throw new Error('Each plugin should have a name.'); } if (_.find(allPlugins, { name: plugin.name })) { console.warn('You should not add a plugin with same name: ' + plugin.name); return; } allPlugins.push(plugin); }
javascript
function addPlugin(plugin) { if (!plugin) { return; } if (!needFilterPlugin) { console.warn('You are adding a plugin after getPlugins is called.'); } needFilterPlugin = true; if (!plugin.name) { console.log('plugin: ', plugin); throw new Error('Each plugin should have a name.'); } if (_.find(allPlugins, { name: plugin.name })) { console.warn('You should not add a plugin with same name: ' + plugin.name); return; } allPlugins.push(plugin); }
[ "function", "addPlugin", "(", "plugin", ")", "{", "if", "(", "!", "plugin", ")", "{", "return", ";", "}", "if", "(", "!", "needFilterPlugin", ")", "{", "console", ".", "warn", "(", "'You are adding a plugin after getPlugins is called.'", ")", ";", "}", "needFilterPlugin", "=", "true", ";", "if", "(", "!", "plugin", ".", "name", ")", "{", "console", ".", "log", "(", "'plugin: '", ",", "plugin", ")", ";", "throw", "new", "Error", "(", "'Each plugin should have a name.'", ")", ";", "}", "if", "(", "_", ".", "find", "(", "allPlugins", ",", "{", "name", ":", "plugin", ".", "name", "}", ")", ")", "{", "console", ".", "warn", "(", "'You should not add a plugin with same name: '", "+", "plugin", ".", "name", ")", ";", "return", ";", "}", "allPlugins", ".", "push", "(", "plugin", ")", ";", "}" ]
Dynamically add an plugin
[ "Dynamically", "add", "an", "plugin" ]
e98ab59da85a517717e1ff4e7c724d4c917a45b8
https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/plugin.js#L173-L190
train
rekit/rekit-core
core/template.js
generate
function generate(targetPath, args) { if ( !args.template && (!args.templateFile || (args.templateFile && !vio.fileExists(args.templateFile))) ) { const err = new Error(`No template file found: ${args.templateFile}`); err.code = 'TEMPLATE_FILE_NOT_FOUND'; throw err; } const tpl = args.template || vio.getContent(args.templateFile); const compiled = _.template(tpl, args.templateOptions || {}); const result = compiled(args.context || {}); vio.save(targetPath, result); }
javascript
function generate(targetPath, args) { if ( !args.template && (!args.templateFile || (args.templateFile && !vio.fileExists(args.templateFile))) ) { const err = new Error(`No template file found: ${args.templateFile}`); err.code = 'TEMPLATE_FILE_NOT_FOUND'; throw err; } const tpl = args.template || vio.getContent(args.templateFile); const compiled = _.template(tpl, args.templateOptions || {}); const result = compiled(args.context || {}); vio.save(targetPath, result); }
[ "function", "generate", "(", "targetPath", ",", "args", ")", "{", "if", "(", "!", "args", ".", "template", "&&", "(", "!", "args", ".", "templateFile", "||", "(", "args", ".", "templateFile", "&&", "!", "vio", ".", "fileExists", "(", "args", ".", "templateFile", ")", ")", ")", ")", "{", "const", "err", "=", "new", "Error", "(", "`", "${", "args", ".", "templateFile", "}", "`", ")", ";", "err", ".", "code", "=", "'TEMPLATE_FILE_NOT_FOUND'", ";", "throw", "err", ";", "}", "const", "tpl", "=", "args", ".", "template", "||", "vio", ".", "getContent", "(", "args", ".", "templateFile", ")", ";", "const", "compiled", "=", "_", ".", "template", "(", "tpl", ",", "args", ".", "templateOptions", "||", "{", "}", ")", ";", "const", "result", "=", "compiled", "(", "args", ".", "context", "||", "{", "}", ")", ";", "vio", ".", "save", "(", "targetPath", ",", "result", ")", ";", "}" ]
Process the template file and save the result to virtual IO. If the target file has existed, throw fatal error and exit. @param {string} targetPath - The path to save the result. @param {Object} args - The path to save the result. @param {string} args.template - The template string to process. @param {string} args.templateFile - If no 'template' defined, read the template file to process. One of template and templateFile should be provided. @param {Object} args.context - The context to process the template. @alias module:template.generate @example const template = require('rekit-core').template; const tpl = 'hello ${user}!'; template.generate('path/to/result.txt', { template: tpl, context: { user: 'Nate' } }); // Result => create a file 'path/to/result.txt' which contains text: 'hello Nate!' // NOTE the result is only in vio, you need to call vio.flush() to write to disk.
[ "Process", "the", "template", "file", "and", "save", "the", "result", "to", "virtual", "IO", ".", "If", "the", "target", "file", "has", "existed", "throw", "fatal", "error", "and", "exit", "." ]
e98ab59da85a517717e1ff4e7c724d4c917a45b8
https://github.com/rekit/rekit-core/blob/e98ab59da85a517717e1ff4e7c724d4c917a45b8/core/template.js#L41-L55
train
crcn/caplet.js
lib/model.js
function() { var data = {}; if (this.data && !isObject(this.data)) { return this.data; } // TODO - don't do this yet until virt properties are checked // var keys = Object.keys(this); var keys = Object.keys(this.data ? this.data : this); for (var i = 0, n = keys.length; i < n; i++) { var key = keys[i]; if (key in this.constructor.prototype || key.charCodeAt(0) === 95) { continue; } data[key] = this[key]; } return data; }
javascript
function() { var data = {}; if (this.data && !isObject(this.data)) { return this.data; } // TODO - don't do this yet until virt properties are checked // var keys = Object.keys(this); var keys = Object.keys(this.data ? this.data : this); for (var i = 0, n = keys.length; i < n; i++) { var key = keys[i]; if (key in this.constructor.prototype || key.charCodeAt(0) === 95) { continue; } data[key] = this[key]; } return data; }
[ "function", "(", ")", "{", "var", "data", "=", "{", "}", ";", "if", "(", "this", ".", "data", "&&", "!", "isObject", "(", "this", ".", "data", ")", ")", "{", "return", "this", ".", "data", ";", "}", "var", "keys", "=", "Object", ".", "keys", "(", "this", ".", "data", "?", "this", ".", "data", ":", "this", ")", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "keys", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "key", "in", "this", ".", "constructor", ".", "prototype", "||", "key", ".", "charCodeAt", "(", "0", ")", "===", "95", ")", "{", "continue", ";", "}", "data", "[", "key", "]", "=", "this", "[", "key", "]", ";", "}", "return", "data", ";", "}" ]
serialize this model back into a data object
[ "serialize", "this", "model", "back", "into", "a", "data", "object" ]
63af94de8ddab8576f6df3a384e40157d7f7c5b1
https://github.com/crcn/caplet.js/blob/63af94de8ddab8576f6df3a384e40157d7f7c5b1/lib/model.js#L64-L86
train