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
jasonrojas/node-captions
lib/srt.js
function(filedata, callback) { var lines; lines = filedata.toString().split(/(?:\r\n|\r|\n)/gm); if (module.exports.verify(lines)) { return callback(undefined, lines); } return callback('INVALID_SRT_FORMAT'); }
javascript
function(filedata, callback) { var lines; lines = filedata.toString().split(/(?:\r\n|\r|\n)/gm); if (module.exports.verify(lines)) { return callback(undefined, lines); } return callback('INVALID_SRT_FORMAT'); }
[ "function", "(", "filedata", ",", "callback", ")", "{", "var", "lines", ";", "lines", "=", "filedata", ".", "toString", "(", ")", ".", "split", "(", "/", "(?:\\r\\n|\\r|\\n)", "/", "gm", ")", ";", "if", "(", "module", ".", "exports", ".", "verify", "(", "lines", ")", ")", "{", "return", "callback", "(", "undefined", ",", "lines", ")", ";", "}", "return", "callback", "(", "'INVALID_SRT_FORMAT'", ")", ";", "}" ]
Parses srt captions, errors if format is invalid @function @param {string} filedata - String of caption data @param {callback} callback - function to call when complete @public
[ "Parses", "srt", "captions", "errors", "if", "format", "is", "invalid" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L91-L98
train
jasonrojas/node-captions
lib/srt.js
function(data) { var json = {}, index = 0, id, text, startTimeMicro, durationMicro, invalidText = /^\s+$/, endTimeMicro, time, lastNonEmptyLine; function getLastNonEmptyLine(linesArray) { var idx = linesArray.length - 1; while (idx >= 0 && !linesArray[idx]) { idx--; } return idx; } json.captions = []; lastNonEmptyLine = getLastNonEmptyLine(data) + 1; while (index < lastNonEmptyLine) { if (data[index]) { text = []; //Find the ID line.. if (/^[0-9]+$/.test(data[index])) { //found id line id = parseInt(data[index], 10); index++; } if (!data[index].split) { // for some reason this is not a string index++; continue; } //next line has to be timestamp right? right? time = data[index].split(/[\t ]*-->[\t ]*/); startTimeMicro = module.exports.translateTime(time[0]); endTimeMicro = module.exports.translateTime(time[1]); durationMicro = parseInt(parseInt(endTimeMicro, 10) - parseInt(startTimeMicro, 10), 10); if (!startTimeMicro || !endTimeMicro) { // no valid timestamp index++; continue; } index++; while (data[index]) { text.push(data[index]); index++; if (!data[index] && !invalidText.test(text.join('\n'))) { json.captions.push({ id: id, text: module.exports.addMacros(text.join('\n')), startTimeMicro: startTimeMicro, durationSeconds: parseInt(durationMicro / 1000, 10) / 1000, endTimeMicro: endTimeMicro }); break; } } } index++; } return json.captions; }
javascript
function(data) { var json = {}, index = 0, id, text, startTimeMicro, durationMicro, invalidText = /^\s+$/, endTimeMicro, time, lastNonEmptyLine; function getLastNonEmptyLine(linesArray) { var idx = linesArray.length - 1; while (idx >= 0 && !linesArray[idx]) { idx--; } return idx; } json.captions = []; lastNonEmptyLine = getLastNonEmptyLine(data) + 1; while (index < lastNonEmptyLine) { if (data[index]) { text = []; //Find the ID line.. if (/^[0-9]+$/.test(data[index])) { //found id line id = parseInt(data[index], 10); index++; } if (!data[index].split) { // for some reason this is not a string index++; continue; } //next line has to be timestamp right? right? time = data[index].split(/[\t ]*-->[\t ]*/); startTimeMicro = module.exports.translateTime(time[0]); endTimeMicro = module.exports.translateTime(time[1]); durationMicro = parseInt(parseInt(endTimeMicro, 10) - parseInt(startTimeMicro, 10), 10); if (!startTimeMicro || !endTimeMicro) { // no valid timestamp index++; continue; } index++; while (data[index]) { text.push(data[index]); index++; if (!data[index] && !invalidText.test(text.join('\n'))) { json.captions.push({ id: id, text: module.exports.addMacros(text.join('\n')), startTimeMicro: startTimeMicro, durationSeconds: parseInt(durationMicro / 1000, 10) / 1000, endTimeMicro: endTimeMicro }); break; } } } index++; } return json.captions; }
[ "function", "(", "data", ")", "{", "var", "json", "=", "{", "}", ",", "index", "=", "0", ",", "id", ",", "text", ",", "startTimeMicro", ",", "durationMicro", ",", "invalidText", "=", "/", "^\\s+$", "/", ",", "endTimeMicro", ",", "time", ",", "lastNonEmptyLine", ";", "function", "getLastNonEmptyLine", "(", "linesArray", ")", "{", "var", "idx", "=", "linesArray", ".", "length", "-", "1", ";", "while", "(", "idx", ">=", "0", "&&", "!", "linesArray", "[", "idx", "]", ")", "{", "idx", "--", ";", "}", "return", "idx", ";", "}", "json", ".", "captions", "=", "[", "]", ";", "lastNonEmptyLine", "=", "getLastNonEmptyLine", "(", "data", ")", "+", "1", ";", "while", "(", "index", "<", "lastNonEmptyLine", ")", "{", "if", "(", "data", "[", "index", "]", ")", "{", "text", "=", "[", "]", ";", "if", "(", "/", "^[0-9]+$", "/", ".", "test", "(", "data", "[", "index", "]", ")", ")", "{", "id", "=", "parseInt", "(", "data", "[", "index", "]", ",", "10", ")", ";", "index", "++", ";", "}", "if", "(", "!", "data", "[", "index", "]", ".", "split", ")", "{", "index", "++", ";", "continue", ";", "}", "time", "=", "data", "[", "index", "]", ".", "split", "(", "/", "[\\t ]*", "/", ")", ";", "startTimeMicro", "=", "module", ".", "exports", ".", "translateTime", "(", "time", "[", "0", "]", ")", ";", "endTimeMicro", "=", "module", ".", "exports", ".", "translateTime", "(", "time", "[", "1", "]", ")", ";", "durationMicro", "=", "parseInt", "(", "parseInt", "(", "endTimeMicro", ",", "10", ")", "-", "parseInt", "(", "startTimeMicro", ",", "10", ")", ",", "10", ")", ";", "if", "(", "!", "startTimeMicro", "||", "!", "endTimeMicro", ")", "{", "index", "++", ";", "continue", ";", "}", "index", "++", ";", "while", "(", "data", "[", "index", "]", ")", "{", "text", ".", "push", "(", "data", "[", "index", "]", ")", ";", "index", "++", ";", "if", "(", "!", "data", "[", "index", "]", "&&", "!", "invalidText", ".", "test", "(", "text", ".", "join", "(", "'\\n'", ")", ")", ")", "\\n", "}", "}", "{", "json", ".", "captions", ".", "push", "(", "{", "id", ":", "id", ",", "text", ":", "module", ".", "exports", ".", "addMacros", "(", "text", ".", "join", "(", "'\\n'", ")", ")", ",", "\\n", ",", "startTimeMicro", ":", "startTimeMicro", ",", "durationSeconds", ":", "parseInt", "(", "durationMicro", "/", "1000", ",", "10", ")", "/", "1000", "}", ")", ";", "endTimeMicro", ":", "endTimeMicro", "}", "}", "break", ";", "}" ]
converts SRT to JSON format @function @param {array} data - output from read usually @public
[ "converts", "SRT", "to", "JSON", "format" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L116-L183
train
jasonrojas/node-captions
lib/srt.js
function(timestamp) { if (!timestamp) { return; } //TODO check this //var secondsPerStamp = 1.001, var timesplit = timestamp.replace(',', ':').split(':'); return (parseInt(timesplit[0], 10) * 3600 + parseInt(timesplit[1], 10) * 60 + parseInt(timesplit[2], 10) + parseInt(timesplit[3], 10) / 1000) * 1000 * 1000; }
javascript
function(timestamp) { if (!timestamp) { return; } //TODO check this //var secondsPerStamp = 1.001, var timesplit = timestamp.replace(',', ':').split(':'); return (parseInt(timesplit[0], 10) * 3600 + parseInt(timesplit[1], 10) * 60 + parseInt(timesplit[2], 10) + parseInt(timesplit[3], 10) / 1000) * 1000 * 1000; }
[ "function", "(", "timestamp", ")", "{", "if", "(", "!", "timestamp", ")", "{", "return", ";", "}", "var", "timesplit", "=", "timestamp", ".", "replace", "(", "','", ",", "':'", ")", ".", "split", "(", "':'", ")", ";", "return", "(", "parseInt", "(", "timesplit", "[", "0", "]", ",", "10", ")", "*", "3600", "+", "parseInt", "(", "timesplit", "[", "1", "]", ",", "10", ")", "*", "60", "+", "parseInt", "(", "timesplit", "[", "2", "]", ",", "10", ")", "+", "parseInt", "(", "timesplit", "[", "3", "]", ",", "10", ")", "/", "1000", ")", "*", "1000", "*", "1000", ";", "}" ]
translates timestamp to microseconds @function @param {string} timestamp - string timestamp from srt file @public
[ "translates", "timestamp", "to", "microseconds" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L190-L202
train
jasonrojas/node-captions
lib/srt.js
function(text) { return macros.cleanMacros(text.replace(/\n/g, '{break}').replace(/<i>/g, '{italic}').replace(/<\/i>/g, '{end-italic}')); }
javascript
function(text) { return macros.cleanMacros(text.replace(/\n/g, '{break}').replace(/<i>/g, '{italic}').replace(/<\/i>/g, '{end-italic}')); }
[ "function", "(", "text", ")", "{", "return", "macros", ".", "cleanMacros", "(", "text", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'{break}'", ")", ".", "replace", "(", "/", "<i>", "/", "g", ",", "'{italic}'", ")", ".", "replace", "(", "/", "<\\/i>", "/", "g", ",", "'{end-italic}'", ")", ")", ";", "}" ]
converts SRT stylings to macros @function @param {string} text - text to render macros for @public
[ "converts", "SRT", "stylings", "to", "macros" ]
4b7fd97dd36ea14bff393781f1d609644bcd61a3
https://github.com/jasonrojas/node-captions/blob/4b7fd97dd36ea14bff393781f1d609644bcd61a3/lib/srt.js#L209-L211
train
raveljs/ravel
lib/util/redis_session_store.js
finishBasicPromise
function finishBasicPromise (resolve, reject) { return (err, res) => { if (err) { return reject(err); } else { return resolve(res); } }; }
javascript
function finishBasicPromise (resolve, reject) { return (err, res) => { if (err) { return reject(err); } else { return resolve(res); } }; }
[ "function", "finishBasicPromise", "(", "resolve", ",", "reject", ")", "{", "return", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "else", "{", "return", "resolve", "(", "res", ")", ";", "}", "}", ";", "}" ]
Shorthand for adapting callbacks to `Promise`s. @param {Function} resolve - A resolve function. @param {Function} reject - A reject function. @private
[ "Shorthand", "for", "adapting", "callbacks", "to", "Promise", "s", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/util/redis_session_store.js#L13-L21
train
raveljs/ravel
lib/core/routes.js
initRoutes
function initRoutes (ravelInstance, koaRouter) { const proto = Object.getPrototypeOf(this); // handle class-level @mapping decorators const classMeta = Metadata.getClassMeta(proto, '@mapping', Object.create(null)); for (const r of Object.keys(classMeta)) { buildRoute(ravelInstance, this, koaRouter, r, classMeta[r]); } // handle methods decorated with @mapping const meta = Metadata.getMeta(proto).method; const annotatedMethods = Object.keys(meta); for (const r of annotatedMethods) { const methodMeta = Metadata.getMethodMetaValue(proto, r, '@mapping', 'info'); if (methodMeta) { buildRoute(ravelInstance, this, koaRouter, r, methodMeta); } } }
javascript
function initRoutes (ravelInstance, koaRouter) { const proto = Object.getPrototypeOf(this); // handle class-level @mapping decorators const classMeta = Metadata.getClassMeta(proto, '@mapping', Object.create(null)); for (const r of Object.keys(classMeta)) { buildRoute(ravelInstance, this, koaRouter, r, classMeta[r]); } // handle methods decorated with @mapping const meta = Metadata.getMeta(proto).method; const annotatedMethods = Object.keys(meta); for (const r of annotatedMethods) { const methodMeta = Metadata.getMethodMetaValue(proto, r, '@mapping', 'info'); if (methodMeta) { buildRoute(ravelInstance, this, koaRouter, r, methodMeta); } } }
[ "function", "initRoutes", "(", "ravelInstance", ",", "koaRouter", ")", "{", "const", "proto", "=", "Object", ".", "getPrototypeOf", "(", "this", ")", ";", "const", "classMeta", "=", "Metadata", ".", "getClassMeta", "(", "proto", ",", "'@mapping'", ",", "Object", ".", "create", "(", "null", ")", ")", ";", "for", "(", "const", "r", "of", "Object", ".", "keys", "(", "classMeta", ")", ")", "{", "buildRoute", "(", "ravelInstance", ",", "this", ",", "koaRouter", ",", "r", ",", "classMeta", "[", "r", "]", ")", ";", "}", "const", "meta", "=", "Metadata", ".", "getMeta", "(", "proto", ")", ".", "method", ";", "const", "annotatedMethods", "=", "Object", ".", "keys", "(", "meta", ")", ";", "for", "(", "const", "r", "of", "annotatedMethods", ")", "{", "const", "methodMeta", "=", "Metadata", ".", "getMethodMetaValue", "(", "proto", ",", "r", ",", "'@mapping'", ",", "'info'", ")", ";", "if", "(", "methodMeta", ")", "{", "buildRoute", "(", "ravelInstance", ",", "this", ",", "koaRouter", ",", "r", ",", "methodMeta", ")", ";", "}", "}", "}" ]
Initializer for this `Routes` class. @param {Ravel} ravelInstance - Instance of a Ravel app. @param {Object} koaRouter - Instance of koa-router. @private
[ "Initializer", "for", "this", "Routes", "class", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/core/routes.js#L141-L158
train
appcues/snabbdom-virtualize
src/nodes.js
getClasses
function getClasses(element) { const className = element.className; const classes = {}; if (className !== null && className.length > 0) { className.split(' ').forEach((className) => { if (className.trim().length) { classes[className.trim()] = true; } }); } return classes; }
javascript
function getClasses(element) { const className = element.className; const classes = {}; if (className !== null && className.length > 0) { className.split(' ').forEach((className) => { if (className.trim().length) { classes[className.trim()] = true; } }); } return classes; }
[ "function", "getClasses", "(", "element", ")", "{", "const", "className", "=", "element", ".", "className", ";", "const", "classes", "=", "{", "}", ";", "if", "(", "className", "!==", "null", "&&", "className", ".", "length", ">", "0", ")", "{", "className", ".", "split", "(", "' '", ")", ".", "forEach", "(", "(", "className", ")", "=>", "{", "if", "(", "className", ".", "trim", "(", ")", ".", "length", ")", "{", "classes", "[", "className", ".", "trim", "(", ")", "]", "=", "true", ";", "}", "}", ")", ";", "}", "return", "classes", ";", "}" ]
Builds the class object for the VNode.
[ "Builds", "the", "class", "object", "for", "the", "VNode", "." ]
f3fd12de0911ed575751e5c13f94c3ffc6d795c4
https://github.com/appcues/snabbdom-virtualize/blob/f3fd12de0911ed575751e5c13f94c3ffc6d795c4/src/nodes.js#L85-L96
train
appcues/snabbdom-virtualize
src/nodes.js
getStyle
function getStyle(element) { const style = element.style; const styles = {}; for (let i = 0; i < style.length; i++) { const name = style.item(i); const transformedName = transformName(name); styles[transformedName] = style.getPropertyValue(name); } return styles; }
javascript
function getStyle(element) { const style = element.style; const styles = {}; for (let i = 0; i < style.length; i++) { const name = style.item(i); const transformedName = transformName(name); styles[transformedName] = style.getPropertyValue(name); } return styles; }
[ "function", "getStyle", "(", "element", ")", "{", "const", "style", "=", "element", ".", "style", ";", "const", "styles", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "style", ".", "length", ";", "i", "++", ")", "{", "const", "name", "=", "style", ".", "item", "(", "i", ")", ";", "const", "transformedName", "=", "transformName", "(", "name", ")", ";", "styles", "[", "transformedName", "]", "=", "style", ".", "getPropertyValue", "(", "name", ")", ";", "}", "return", "styles", ";", "}" ]
Builds the style object for the VNode.
[ "Builds", "the", "style", "object", "for", "the", "VNode", "." ]
f3fd12de0911ed575751e5c13f94c3ffc6d795c4
https://github.com/appcues/snabbdom-virtualize/blob/f3fd12de0911ed575751e5c13f94c3ffc6d795c4/src/nodes.js#L99-L108
train
raveljs/ravel
lib/core/params.js
function (value) { const IllegalValue = this.$err.IllegalValue; if (typeof value !== 'string') { return value; } const result = value.replace(ENVVAR_PATTERN, function () { const varname = arguments[1]; if (process.env[varname] === undefined) { throw new IllegalValue(`Environment variable ${varname} was referenced but not set`); } return process.env[varname]; }); return result; }
javascript
function (value) { const IllegalValue = this.$err.IllegalValue; if (typeof value !== 'string') { return value; } const result = value.replace(ENVVAR_PATTERN, function () { const varname = arguments[1]; if (process.env[varname] === undefined) { throw new IllegalValue(`Environment variable ${varname} was referenced but not set`); } return process.env[varname]; }); return result; }
[ "function", "(", "value", ")", "{", "const", "IllegalValue", "=", "this", ".", "$err", ".", "IllegalValue", ";", "if", "(", "typeof", "value", "!==", "'string'", ")", "{", "return", "value", ";", "}", "const", "result", "=", "value", ".", "replace", "(", "ENVVAR_PATTERN", ",", "function", "(", ")", "{", "const", "varname", "=", "arguments", "[", "1", "]", ";", "if", "(", "process", ".", "env", "[", "varname", "]", "===", "undefined", ")", "{", "throw", "new", "IllegalValue", "(", "`", "${", "varname", "}", "`", ")", ";", "}", "return", "process", ".", "env", "[", "varname", "]", ";", "}", ")", ";", "return", "result", ";", "}" ]
Interpolates config values with the values of the environment variables of the process. @private @param {any} value - The value specified for a parameter; possibly an environment variable.
[ "Interpolates", "config", "values", "with", "the", "values", "of", "the", "environment", "variables", "of", "the", "process", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/core/params.js#L30-L44
train
duereg/normalize-object
src/normalize-object.js
normalize
function normalize(obj, caseType = 'camel') { let ret = obj; const method = methods[caseType]; if (Array.isArray(obj)) { ret = []; let i = 0; while (i < obj.length) { ret.push(normalize(obj[i], caseType)); ++i; } } else if (isPlainObject(obj)) { ret = {}; // eslint-disable-next-line guard-for-in, no-restricted-syntax for (const k in obj) { ret[method(k)] = normalize(obj[k], caseType); } } return ret; }
javascript
function normalize(obj, caseType = 'camel') { let ret = obj; const method = methods[caseType]; if (Array.isArray(obj)) { ret = []; let i = 0; while (i < obj.length) { ret.push(normalize(obj[i], caseType)); ++i; } } else if (isPlainObject(obj)) { ret = {}; // eslint-disable-next-line guard-for-in, no-restricted-syntax for (const k in obj) { ret[method(k)] = normalize(obj[k], caseType); } } return ret; }
[ "function", "normalize", "(", "obj", ",", "caseType", "=", "'camel'", ")", "{", "let", "ret", "=", "obj", ";", "const", "method", "=", "methods", "[", "caseType", "]", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "ret", "=", "[", "]", ";", "let", "i", "=", "0", ";", "while", "(", "i", "<", "obj", ".", "length", ")", "{", "ret", ".", "push", "(", "normalize", "(", "obj", "[", "i", "]", ",", "caseType", ")", ")", ";", "++", "i", ";", "}", "}", "else", "if", "(", "isPlainObject", "(", "obj", ")", ")", "{", "ret", "=", "{", "}", ";", "for", "(", "const", "k", "in", "obj", ")", "{", "ret", "[", "method", "(", "k", ")", "]", "=", "normalize", "(", "obj", "[", "k", "]", ",", "caseType", ")", ";", "}", "}", "return", "ret", ";", "}" ]
Normalize all keys of `obj` recursively. @param {Object} obj to normalize @param {String} caseType type of case to convert object to @return {Object} @api public
[ "Normalize", "all", "keys", "of", "obj", "recursively", "." ]
21768211e549b3b85f1a9432d79692738c590ef5
https://github.com/duereg/normalize-object/blob/21768211e549b3b85f1a9432d79692738c590ef5/src/normalize-object.js#L17-L38
train
raveljs/ravel
lib/core/module.js
connectHandlers
function connectHandlers (decorator, event) { const handlers = Metadata.getClassMeta(Object.getPrototypeOf(self), decorator, Object.create(null)); for (const f of Object.keys(handlers)) { ravelInstance.once(event, (...args) => { ravelInstance.$log.trace(`${name}: Invoking ${decorator} ${f}`); handlers[f].apply(self, args); }); } }
javascript
function connectHandlers (decorator, event) { const handlers = Metadata.getClassMeta(Object.getPrototypeOf(self), decorator, Object.create(null)); for (const f of Object.keys(handlers)) { ravelInstance.once(event, (...args) => { ravelInstance.$log.trace(`${name}: Invoking ${decorator} ${f}`); handlers[f].apply(self, args); }); } }
[ "function", "connectHandlers", "(", "decorator", ",", "event", ")", "{", "const", "handlers", "=", "Metadata", ".", "getClassMeta", "(", "Object", ".", "getPrototypeOf", "(", "self", ")", ",", "decorator", ",", "Object", ".", "create", "(", "null", ")", ")", ";", "for", "(", "const", "f", "of", "Object", ".", "keys", "(", "handlers", ")", ")", "{", "ravelInstance", ".", "once", "(", "event", ",", "(", "...", "args", ")", "=>", "{", "ravelInstance", ".", "$log", ".", "trace", "(", "`", "${", "name", "}", "${", "decorator", "}", "${", "f", "}", "`", ")", ";", "handlers", "[", "f", "]", ".", "apply", "(", "self", ",", "args", ")", ";", "}", ")", ";", "}", "}" ]
connect any Ravel lifecycle handlers to the appropriate events
[ "connect", "any", "Ravel", "lifecycle", "handlers", "to", "the", "appropriate", "events" ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/core/module.js#L21-L29
train
apathetic/scrollify
dist/scrollify.es6.js
translateX
function translateX(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var offset = (to - from) * progress + from; this.transforms.position[0] = offset; }
javascript
function translateX(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var offset = (to - from) * progress + from; this.transforms.position[0] = offset; }
[ "function", "translateX", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "0", ";", "var", "from", "=", "(", "this", ".", "options", ".", "from", "!==", "undefined", ")", "?", "this", ".", "options", ".", "from", ":", "0", ";", "var", "offset", "=", "(", "to", "-", "from", ")", "*", "progress", "+", "from", ";", "this", ".", "transforms", ".", "position", "[", "0", "]", "=", "offset", ";", "}" ]
Translate an element along the X-axis. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Translate", "an", "element", "along", "the", "X", "-", "axis", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L656-L662
train
apathetic/scrollify
dist/scrollify.es6.js
scale
function scale(progress) { var to = (this.options.to !== undefined) ? this.options.to : 1; var from = (this.options.from !== undefined) ? this.options.from : this.transforms.scale[0]; var scale = (to - from) * progress + from; this.transforms.scale[0] = scale; this.transforms.scale[1] = scale; }
javascript
function scale(progress) { var to = (this.options.to !== undefined) ? this.options.to : 1; var from = (this.options.from !== undefined) ? this.options.from : this.transforms.scale[0]; var scale = (to - from) * progress + from; this.transforms.scale[0] = scale; this.transforms.scale[1] = scale; }
[ "function", "scale", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "1", ";", "var", "from", "=", "(", "this", ".", "options", ".", "from", "!==", "undefined", ")", "?", "this", ".", "options", ".", "from", ":", "this", ".", "transforms", ".", "scale", "[", "0", "]", ";", "var", "scale", "=", "(", "to", "-", "from", ")", "*", "progress", "+", "from", ";", "this", ".", "transforms", ".", "scale", "[", "0", "]", "=", "scale", ";", "this", ".", "transforms", ".", "scale", "[", "1", "]", "=", "scale", ";", "}" ]
Uniformly scale an element along both axis'. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Uniformly", "scale", "an", "element", "along", "both", "axis", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L706-L713
train
apathetic/scrollify
dist/scrollify.es6.js
fade
function fade(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 1; var opacity = (to - from) * progress + from; this.element.style.opacity = opacity; }
javascript
function fade(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 1; var opacity = (to - from) * progress + from; this.element.style.opacity = opacity; }
[ "function", "fade", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "0", ";", "var", "from", "=", "(", "this", ".", "options", ".", "from", "!==", "undefined", ")", "?", "this", ".", "options", ".", "from", ":", "1", ";", "var", "opacity", "=", "(", "to", "-", "from", ")", "*", "progress", "+", "from", ";", "this", ".", "element", ".", "style", ".", "opacity", "=", "opacity", ";", "}" ]
Update an element's opacity. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Update", "an", "element", "s", "opacity", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L721-L727
train
apathetic/scrollify
dist/scrollify.es6.js
blur
function blur(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var amount = (to - from) * progress + from; this.element.style.filter = 'blur(' + amount + 'px)'; }
javascript
function blur(progress) { var to = (this.options.to !== undefined) ? this.options.to : 0; var from = (this.options.from !== undefined) ? this.options.from : 0; var amount = (to - from) * progress + from; this.element.style.filter = 'blur(' + amount + 'px)'; }
[ "function", "blur", "(", "progress", ")", "{", "var", "to", "=", "(", "this", ".", "options", ".", "to", "!==", "undefined", ")", "?", "this", ".", "options", ".", "to", ":", "0", ";", "var", "from", "=", "(", "this", ".", "options", ".", "from", "!==", "undefined", ")", "?", "this", ".", "options", ".", "from", ":", "0", ";", "var", "amount", "=", "(", "to", "-", "from", ")", "*", "progress", "+", "from", ";", "this", ".", "element", ".", "style", ".", "filter", "=", "'blur('", "+", "amount", "+", "'px)'", ";", "}" ]
Update an element's blur. @param {Float} progress Current progress of the scene, between 0 and 1. @this {Object} @return {void}
[ "Update", "an", "element", "s", "blur", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L735-L741
train
apathetic/scrollify
dist/scrollify.es6.js
parallax
function parallax(progress) { var range = this.options.range || 0; var offset = progress * range; // TODO add provision for speed as well this.transforms.position[1] = offset; // just vertical for now }
javascript
function parallax(progress) { var range = this.options.range || 0; var offset = progress * range; // TODO add provision for speed as well this.transforms.position[1] = offset; // just vertical for now }
[ "function", "parallax", "(", "progress", ")", "{", "var", "range", "=", "this", ".", "options", ".", "range", "||", "0", ";", "var", "offset", "=", "progress", "*", "range", ";", "this", ".", "transforms", ".", "position", "[", "1", "]", "=", "offset", ";", "}" ]
Parallax an element. @param {Float} progress Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Parallax", "an", "element", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L749-L754
train
apathetic/scrollify
dist/scrollify.es6.js
toggle
function toggle(progress) { var opts = this.options; var element = this.element; var times = Object.keys(opts); times.forEach(function(time) { var css = opts[time]; if (progress > time) { element.classList.add(css); } else { element.classList.remove(css); } }); }
javascript
function toggle(progress) { var opts = this.options; var element = this.element; var times = Object.keys(opts); times.forEach(function(time) { var css = opts[time]; if (progress > time) { element.classList.add(css); } else { element.classList.remove(css); } }); }
[ "function", "toggle", "(", "progress", ")", "{", "var", "opts", "=", "this", ".", "options", ";", "var", "element", "=", "this", ".", "element", ";", "var", "times", "=", "Object", ".", "keys", "(", "opts", ")", ";", "times", ".", "forEach", "(", "function", "(", "time", ")", "{", "var", "css", "=", "opts", "[", "time", "]", ";", "if", "(", "progress", ">", "time", ")", "{", "element", ".", "classList", ".", "add", "(", "css", ")", ";", "}", "else", "{", "element", ".", "classList", ".", "remove", "(", "css", ")", ";", "}", "}", ")", ";", "}" ]
Toggle a class on or off. @param {Float} progress: Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
[ "Toggle", "a", "class", "on", "or", "off", "." ]
9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45
https://github.com/apathetic/scrollify/blob/9aa7b5405f65d0e2cf15e648d647a56f9c4f2d45/dist/scrollify.es6.js#L762-L776
train
bpmn-io/bpmn-questionnaire
lib/components/Diagram.js
Diagram
function Diagram(index, options, question) { this.index = index; this.options = options; this.question = question; this.element = createElement(h('li.list-group-item', { style: { width: '100%', height: '500px' } })); this.viewer; if (options.xml) { // Load XML this.xml = options.xml; } else if (options.url) { var that = this; // Load XML via AJAX var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { that.xml = xhr.responseText; } }; xhr.open("GET", options.url, true); xhr.send(); } else { throw new Error('Unable to load diagram, no resource specified'); } this.initState = Immutable({ selected: [] }); this.state = this.initState.asMutable({deep: true}); }
javascript
function Diagram(index, options, question) { this.index = index; this.options = options; this.question = question; this.element = createElement(h('li.list-group-item', { style: { width: '100%', height: '500px' } })); this.viewer; if (options.xml) { // Load XML this.xml = options.xml; } else if (options.url) { var that = this; // Load XML via AJAX var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { that.xml = xhr.responseText; } }; xhr.open("GET", options.url, true); xhr.send(); } else { throw new Error('Unable to load diagram, no resource specified'); } this.initState = Immutable({ selected: [] }); this.state = this.initState.asMutable({deep: true}); }
[ "function", "Diagram", "(", "index", ",", "options", ",", "question", ")", "{", "this", ".", "index", "=", "index", ";", "this", ".", "options", "=", "options", ";", "this", ".", "question", "=", "question", ";", "this", ".", "element", "=", "createElement", "(", "h", "(", "'li.list-group-item'", ",", "{", "style", ":", "{", "width", ":", "'100%'", ",", "height", ":", "'500px'", "}", "}", ")", ")", ";", "this", ".", "viewer", ";", "if", "(", "options", ".", "xml", ")", "{", "this", ".", "xml", "=", "options", ".", "xml", ";", "}", "else", "if", "(", "options", ".", "url", ")", "{", "var", "that", "=", "this", ";", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "==", "4", "&&", "xhr", ".", "status", "==", "200", ")", "{", "that", ".", "xml", "=", "xhr", ".", "responseText", ";", "}", "}", ";", "xhr", ".", "open", "(", "\"GET\"", ",", "options", ".", "url", ",", "true", ")", ";", "xhr", ".", "send", "(", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unable to load diagram, no resource specified'", ")", ";", "}", "this", ".", "initState", "=", "Immutable", "(", "{", "selected", ":", "[", "]", "}", ")", ";", "this", ".", "state", "=", "this", ".", "initState", ".", "asMutable", "(", "{", "deep", ":", "true", "}", ")", ";", "}" ]
Diagram component. @param {number} index - Index of question. @param {Object} options - Options. @param {Object} question - Reference to the Question instance.
[ "Diagram", "component", "." ]
1f4dc63272f99a491a7ce2a5db7c1d56c3e82132
https://github.com/bpmn-io/bpmn-questionnaire/blob/1f4dc63272f99a491a7ce2a5db7c1d56c3e82132/lib/components/Diagram.js#L25-L73
train
raveljs/ravel
lib/util/kvstore.js
createClient
function createClient (ravelInstance, restrict = true) { const localRedis = ravelInstance.get('redis port') === undefined || ravelInstance.get('redis host') === undefined; ravelInstance.on('post init', () => { ravelInstance.$log.info(localRedis ? 'Using in-memory key-value store. Please do not scale this app horizontally.' : `Using redis at ${ravelInstance.get('redis host')}:${ravelInstance.get('redis port')}`); }); let client; if (localRedis) { const mock = require('redis-mock'); mock.removeAllListeners(); // redis-mock doesn't clean up after itself very well. client = mock.createClient(); client.flushall(); // in case this has been required before } else { client = redis.createClient( ravelInstance.get('redis port'), ravelInstance.get('redis host'), { 'no_ready_check': true, 'retry_strategy': retryStrategy(ravelInstance) }); } if (ravelInstance.get('redis password')) { client.auth(ravelInstance.get('redis password')); } // log errors client.on('error', ravelInstance.$log.error); // keepalive when not testing const redisKeepaliveInterval = setInterval(() => { client && client.ping && client.ping(); }, ravelInstance.get('redis keepalive interval')); ravelInstance.once('end', () => { clearInterval(redisKeepaliveInterval); }); if (restrict) { disable(client, 'quit'); disable(client, 'subscribe'); disable(client, 'psubscribe'); disable(client, 'unsubscribe'); disable(client, 'punsubscribe'); } else { const origQuit = client.quit; client.quit = function (...args) { clearInterval(redisKeepaliveInterval); return origQuit.apply(client, args); }; } client.clone = function () { return createClient(ravelInstance, false); }; return client; }
javascript
function createClient (ravelInstance, restrict = true) { const localRedis = ravelInstance.get('redis port') === undefined || ravelInstance.get('redis host') === undefined; ravelInstance.on('post init', () => { ravelInstance.$log.info(localRedis ? 'Using in-memory key-value store. Please do not scale this app horizontally.' : `Using redis at ${ravelInstance.get('redis host')}:${ravelInstance.get('redis port')}`); }); let client; if (localRedis) { const mock = require('redis-mock'); mock.removeAllListeners(); // redis-mock doesn't clean up after itself very well. client = mock.createClient(); client.flushall(); // in case this has been required before } else { client = redis.createClient( ravelInstance.get('redis port'), ravelInstance.get('redis host'), { 'no_ready_check': true, 'retry_strategy': retryStrategy(ravelInstance) }); } if (ravelInstance.get('redis password')) { client.auth(ravelInstance.get('redis password')); } // log errors client.on('error', ravelInstance.$log.error); // keepalive when not testing const redisKeepaliveInterval = setInterval(() => { client && client.ping && client.ping(); }, ravelInstance.get('redis keepalive interval')); ravelInstance.once('end', () => { clearInterval(redisKeepaliveInterval); }); if (restrict) { disable(client, 'quit'); disable(client, 'subscribe'); disable(client, 'psubscribe'); disable(client, 'unsubscribe'); disable(client, 'punsubscribe'); } else { const origQuit = client.quit; client.quit = function (...args) { clearInterval(redisKeepaliveInterval); return origQuit.apply(client, args); }; } client.clone = function () { return createClient(ravelInstance, false); }; return client; }
[ "function", "createClient", "(", "ravelInstance", ",", "restrict", "=", "true", ")", "{", "const", "localRedis", "=", "ravelInstance", ".", "get", "(", "'redis port'", ")", "===", "undefined", "||", "ravelInstance", ".", "get", "(", "'redis host'", ")", "===", "undefined", ";", "ravelInstance", ".", "on", "(", "'post init'", ",", "(", ")", "=>", "{", "ravelInstance", ".", "$log", ".", "info", "(", "localRedis", "?", "'Using in-memory key-value store. Please do not scale this app horizontally.'", ":", "`", "${", "ravelInstance", ".", "get", "(", "'redis host'", ")", "}", "${", "ravelInstance", ".", "get", "(", "'redis port'", ")", "}", "`", ")", ";", "}", ")", ";", "let", "client", ";", "if", "(", "localRedis", ")", "{", "const", "mock", "=", "require", "(", "'redis-mock'", ")", ";", "mock", ".", "removeAllListeners", "(", ")", ";", "client", "=", "mock", ".", "createClient", "(", ")", ";", "client", ".", "flushall", "(", ")", ";", "}", "else", "{", "client", "=", "redis", ".", "createClient", "(", "ravelInstance", ".", "get", "(", "'redis port'", ")", ",", "ravelInstance", ".", "get", "(", "'redis host'", ")", ",", "{", "'no_ready_check'", ":", "true", ",", "'retry_strategy'", ":", "retryStrategy", "(", "ravelInstance", ")", "}", ")", ";", "}", "if", "(", "ravelInstance", ".", "get", "(", "'redis password'", ")", ")", "{", "client", ".", "auth", "(", "ravelInstance", ".", "get", "(", "'redis password'", ")", ")", ";", "}", "client", ".", "on", "(", "'error'", ",", "ravelInstance", ".", "$log", ".", "error", ")", ";", "const", "redisKeepaliveInterval", "=", "setInterval", "(", "(", ")", "=>", "{", "client", "&&", "client", ".", "ping", "&&", "client", ".", "ping", "(", ")", ";", "}", ",", "ravelInstance", ".", "get", "(", "'redis keepalive interval'", ")", ")", ";", "ravelInstance", ".", "once", "(", "'end'", ",", "(", ")", "=>", "{", "clearInterval", "(", "redisKeepaliveInterval", ")", ";", "}", ")", ";", "if", "(", "restrict", ")", "{", "disable", "(", "client", ",", "'quit'", ")", ";", "disable", "(", "client", ",", "'subscribe'", ")", ";", "disable", "(", "client", ",", "'psubscribe'", ")", ";", "disable", "(", "client", ",", "'unsubscribe'", ")", ";", "disable", "(", "client", ",", "'punsubscribe'", ")", ";", "}", "else", "{", "const", "origQuit", "=", "client", ".", "quit", ";", "client", ".", "quit", "=", "function", "(", "...", "args", ")", "{", "clearInterval", "(", "redisKeepaliveInterval", ")", ";", "return", "origQuit", ".", "apply", "(", "client", ",", "args", ")", ";", "}", ";", "}", "client", ".", "clone", "=", "function", "(", ")", "{", "return", "createClient", "(", "ravelInstance", ",", "false", ")", ";", "}", ";", "return", "client", ";", "}" ]
Returns a fresh connection to Redis. @param {Ravel} ravelInstance - An instance of a Ravel app. @param {boolean} restrict - Iff true, disable `exit`, `subcribe`, `psubscribe`, `unsubscribe` and `punsubscribe`. @returns {Object} Returns a fresh connection to Redis. @private
[ "Returns", "a", "fresh", "connection", "to", "Redis", "." ]
f2a03283479c94443cf94cd00d9ac720645e05fc
https://github.com/raveljs/ravel/blob/f2a03283479c94443cf94cd00d9ac720645e05fc/lib/util/kvstore.js#L52-L107
train
bpmn-io/bpmn-questionnaire
lib/BpmnQuestionnaire.js
BpmnQuestionnaire
function BpmnQuestionnaire(options) { // Check if options was provided if (!options) { throw new Error('No options provided'); } if (has(options, 'questionnaireJson')) { this.questionnaireJson = options.questionnaireJson; } else { // Report error throw new Error('No questionnaire specified'); } // Events this.events = new EventEmitter(); // Services this.services = { translator: (function(){ var translator; if(has(options, 'plugins.translator')) { // translator = new Translator(options.plugins.translator) translator = new Translator(options.plugins.translator); } else { translator = new Translator(); } return translator.translate.bind(translator); }()) } // Check if types were provided if (options.types) { this.types = options.types; } // Check if questions were provided if (this.questionnaireJson.questions.length) { this.questions = []; var that = this; // Create questions this.questionnaireJson.questions.forEach(function(question, index) { // Check if type of question was provided if (!typeof that.types[question.type] === 'function') { // Report error throw new Error('Type not specified'); } else { // Add instance of question to array of questions that.questions.push( new that.types[question.type](index, question, that) ); } }); } else { // Report error throw new Error('No questions specified'); } // Initial state is immutable this.initState = Immutable({ currentQuestion: 0, progress: 0, view: 'intro' }); // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); // Set up loop this.loop = mainLoop(this.state, this.render.bind(this), { create: require("virtual-dom/create-element"), diff: require("virtual-dom/diff"), patch: require("virtual-dom/patch") }); // Check if container element was specified if (!options.container) { throw new Error('No container element specified'); } // Append questionnaire to container element if (typeof options.container === 'string') { // Search for element with given ID var container = document.getElementById(options.container); // Error handling if (!container) { throw new Error('Container element not found'); } this.container = container; } else if (options.container.appendChild) { // Append questionnaire this.container = options.container; } else { throw new Error('Container element not found'); } // Append questionnaire this.container.appendChild(this.loop.target); }
javascript
function BpmnQuestionnaire(options) { // Check if options was provided if (!options) { throw new Error('No options provided'); } if (has(options, 'questionnaireJson')) { this.questionnaireJson = options.questionnaireJson; } else { // Report error throw new Error('No questionnaire specified'); } // Events this.events = new EventEmitter(); // Services this.services = { translator: (function(){ var translator; if(has(options, 'plugins.translator')) { // translator = new Translator(options.plugins.translator) translator = new Translator(options.plugins.translator); } else { translator = new Translator(); } return translator.translate.bind(translator); }()) } // Check if types were provided if (options.types) { this.types = options.types; } // Check if questions were provided if (this.questionnaireJson.questions.length) { this.questions = []; var that = this; // Create questions this.questionnaireJson.questions.forEach(function(question, index) { // Check if type of question was provided if (!typeof that.types[question.type] === 'function') { // Report error throw new Error('Type not specified'); } else { // Add instance of question to array of questions that.questions.push( new that.types[question.type](index, question, that) ); } }); } else { // Report error throw new Error('No questions specified'); } // Initial state is immutable this.initState = Immutable({ currentQuestion: 0, progress: 0, view: 'intro' }); // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); // Set up loop this.loop = mainLoop(this.state, this.render.bind(this), { create: require("virtual-dom/create-element"), diff: require("virtual-dom/diff"), patch: require("virtual-dom/patch") }); // Check if container element was specified if (!options.container) { throw new Error('No container element specified'); } // Append questionnaire to container element if (typeof options.container === 'string') { // Search for element with given ID var container = document.getElementById(options.container); // Error handling if (!container) { throw new Error('Container element not found'); } this.container = container; } else if (options.container.appendChild) { // Append questionnaire this.container = options.container; } else { throw new Error('Container element not found'); } // Append questionnaire this.container.appendChild(this.loop.target); }
[ "function", "BpmnQuestionnaire", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "throw", "new", "Error", "(", "'No options provided'", ")", ";", "}", "if", "(", "has", "(", "options", ",", "'questionnaireJson'", ")", ")", "{", "this", ".", "questionnaireJson", "=", "options", ".", "questionnaireJson", ";", "}", "else", "{", "throw", "new", "Error", "(", "'No questionnaire specified'", ")", ";", "}", "this", ".", "events", "=", "new", "EventEmitter", "(", ")", ";", "this", ".", "services", "=", "{", "translator", ":", "(", "function", "(", ")", "{", "var", "translator", ";", "if", "(", "has", "(", "options", ",", "'plugins.translator'", ")", ")", "{", "translator", "=", "new", "Translator", "(", "options", ".", "plugins", ".", "translator", ")", ";", "}", "else", "{", "translator", "=", "new", "Translator", "(", ")", ";", "}", "return", "translator", ".", "translate", ".", "bind", "(", "translator", ")", ";", "}", "(", ")", ")", "}", "if", "(", "options", ".", "types", ")", "{", "this", ".", "types", "=", "options", ".", "types", ";", "}", "if", "(", "this", ".", "questionnaireJson", ".", "questions", ".", "length", ")", "{", "this", ".", "questions", "=", "[", "]", ";", "var", "that", "=", "this", ";", "this", ".", "questionnaireJson", ".", "questions", ".", "forEach", "(", "function", "(", "question", ",", "index", ")", "{", "if", "(", "!", "typeof", "that", ".", "types", "[", "question", ".", "type", "]", "===", "'function'", ")", "{", "throw", "new", "Error", "(", "'Type not specified'", ")", ";", "}", "else", "{", "that", ".", "questions", ".", "push", "(", "new", "that", ".", "types", "[", "question", ".", "type", "]", "(", "index", ",", "question", ",", "that", ")", ")", ";", "}", "}", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'No questions specified'", ")", ";", "}", "this", ".", "initState", "=", "Immutable", "(", "{", "currentQuestion", ":", "0", ",", "progress", ":", "0", ",", "view", ":", "'intro'", "}", ")", ";", "this", ".", "state", "=", "this", ".", "initState", ".", "asMutable", "(", "{", "deep", ":", "true", "}", ")", ";", "this", ".", "loop", "=", "mainLoop", "(", "this", ".", "state", ",", "this", ".", "render", ".", "bind", "(", "this", ")", ",", "{", "create", ":", "require", "(", "\"virtual-dom/create-element\"", ")", ",", "diff", ":", "require", "(", "\"virtual-dom/diff\"", ")", ",", "patch", ":", "require", "(", "\"virtual-dom/patch\"", ")", "}", ")", ";", "if", "(", "!", "options", ".", "container", ")", "{", "throw", "new", "Error", "(", "'No container element specified'", ")", ";", "}", "if", "(", "typeof", "options", ".", "container", "===", "'string'", ")", "{", "var", "container", "=", "document", ".", "getElementById", "(", "options", ".", "container", ")", ";", "if", "(", "!", "container", ")", "{", "throw", "new", "Error", "(", "'Container element not found'", ")", ";", "}", "this", ".", "container", "=", "container", ";", "}", "else", "if", "(", "options", ".", "container", ".", "appendChild", ")", "{", "this", ".", "container", "=", "options", ".", "container", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Container element not found'", ")", ";", "}", "this", ".", "container", ".", "appendChild", "(", "this", ".", "loop", ".", "target", ")", ";", "}" ]
Creates a new instance of a questionnaire and appends it to a container element. @constructor @param {Object} options - Options. @param {Object} options.questionnaireJson - Questionnaire. @param {Object} options.types - Types. @param {Object|string} - options.container - Element or ID of element that's going to contain the questionnaire.
[ "Creates", "a", "new", "instance", "of", "a", "questionnaire", "and", "appends", "it", "to", "a", "container", "element", "." ]
1f4dc63272f99a491a7ce2a5db7c1d56c3e82132
https://github.com/bpmn-io/bpmn-questionnaire/blob/1f4dc63272f99a491a7ce2a5db7c1d56c3e82132/lib/BpmnQuestionnaire.js#L42-L152
train
bpmn-io/bpmn-questionnaire
lib/BpmnQuestionnaire.js
function (index, options, questionnaire) { this.index = index; this.options = options; this.questionnaire = questionnaire; if (options.diagram) { this.diagram = new Diagram(index, options.diagram, this); } // Initial state is immutable this.initState = Immutable({ validAnswer: false, rightAnswer: false, view: 'question' }); // Prevent overwriting default properties of state and assign provided properties to initial state if (has(spec, 'addToState')) { if(!has(spec.addToState, 'validAnswer') && !has(spec.addToState, 'rightAnswer') && !has(spec.addToState, 'view')) { // Merge immutable with object this.initState = this.initState.merge(spec.addToState); } } // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); }
javascript
function (index, options, questionnaire) { this.index = index; this.options = options; this.questionnaire = questionnaire; if (options.diagram) { this.diagram = new Diagram(index, options.diagram, this); } // Initial state is immutable this.initState = Immutable({ validAnswer: false, rightAnswer: false, view: 'question' }); // Prevent overwriting default properties of state and assign provided properties to initial state if (has(spec, 'addToState')) { if(!has(spec.addToState, 'validAnswer') && !has(spec.addToState, 'rightAnswer') && !has(spec.addToState, 'view')) { // Merge immutable with object this.initState = this.initState.merge(spec.addToState); } } // Set state to mutable copy of initial state this.state = this.initState.asMutable({deep: true}); }
[ "function", "(", "index", ",", "options", ",", "questionnaire", ")", "{", "this", ".", "index", "=", "index", ";", "this", ".", "options", "=", "options", ";", "this", ".", "questionnaire", "=", "questionnaire", ";", "if", "(", "options", ".", "diagram", ")", "{", "this", ".", "diagram", "=", "new", "Diagram", "(", "index", ",", "options", ".", "diagram", ",", "this", ")", ";", "}", "this", ".", "initState", "=", "Immutable", "(", "{", "validAnswer", ":", "false", ",", "rightAnswer", ":", "false", ",", "view", ":", "'question'", "}", ")", ";", "if", "(", "has", "(", "spec", ",", "'addToState'", ")", ")", "{", "if", "(", "!", "has", "(", "spec", ".", "addToState", ",", "'validAnswer'", ")", "&&", "!", "has", "(", "spec", ".", "addToState", ",", "'rightAnswer'", ")", "&&", "!", "has", "(", "spec", ".", "addToState", ",", "'view'", ")", ")", "{", "this", ".", "initState", "=", "this", ".", "initState", ".", "merge", "(", "spec", ".", "addToState", ")", ";", "}", "}", "this", ".", "state", "=", "this", ".", "initState", ".", "asMutable", "(", "{", "deep", ":", "true", "}", ")", ";", "}" ]
Contructor function that serves as a base for every type. Methods and properties defined in spec will be assigned to the prototype of this constructor. @param {number} index - Index of question inside the array of questions. @param {Object} options - Object containing the actual question. @param {Object} questionnaire - Reference to the questionnaire instance.
[ "Contructor", "function", "that", "serves", "as", "a", "base", "for", "every", "type", ".", "Methods", "and", "properties", "defined", "in", "spec", "will", "be", "assigned", "to", "the", "prototype", "of", "this", "constructor", "." ]
1f4dc63272f99a491a7ce2a5db7c1d56c3e82132
https://github.com/bpmn-io/bpmn-questionnaire/blob/1f4dc63272f99a491a7ce2a5db7c1d56c3e82132/lib/BpmnQuestionnaire.js#L360-L390
train
cmrigney/fast-xml2js
index.js
parseString
function parseString(xml, cb) { return fastxml2js.parseString(xml, function(err, data) { //So that it's asynchronous process.nextTick(function() { cb(err, data); }); }); }
javascript
function parseString(xml, cb) { return fastxml2js.parseString(xml, function(err, data) { //So that it's asynchronous process.nextTick(function() { cb(err, data); }); }); }
[ "function", "parseString", "(", "xml", ",", "cb", ")", "{", "return", "fastxml2js", ".", "parseString", "(", "xml", ",", "function", "(", "err", ",", "data", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "cb", "(", "err", ",", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Callback after xml is parsed @callback parseCallback @param {string} err Error string describing an error that occurred @param {object} obj Resulting parsed JS object Parses an XML string into a JS object @param {string} xml @param {parseCallback} cb
[ "Callback", "after", "xml", "is", "parsed" ]
65b235b04eb0af386f61c59b4fb50063142a1653
https://github.com/cmrigney/fast-xml2js/blob/65b235b04eb0af386f61c59b4fb50063142a1653/index.js#L15-L22
train
crucialfelix/supercolliderjs
src/dryads/middleware/scserver.js
_callIfFn
function _callIfFn(thing, context, properties) { return _.isFunction(thing) ? thing(context, properties) : thing; }
javascript
function _callIfFn(thing, context, properties) { return _.isFunction(thing) ? thing(context, properties) : thing; }
[ "function", "_callIfFn", "(", "thing", ",", "context", ",", "properties", ")", "{", "return", "_", ".", "isFunction", "(", "thing", ")", "?", "thing", "(", "context", ",", "properties", ")", ":", "thing", ";", "}" ]
If its a Function then call it with context and properties @private
[ "If", "its", "a", "Function", "then", "call", "it", "with", "context", "and", "properties" ]
77a26c02cf1cdfe5b86699810ab46c6c315f975c
https://github.com/crucialfelix/supercolliderjs/blob/77a26c02cf1cdfe5b86699810ab46c6c315f975c/src/dryads/middleware/scserver.js#L141-L143
train
YogaGlo/grunt-docker-compose
tasks/dockerCompose.js
servicesRunning
function servicesRunning() { var composeArgs = ['ps']; // If we're tailing just the main service's logs, then we only check that service if (service === '<%= dockerCompose.options.mainService %>') { composeArgs.push(grunt.config.get('dockerCompose.options.mainService')); } // get the stdout of docker-compose ps, store as Array, and drop the header lines. var serviceList = spawn('docker-compose', composeArgs).stdout.toString().split('\n').slice(2), upCount = 0; // if we are left with 1 line or less, then nothing is running. if (serviceList.length <= 1) { return false; } function isUp(service) { if (service.indexOf('Up') > 0) { upCount++; } } serviceList.forEach(isUp); return upCount > 0; }
javascript
function servicesRunning() { var composeArgs = ['ps']; // If we're tailing just the main service's logs, then we only check that service if (service === '<%= dockerCompose.options.mainService %>') { composeArgs.push(grunt.config.get('dockerCompose.options.mainService')); } // get the stdout of docker-compose ps, store as Array, and drop the header lines. var serviceList = spawn('docker-compose', composeArgs).stdout.toString().split('\n').slice(2), upCount = 0; // if we are left with 1 line or less, then nothing is running. if (serviceList.length <= 1) { return false; } function isUp(service) { if (service.indexOf('Up') > 0) { upCount++; } } serviceList.forEach(isUp); return upCount > 0; }
[ "function", "servicesRunning", "(", ")", "{", "var", "composeArgs", "=", "[", "'ps'", "]", ";", "if", "(", "service", "===", "'<%= dockerCompose.options.mainService %>'", ")", "{", "composeArgs", ".", "push", "(", "grunt", ".", "config", ".", "get", "(", "'dockerCompose.options.mainService'", ")", ")", ";", "}", "var", "serviceList", "=", "spawn", "(", "'docker-compose'", ",", "composeArgs", ")", ".", "stdout", ".", "toString", "(", ")", ".", "split", "(", "'\\n'", ")", ".", "\\n", "slice", ",", "(", "2", ")", ";", "upCount", "=", "0", "if", "(", "serviceList", ".", "length", "<=", "1", ")", "{", "return", "false", ";", "}", "function", "isUp", "(", "service", ")", "{", "if", "(", "service", ".", "indexOf", "(", "'Up'", ")", ">", "0", ")", "{", "upCount", "++", ";", "}", "}", "serviceList", ".", "forEach", "(", "isUp", ")", ";", "}" ]
do we have any services running?
[ "do", "we", "have", "any", "services", "running?" ]
6c7f0ab9133d2b049a3497eb05f11f83fbd8c73d
https://github.com/YogaGlo/grunt-docker-compose/blob/6c7f0ab9133d2b049a3497eb05f11f83fbd8c73d/tasks/dockerCompose.js#L253-L279
train
elo7/async-define
async-define.js
_define
function _define(/* <exports>, name, dependencies, factory */) { var // extract arguments argv = arguments, argc = argv.length, // extract arguments from function call - (exports?, name?, modules?, factory) exports = argv[argc - 4] || {}, name = argv[argc - 3] || Math.floor(new Date().getTime() * (Math.random())), // if name is undefined or falsy value we add some timestamp like to name. dependencies = argv[argc - 2] || [], factory = argv[argc - 1], // helper variables params = [], dependencies_satisfied = true, dependency_name, result, config_dependencies_iterator = 0, dependencies_iterator = 0, config_dependencies_index = -1; if (DEVELOPMENT) { _set_debug_timer(); } // config dependecies if (_define.prototype.config_dependencies && _define.prototype.config_dependencies.constructor === Array) { var config_dependencies = _define.prototype.config_dependencies || []; var config_dependencies_size = config_dependencies.length; for (; config_dependencies_iterator < config_dependencies_size; config_dependencies_iterator++) { if (name === config_dependencies[config_dependencies_iterator]) { config_dependencies_index = config_dependencies_iterator; } } if (config_dependencies_index !== -1) { config_dependencies.splice(config_dependencies_index, 1) } else { dependencies = dependencies.concat(config_dependencies); } } // find params for (; dependencies_iterator < dependencies.length; dependencies_iterator++) { dependency_name = dependencies[dependencies_iterator]; // if this dependency exists, push it to param injection if (modules.hasOwnProperty(dependency_name)) { params.push(modules[dependency_name]); } else if (dependency_name === 'exports') { params.push(exports); } else { if (argc !== 4) { // if 4 values, is reexecuting // no module found. save these arguments for future execution. define_queue[dependency_name] = define_queue[dependency_name] || []; define_queue[dependency_name].push([exports, name, dependencies, factory]); } dependencies_satisfied = false; } } // all dependencies are satisfied, so proceed if (dependencies_satisfied) { if (!modules.hasOwnProperty(name)) { // execute this module result = factory.apply(this, params); if (result) { modules[name] = result; } else { // assuming result is in exports object modules[name] = exports; } } // execute others waiting for this module while (define_queue[name] && (argv = define_queue[name].pop())) { _define.apply(this, argv); } } }
javascript
function _define(/* <exports>, name, dependencies, factory */) { var // extract arguments argv = arguments, argc = argv.length, // extract arguments from function call - (exports?, name?, modules?, factory) exports = argv[argc - 4] || {}, name = argv[argc - 3] || Math.floor(new Date().getTime() * (Math.random())), // if name is undefined or falsy value we add some timestamp like to name. dependencies = argv[argc - 2] || [], factory = argv[argc - 1], // helper variables params = [], dependencies_satisfied = true, dependency_name, result, config_dependencies_iterator = 0, dependencies_iterator = 0, config_dependencies_index = -1; if (DEVELOPMENT) { _set_debug_timer(); } // config dependecies if (_define.prototype.config_dependencies && _define.prototype.config_dependencies.constructor === Array) { var config_dependencies = _define.prototype.config_dependencies || []; var config_dependencies_size = config_dependencies.length; for (; config_dependencies_iterator < config_dependencies_size; config_dependencies_iterator++) { if (name === config_dependencies[config_dependencies_iterator]) { config_dependencies_index = config_dependencies_iterator; } } if (config_dependencies_index !== -1) { config_dependencies.splice(config_dependencies_index, 1) } else { dependencies = dependencies.concat(config_dependencies); } } // find params for (; dependencies_iterator < dependencies.length; dependencies_iterator++) { dependency_name = dependencies[dependencies_iterator]; // if this dependency exists, push it to param injection if (modules.hasOwnProperty(dependency_name)) { params.push(modules[dependency_name]); } else if (dependency_name === 'exports') { params.push(exports); } else { if (argc !== 4) { // if 4 values, is reexecuting // no module found. save these arguments for future execution. define_queue[dependency_name] = define_queue[dependency_name] || []; define_queue[dependency_name].push([exports, name, dependencies, factory]); } dependencies_satisfied = false; } } // all dependencies are satisfied, so proceed if (dependencies_satisfied) { if (!modules.hasOwnProperty(name)) { // execute this module result = factory.apply(this, params); if (result) { modules[name] = result; } else { // assuming result is in exports object modules[name] = exports; } } // execute others waiting for this module while (define_queue[name] && (argv = define_queue[name].pop())) { _define.apply(this, argv); } } }
[ "function", "_define", "(", ")", "{", "var", "argv", "=", "arguments", ",", "argc", "=", "argv", ".", "length", ",", "exports", "=", "argv", "[", "argc", "-", "4", "]", "||", "{", "}", ",", "name", "=", "argv", "[", "argc", "-", "3", "]", "||", "Math", ".", "floor", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "*", "(", "Math", ".", "random", "(", ")", ")", ")", ",", "dependencies", "=", "argv", "[", "argc", "-", "2", "]", "||", "[", "]", ",", "factory", "=", "argv", "[", "argc", "-", "1", "]", ",", "params", "=", "[", "]", ",", "dependencies_satisfied", "=", "true", ",", "dependency_name", ",", "result", ",", "config_dependencies_iterator", "=", "0", ",", "dependencies_iterator", "=", "0", ",", "config_dependencies_index", "=", "-", "1", ";", "if", "(", "DEVELOPMENT", ")", "{", "_set_debug_timer", "(", ")", ";", "}", "if", "(", "_define", ".", "prototype", ".", "config_dependencies", "&&", "_define", ".", "prototype", ".", "config_dependencies", ".", "constructor", "===", "Array", ")", "{", "var", "config_dependencies", "=", "_define", ".", "prototype", ".", "config_dependencies", "||", "[", "]", ";", "var", "config_dependencies_size", "=", "config_dependencies", ".", "length", ";", "for", "(", ";", "config_dependencies_iterator", "<", "config_dependencies_size", ";", "config_dependencies_iterator", "++", ")", "{", "if", "(", "name", "===", "config_dependencies", "[", "config_dependencies_iterator", "]", ")", "{", "config_dependencies_index", "=", "config_dependencies_iterator", ";", "}", "}", "if", "(", "config_dependencies_index", "!==", "-", "1", ")", "{", "config_dependencies", ".", "splice", "(", "config_dependencies_index", ",", "1", ")", "}", "else", "{", "dependencies", "=", "dependencies", ".", "concat", "(", "config_dependencies", ")", ";", "}", "}", "for", "(", ";", "dependencies_iterator", "<", "dependencies", ".", "length", ";", "dependencies_iterator", "++", ")", "{", "dependency_name", "=", "dependencies", "[", "dependencies_iterator", "]", ";", "if", "(", "modules", ".", "hasOwnProperty", "(", "dependency_name", ")", ")", "{", "params", ".", "push", "(", "modules", "[", "dependency_name", "]", ")", ";", "}", "else", "if", "(", "dependency_name", "===", "'exports'", ")", "{", "params", ".", "push", "(", "exports", ")", ";", "}", "else", "{", "if", "(", "argc", "!==", "4", ")", "{", "define_queue", "[", "dependency_name", "]", "=", "define_queue", "[", "dependency_name", "]", "||", "[", "]", ";", "define_queue", "[", "dependency_name", "]", ".", "push", "(", "[", "exports", ",", "name", ",", "dependencies", ",", "factory", "]", ")", ";", "}", "dependencies_satisfied", "=", "false", ";", "}", "}", "if", "(", "dependencies_satisfied", ")", "{", "if", "(", "!", "modules", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "result", "=", "factory", ".", "apply", "(", "this", ",", "params", ")", ";", "if", "(", "result", ")", "{", "modules", "[", "name", "]", "=", "result", ";", "}", "else", "{", "modules", "[", "name", "]", "=", "exports", ";", "}", "}", "while", "(", "define_queue", "[", "name", "]", "&&", "(", "argv", "=", "define_queue", "[", "name", "]", ".", "pop", "(", ")", ")", ")", "{", "_define", ".", "apply", "(", "this", ",", "argv", ")", ";", "}", "}", "}" ]
the 'define' function
[ "the", "define", "function" ]
33d411de98c8004de4ffe1c6515643fc8ae5e192
https://github.com/elo7/async-define/blob/33d411de98c8004de4ffe1c6515643fc8ae5e192/async-define.js#L95-L176
train
nymag/dom
index.js
matches
function matches(node, selector) { var parent, matches, i; if (node.matches) { return node.matches(selector); } else { parent = node.parentElement; matches = parent ? parent.querySelectorAll(selector) : []; i = 0; while (matches[i] && matches[i] !== node) { i++; } return !!matches[i]; } }
javascript
function matches(node, selector) { var parent, matches, i; if (node.matches) { return node.matches(selector); } else { parent = node.parentElement; matches = parent ? parent.querySelectorAll(selector) : []; i = 0; while (matches[i] && matches[i] !== node) { i++; } return !!matches[i]; } }
[ "function", "matches", "(", "node", ",", "selector", ")", "{", "var", "parent", ",", "matches", ",", "i", ";", "if", "(", "node", ".", "matches", ")", "{", "return", "node", ".", "matches", "(", "selector", ")", ";", "}", "else", "{", "parent", "=", "node", ".", "parentElement", ";", "matches", "=", "parent", "?", "parent", ".", "querySelectorAll", "(", "selector", ")", ":", "[", "]", ";", "i", "=", "0", ";", "while", "(", "matches", "[", "i", "]", "&&", "matches", "[", "i", "]", "!==", "node", ")", "{", "i", "++", ";", "}", "return", "!", "!", "matches", "[", "i", "]", ";", "}", "}" ]
Returns true if the element would be selected by the specified selector. Essentially a polyfill, but necessary for `closest`. @param {Node} node preferably an Element for better performance, but it will accept any Node. @param {string} selector @returns {boolean}
[ "Returns", "true", "if", "the", "element", "would", "be", "selected", "by", "the", "specified", "selector", ".", "Essentially", "a", "polyfill", "but", "necessary", "for", "closest", "." ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L81-L95
train
nymag/dom
index.js
closest
function closest(node, parentSelector) { var cursor = node; if (!parentSelector || typeof parentSelector !== 'string') { throw new Error('Please specify a selector to match against!'); } while (cursor && !matches(cursor, parentSelector)) { cursor = cursor.parentNode; } if (!cursor) { return null; } else { return cursor; } }
javascript
function closest(node, parentSelector) { var cursor = node; if (!parentSelector || typeof parentSelector !== 'string') { throw new Error('Please specify a selector to match against!'); } while (cursor && !matches(cursor, parentSelector)) { cursor = cursor.parentNode; } if (!cursor) { return null; } else { return cursor; } }
[ "function", "closest", "(", "node", ",", "parentSelector", ")", "{", "var", "cursor", "=", "node", ";", "if", "(", "!", "parentSelector", "||", "typeof", "parentSelector", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Please specify a selector to match against!'", ")", ";", "}", "while", "(", "cursor", "&&", "!", "matches", "(", "cursor", ",", "parentSelector", ")", ")", "{", "cursor", "=", "cursor", ".", "parentNode", ";", "}", "if", "(", "!", "cursor", ")", "{", "return", "null", ";", "}", "else", "{", "return", "cursor", ";", "}", "}" ]
get closest element that matches selector starting with the element itself and traversing up through parents. @param {Element} node @param {string} parentSelector @return {Element|null}
[ "get", "closest", "element", "that", "matches", "selector", "starting", "with", "the", "element", "itself", "and", "traversing", "up", "through", "parents", "." ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L103-L119
train
nymag/dom
index.js
wrapElements
function wrapElements(els, wrapper) { var wrapperEl = document.createElement(wrapper); // make sure elements are in an array if (els instanceof HTMLElement) { els = [els]; } else { els = Array.prototype.slice.call(els); } _each(els, function (el) { // put it into the wrapper, remove it from its parent el.parentNode.removeChild(el); wrapperEl.appendChild(el); }); // return the wrapped elements return wrapperEl; }
javascript
function wrapElements(els, wrapper) { var wrapperEl = document.createElement(wrapper); // make sure elements are in an array if (els instanceof HTMLElement) { els = [els]; } else { els = Array.prototype.slice.call(els); } _each(els, function (el) { // put it into the wrapper, remove it from its parent el.parentNode.removeChild(el); wrapperEl.appendChild(el); }); // return the wrapped elements return wrapperEl; }
[ "function", "wrapElements", "(", "els", ",", "wrapper", ")", "{", "var", "wrapperEl", "=", "document", ".", "createElement", "(", "wrapper", ")", ";", "if", "(", "els", "instanceof", "HTMLElement", ")", "{", "els", "=", "[", "els", "]", ";", "}", "else", "{", "els", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "els", ")", ";", "}", "_each", "(", "els", ",", "function", "(", "el", ")", "{", "el", ".", "parentNode", ".", "removeChild", "(", "el", ")", ";", "wrapperEl", ".", "appendChild", "(", "el", ")", ";", "}", ")", ";", "return", "wrapperEl", ";", "}" ]
wrap elements in another element @param {NodeList|Element} els @param {string} wrapper @returns {Element} wrapperEl
[ "wrap", "elements", "in", "another", "element" ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L178-L196
train
nymag/dom
index.js
unwrapElements
function unwrapElements(parent, wrapper) { var el = wrapper.childNodes[0]; // ok, so this looks weird, right? // turns out, appending nodes to another node will remove them // from the live NodeList, so we can keep iterating over the // first item in that list and grab all of them. Nice! while (el) { parent.appendChild(el); el = wrapper.childNodes[0]; } parent.removeChild(wrapper); }
javascript
function unwrapElements(parent, wrapper) { var el = wrapper.childNodes[0]; // ok, so this looks weird, right? // turns out, appending nodes to another node will remove them // from the live NodeList, so we can keep iterating over the // first item in that list and grab all of them. Nice! while (el) { parent.appendChild(el); el = wrapper.childNodes[0]; } parent.removeChild(wrapper); }
[ "function", "unwrapElements", "(", "parent", ",", "wrapper", ")", "{", "var", "el", "=", "wrapper", ".", "childNodes", "[", "0", "]", ";", "while", "(", "el", ")", "{", "parent", ".", "appendChild", "(", "el", ")", ";", "el", "=", "wrapper", ".", "childNodes", "[", "0", "]", ";", "}", "parent", ".", "removeChild", "(", "wrapper", ")", ";", "}" ]
unwrap elements from another element @param {Element} parent @param {Element} wrapper
[ "unwrap", "elements", "from", "another", "element" ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L203-L216
train
nymag/dom
index.js
createRemoveNodeHandler
function createRemoveNodeHandler(el, fn) { return function (mutations, observer) { mutations.forEach(function (mutation) { if (_includes(mutation.removedNodes, el)) { fn(); observer.disconnect(); } }); }; }
javascript
function createRemoveNodeHandler(el, fn) { return function (mutations, observer) { mutations.forEach(function (mutation) { if (_includes(mutation.removedNodes, el)) { fn(); observer.disconnect(); } }); }; }
[ "function", "createRemoveNodeHandler", "(", "el", ",", "fn", ")", "{", "return", "function", "(", "mutations", ",", "observer", ")", "{", "mutations", ".", "forEach", "(", "function", "(", "mutation", ")", "{", "if", "(", "_includes", "(", "mutation", ".", "removedNodes", ",", "el", ")", ")", "{", "fn", "(", ")", ";", "observer", ".", "disconnect", "(", ")", ";", "}", "}", ")", ";", "}", ";", "}" ]
Create a remove node handler that runs fn and removes the observer. @param {Element} el @param {Function} fn @returns {Function}
[ "Create", "a", "remove", "node", "handler", "that", "runs", "fn", "and", "removes", "the", "observer", "." ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L224-L233
train
nymag/dom
index.js
getPos
function getPos(el) { var rect = el.getBoundingClientRect(), scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; return { top: rect.top + scrollY, bottom: rect.top + rect.height + scrollY, height: rect.height }; }
javascript
function getPos(el) { var rect = el.getBoundingClientRect(), scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; return { top: rect.top + scrollY, bottom: rect.top + rect.height + scrollY, height: rect.height }; }
[ "function", "getPos", "(", "el", ")", "{", "var", "rect", "=", "el", ".", "getBoundingClientRect", "(", ")", ",", "scrollY", "=", "window", ".", "pageYOffset", "||", "document", ".", "documentElement", ".", "scrollTop", "||", "document", ".", "body", ".", "scrollTop", ";", "return", "{", "top", ":", "rect", ".", "top", "+", "scrollY", ",", "bottom", ":", "rect", ".", "top", "+", "rect", ".", "height", "+", "scrollY", ",", "height", ":", "rect", ".", "height", "}", ";", "}" ]
Get the position of a DOM element @param {Element} el @return {object}
[ "Get", "the", "position", "of", "a", "DOM", "element" ]
1f69f55d70e6764f46f4d092fc90d16d23ec8e0b
https://github.com/nymag/dom/blob/1f69f55d70e6764f46f4d092fc90d16d23ec8e0b/index.js#L252-L261
train
ShoppinPal/vend-nodejs-sdk
lib/utils.js
function(tokenService, domainPrefix) { var tokenUrl = tokenService.replace(/\{DOMAIN_PREFIX\}/, domainPrefix); log.debug('token Url: '+ tokenUrl); return tokenUrl; }
javascript
function(tokenService, domainPrefix) { var tokenUrl = tokenService.replace(/\{DOMAIN_PREFIX\}/, domainPrefix); log.debug('token Url: '+ tokenUrl); return tokenUrl; }
[ "function", "(", "tokenService", ",", "domainPrefix", ")", "{", "var", "tokenUrl", "=", "tokenService", ".", "replace", "(", "/", "\\{DOMAIN_PREFIX\\}", "/", ",", "domainPrefix", ")", ";", "log", ".", "debug", "(", "'token Url: '", "+", "tokenUrl", ")", ";", "return", "tokenUrl", ";", "}" ]
If tokenService already has a domainPrefix set because the API consumer passed in a full URL instead of a substitutable one ... then the replace acts as a no-op. @param tokenService @param domain_prefix @returns {*|XML|string|void}
[ "If", "tokenService", "already", "has", "a", "domainPrefix", "set", "because", "the", "API", "consumer", "passed", "in", "a", "full", "URL", "instead", "of", "a", "substitutable", "one", "...", "then", "the", "replace", "acts", "as", "a", "no", "-", "op", "." ]
7ba24d12b5e68f9e364725fbcdfaff483d81a47c
https://github.com/ShoppinPal/vend-nodejs-sdk/blob/7ba24d12b5e68f9e364725fbcdfaff483d81a47c/lib/utils.js#L66-L70
train
gethuman/pancakes
lib/factories/adapter.factory.js
AdapterFactory
function AdapterFactory(injector) { if (!injector.adapters) { return; } var me = this; this.adapterMap = {}; _.each(injector.adapterMap, function (adapterName, adapterType) { var adapter = injector.adapters[adapterName]; if (adapter) { me.adapterMap[adapterType + 'adapter'] = adapter; } }); }
javascript
function AdapterFactory(injector) { if (!injector.adapters) { return; } var me = this; this.adapterMap = {}; _.each(injector.adapterMap, function (adapterName, adapterType) { var adapter = injector.adapters[adapterName]; if (adapter) { me.adapterMap[adapterType + 'adapter'] = adapter; } }); }
[ "function", "AdapterFactory", "(", "injector", ")", "{", "if", "(", "!", "injector", ".", "adapters", ")", "{", "return", ";", "}", "var", "me", "=", "this", ";", "this", ".", "adapterMap", "=", "{", "}", ";", "_", ".", "each", "(", "injector", ".", "adapterMap", ",", "function", "(", "adapterName", ",", "adapterType", ")", "{", "var", "adapter", "=", "injector", ".", "adapters", "[", "adapterName", "]", ";", "if", "(", "adapter", ")", "{", "me", ".", "adapterMap", "[", "adapterType", "+", "'adapter'", "]", "=", "adapter", ";", "}", "}", ")", ";", "}" ]
Initialize the cache @param injector @constructor
[ "Initialize", "the", "cache" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/adapter.factory.js#L14-L25
train
gethuman/pancakes
lib/utensils.js
getCamelCase
function getCamelCase(filePath) { if (!filePath) { return ''; } // clip off everything by after the last slash and the .js filePath = filePath.substring(filePath.lastIndexOf(delim) + 1); if (filePath.substring(filePath.length - 3) === '.js') { filePath = filePath.substring(0, filePath.length - 3); } // replace dots with caps var parts = filePath.split('.'); var i; for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } // replace dashs with caps filePath = parts.join(''); parts = filePath.split('-'); for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return parts.join(''); }
javascript
function getCamelCase(filePath) { if (!filePath) { return ''; } // clip off everything by after the last slash and the .js filePath = filePath.substring(filePath.lastIndexOf(delim) + 1); if (filePath.substring(filePath.length - 3) === '.js') { filePath = filePath.substring(0, filePath.length - 3); } // replace dots with caps var parts = filePath.split('.'); var i; for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } // replace dashs with caps filePath = parts.join(''); parts = filePath.split('-'); for (i = 1; i < parts.length; i++) { parts[i] = parts[i].substring(0, 1).toUpperCase() + parts[i].substring(1); } return parts.join(''); }
[ "function", "getCamelCase", "(", "filePath", ")", "{", "if", "(", "!", "filePath", ")", "{", "return", "''", ";", "}", "filePath", "=", "filePath", ".", "substring", "(", "filePath", ".", "lastIndexOf", "(", "delim", ")", "+", "1", ")", ";", "if", "(", "filePath", ".", "substring", "(", "filePath", ".", "length", "-", "3", ")", "===", "'.js'", ")", "{", "filePath", "=", "filePath", ".", "substring", "(", "0", ",", "filePath", ".", "length", "-", "3", ")", ";", "}", "var", "parts", "=", "filePath", ".", "split", "(", "'.'", ")", ";", "var", "i", ";", "for", "(", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "parts", "[", "i", "]", "=", "parts", "[", "i", "]", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "parts", "[", "i", "]", ".", "substring", "(", "1", ")", ";", "}", "filePath", "=", "parts", ".", "join", "(", "''", ")", ";", "parts", "=", "filePath", ".", "split", "(", "'-'", ")", ";", "for", "(", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "parts", "[", "i", "]", "=", "parts", "[", "i", "]", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "parts", "[", "i", "]", ".", "substring", "(", "1", ")", ";", "}", "return", "parts", ".", "join", "(", "''", ")", ";", "}" ]
Get module name from a full file path. This is done by removing the parent dirs and replacing dot naming with camelCase @param filePath Full file path to a pancakes module @return {String} The name of the module.
[ "Get", "module", "name", "from", "a", "full", "file", "path", ".", "This", "is", "done", "by", "removing", "the", "parent", "dirs", "and", "replacing", "dot", "naming", "with", "camelCase" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L31-L59
train
gethuman/pancakes
lib/utensils.js
getPascalCase
function getPascalCase(filePath) { var camelCase = getCamelCase(filePath); return camelCase.substring(0, 1).toUpperCase() + camelCase.substring(1); }
javascript
function getPascalCase(filePath) { var camelCase = getCamelCase(filePath); return camelCase.substring(0, 1).toUpperCase() + camelCase.substring(1); }
[ "function", "getPascalCase", "(", "filePath", ")", "{", "var", "camelCase", "=", "getCamelCase", "(", "filePath", ")", ";", "return", "camelCase", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "camelCase", ".", "substring", "(", "1", ")", ";", "}" ]
Get the Pascal Case for a given path @param filePath @returns {string}
[ "Get", "the", "Pascal", "Case", "for", "a", "given", "path" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L66-L69
train
gethuman/pancakes
lib/utensils.js
getModulePath
function getModulePath(filePath, fileName) { if (isJavaScript(fileName)) { fileName = fileName.substring(0, fileName.length - 3); } return filePath + '/' + fileName; }
javascript
function getModulePath(filePath, fileName) { if (isJavaScript(fileName)) { fileName = fileName.substring(0, fileName.length - 3); } return filePath + '/' + fileName; }
[ "function", "getModulePath", "(", "filePath", ",", "fileName", ")", "{", "if", "(", "isJavaScript", "(", "fileName", ")", ")", "{", "fileName", "=", "fileName", ".", "substring", "(", "0", ",", "fileName", ".", "length", "-", "3", ")", ";", "}", "return", "filePath", "+", "'/'", "+", "fileName", ";", "}" ]
Get the module path that will be used with the require @param filePath @param fileName @returns {string}
[ "Get", "the", "module", "path", "that", "will", "be", "used", "with", "the", "require" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L101-L107
train
gethuman/pancakes
lib/utensils.js
parseIfJson
function parseIfJson(val) { if (_.isString(val)) { val = val.trim(); if (val.substring(0, 1) === '{' && val.substring(val.length - 1) === '}') { try { val = JSON.parse(val); } catch (ex) { /* eslint no-console:0 */ console.log(ex); } } } return val; }
javascript
function parseIfJson(val) { if (_.isString(val)) { val = val.trim(); if (val.substring(0, 1) === '{' && val.substring(val.length - 1) === '}') { try { val = JSON.parse(val); } catch (ex) { /* eslint no-console:0 */ console.log(ex); } } } return val; }
[ "function", "parseIfJson", "(", "val", ")", "{", "if", "(", "_", ".", "isString", "(", "val", ")", ")", "{", "val", "=", "val", ".", "trim", "(", ")", ";", "if", "(", "val", ".", "substring", "(", "0", ",", "1", ")", "===", "'{'", "&&", "val", ".", "substring", "(", "val", ".", "length", "-", "1", ")", "===", "'}'", ")", "{", "try", "{", "val", "=", "JSON", ".", "parse", "(", "val", ")", ";", "}", "catch", "(", "ex", ")", "{", "console", ".", "log", "(", "ex", ")", ";", "}", "}", "}", "return", "val", ";", "}" ]
If a value is a string of json, parse it out into an object @param val @returns {*}
[ "If", "a", "value", "is", "a", "string", "of", "json", "parse", "it", "out", "into", "an", "object" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L114-L128
train
gethuman/pancakes
lib/utensils.js
chainPromises
function chainPromises(calls, val) { if (!calls || !calls.length) { return Q.when(val); } return calls.reduce(Q.when, Q.when(val)); }
javascript
function chainPromises(calls, val) { if (!calls || !calls.length) { return Q.when(val); } return calls.reduce(Q.when, Q.when(val)); }
[ "function", "chainPromises", "(", "calls", ",", "val", ")", "{", "if", "(", "!", "calls", "||", "!", "calls", ".", "length", ")", "{", "return", "Q", ".", "when", "(", "val", ")", ";", "}", "return", "calls", ".", "reduce", "(", "Q", ".", "when", ",", "Q", ".", "when", "(", "val", ")", ")", ";", "}" ]
Simple function for chaining an array of promise functions. Every function in the promise chain needs to be uniform and accept the same input parameter. This is used for a number of things, but most importantly for the service call chain by API. @param calls Functions that should all take in a value and return a promise or another object @param val The initial value to be passed into the promise chain
[ "Simple", "function", "for", "chaining", "an", "array", "of", "promise", "functions", ".", "Every", "function", "in", "the", "promise", "chain", "needs", "to", "be", "uniform", "and", "accept", "the", "same", "input", "parameter", ".", "This", "is", "used", "for", "a", "number", "of", "things", "but", "most", "importantly", "for", "the", "service", "call", "chain", "by", "API", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L139-L142
train
gethuman/pancakes
lib/utensils.js
checksum
function checksum(str) { crcTbl = crcTbl || makeCRCTable(); /* jslint bitwise: true */ var crc = 0 ^ (-1); for (var i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTbl[(crc ^ str.charCodeAt(i)) & 0xFF]; } return (crc ^ (-1)) >>> 0; }
javascript
function checksum(str) { crcTbl = crcTbl || makeCRCTable(); /* jslint bitwise: true */ var crc = 0 ^ (-1); for (var i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTbl[(crc ^ str.charCodeAt(i)) & 0xFF]; } return (crc ^ (-1)) >>> 0; }
[ "function", "checksum", "(", "str", ")", "{", "crcTbl", "=", "crcTbl", "||", "makeCRCTable", "(", ")", ";", "var", "crc", "=", "0", "^", "(", "-", "1", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "crc", "=", "(", "crc", ">>>", "8", ")", "^", "crcTbl", "[", "(", "crc", "^", "str", ".", "charCodeAt", "(", "i", ")", ")", "&", "0xFF", "]", ";", "}", "return", "(", "crc", "^", "(", "-", "1", ")", ")", ">>>", "0", ";", "}" ]
Generate a checkum for a string @param str @returns {number}
[ "Generate", "a", "checkum", "for", "a", "string" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/utensils.js#L195-L206
train
gethuman/pancakes
lib/dependency.injector.js
DependencyInjector
function DependencyInjector(opts) { var rootDefault = p.join(__dirname, '../../..'); this.rootDir = opts.rootDir || rootDefault; // project base dir (default is a guess) this.require = opts.require || require; // we need require from the project this.container = opts.container || 'api'; // resource has diff profiles for diff containers this.servicesDir = opts.servicesDir || 'services'; // dir where services reside this.tplDir = opts.tplDir || 'dist/tpls'; // precompiled templates this.debug = opts.debug || false; // debug mode will have us firing more events this.debugPattern = opts.debugPattern; // by default if debug on, we view EVERYTHING this.debugHandler = opts.debugHandler; // function used when debug event occurs this.adapters = opts.adapters || {}; // if client uses plugins, they will pass in adapters this.reactors = opts.reactors || {}; // if client uses plugins, they will pass in reactors this.adapterMap = this.loadAdapterMap(opts); // mappings from adapter type to impl this.aliases = this.loadAliases(opts); // mapping of names to locations this.factories = this.loadFactories(opts); // load all the factories }
javascript
function DependencyInjector(opts) { var rootDefault = p.join(__dirname, '../../..'); this.rootDir = opts.rootDir || rootDefault; // project base dir (default is a guess) this.require = opts.require || require; // we need require from the project this.container = opts.container || 'api'; // resource has diff profiles for diff containers this.servicesDir = opts.servicesDir || 'services'; // dir where services reside this.tplDir = opts.tplDir || 'dist/tpls'; // precompiled templates this.debug = opts.debug || false; // debug mode will have us firing more events this.debugPattern = opts.debugPattern; // by default if debug on, we view EVERYTHING this.debugHandler = opts.debugHandler; // function used when debug event occurs this.adapters = opts.adapters || {}; // if client uses plugins, they will pass in adapters this.reactors = opts.reactors || {}; // if client uses plugins, they will pass in reactors this.adapterMap = this.loadAdapterMap(opts); // mappings from adapter type to impl this.aliases = this.loadAliases(opts); // mapping of names to locations this.factories = this.loadFactories(opts); // load all the factories }
[ "function", "DependencyInjector", "(", "opts", ")", "{", "var", "rootDefault", "=", "p", ".", "join", "(", "__dirname", ",", "'../../..'", ")", ";", "this", ".", "rootDir", "=", "opts", ".", "rootDir", "||", "rootDefault", ";", "this", ".", "require", "=", "opts", ".", "require", "||", "require", ";", "this", ".", "container", "=", "opts", ".", "container", "||", "'api'", ";", "this", ".", "servicesDir", "=", "opts", ".", "servicesDir", "||", "'services'", ";", "this", ".", "tplDir", "=", "opts", ".", "tplDir", "||", "'dist/tpls'", ";", "this", ".", "debug", "=", "opts", ".", "debug", "||", "false", ";", "this", ".", "debugPattern", "=", "opts", ".", "debugPattern", ";", "this", ".", "debugHandler", "=", "opts", ".", "debugHandler", ";", "this", ".", "adapters", "=", "opts", ".", "adapters", "||", "{", "}", ";", "this", ".", "reactors", "=", "opts", ".", "reactors", "||", "{", "}", ";", "this", ".", "adapterMap", "=", "this", ".", "loadAdapterMap", "(", "opts", ")", ";", "this", ".", "aliases", "=", "this", ".", "loadAliases", "(", "opts", ")", ";", "this", ".", "factories", "=", "this", ".", "loadFactories", "(", "opts", ")", ";", "}" ]
Initialize the injector with input options @param opts @constructor
[ "Initialize", "the", "injector", "with", "input", "options" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L27-L42
train
gethuman/pancakes
lib/dependency.injector.js
loadFactories
function loadFactories(opts) { this.flapjackFactory = new FlapjackFactory(this); return [ new InternalObjFactory(this), new AdapterFactory(this), new ServiceFactory(this), new ModelFactory(this), new UipartFactory(this), this.flapjackFactory, new ModulePluginFactory(this, opts.modulePlugins), new DefaultFactory(this) ]; }
javascript
function loadFactories(opts) { this.flapjackFactory = new FlapjackFactory(this); return [ new InternalObjFactory(this), new AdapterFactory(this), new ServiceFactory(this), new ModelFactory(this), new UipartFactory(this), this.flapjackFactory, new ModulePluginFactory(this, opts.modulePlugins), new DefaultFactory(this) ]; }
[ "function", "loadFactories", "(", "opts", ")", "{", "this", ".", "flapjackFactory", "=", "new", "FlapjackFactory", "(", "this", ")", ";", "return", "[", "new", "InternalObjFactory", "(", "this", ")", ",", "new", "AdapterFactory", "(", "this", ")", ",", "new", "ServiceFactory", "(", "this", ")", ",", "new", "ModelFactory", "(", "this", ")", ",", "new", "UipartFactory", "(", "this", ")", ",", "this", ".", "flapjackFactory", ",", "new", "ModulePluginFactory", "(", "this", ",", "opts", ".", "modulePlugins", ")", ",", "new", "DefaultFactory", "(", "this", ")", "]", ";", "}" ]
Load all the factories @returns {Array}
[ "Load", "all", "the", "factories" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L74-L87
train
gethuman/pancakes
lib/dependency.injector.js
loadMappings
function loadMappings(rootDir, paths) { var mappings = {}, i, j, fullPath, fileNames, fileName, path, name, val; if (!paths) { return mappings; } for (i = 0; i < paths.length; i++) { path = paths[i]; fullPath = rootDir + '/' + path; // if the directory doesn't exist, then skip to the next loop iteration if (!fs.existsSync(p.normalize(fullPath))) { continue; } // loop through all files in this folder fileNames = fs.readdirSync(p.normalize(fullPath)); for (j = 0; j < fileNames.length; j++) { fileName = fileNames[j]; // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { name = utils.getCamelCase(fileName); val = utils.getModulePath(path, fileName); mappings[name] = val; mappings[name.substring(0, 1).toUpperCase() + name.substring(1)] = val; // store PascalCase as well } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(p.join(fullPath, fileName)).isDirectory()) { _.extend(mappings, this.loadMappings(rootDir, [path + '/' + fileName])); } } } return mappings; }
javascript
function loadMappings(rootDir, paths) { var mappings = {}, i, j, fullPath, fileNames, fileName, path, name, val; if (!paths) { return mappings; } for (i = 0; i < paths.length; i++) { path = paths[i]; fullPath = rootDir + '/' + path; // if the directory doesn't exist, then skip to the next loop iteration if (!fs.existsSync(p.normalize(fullPath))) { continue; } // loop through all files in this folder fileNames = fs.readdirSync(p.normalize(fullPath)); for (j = 0; j < fileNames.length; j++) { fileName = fileNames[j]; // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { name = utils.getCamelCase(fileName); val = utils.getModulePath(path, fileName); mappings[name] = val; mappings[name.substring(0, 1).toUpperCase() + name.substring(1)] = val; // store PascalCase as well } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(p.join(fullPath, fileName)).isDirectory()) { _.extend(mappings, this.loadMappings(rootDir, [path + '/' + fileName])); } } } return mappings; }
[ "function", "loadMappings", "(", "rootDir", ",", "paths", ")", "{", "var", "mappings", "=", "{", "}", ",", "i", ",", "j", ",", "fullPath", ",", "fileNames", ",", "fileName", ",", "path", ",", "name", ",", "val", ";", "if", "(", "!", "paths", ")", "{", "return", "mappings", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "paths", ".", "length", ";", "i", "++", ")", "{", "path", "=", "paths", "[", "i", "]", ";", "fullPath", "=", "rootDir", "+", "'/'", "+", "path", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "p", ".", "normalize", "(", "fullPath", ")", ")", ")", "{", "continue", ";", "}", "fileNames", "=", "fs", ".", "readdirSync", "(", "p", ".", "normalize", "(", "fullPath", ")", ")", ";", "for", "(", "j", "=", "0", ";", "j", "<", "fileNames", ".", "length", ";", "j", "++", ")", "{", "fileName", "=", "fileNames", "[", "j", "]", ";", "if", "(", "utils", ".", "isJavaScript", "(", "fileName", ")", "&&", "!", "fileName", ".", "match", "(", "/", "^.*\\.service\\.js$", "/", ")", ")", "{", "name", "=", "utils", ".", "getCamelCase", "(", "fileName", ")", ";", "val", "=", "utils", ".", "getModulePath", "(", "path", ",", "fileName", ")", ";", "mappings", "[", "name", "]", "=", "val", ";", "mappings", "[", "name", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "name", ".", "substring", "(", "1", ")", "]", "=", "val", ";", "}", "else", "if", "(", "fs", ".", "lstatSync", "(", "p", ".", "join", "(", "fullPath", ",", "fileName", ")", ")", ".", "isDirectory", "(", ")", ")", "{", "_", ".", "extend", "(", "mappings", ",", "this", ".", "loadMappings", "(", "rootDir", ",", "[", "path", "+", "'/'", "+", "fileName", "]", ")", ")", ";", "}", "}", "}", "return", "mappings", ";", "}" ]
Based on a given directory, get the mappings of camelCase name for a given file to the file's relative path from the app root. @param rootDir @param paths @returns {{}} The mappings of param name to location
[ "Based", "on", "a", "given", "directory", "get", "the", "mappings", "of", "camelCase", "name", "for", "a", "given", "file", "to", "the", "file", "s", "relative", "path", "from", "the", "app", "root", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L122-L160
train
gethuman/pancakes
lib/dependency.injector.js
exists
function exists(modulePath, options) { if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } var len = this.factories.length - 1; // -1 because we don't want the default factory for (var i = 0; this.factories && i < len; i++) { if (this.factories[i].isCandidate(modulePath, options)) { return true; } } return false; }
javascript
function exists(modulePath, options) { if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } var len = this.factories.length - 1; // -1 because we don't want the default factory for (var i = 0; this.factories && i < len; i++) { if (this.factories[i].isCandidate(modulePath, options)) { return true; } } return false; }
[ "function", "exists", "(", "modulePath", ",", "options", ")", "{", "if", "(", "this", ".", "aliases", "[", "modulePath", "]", ")", "{", "modulePath", "=", "this", ".", "aliases", "[", "modulePath", "]", ";", "}", "var", "len", "=", "this", ".", "factories", ".", "length", "-", "1", ";", "for", "(", "var", "i", "=", "0", ";", "this", ".", "factories", "&&", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "this", ".", "factories", "[", "i", "]", ".", "isCandidate", "(", "modulePath", ",", "options", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine if an @param modulePath @param options @returns {boolean}
[ "Determine", "if", "an" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L168-L182
train
gethuman/pancakes
lib/dependency.injector.js
loadModule
function loadModule(modulePath, moduleStack, options) { var newModule, i; options = options || {}; // if modulePath is null return null if (!modulePath) { return null; } // if actual flapjack sent in as the module path then switch things around so modulePath name is unique if (_.isFunction(modulePath)) { options.flapjack = modulePath; modulePath = 'module-' + (new Date()).getTime(); } // if we already have a flapjack, make the modulePath unique per the options else if (options.flapjack) { modulePath = (options.app || 'common') + '.' + modulePath + '.' + (options.type || 'default'); } // else we need to get code from the file system, so check to see if we need to switch a mapped name to its path else if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } // if module name already in the stack, then circular reference moduleStack = moduleStack || []; if (moduleStack.indexOf(modulePath) >= 0) { throw new Error('Circular reference since ' + modulePath + ' is in ' + JSON.stringify(moduleStack)); } // add the path to the stack so we don't have a circular dependency moduleStack.push(modulePath); // try to find a factory that can create/get a module for the given path for (i = 0; this.factories && i < this.factories.length; i++) { if (this.factories[i].isCandidate(modulePath, options)) { newModule = this.factories[i].create(modulePath, moduleStack, options); break; } } // if no module found log error if (!newModule && moduleStack && moduleStack.length > 1) { /* eslint no-console:0 */ console.log('ERROR: ' + moduleStack[moduleStack.length - 2] + ' dependency ' + modulePath + ' not found.'); } // pop the current item off the stack moduleStack.pop(); // return the new module (or the default {} if no factories found) return newModule; }
javascript
function loadModule(modulePath, moduleStack, options) { var newModule, i; options = options || {}; // if modulePath is null return null if (!modulePath) { return null; } // if actual flapjack sent in as the module path then switch things around so modulePath name is unique if (_.isFunction(modulePath)) { options.flapjack = modulePath; modulePath = 'module-' + (new Date()).getTime(); } // if we already have a flapjack, make the modulePath unique per the options else if (options.flapjack) { modulePath = (options.app || 'common') + '.' + modulePath + '.' + (options.type || 'default'); } // else we need to get code from the file system, so check to see if we need to switch a mapped name to its path else if (this.aliases[modulePath]) { modulePath = this.aliases[modulePath]; } // if module name already in the stack, then circular reference moduleStack = moduleStack || []; if (moduleStack.indexOf(modulePath) >= 0) { throw new Error('Circular reference since ' + modulePath + ' is in ' + JSON.stringify(moduleStack)); } // add the path to the stack so we don't have a circular dependency moduleStack.push(modulePath); // try to find a factory that can create/get a module for the given path for (i = 0; this.factories && i < this.factories.length; i++) { if (this.factories[i].isCandidate(modulePath, options)) { newModule = this.factories[i].create(modulePath, moduleStack, options); break; } } // if no module found log error if (!newModule && moduleStack && moduleStack.length > 1) { /* eslint no-console:0 */ console.log('ERROR: ' + moduleStack[moduleStack.length - 2] + ' dependency ' + modulePath + ' not found.'); } // pop the current item off the stack moduleStack.pop(); // return the new module (or the default {} if no factories found) return newModule; }
[ "function", "loadModule", "(", "modulePath", ",", "moduleStack", ",", "options", ")", "{", "var", "newModule", ",", "i", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "modulePath", ")", "{", "return", "null", ";", "}", "if", "(", "_", ".", "isFunction", "(", "modulePath", ")", ")", "{", "options", ".", "flapjack", "=", "modulePath", ";", "modulePath", "=", "'module-'", "+", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", ";", "}", "else", "if", "(", "options", ".", "flapjack", ")", "{", "modulePath", "=", "(", "options", ".", "app", "||", "'common'", ")", "+", "'.'", "+", "modulePath", "+", "'.'", "+", "(", "options", ".", "type", "||", "'default'", ")", ";", "}", "else", "if", "(", "this", ".", "aliases", "[", "modulePath", "]", ")", "{", "modulePath", "=", "this", ".", "aliases", "[", "modulePath", "]", ";", "}", "moduleStack", "=", "moduleStack", "||", "[", "]", ";", "if", "(", "moduleStack", ".", "indexOf", "(", "modulePath", ")", ">=", "0", ")", "{", "throw", "new", "Error", "(", "'Circular reference since '", "+", "modulePath", "+", "' is in '", "+", "JSON", ".", "stringify", "(", "moduleStack", ")", ")", ";", "}", "moduleStack", ".", "push", "(", "modulePath", ")", ";", "for", "(", "i", "=", "0", ";", "this", ".", "factories", "&&", "i", "<", "this", ".", "factories", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "factories", "[", "i", "]", ".", "isCandidate", "(", "modulePath", ",", "options", ")", ")", "{", "newModule", "=", "this", ".", "factories", "[", "i", "]", ".", "create", "(", "modulePath", ",", "moduleStack", ",", "options", ")", ";", "break", ";", "}", "}", "if", "(", "!", "newModule", "&&", "moduleStack", "&&", "moduleStack", ".", "length", ">", "1", ")", "{", "console", ".", "log", "(", "'ERROR: '", "+", "moduleStack", "[", "moduleStack", ".", "length", "-", "2", "]", "+", "' dependency '", "+", "modulePath", "+", "' not found.'", ")", ";", "}", "moduleStack", ".", "pop", "(", ")", ";", "return", "newModule", ";", "}" ]
Load a module using the pancakes injector. The injector relies on a number of factories to do the actual injection. The first factory that can handle a given modulePath input attempts to generate an object or return something from cache that can then be returned back to the caller. @param modulePath Path to module @param moduleStack Stack of modules in recursive call (to prevent circular references) @param options Optional values used by some factories
[ "Load", "a", "module", "using", "the", "pancakes", "injector", ".", "The", "injector", "relies", "on", "a", "number", "of", "factories", "to", "do", "the", "actual", "injection", ".", "The", "first", "factory", "that", "can", "handle", "a", "given", "modulePath", "input", "attempts", "to", "generate", "an", "object", "or", "return", "something", "from", "cache", "that", "can", "then", "be", "returned", "back", "to", "the", "caller", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L193-L245
train
gethuman/pancakes
lib/dependency.injector.js
injectFlapjack
function injectFlapjack(flapjack, moduleStack, options) { options = options || {}; // if server is false, then return null var moduleInfo = annotations.getModuleInfo(flapjack); if (moduleInfo && moduleInfo.server === false && !options.test) { return null; } // param map is combo of param map set by user, params discovered and current annotation var aliases = _.extend({}, this.aliases, annotations.getServerAliases(flapjack, null)); var params = annotations.getParameters(flapjack); var deps = options.dependencies || {}; var paramModules = []; var me = this; // loop through the params so we can collect the object that will be injected _.each(params, function (param) { var dep = deps[param]; // if mapping exists, switch to the mapping (ex. pancakes -> lib/pancakes) if (aliases[param]) { param = aliases[param]; } // either get the module from the input dependencies or recursively call inject try { paramModules.push(dep || deps[param] || me.loadModule(param, moduleStack)); } catch (ex) { var errMsg = ex.stack || ex; throw new Error('While injecting function, ran into invalid parameter.\nparam: ' + param + '\nstack: ' + JSON.stringify(moduleStack) + '\nfunction: ' + flapjack.toString().substring(0, 100) + '...\nerror: ' + errMsg); } }); // call the flapjack function passing in the array of modules as parameters return flapjack.apply(null, paramModules); }
javascript
function injectFlapjack(flapjack, moduleStack, options) { options = options || {}; // if server is false, then return null var moduleInfo = annotations.getModuleInfo(flapjack); if (moduleInfo && moduleInfo.server === false && !options.test) { return null; } // param map is combo of param map set by user, params discovered and current annotation var aliases = _.extend({}, this.aliases, annotations.getServerAliases(flapjack, null)); var params = annotations.getParameters(flapjack); var deps = options.dependencies || {}; var paramModules = []; var me = this; // loop through the params so we can collect the object that will be injected _.each(params, function (param) { var dep = deps[param]; // if mapping exists, switch to the mapping (ex. pancakes -> lib/pancakes) if (aliases[param]) { param = aliases[param]; } // either get the module from the input dependencies or recursively call inject try { paramModules.push(dep || deps[param] || me.loadModule(param, moduleStack)); } catch (ex) { var errMsg = ex.stack || ex; throw new Error('While injecting function, ran into invalid parameter.\nparam: ' + param + '\nstack: ' + JSON.stringify(moduleStack) + '\nfunction: ' + flapjack.toString().substring(0, 100) + '...\nerror: ' + errMsg); } }); // call the flapjack function passing in the array of modules as parameters return flapjack.apply(null, paramModules); }
[ "function", "injectFlapjack", "(", "flapjack", ",", "moduleStack", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "moduleInfo", "=", "annotations", ".", "getModuleInfo", "(", "flapjack", ")", ";", "if", "(", "moduleInfo", "&&", "moduleInfo", ".", "server", "===", "false", "&&", "!", "options", ".", "test", ")", "{", "return", "null", ";", "}", "var", "aliases", "=", "_", ".", "extend", "(", "{", "}", ",", "this", ".", "aliases", ",", "annotations", ".", "getServerAliases", "(", "flapjack", ",", "null", ")", ")", ";", "var", "params", "=", "annotations", ".", "getParameters", "(", "flapjack", ")", ";", "var", "deps", "=", "options", ".", "dependencies", "||", "{", "}", ";", "var", "paramModules", "=", "[", "]", ";", "var", "me", "=", "this", ";", "_", ".", "each", "(", "params", ",", "function", "(", "param", ")", "{", "var", "dep", "=", "deps", "[", "param", "]", ";", "if", "(", "aliases", "[", "param", "]", ")", "{", "param", "=", "aliases", "[", "param", "]", ";", "}", "try", "{", "paramModules", ".", "push", "(", "dep", "||", "deps", "[", "param", "]", "||", "me", ".", "loadModule", "(", "param", ",", "moduleStack", ")", ")", ";", "}", "catch", "(", "ex", ")", "{", "var", "errMsg", "=", "ex", ".", "stack", "||", "ex", ";", "throw", "new", "Error", "(", "'While injecting function, ran into invalid parameter.\\nparam: '", "+", "\\n", "+", "param", "+", "'\\nstack: '", "+", "\\n", "+", "JSON", ".", "stringify", "(", "moduleStack", ")", "+", "'\\nfunction: '", "+", "\\n", ")", ";", "}", "}", ")", ";", "flapjack", ".", "toString", "(", ")", ".", "substring", "(", "0", ",", "100", ")", "}" ]
Given a flapjack load all the params and instantiated it. This fn is used by the FlapjackFactory and ModulePluginFactory. @param flapjack @param moduleStack @param options @returns {*}
[ "Given", "a", "flapjack", "load", "all", "the", "params", "and", "instantiated", "it", ".", "This", "fn", "is", "used", "by", "the", "FlapjackFactory", "and", "ModulePluginFactory", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/dependency.injector.js#L256-L295
train
gethuman/pancakes
lib/factories/module.plugin.factory.js
loadModulePlugins
function loadModulePlugins(modulePlugins) { var serverModules = {}; var me = this; // add modules from each plugin to the serverModules map _.each(modulePlugins, function (modulePlugin) { _.extend(serverModules, me.loadModules(modulePlugin.rootDir, modulePlugin.serverModuleDirs)); }); return serverModules; }
javascript
function loadModulePlugins(modulePlugins) { var serverModules = {}; var me = this; // add modules from each plugin to the serverModules map _.each(modulePlugins, function (modulePlugin) { _.extend(serverModules, me.loadModules(modulePlugin.rootDir, modulePlugin.serverModuleDirs)); }); return serverModules; }
[ "function", "loadModulePlugins", "(", "modulePlugins", ")", "{", "var", "serverModules", "=", "{", "}", ";", "var", "me", "=", "this", ";", "_", ".", "each", "(", "modulePlugins", ",", "function", "(", "modulePlugin", ")", "{", "_", ".", "extend", "(", "serverModules", ",", "me", ".", "loadModules", "(", "modulePlugin", ".", "rootDir", ",", "modulePlugin", ".", "serverModuleDirs", ")", ")", ";", "}", ")", ";", "return", "serverModules", ";", "}" ]
Loop through each plugin and add each module to a map @param modulePlugins
[ "Loop", "through", "each", "plugin", "and", "add", "each", "module", "to", "a", "map" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/module.plugin.factory.js#L31-L41
train
gethuman/pancakes
lib/factories/module.plugin.factory.js
loadModules
function loadModules(rootDir, paths) { var serverModules = {}; var me = this; // return empty object if no rootDir or paths if (!rootDir || !paths) { return serverModules; } // loop through paths and load all modules in those directories _.each(paths, function (relativePath) { var fullPath = path.normalize(rootDir + delim + relativePath); // if the directory doesn't exist, then skip to the next loop iteration if (fs.existsSync(fullPath)) { _.each(fs.readdirSync(fullPath), function (fileName) { // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { var nameLower = utils.getCamelCase(fileName).toLowerCase(); var fullFilePath = path.normalize(fullPath + '/' + fileName); // there are 2 diff potential aliases for any given server module serverModules[nameLower + 'fromplugin'] = serverModules[nameLower] = require(fullFilePath); } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(path.join(fullPath, fileName)).isDirectory()) { _.extend(serverModules, me.loadModules(rootDir, [relativePath + '/' + fileName])); } }); } }); return serverModules; }
javascript
function loadModules(rootDir, paths) { var serverModules = {}; var me = this; // return empty object if no rootDir or paths if (!rootDir || !paths) { return serverModules; } // loop through paths and load all modules in those directories _.each(paths, function (relativePath) { var fullPath = path.normalize(rootDir + delim + relativePath); // if the directory doesn't exist, then skip to the next loop iteration if (fs.existsSync(fullPath)) { _.each(fs.readdirSync(fullPath), function (fileName) { // if it is a javascript file and it DOES NOT end in .service.js, then save the mapping if (utils.isJavaScript(fileName) && !fileName.match(/^.*\.service\.js$/)) { var nameLower = utils.getCamelCase(fileName).toLowerCase(); var fullFilePath = path.normalize(fullPath + '/' + fileName); // there are 2 diff potential aliases for any given server module serverModules[nameLower + 'fromplugin'] = serverModules[nameLower] = require(fullFilePath); } // else if we are dealing with a directory, recurse down into the folder else if (fs.lstatSync(path.join(fullPath, fileName)).isDirectory()) { _.extend(serverModules, me.loadModules(rootDir, [relativePath + '/' + fileName])); } }); } }); return serverModules; }
[ "function", "loadModules", "(", "rootDir", ",", "paths", ")", "{", "var", "serverModules", "=", "{", "}", ";", "var", "me", "=", "this", ";", "if", "(", "!", "rootDir", "||", "!", "paths", ")", "{", "return", "serverModules", ";", "}", "_", ".", "each", "(", "paths", ",", "function", "(", "relativePath", ")", "{", "var", "fullPath", "=", "path", ".", "normalize", "(", "rootDir", "+", "delim", "+", "relativePath", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "fullPath", ")", ")", "{", "_", ".", "each", "(", "fs", ".", "readdirSync", "(", "fullPath", ")", ",", "function", "(", "fileName", ")", "{", "if", "(", "utils", ".", "isJavaScript", "(", "fileName", ")", "&&", "!", "fileName", ".", "match", "(", "/", "^.*\\.service\\.js$", "/", ")", ")", "{", "var", "nameLower", "=", "utils", ".", "getCamelCase", "(", "fileName", ")", ".", "toLowerCase", "(", ")", ";", "var", "fullFilePath", "=", "path", ".", "normalize", "(", "fullPath", "+", "'/'", "+", "fileName", ")", ";", "serverModules", "[", "nameLower", "+", "'fromplugin'", "]", "=", "serverModules", "[", "nameLower", "]", "=", "require", "(", "fullFilePath", ")", ";", "}", "else", "if", "(", "fs", ".", "lstatSync", "(", "path", ".", "join", "(", "fullPath", ",", "fileName", ")", ")", ".", "isDirectory", "(", ")", ")", "{", "_", ".", "extend", "(", "serverModules", ",", "me", ".", "loadModules", "(", "rootDir", ",", "[", "relativePath", "+", "'/'", "+", "fileName", "]", ")", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "return", "serverModules", ";", "}" ]
Recursively go through dirs and add modules to a server modules map that is returned @param rootDir @param paths @returns {*}
[ "Recursively", "go", "through", "dirs", "and", "add", "modules", "to", "a", "server", "modules", "map", "that", "is", "returned" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/module.plugin.factory.js#L49-L84
train
gethuman/pancakes
lib/api.route.handler.js
traverseFilters
function traverseFilters(config, levels, levelIdx) { var lastIdx = levels.length - 1; var val, filters; if (!config || levelIdx > lastIdx) { return null; } val = config[levels[levelIdx]]; if (levelIdx === lastIdx) { if (val) { return val; } else { return config.all; } } else { filters = traverseFilters(val, levels, levelIdx + 1); if (!filters) { filters = traverseFilters(config.all, levels, levelIdx + 1); } return filters; } }
javascript
function traverseFilters(config, levels, levelIdx) { var lastIdx = levels.length - 1; var val, filters; if (!config || levelIdx > lastIdx) { return null; } val = config[levels[levelIdx]]; if (levelIdx === lastIdx) { if (val) { return val; } else { return config.all; } } else { filters = traverseFilters(val, levels, levelIdx + 1); if (!filters) { filters = traverseFilters(config.all, levels, levelIdx + 1); } return filters; } }
[ "function", "traverseFilters", "(", "config", ",", "levels", ",", "levelIdx", ")", "{", "var", "lastIdx", "=", "levels", ".", "length", "-", "1", ";", "var", "val", ",", "filters", ";", "if", "(", "!", "config", "||", "levelIdx", ">", "lastIdx", ")", "{", "return", "null", ";", "}", "val", "=", "config", "[", "levels", "[", "levelIdx", "]", "]", ";", "if", "(", "levelIdx", "===", "lastIdx", ")", "{", "if", "(", "val", ")", "{", "return", "val", ";", "}", "else", "{", "return", "config", ".", "all", ";", "}", "}", "else", "{", "filters", "=", "traverseFilters", "(", "val", ",", "levels", ",", "levelIdx", "+", "1", ")", ";", "if", "(", "!", "filters", ")", "{", "filters", "=", "traverseFilters", "(", "config", ".", "all", ",", "levels", ",", "levelIdx", "+", "1", ")", ";", "}", "return", "filters", ";", "}", "}" ]
Recurse through the filter config to get the right filter values @param config @param levels @param levelIdx @returns {*}
[ "Recurse", "through", "the", "filter", "config", "to", "get", "the", "right", "filter", "values" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/api.route.handler.js#L27-L51
train
gethuman/pancakes
lib/api.route.handler.js
getFilters
function getFilters(resourceName, adapterName, operation) { var filterConfig = injector.loadModule('filterConfig'); var filters = { before: [], after: [] }; if (!filterConfig) { return filters; } var levels = [resourceName, adapterName, operation, 'before']; filters.before = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); levels = [resourceName, adapterName, operation, 'after']; filters.after = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); return filters; }
javascript
function getFilters(resourceName, adapterName, operation) { var filterConfig = injector.loadModule('filterConfig'); var filters = { before: [], after: [] }; if (!filterConfig) { return filters; } var levels = [resourceName, adapterName, operation, 'before']; filters.before = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); levels = [resourceName, adapterName, operation, 'after']; filters.after = (traverseFilters(filterConfig, levels, 0) || []).map(function (name) { return injector.loadModule(name + 'Filter'); }); return filters; }
[ "function", "getFilters", "(", "resourceName", ",", "adapterName", ",", "operation", ")", "{", "var", "filterConfig", "=", "injector", ".", "loadModule", "(", "'filterConfig'", ")", ";", "var", "filters", "=", "{", "before", ":", "[", "]", ",", "after", ":", "[", "]", "}", ";", "if", "(", "!", "filterConfig", ")", "{", "return", "filters", ";", "}", "var", "levels", "=", "[", "resourceName", ",", "adapterName", ",", "operation", ",", "'before'", "]", ";", "filters", ".", "before", "=", "(", "traverseFilters", "(", "filterConfig", ",", "levels", ",", "0", ")", "||", "[", "]", ")", ".", "map", "(", "function", "(", "name", ")", "{", "return", "injector", ".", "loadModule", "(", "name", "+", "'Filter'", ")", ";", "}", ")", ";", "levels", "=", "[", "resourceName", ",", "adapterName", ",", "operation", ",", "'after'", "]", ";", "filters", ".", "after", "=", "(", "traverseFilters", "(", "filterConfig", ",", "levels", ",", "0", ")", "||", "[", "]", ")", ".", "map", "(", "function", "(", "name", ")", "{", "return", "injector", ".", "loadModule", "(", "name", "+", "'Filter'", ")", ";", "}", ")", ";", "return", "filters", ";", "}" ]
Get before and after filters based on the current request and the filter config @param resourceName @param adapterName @param operation @returns {{}}
[ "Get", "before", "and", "after", "filters", "based", "on", "the", "current", "request", "and", "the", "filter", "config" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/api.route.handler.js#L60-L77
train
gethuman/pancakes
lib/api.route.handler.js
processApiCall
function processApiCall(resource, operation, requestParams) { var service = injector.loadModule(utensils.getCamelCase(resource.name + '.service')); var adapterName = resource.adapters.api; // remove the keys that start with onBehalfOf _.each(requestParams, function (val, key) { if (key.indexOf('onBehalfOf') === 0) { delete requestParams[key]; } }); // hack fix for when _id not filled in if (requestParams._id === '{_id}') { delete requestParams._id; } // loop through request values and parse json for (var key in requestParams) { if (requestParams.hasOwnProperty(key)) { requestParams[key] = utensils.parseIfJson(requestParams[key]); } } var filters = getFilters(resource.name, adapterName, operation); return utensils.chainPromises(filters.before, requestParams) .then(function (filteredRequest) { requestParams = filteredRequest; return service[operation](requestParams); }) .then(function (data) { return utensils.chainPromises(filters.after, { caller: requestParams.caller, lang: requestParams.lang, resource: resource, inputData: requestParams.data, data: data }); }); }
javascript
function processApiCall(resource, operation, requestParams) { var service = injector.loadModule(utensils.getCamelCase(resource.name + '.service')); var adapterName = resource.adapters.api; // remove the keys that start with onBehalfOf _.each(requestParams, function (val, key) { if (key.indexOf('onBehalfOf') === 0) { delete requestParams[key]; } }); // hack fix for when _id not filled in if (requestParams._id === '{_id}') { delete requestParams._id; } // loop through request values and parse json for (var key in requestParams) { if (requestParams.hasOwnProperty(key)) { requestParams[key] = utensils.parseIfJson(requestParams[key]); } } var filters = getFilters(resource.name, adapterName, operation); return utensils.chainPromises(filters.before, requestParams) .then(function (filteredRequest) { requestParams = filteredRequest; return service[operation](requestParams); }) .then(function (data) { return utensils.chainPromises(filters.after, { caller: requestParams.caller, lang: requestParams.lang, resource: resource, inputData: requestParams.data, data: data }); }); }
[ "function", "processApiCall", "(", "resource", ",", "operation", ",", "requestParams", ")", "{", "var", "service", "=", "injector", ".", "loadModule", "(", "utensils", ".", "getCamelCase", "(", "resource", ".", "name", "+", "'.service'", ")", ")", ";", "var", "adapterName", "=", "resource", ".", "adapters", ".", "api", ";", "_", ".", "each", "(", "requestParams", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "key", ".", "indexOf", "(", "'onBehalfOf'", ")", "===", "0", ")", "{", "delete", "requestParams", "[", "key", "]", ";", "}", "}", ")", ";", "if", "(", "requestParams", ".", "_id", "===", "'{_id}'", ")", "{", "delete", "requestParams", ".", "_id", ";", "}", "for", "(", "var", "key", "in", "requestParams", ")", "{", "if", "(", "requestParams", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "requestParams", "[", "key", "]", "=", "utensils", ".", "parseIfJson", "(", "requestParams", "[", "key", "]", ")", ";", "}", "}", "var", "filters", "=", "getFilters", "(", "resource", ".", "name", ",", "adapterName", ",", "operation", ")", ";", "return", "utensils", ".", "chainPromises", "(", "filters", ".", "before", ",", "requestParams", ")", ".", "then", "(", "function", "(", "filteredRequest", ")", "{", "requestParams", "=", "filteredRequest", ";", "return", "service", "[", "operation", "]", "(", "requestParams", ")", ";", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "utensils", ".", "chainPromises", "(", "filters", ".", "after", ",", "{", "caller", ":", "requestParams", ".", "caller", ",", "lang", ":", "requestParams", ".", "lang", ",", "resource", ":", "resource", ",", "inputData", ":", "requestParams", ".", "data", ",", "data", ":", "data", "}", ")", ";", "}", ")", ";", "}" ]
Process an API call. This method is called from the server plugin. Basically, the server plugin is in charge of taking the API request initially and translating the input values from the web framework specific format to the pancakes format. Then the server plugin calls this method with the generic pancancakes values. @param resource @param operation @param requestParams
[ "Process", "an", "API", "call", ".", "This", "method", "is", "called", "from", "the", "server", "plugin", ".", "Basically", "the", "server", "plugin", "is", "in", "charge", "of", "taking", "the", "API", "request", "initially", "and", "translating", "the", "input", "values", "from", "the", "web", "framework", "specific", "format", "to", "the", "pancakes", "format", ".", "Then", "the", "server", "plugin", "calls", "this", "method", "with", "the", "generic", "pancancakes", "values", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/api.route.handler.js#L89-L125
train
gethuman/pancakes
lib/web.route.handler.js
loadInlineCss
function loadInlineCss(rootDir, apps) { _.each(apps, function (app, appName) { _.each(app.routes, function (route) { var filePath = rootDir + '/app/' + appName + '/inline/' + route.name + '.css'; if (route.inline && fs.existsSync(filePath)) { inlineCssCache[appName + '||' + route.name] = fs.readFileSync(filePath, { encoding: 'utf8' }); } }); }); }
javascript
function loadInlineCss(rootDir, apps) { _.each(apps, function (app, appName) { _.each(app.routes, function (route) { var filePath = rootDir + '/app/' + appName + '/inline/' + route.name + '.css'; if (route.inline && fs.existsSync(filePath)) { inlineCssCache[appName + '||' + route.name] = fs.readFileSync(filePath, { encoding: 'utf8' }); } }); }); }
[ "function", "loadInlineCss", "(", "rootDir", ",", "apps", ")", "{", "_", ".", "each", "(", "apps", ",", "function", "(", "app", ",", "appName", ")", "{", "_", ".", "each", "(", "app", ".", "routes", ",", "function", "(", "route", ")", "{", "var", "filePath", "=", "rootDir", "+", "'/app/'", "+", "appName", "+", "'/inline/'", "+", "route", ".", "name", "+", "'.css'", ";", "if", "(", "route", ".", "inline", "&&", "fs", ".", "existsSync", "(", "filePath", ")", ")", "{", "inlineCssCache", "[", "appName", "+", "'||'", "+", "route", ".", "name", "]", "=", "fs", ".", "readFileSync", "(", "filePath", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Load all inline css files from the file system @param rootDir @param apps
[ "Load", "all", "inline", "css", "files", "from", "the", "file", "system" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L39-L48
train
gethuman/pancakes
lib/web.route.handler.js
convertUrlSegmentToRegex
function convertUrlSegmentToRegex(segment) { // if it has this format "{stuff}" - then it's regex-y var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); if (beginIdx < 0) { return segment; } // if capturing regex and trim trailing "}" // this could be a named regex {id:[0-9]+} or just name {companySlug} var pieces = segment.split(':'); if (pieces.length === 2) { if ( pieces[1] === (urlPathPatternSymbol + '}') ) { // special case where we want to capture the whole remaining path, even slashes, like /search/a/b/c/ return urlPathPattern; } else { return '(' + pieces[1].substring(0, pieces[1].length - 1) + ')'; } } else if (pieces.length === 1) { return segment.substring(0, beginIdx) + '[^\\/]+' + segment.substring(endIdx + 1); } else { throw new Error('Weird URL segment- don\'t know how to parse! ' + segment); } }
javascript
function convertUrlSegmentToRegex(segment) { // if it has this format "{stuff}" - then it's regex-y var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); if (beginIdx < 0) { return segment; } // if capturing regex and trim trailing "}" // this could be a named regex {id:[0-9]+} or just name {companySlug} var pieces = segment.split(':'); if (pieces.length === 2) { if ( pieces[1] === (urlPathPatternSymbol + '}') ) { // special case where we want to capture the whole remaining path, even slashes, like /search/a/b/c/ return urlPathPattern; } else { return '(' + pieces[1].substring(0, pieces[1].length - 1) + ')'; } } else if (pieces.length === 1) { return segment.substring(0, beginIdx) + '[^\\/]+' + segment.substring(endIdx + 1); } else { throw new Error('Weird URL segment- don\'t know how to parse! ' + segment); } }
[ "function", "convertUrlSegmentToRegex", "(", "segment", ")", "{", "var", "beginIdx", "=", "segment", ".", "indexOf", "(", "'{'", ")", ";", "var", "endIdx", "=", "segment", ".", "indexOf", "(", "'}'", ")", ";", "if", "(", "beginIdx", "<", "0", ")", "{", "return", "segment", ";", "}", "var", "pieces", "=", "segment", ".", "split", "(", "':'", ")", ";", "if", "(", "pieces", ".", "length", "===", "2", ")", "{", "if", "(", "pieces", "[", "1", "]", "===", "(", "urlPathPatternSymbol", "+", "'}'", ")", ")", "{", "return", "urlPathPattern", ";", "}", "else", "{", "return", "'('", "+", "pieces", "[", "1", "]", ".", "substring", "(", "0", ",", "pieces", "[", "1", "]", ".", "length", "-", "1", ")", "+", "')'", ";", "}", "}", "else", "if", "(", "pieces", ".", "length", "===", "1", ")", "{", "return", "segment", ".", "substring", "(", "0", ",", "beginIdx", ")", "+", "'[^\\\\/]+'", "+", "\\\\", ";", "}", "else", "segment", ".", "substring", "(", "endIdx", "+", "1", ")", "}" ]
Convert a segment of URL to a regex pattern for full URL casting below @param segment @returns string A segment as a URL pattern string
[ "Convert", "a", "segment", "of", "URL", "to", "a", "regex", "pattern", "for", "full", "URL", "casting", "below" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L55-L83
train
gethuman/pancakes
lib/web.route.handler.js
getTokenValuesFromUrl
function getTokenValuesFromUrl(pattern, url) { var tokenValues = {}, urlSegments = url.split('/'); pattern.split('/').forEach(function (segment, idx) { // this has this form {stuff}, so let's dig var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); var endLen = segment.length - endIdx - 1; var urlSegment = urlSegments[idx]; if (beginIdx > -1) { // peel off the { and } at the ends segment = segment.substring(beginIdx + 1, endIdx); var pieces = segment.split(':'); if (pieces.length === 2 && pieces[1] === urlPathPatternSymbol ) { var vals = [urlSegment.substring(beginIdx, urlSegment.length - endLen)]; for ( var i = idx + 1, len = urlSegments.length; i < len; i++ ) { vals.push(urlSegments[i]); } tokenValues[pieces[0]] = vals.join('%20'); // join any remaining segments with a space } else if (pieces.length === 2 || pieces.length === 1) { tokenValues[pieces[0]] = urlSegment.substring(beginIdx, urlSegment.length - endLen); } } // else no token to grab }); return tokenValues; }
javascript
function getTokenValuesFromUrl(pattern, url) { var tokenValues = {}, urlSegments = url.split('/'); pattern.split('/').forEach(function (segment, idx) { // this has this form {stuff}, so let's dig var beginIdx = segment.indexOf('{'); var endIdx = segment.indexOf('}'); var endLen = segment.length - endIdx - 1; var urlSegment = urlSegments[idx]; if (beginIdx > -1) { // peel off the { and } at the ends segment = segment.substring(beginIdx + 1, endIdx); var pieces = segment.split(':'); if (pieces.length === 2 && pieces[1] === urlPathPatternSymbol ) { var vals = [urlSegment.substring(beginIdx, urlSegment.length - endLen)]; for ( var i = idx + 1, len = urlSegments.length; i < len; i++ ) { vals.push(urlSegments[i]); } tokenValues[pieces[0]] = vals.join('%20'); // join any remaining segments with a space } else if (pieces.length === 2 || pieces.length === 1) { tokenValues[pieces[0]] = urlSegment.substring(beginIdx, urlSegment.length - endLen); } } // else no token to grab }); return tokenValues; }
[ "function", "getTokenValuesFromUrl", "(", "pattern", ",", "url", ")", "{", "var", "tokenValues", "=", "{", "}", ",", "urlSegments", "=", "url", ".", "split", "(", "'/'", ")", ";", "pattern", ".", "split", "(", "'/'", ")", ".", "forEach", "(", "function", "(", "segment", ",", "idx", ")", "{", "var", "beginIdx", "=", "segment", ".", "indexOf", "(", "'{'", ")", ";", "var", "endIdx", "=", "segment", ".", "indexOf", "(", "'}'", ")", ";", "var", "endLen", "=", "segment", ".", "length", "-", "endIdx", "-", "1", ";", "var", "urlSegment", "=", "urlSegments", "[", "idx", "]", ";", "if", "(", "beginIdx", ">", "-", "1", ")", "{", "segment", "=", "segment", ".", "substring", "(", "beginIdx", "+", "1", ",", "endIdx", ")", ";", "var", "pieces", "=", "segment", ".", "split", "(", "':'", ")", ";", "if", "(", "pieces", ".", "length", "===", "2", "&&", "pieces", "[", "1", "]", "===", "urlPathPatternSymbol", ")", "{", "var", "vals", "=", "[", "urlSegment", ".", "substring", "(", "beginIdx", ",", "urlSegment", ".", "length", "-", "endLen", ")", "]", ";", "for", "(", "var", "i", "=", "idx", "+", "1", ",", "len", "=", "urlSegments", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "vals", ".", "push", "(", "urlSegments", "[", "i", "]", ")", ";", "}", "tokenValues", "[", "pieces", "[", "0", "]", "]", "=", "vals", ".", "join", "(", "'%20'", ")", ";", "}", "else", "if", "(", "pieces", ".", "length", "===", "2", "||", "pieces", ".", "length", "===", "1", ")", "{", "tokenValues", "[", "pieces", "[", "0", "]", "]", "=", "urlSegment", ".", "substring", "(", "beginIdx", ",", "urlSegment", ".", "length", "-", "endLen", ")", ";", "}", "}", "}", ")", ";", "return", "tokenValues", ";", "}" ]
Use a given pattern to extract tokens from a given URL @param pattern @param url @returns {{}}
[ "Use", "a", "given", "pattern", "to", "extract", "tokens", "from", "a", "given", "URL" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L129-L161
train
gethuman/pancakes
lib/web.route.handler.js
getRouteInfo
function getRouteInfo(appName, urlRequest, query, lang, user, referrer) { var activeUser = user ? { _id: user._id, name: user.username, role: user.role, user: user } : {}; // if route info already in cache, return it var cacheKey = appName + '||' + lang + '||' + urlRequest; var cachedRouteInfo = routeInfoCache[cacheKey]; if (!user && cachedRouteInfo) { cachedRouteInfo.query = query; // query shouldn't be cached return cachedRouteInfo; } // if urlRequest ends in .html it is an amp request so treat it as such var isAmp = /\.html$/.test(urlRequest); if (isAmp) { urlRequest = urlRequest.substring(0, urlRequest.length - 5); } // get the routes and then find the info that matches the current URL var url = urlRequest.toLowerCase(); var i, route, routeInfo; var routes = getRoutes(appName); if (routes) { // loop through routes trying to find the one that matches for (i = 0; i < routes.length; i++) { route = routes[i]; // if there is a match, save the info to cache and return it if (route.urlRegex.test(url)) { routeInfo = _.extend({ appName: appName, referrer: referrer, lang: lang, url: urlRequest, query: query, activeUser: activeUser, isAmp: isAmp, tokens: getTokenValuesFromUrl(route.urlPattern, urlRequest) }, route); // change layout wrapper to amp if request is for amp if (isAmp) { routeInfo.wrapper = 'amp'; } // if no user, then save request in cache if (!user) { routeInfoCache[cacheKey] = routeInfo; } return routeInfo; } } } // if we get here, then no route found, so throw 404 error throw new Error('404: ' + appName + ' ' + urlRequest + ' is not a valid request'); }
javascript
function getRouteInfo(appName, urlRequest, query, lang, user, referrer) { var activeUser = user ? { _id: user._id, name: user.username, role: user.role, user: user } : {}; // if route info already in cache, return it var cacheKey = appName + '||' + lang + '||' + urlRequest; var cachedRouteInfo = routeInfoCache[cacheKey]; if (!user && cachedRouteInfo) { cachedRouteInfo.query = query; // query shouldn't be cached return cachedRouteInfo; } // if urlRequest ends in .html it is an amp request so treat it as such var isAmp = /\.html$/.test(urlRequest); if (isAmp) { urlRequest = urlRequest.substring(0, urlRequest.length - 5); } // get the routes and then find the info that matches the current URL var url = urlRequest.toLowerCase(); var i, route, routeInfo; var routes = getRoutes(appName); if (routes) { // loop through routes trying to find the one that matches for (i = 0; i < routes.length; i++) { route = routes[i]; // if there is a match, save the info to cache and return it if (route.urlRegex.test(url)) { routeInfo = _.extend({ appName: appName, referrer: referrer, lang: lang, url: urlRequest, query: query, activeUser: activeUser, isAmp: isAmp, tokens: getTokenValuesFromUrl(route.urlPattern, urlRequest) }, route); // change layout wrapper to amp if request is for amp if (isAmp) { routeInfo.wrapper = 'amp'; } // if no user, then save request in cache if (!user) { routeInfoCache[cacheKey] = routeInfo; } return routeInfo; } } } // if we get here, then no route found, so throw 404 error throw new Error('404: ' + appName + ' ' + urlRequest + ' is not a valid request'); }
[ "function", "getRouteInfo", "(", "appName", ",", "urlRequest", ",", "query", ",", "lang", ",", "user", ",", "referrer", ")", "{", "var", "activeUser", "=", "user", "?", "{", "_id", ":", "user", ".", "_id", ",", "name", ":", "user", ".", "username", ",", "role", ":", "user", ".", "role", ",", "user", ":", "user", "}", ":", "{", "}", ";", "var", "cacheKey", "=", "appName", "+", "'||'", "+", "lang", "+", "'||'", "+", "urlRequest", ";", "var", "cachedRouteInfo", "=", "routeInfoCache", "[", "cacheKey", "]", ";", "if", "(", "!", "user", "&&", "cachedRouteInfo", ")", "{", "cachedRouteInfo", ".", "query", "=", "query", ";", "return", "cachedRouteInfo", ";", "}", "var", "isAmp", "=", "/", "\\.html$", "/", ".", "test", "(", "urlRequest", ")", ";", "if", "(", "isAmp", ")", "{", "urlRequest", "=", "urlRequest", ".", "substring", "(", "0", ",", "urlRequest", ".", "length", "-", "5", ")", ";", "}", "var", "url", "=", "urlRequest", ".", "toLowerCase", "(", ")", ";", "var", "i", ",", "route", ",", "routeInfo", ";", "var", "routes", "=", "getRoutes", "(", "appName", ")", ";", "if", "(", "routes", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "routes", ".", "length", ";", "i", "++", ")", "{", "route", "=", "routes", "[", "i", "]", ";", "if", "(", "route", ".", "urlRegex", ".", "test", "(", "url", ")", ")", "{", "routeInfo", "=", "_", ".", "extend", "(", "{", "appName", ":", "appName", ",", "referrer", ":", "referrer", ",", "lang", ":", "lang", ",", "url", ":", "urlRequest", ",", "query", ":", "query", ",", "activeUser", ":", "activeUser", ",", "isAmp", ":", "isAmp", ",", "tokens", ":", "getTokenValuesFromUrl", "(", "route", ".", "urlPattern", ",", "urlRequest", ")", "}", ",", "route", ")", ";", "if", "(", "isAmp", ")", "{", "routeInfo", ".", "wrapper", "=", "'amp'", ";", "}", "if", "(", "!", "user", ")", "{", "routeInfoCache", "[", "cacheKey", "]", "=", "routeInfo", ";", "}", "return", "routeInfo", ";", "}", "}", "}", "throw", "new", "Error", "(", "'404: '", "+", "appName", "+", "' '", "+", "urlRequest", "+", "' is not a valid request'", ")", ";", "}" ]
Get info for particular route @param appName @param urlRequest @param query @param lang @param user @param referrer @returns {{}} The routeInfo for a particular request
[ "Get", "info", "for", "particular", "route" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L208-L269
train
gethuman/pancakes
lib/web.route.handler.js
setDefaults
function setDefaults(model, defaults) { if (!defaults) { return; } _.each(defaults, function (value, key) { if (model[key] === undefined) { model[key] = value; } }); }
javascript
function setDefaults(model, defaults) { if (!defaults) { return; } _.each(defaults, function (value, key) { if (model[key] === undefined) { model[key] = value; } }); }
[ "function", "setDefaults", "(", "model", ",", "defaults", ")", "{", "if", "(", "!", "defaults", ")", "{", "return", ";", "}", "_", ".", "each", "(", "defaults", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "model", "[", "key", "]", "===", "undefined", ")", "{", "model", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "}" ]
If a default value doesn't exist in the model, set it @param model @param defaults
[ "If", "a", "default", "value", "doesn", "t", "exist", "in", "the", "model", "set", "it" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L276-L284
train
gethuman/pancakes
lib/web.route.handler.js
getInitialModel
function getInitialModel(routeInfo, page) { var initModelDeps = { appName: routeInfo.appName, tokens: routeInfo.tokens, routeInfo: routeInfo, defaults: page.defaults, activeUser: routeInfo.activeUser || {}, currentScope: {} }; // if no model, just return empty object if (!page.model) { return Q.when({}); } // if function, inject and the returned value is the model else if (_.isFunction(page.model)) { return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps })); } else { throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model); } }
javascript
function getInitialModel(routeInfo, page) { var initModelDeps = { appName: routeInfo.appName, tokens: routeInfo.tokens, routeInfo: routeInfo, defaults: page.defaults, activeUser: routeInfo.activeUser || {}, currentScope: {} }; // if no model, just return empty object if (!page.model) { return Q.when({}); } // if function, inject and the returned value is the model else if (_.isFunction(page.model)) { return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps })); } else { throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model); } }
[ "function", "getInitialModel", "(", "routeInfo", ",", "page", ")", "{", "var", "initModelDeps", "=", "{", "appName", ":", "routeInfo", ".", "appName", ",", "tokens", ":", "routeInfo", ".", "tokens", ",", "routeInfo", ":", "routeInfo", ",", "defaults", ":", "page", ".", "defaults", ",", "activeUser", ":", "routeInfo", ".", "activeUser", "||", "{", "}", ",", "currentScope", ":", "{", "}", "}", ";", "if", "(", "!", "page", ".", "model", ")", "{", "return", "Q", ".", "when", "(", "{", "}", ")", ";", "}", "else", "if", "(", "_", ".", "isFunction", "(", "page", ".", "model", ")", ")", "{", "return", "Q", ".", "when", "(", "injector", ".", "loadModule", "(", "page", ".", "model", ",", "null", ",", "{", "dependencies", ":", "initModelDeps", "}", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "routeInfo", ".", "name", "+", "' page invalid model() format: '", "+", "page", ".", "model", ")", ";", "}", "}" ]
Get the initial model for a given page @param routeInfo @param page
[ "Get", "the", "initial", "model", "for", "a", "given", "page" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L291-L312
train
gethuman/pancakes
lib/web.route.handler.js
processWebRequest
function processWebRequest(routeInfo, callbacks) { var appName = routeInfo.appName; var serverOnly = !!routeInfo.query.server; var page = injector.loadModule('app/' + appName + '/pages/' + routeInfo.name + '.page'); // get the callbacks var serverPreprocessing = callbacks.serverPreprocessing || function () { return false; }; var appAddToModel = callbacks.addToModel || function () {}; var pageCacheService = callbacks.pageCacheService || defaultPageCache; var initialModel, cacheKey; return getInitialModel(routeInfo, page) .then(function (model) { initialModel = model || {}; // if the server pre-processing returns true, then return without doing anything // this is because the pre-processor sent a reply to the user already if (serverPreprocessing(routeInfo, page, model)) { return true; } //TODO: may be weird edge cases with this. need to test more to ensure performance and uniqueness // but note that we have an hour default timeout for the redis cache just in case // and we have the redis LRU config set up so the least recently used will get pushed out cacheKey = utensils.checksum(routeInfo.lang + '||' + routeInfo.appName + '||' + routeInfo.url + '||' + JSON.stringify(model)); return pageCacheService.get({ key: cacheKey }); }) .then(function (cachedPage) { if (cachedPage === true) { return null; } if (cachedPage && !serverOnly) { return cachedPage; } // allow the app level to modify the model before rendering appAddToModel(initialModel, routeInfo); // finally use the client side plugin to do the rendering return clientPlugin.renderPage(routeInfo, page, initialModel, inlineCssCache[appName + '||' + routeInfo.name]); }) .then(function (renderedPage) { if (!serverOnly && renderedPage) { pageCacheService.set({ key: cacheKey, value: renderedPage }); } return renderedPage; }); }
javascript
function processWebRequest(routeInfo, callbacks) { var appName = routeInfo.appName; var serverOnly = !!routeInfo.query.server; var page = injector.loadModule('app/' + appName + '/pages/' + routeInfo.name + '.page'); // get the callbacks var serverPreprocessing = callbacks.serverPreprocessing || function () { return false; }; var appAddToModel = callbacks.addToModel || function () {}; var pageCacheService = callbacks.pageCacheService || defaultPageCache; var initialModel, cacheKey; return getInitialModel(routeInfo, page) .then(function (model) { initialModel = model || {}; // if the server pre-processing returns true, then return without doing anything // this is because the pre-processor sent a reply to the user already if (serverPreprocessing(routeInfo, page, model)) { return true; } //TODO: may be weird edge cases with this. need to test more to ensure performance and uniqueness // but note that we have an hour default timeout for the redis cache just in case // and we have the redis LRU config set up so the least recently used will get pushed out cacheKey = utensils.checksum(routeInfo.lang + '||' + routeInfo.appName + '||' + routeInfo.url + '||' + JSON.stringify(model)); return pageCacheService.get({ key: cacheKey }); }) .then(function (cachedPage) { if (cachedPage === true) { return null; } if (cachedPage && !serverOnly) { return cachedPage; } // allow the app level to modify the model before rendering appAddToModel(initialModel, routeInfo); // finally use the client side plugin to do the rendering return clientPlugin.renderPage(routeInfo, page, initialModel, inlineCssCache[appName + '||' + routeInfo.name]); }) .then(function (renderedPage) { if (!serverOnly && renderedPage) { pageCacheService.set({ key: cacheKey, value: renderedPage }); } return renderedPage; }); }
[ "function", "processWebRequest", "(", "routeInfo", ",", "callbacks", ")", "{", "var", "appName", "=", "routeInfo", ".", "appName", ";", "var", "serverOnly", "=", "!", "!", "routeInfo", ".", "query", ".", "server", ";", "var", "page", "=", "injector", ".", "loadModule", "(", "'app/'", "+", "appName", "+", "'/pages/'", "+", "routeInfo", ".", "name", "+", "'.page'", ")", ";", "var", "serverPreprocessing", "=", "callbacks", ".", "serverPreprocessing", "||", "function", "(", ")", "{", "return", "false", ";", "}", ";", "var", "appAddToModel", "=", "callbacks", ".", "addToModel", "||", "function", "(", ")", "{", "}", ";", "var", "pageCacheService", "=", "callbacks", ".", "pageCacheService", "||", "defaultPageCache", ";", "var", "initialModel", ",", "cacheKey", ";", "return", "getInitialModel", "(", "routeInfo", ",", "page", ")", ".", "then", "(", "function", "(", "model", ")", "{", "initialModel", "=", "model", "||", "{", "}", ";", "if", "(", "serverPreprocessing", "(", "routeInfo", ",", "page", ",", "model", ")", ")", "{", "return", "true", ";", "}", "cacheKey", "=", "utensils", ".", "checksum", "(", "routeInfo", ".", "lang", "+", "'||'", "+", "routeInfo", ".", "appName", "+", "'||'", "+", "routeInfo", ".", "url", "+", "'||'", "+", "JSON", ".", "stringify", "(", "model", ")", ")", ";", "return", "pageCacheService", ".", "get", "(", "{", "key", ":", "cacheKey", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "cachedPage", ")", "{", "if", "(", "cachedPage", "===", "true", ")", "{", "return", "null", ";", "}", "if", "(", "cachedPage", "&&", "!", "serverOnly", ")", "{", "return", "cachedPage", ";", "}", "appAddToModel", "(", "initialModel", ",", "routeInfo", ")", ";", "return", "clientPlugin", ".", "renderPage", "(", "routeInfo", ",", "page", ",", "initialModel", ",", "inlineCssCache", "[", "appName", "+", "'||'", "+", "routeInfo", ".", "name", "]", ")", ";", "}", ")", ".", "then", "(", "function", "(", "renderedPage", ")", "{", "if", "(", "!", "serverOnly", "&&", "renderedPage", ")", "{", "pageCacheService", ".", "set", "(", "{", "key", ":", "cacheKey", ",", "value", ":", "renderedPage", "}", ")", ";", "}", "return", "renderedPage", ";", "}", ")", ";", "}" ]
This function is called by the server plugin when we have a request and we need to process it. The plugin should handle translating the server platform specific values into our routeInfo @param routeInfo @param callbacks
[ "This", "function", "is", "called", "by", "the", "server", "plugin", "when", "we", "have", "a", "request", "and", "we", "need", "to", "process", "it", ".", "The", "plugin", "should", "handle", "translating", "the", "server", "platform", "specific", "values", "into", "our", "routeInfo" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/web.route.handler.js#L322-L368
train
gethuman/pancakes
lib/transformers/transformer.factory.js
generateTransformer
function generateTransformer(name, transformerFns, templateDir, pluginOptions) { var Transformer = function () {}; var transformer = new Transformer(); // add function mixins to the transformer _.extend(transformer, transformerFns, baseTransformer, annotationHelper, utensils, pluginOptions); // add reference to the template function transformer.setTemplate(templateDir, name, pluginOptions.clientType); // each transformer can reference each other transformer.transformers = cache; // return the transformer return transformer; }
javascript
function generateTransformer(name, transformerFns, templateDir, pluginOptions) { var Transformer = function () {}; var transformer = new Transformer(); // add function mixins to the transformer _.extend(transformer, transformerFns, baseTransformer, annotationHelper, utensils, pluginOptions); // add reference to the template function transformer.setTemplate(templateDir, name, pluginOptions.clientType); // each transformer can reference each other transformer.transformers = cache; // return the transformer return transformer; }
[ "function", "generateTransformer", "(", "name", ",", "transformerFns", ",", "templateDir", ",", "pluginOptions", ")", "{", "var", "Transformer", "=", "function", "(", ")", "{", "}", ";", "var", "transformer", "=", "new", "Transformer", "(", ")", ";", "_", ".", "extend", "(", "transformer", ",", "transformerFns", ",", "baseTransformer", ",", "annotationHelper", ",", "utensils", ",", "pluginOptions", ")", ";", "transformer", ".", "setTemplate", "(", "templateDir", ",", "name", ",", "pluginOptions", ".", "clientType", ")", ";", "transformer", ".", "transformers", "=", "cache", ";", "return", "transformer", ";", "}" ]
Generate a transformer object based off the input params @param name @param transformerFns @param templateDir @param pluginOptions
[ "Generate", "a", "transformer", "object", "based", "off", "the", "input", "params" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/transformer.factory.js#L20-L36
train
gethuman/pancakes
lib/transformers/transformer.factory.js
getTransformer
function getTransformer(name, clientPlugin, pluginOptions) { // if in cache, just return it if (cache[name]) { return cache[name]; } var transformers = clientPlugin.transformers; var templateDir = clientPlugin.templateDir; // if no transformer, throw error if (!transformers[name]) { throw new Error('No transformer called ' + name); } // generate all the transformers _.each(transformers, function (transformer, transformerName) { cache[transformerName] = generateTransformer(transformerName, transformer, templateDir, pluginOptions); }); // return the specific one that was requested return cache[name]; }
javascript
function getTransformer(name, clientPlugin, pluginOptions) { // if in cache, just return it if (cache[name]) { return cache[name]; } var transformers = clientPlugin.transformers; var templateDir = clientPlugin.templateDir; // if no transformer, throw error if (!transformers[name]) { throw new Error('No transformer called ' + name); } // generate all the transformers _.each(transformers, function (transformer, transformerName) { cache[transformerName] = generateTransformer(transformerName, transformer, templateDir, pluginOptions); }); // return the specific one that was requested return cache[name]; }
[ "function", "getTransformer", "(", "name", ",", "clientPlugin", ",", "pluginOptions", ")", "{", "if", "(", "cache", "[", "name", "]", ")", "{", "return", "cache", "[", "name", "]", ";", "}", "var", "transformers", "=", "clientPlugin", ".", "transformers", ";", "var", "templateDir", "=", "clientPlugin", ".", "templateDir", ";", "if", "(", "!", "transformers", "[", "name", "]", ")", "{", "throw", "new", "Error", "(", "'No transformer called '", "+", "name", ")", ";", "}", "_", ".", "each", "(", "transformers", ",", "function", "(", "transformer", ",", "transformerName", ")", "{", "cache", "[", "transformerName", "]", "=", "generateTransformer", "(", "transformerName", ",", "transformer", ",", "templateDir", ",", "pluginOptions", ")", ";", "}", ")", ";", "return", "cache", "[", "name", "]", ";", "}" ]
Get a particular transformer from cache or generate it @param name @param clientPlugin @param pluginOptions
[ "Get", "a", "particular", "transformer", "from", "cache", "or", "generate", "it" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/transformer.factory.js#L44-L62
train
gethuman/pancakes
lib/pancakes.js
init
function init(opts) { opts = opts || {}; // include pancakes instance into options that we pass to plugins opts.pluginOptions = opts.pluginOptions || {}; opts.pluginOptions.pancakes = exports; injector = new DependencyInjector(opts); var ClientPlugin = opts.clientPlugin; var ServerPlugin = opts.serverPlugin; if (ClientPlugin) { clientPlugin = new ClientPlugin(opts); } if (ServerPlugin) { serverPlugin = new ServerPlugin(opts); } apiRouteHandler.init({ injector: injector }); webRouteHandler.init({ injector: injector, clientPlugin: clientPlugin, rootDir: opts.rootDir }); }
javascript
function init(opts) { opts = opts || {}; // include pancakes instance into options that we pass to plugins opts.pluginOptions = opts.pluginOptions || {}; opts.pluginOptions.pancakes = exports; injector = new DependencyInjector(opts); var ClientPlugin = opts.clientPlugin; var ServerPlugin = opts.serverPlugin; if (ClientPlugin) { clientPlugin = new ClientPlugin(opts); } if (ServerPlugin) { serverPlugin = new ServerPlugin(opts); } apiRouteHandler.init({ injector: injector }); webRouteHandler.init({ injector: injector, clientPlugin: clientPlugin, rootDir: opts.rootDir }); }
[ "function", "init", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "opts", ".", "pluginOptions", "=", "opts", ".", "pluginOptions", "||", "{", "}", ";", "opts", ".", "pluginOptions", ".", "pancakes", "=", "exports", ";", "injector", "=", "new", "DependencyInjector", "(", "opts", ")", ";", "var", "ClientPlugin", "=", "opts", ".", "clientPlugin", ";", "var", "ServerPlugin", "=", "opts", ".", "serverPlugin", ";", "if", "(", "ClientPlugin", ")", "{", "clientPlugin", "=", "new", "ClientPlugin", "(", "opts", ")", ";", "}", "if", "(", "ServerPlugin", ")", "{", "serverPlugin", "=", "new", "ServerPlugin", "(", "opts", ")", ";", "}", "apiRouteHandler", ".", "init", "(", "{", "injector", ":", "injector", "}", ")", ";", "webRouteHandler", ".", "init", "(", "{", "injector", ":", "injector", ",", "clientPlugin", ":", "clientPlugin", ",", "rootDir", ":", "opts", ".", "rootDir", "}", ")", ";", "}" ]
For now this is just a passthrough to the injector's init function @param opts
[ "For", "now", "this", "is", "just", "a", "passthrough", "to", "the", "injector", "s", "init", "function" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L24-L40
train
gethuman/pancakes
lib/pancakes.js
initContainer
function initContainer(opts) { var apps, appDir; container = opts.container; // if batch, preload that dir container === 'batch' ? opts.preload.push('batch') : opts.preload.push('middleware'); if (container === 'webserver') { appDir = path.join(opts.rootDir, '/app'); apps = fs.readdirSync(appDir); _.each(apps, function (app) { opts.preload = opts.preload.concat([ 'app/' + app + '/filters', 'app/' + app + '/utils' ]); }); } init(opts); }
javascript
function initContainer(opts) { var apps, appDir; container = opts.container; // if batch, preload that dir container === 'batch' ? opts.preload.push('batch') : opts.preload.push('middleware'); if (container === 'webserver') { appDir = path.join(opts.rootDir, '/app'); apps = fs.readdirSync(appDir); _.each(apps, function (app) { opts.preload = opts.preload.concat([ 'app/' + app + '/filters', 'app/' + app + '/utils' ]); }); } init(opts); }
[ "function", "initContainer", "(", "opts", ")", "{", "var", "apps", ",", "appDir", ";", "container", "=", "opts", ".", "container", ";", "container", "===", "'batch'", "?", "opts", ".", "preload", ".", "push", "(", "'batch'", ")", ":", "opts", ".", "preload", ".", "push", "(", "'middleware'", ")", ";", "if", "(", "container", "===", "'webserver'", ")", "{", "appDir", "=", "path", ".", "join", "(", "opts", ".", "rootDir", ",", "'/app'", ")", ";", "apps", "=", "fs", ".", "readdirSync", "(", "appDir", ")", ";", "_", ".", "each", "(", "apps", ",", "function", "(", "app", ")", "{", "opts", ".", "preload", "=", "opts", ".", "preload", ".", "concat", "(", "[", "'app/'", "+", "app", "+", "'/filters'", ",", "'app/'", "+", "app", "+", "'/utils'", "]", ")", ";", "}", ")", ";", "}", "init", "(", "opts", ")", ";", "}" ]
Convenience function for apps to use. Calls init after setting some values. @param opts
[ "Convenience", "function", "for", "apps", "to", "use", ".", "Calls", "init", "after", "setting", "some", "values", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L48-L70
train
gethuman/pancakes
lib/pancakes.js
requireModule
function requireModule(filePath, refreshFlag) { if (refreshFlag) { delete injector.require.cache[filePath]; } return injector.require(filePath); }
javascript
function requireModule(filePath, refreshFlag) { if (refreshFlag) { delete injector.require.cache[filePath]; } return injector.require(filePath); }
[ "function", "requireModule", "(", "filePath", ",", "refreshFlag", ")", "{", "if", "(", "refreshFlag", ")", "{", "delete", "injector", ".", "require", ".", "cache", "[", "filePath", "]", ";", "}", "return", "injector", ".", "require", "(", "filePath", ")", ";", "}" ]
Use the injector require which should be passed in during initialization @param filePath @param refreshFlag @returns {injector.require|*|require}
[ "Use", "the", "injector", "require", "which", "should", "be", "passed", "in", "during", "initialization" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L78-L83
train
gethuman/pancakes
lib/pancakes.js
getService
function getService(name) { if (name.indexOf('.') >= 0) { name = utils.getCamelCase(name); } if (!name.match(/^.*Service$/)) { name += 'Service'; } return cook(name); }
javascript
function getService(name) { if (name.indexOf('.') >= 0) { name = utils.getCamelCase(name); } if (!name.match(/^.*Service$/)) { name += 'Service'; } return cook(name); }
[ "function", "getService", "(", "name", ")", "{", "if", "(", "name", ".", "indexOf", "(", "'.'", ")", ">=", "0", ")", "{", "name", "=", "utils", ".", "getCamelCase", "(", "name", ")", ";", "}", "if", "(", "!", "name", ".", "match", "(", "/", "^.*Service$", "/", ")", ")", "{", "name", "+=", "'Service'", ";", "}", "return", "cook", "(", "name", ")", ";", "}" ]
Get the service for a given resource name @param name
[ "Get", "the", "service", "for", "a", "given", "resource", "name" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L98-L108
train
gethuman/pancakes
lib/pancakes.js
transform
function transform(flapjack, pluginOptions, runtimeOptions) { var name = runtimeOptions.transformer; var transformer = transformerFactory.getTransformer(name, clientPlugin, pluginOptions); var options = _.extend({}, pluginOptions, runtimeOptions); return transformer.transform(flapjack, options); }
javascript
function transform(flapjack, pluginOptions, runtimeOptions) { var name = runtimeOptions.transformer; var transformer = transformerFactory.getTransformer(name, clientPlugin, pluginOptions); var options = _.extend({}, pluginOptions, runtimeOptions); return transformer.transform(flapjack, options); }
[ "function", "transform", "(", "flapjack", ",", "pluginOptions", ",", "runtimeOptions", ")", "{", "var", "name", "=", "runtimeOptions", ".", "transformer", ";", "var", "transformer", "=", "transformerFactory", ".", "getTransformer", "(", "name", ",", "clientPlugin", ",", "pluginOptions", ")", ";", "var", "options", "=", "_", ".", "extend", "(", "{", "}", ",", "pluginOptions", ",", "runtimeOptions", ")", ";", "return", "transformer", ".", "transform", "(", "flapjack", ",", "options", ")", ";", "}" ]
Use the transformer factory to find a transformer and return the generated code @param flapjack @param pluginOptions @param runtimeOptions @returns {*}
[ "Use", "the", "transformer", "factory", "to", "find", "a", "transformer", "and", "return", "the", "generated", "code" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/pancakes.js#L138-L143
train
creationix/topcube
sampleapp/www/todos.js
function(e) { var tooltip = this.$(".ui-tooltip-top"); var val = this.input.val(); tooltip.fadeOut(); if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout); if (val == '' || val == this.input.attr('placeholder')) return; var show = function(){ tooltip.show().fadeIn(); }; this.tooltipTimeout = _.delay(show, 1000); }
javascript
function(e) { var tooltip = this.$(".ui-tooltip-top"); var val = this.input.val(); tooltip.fadeOut(); if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout); if (val == '' || val == this.input.attr('placeholder')) return; var show = function(){ tooltip.show().fadeIn(); }; this.tooltipTimeout = _.delay(show, 1000); }
[ "function", "(", "e", ")", "{", "var", "tooltip", "=", "this", ".", "$", "(", "\".ui-tooltip-top\"", ")", ";", "var", "val", "=", "this", ".", "input", ".", "val", "(", ")", ";", "tooltip", ".", "fadeOut", "(", ")", ";", "if", "(", "this", ".", "tooltipTimeout", ")", "clearTimeout", "(", "this", ".", "tooltipTimeout", ")", ";", "if", "(", "val", "==", "''", "||", "val", "==", "this", ".", "input", ".", "attr", "(", "'placeholder'", ")", ")", "return", ";", "var", "show", "=", "function", "(", ")", "{", "tooltip", ".", "show", "(", ")", ".", "fadeIn", "(", ")", ";", "}", ";", "this", ".", "tooltipTimeout", "=", "_", ".", "delay", "(", "show", ",", "1000", ")", ";", "}" ]
Lazily show the tooltip that tells you to press `enter` to save a new todo item, after one second.
[ "Lazily", "show", "the", "tooltip", "that", "tells", "you", "to", "press", "enter", "to", "save", "a", "new", "todo", "item", "after", "one", "second", "." ]
96ff0177bf8f490cabd78eb7b63be6b1bc126d23
https://github.com/creationix/topcube/blob/96ff0177bf8f490cabd78eb7b63be6b1bc126d23/sampleapp/www/todos.js#L241-L249
train
gethuman/pancakes
lib/factories/uipart.factory.js
getUiPart
function getUiPart(modulePath, options) { var rootDir = this.injector.rootDir; var tplDir = (options && options.tplDir) || 'dist' + delim + 'tpls'; var pathParts = modulePath.split(delim); var appName = pathParts[1]; var len = modulePath.length; var filePath, fullModulePath, uipart, viewObj; // filePath has .js, modulePath does not if (modulePath.substring(len - 3) === '.js') { filePath = rootDir + delim + modulePath; fullModulePath = rootDir + delim + modulePath.substring(0, len - 3); } else { filePath = rootDir + delim + modulePath + '.js'; fullModulePath = rootDir + delim + modulePath; } // if exists, get it if (fs.existsSync(filePath)) { uipart = this.injector.require(fullModulePath); } // else if in an app folder, try the common folder else if (appName !== 'common') { fullModulePath = fullModulePath.replace(delim + appName + delim, delim + 'common' + delim); uipart = this.injector.require(fullModulePath); appName = 'common'; } // if no view, check to see if precompiled in tpl dir var viewFile = fullModulePath.replace( delim + 'app' + delim + appName + delim, delim + tplDir + delim + appName + delim ); if (!uipart.view && fs.existsSync(viewFile + '.js')) { viewObj = this.injector.require(viewFile); uipart.view = function () { return viewObj; }; } return uipart; }
javascript
function getUiPart(modulePath, options) { var rootDir = this.injector.rootDir; var tplDir = (options && options.tplDir) || 'dist' + delim + 'tpls'; var pathParts = modulePath.split(delim); var appName = pathParts[1]; var len = modulePath.length; var filePath, fullModulePath, uipart, viewObj; // filePath has .js, modulePath does not if (modulePath.substring(len - 3) === '.js') { filePath = rootDir + delim + modulePath; fullModulePath = rootDir + delim + modulePath.substring(0, len - 3); } else { filePath = rootDir + delim + modulePath + '.js'; fullModulePath = rootDir + delim + modulePath; } // if exists, get it if (fs.existsSync(filePath)) { uipart = this.injector.require(fullModulePath); } // else if in an app folder, try the common folder else if (appName !== 'common') { fullModulePath = fullModulePath.replace(delim + appName + delim, delim + 'common' + delim); uipart = this.injector.require(fullModulePath); appName = 'common'; } // if no view, check to see if precompiled in tpl dir var viewFile = fullModulePath.replace( delim + 'app' + delim + appName + delim, delim + tplDir + delim + appName + delim ); if (!uipart.view && fs.existsSync(viewFile + '.js')) { viewObj = this.injector.require(viewFile); uipart.view = function () { return viewObj; }; } return uipart; }
[ "function", "getUiPart", "(", "modulePath", ",", "options", ")", "{", "var", "rootDir", "=", "this", ".", "injector", ".", "rootDir", ";", "var", "tplDir", "=", "(", "options", "&&", "options", ".", "tplDir", ")", "||", "'dist'", "+", "delim", "+", "'tpls'", ";", "var", "pathParts", "=", "modulePath", ".", "split", "(", "delim", ")", ";", "var", "appName", "=", "pathParts", "[", "1", "]", ";", "var", "len", "=", "modulePath", ".", "length", ";", "var", "filePath", ",", "fullModulePath", ",", "uipart", ",", "viewObj", ";", "if", "(", "modulePath", ".", "substring", "(", "len", "-", "3", ")", "===", "'.js'", ")", "{", "filePath", "=", "rootDir", "+", "delim", "+", "modulePath", ";", "fullModulePath", "=", "rootDir", "+", "delim", "+", "modulePath", ".", "substring", "(", "0", ",", "len", "-", "3", ")", ";", "}", "else", "{", "filePath", "=", "rootDir", "+", "delim", "+", "modulePath", "+", "'.js'", ";", "fullModulePath", "=", "rootDir", "+", "delim", "+", "modulePath", ";", "}", "if", "(", "fs", ".", "existsSync", "(", "filePath", ")", ")", "{", "uipart", "=", "this", ".", "injector", ".", "require", "(", "fullModulePath", ")", ";", "}", "else", "if", "(", "appName", "!==", "'common'", ")", "{", "fullModulePath", "=", "fullModulePath", ".", "replace", "(", "delim", "+", "appName", "+", "delim", ",", "delim", "+", "'common'", "+", "delim", ")", ";", "uipart", "=", "this", ".", "injector", ".", "require", "(", "fullModulePath", ")", ";", "appName", "=", "'common'", ";", "}", "var", "viewFile", "=", "fullModulePath", ".", "replace", "(", "delim", "+", "'app'", "+", "delim", "+", "appName", "+", "delim", ",", "delim", "+", "tplDir", "+", "delim", "+", "appName", "+", "delim", ")", ";", "if", "(", "!", "uipart", ".", "view", "&&", "fs", ".", "existsSync", "(", "viewFile", "+", "'.js'", ")", ")", "{", "viewObj", "=", "this", ".", "injector", ".", "require", "(", "viewFile", ")", ";", "uipart", ".", "view", "=", "function", "(", ")", "{", "return", "viewObj", ";", "}", ";", "}", "return", "uipart", ";", "}" ]
Get a UI Part @param modulePath @param options @returns {*}
[ "Get", "a", "UI", "Part" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/uipart.factory.js#L55-L97
train
gethuman/pancakes
lib/factories/service.factory.js
ServiceFactory
function ServiceFactory(injector) { this.cache = {}; this.injector = injector || {}; // if we are in debug mode, then add the debug handler var pattern = this.injector.debugPattern || '*.*.*.*.*'; var handler = this.injector.debugHandler || debugHandler; if (this.injector.debug) { eventBus.on(pattern, handler); } }
javascript
function ServiceFactory(injector) { this.cache = {}; this.injector = injector || {}; // if we are in debug mode, then add the debug handler var pattern = this.injector.debugPattern || '*.*.*.*.*'; var handler = this.injector.debugHandler || debugHandler; if (this.injector.debug) { eventBus.on(pattern, handler); } }
[ "function", "ServiceFactory", "(", "injector", ")", "{", "this", ".", "cache", "=", "{", "}", ";", "this", ".", "injector", "=", "injector", "||", "{", "}", ";", "var", "pattern", "=", "this", ".", "injector", ".", "debugPattern", "||", "'*.*.*.*.*'", ";", "var", "handler", "=", "this", ".", "injector", ".", "debugHandler", "||", "debugHandler", ";", "if", "(", "this", ".", "injector", ".", "debug", ")", "{", "eventBus", ".", "on", "(", "pattern", ",", "handler", ")", ";", "}", "}" ]
Simple function to clear the cache @param injector @constructor
[ "Simple", "function", "to", "clear", "the", "cache" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L20-L30
train
gethuman/pancakes
lib/factories/service.factory.js
isCandidate
function isCandidate(modulePath) { modulePath = modulePath || ''; var len = modulePath.length; return modulePath.indexOf('/') < 0 && len > 7 && modulePath.substring(modulePath.length - 7) === 'Service'; }
javascript
function isCandidate(modulePath) { modulePath = modulePath || ''; var len = modulePath.length; return modulePath.indexOf('/') < 0 && len > 7 && modulePath.substring(modulePath.length - 7) === 'Service'; }
[ "function", "isCandidate", "(", "modulePath", ")", "{", "modulePath", "=", "modulePath", "||", "''", ";", "var", "len", "=", "modulePath", ".", "length", ";", "return", "modulePath", ".", "indexOf", "(", "'/'", ")", "<", "0", "&&", "len", ">", "7", "&&", "modulePath", ".", "substring", "(", "modulePath", ".", "length", "-", "7", ")", "===", "'Service'", ";", "}" ]
Candidate if no slash and the modulePath ends in 'Service' @param modulePath @returns {boolean}
[ "Candidate", "if", "no", "slash", "and", "the", "modulePath", "ends", "in", "Service" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L39-L44
train
gethuman/pancakes
lib/factories/service.factory.js
getServiceInfo
function getServiceInfo(serviceName, adapterMap) { var serviceInfo = { serviceName: serviceName }; var serviceParts = utils.splitCamelCase(serviceName); // turn oneTwoThree into ['one', 'two', 'three'] var nbrParts = serviceParts.length; // first check to see if the second to last part is an adapter serviceInfo.adapterName = serviceParts[nbrParts - 2]; // NOTE: last item in array is 'Service' if (adapterMap[serviceInfo.adapterName]) { serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 2).join('.'); } // if not, it means we are dealing with a straight service (ex. postService) else { serviceInfo.adapterName = 'service'; serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 1).join('.'); } serviceInfo.adapterImpl = adapterMap[serviceInfo.adapterName]; return serviceInfo; }
javascript
function getServiceInfo(serviceName, adapterMap) { var serviceInfo = { serviceName: serviceName }; var serviceParts = utils.splitCamelCase(serviceName); // turn oneTwoThree into ['one', 'two', 'three'] var nbrParts = serviceParts.length; // first check to see if the second to last part is an adapter serviceInfo.adapterName = serviceParts[nbrParts - 2]; // NOTE: last item in array is 'Service' if (adapterMap[serviceInfo.adapterName]) { serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 2).join('.'); } // if not, it means we are dealing with a straight service (ex. postService) else { serviceInfo.adapterName = 'service'; serviceInfo.resourceName = serviceParts.slice(0, nbrParts - 1).join('.'); } serviceInfo.adapterImpl = adapterMap[serviceInfo.adapterName]; return serviceInfo; }
[ "function", "getServiceInfo", "(", "serviceName", ",", "adapterMap", ")", "{", "var", "serviceInfo", "=", "{", "serviceName", ":", "serviceName", "}", ";", "var", "serviceParts", "=", "utils", ".", "splitCamelCase", "(", "serviceName", ")", ";", "var", "nbrParts", "=", "serviceParts", ".", "length", ";", "serviceInfo", ".", "adapterName", "=", "serviceParts", "[", "nbrParts", "-", "2", "]", ";", "if", "(", "adapterMap", "[", "serviceInfo", ".", "adapterName", "]", ")", "{", "serviceInfo", ".", "resourceName", "=", "serviceParts", ".", "slice", "(", "0", ",", "nbrParts", "-", "2", ")", ".", "join", "(", "'.'", ")", ";", "}", "else", "{", "serviceInfo", ".", "adapterName", "=", "'service'", ";", "serviceInfo", ".", "resourceName", "=", "serviceParts", ".", "slice", "(", "0", ",", "nbrParts", "-", "1", ")", ".", "join", "(", "'.'", ")", ";", "}", "serviceInfo", ".", "adapterImpl", "=", "adapterMap", "[", "serviceInfo", ".", "adapterName", "]", ";", "return", "serviceInfo", ";", "}" ]
Figure out information about the service based on the module path and the adapter map @param serviceName @param adapterMap @returns {{}}
[ "Figure", "out", "information", "about", "the", "service", "based", "on", "the", "module", "path", "and", "the", "adapter", "map" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L90-L109
train
gethuman/pancakes
lib/factories/service.factory.js
getResource
function getResource(serviceInfo, moduleStack) { var resourceName = serviceInfo.resourceName; var resourcePath = '/resources/' + resourceName + '/' + resourceName + '.resource'; return this.loadIfExists(resourcePath, moduleStack, 'Could not find resource file'); }
javascript
function getResource(serviceInfo, moduleStack) { var resourceName = serviceInfo.resourceName; var resourcePath = '/resources/' + resourceName + '/' + resourceName + '.resource'; return this.loadIfExists(resourcePath, moduleStack, 'Could not find resource file'); }
[ "function", "getResource", "(", "serviceInfo", ",", "moduleStack", ")", "{", "var", "resourceName", "=", "serviceInfo", ".", "resourceName", ";", "var", "resourcePath", "=", "'/resources/'", "+", "resourceName", "+", "'/'", "+", "resourceName", "+", "'.resource'", ";", "return", "this", ".", "loadIfExists", "(", "resourcePath", ",", "moduleStack", ",", "'Could not find resource file'", ")", ";", "}" ]
Get a resource based on the @param serviceInfo @param moduleStack @returns {{}} A resource object
[ "Get", "a", "resource", "based", "on", "the" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L117-L121
train
gethuman/pancakes
lib/factories/service.factory.js
getAdapter
function getAdapter(serviceInfo, resource, moduleStack) { var adapterName = serviceInfo.adapterName; // if adapter name is 'service' and there is a default, switch to the default if (adapterName === 'service' && resource.adapters[this.injector.container]) { adapterName = serviceInfo.adapterName = resource.adapters[this.injector.container]; serviceInfo.adapterImpl = this.injector.adapterMap[adapterName]; serviceInfo.serviceName = utils.getCamelCase(serviceInfo.resourceName + '.' + serviceInfo.adapterName + '.service'); } // if that doesn't work, we will assume the adapter is in the current codebase, so go get it var overridePath = '/resources/' + serviceInfo.resourceName + '/' + serviceInfo.resourceName + '.' + (adapterName === 'service' ? adapterName : adapterName + '.service'); var adapterPath = '/adapters/' + adapterName + '/' + serviceInfo.adapterImpl + '.' + adapterName + '.adapter'; // if override exists, use that one, else use the lower level adapter var Adapter = this.loadIfExists(overridePath, moduleStack, null) || this.injector.adapters[serviceInfo.adapterImpl] || this.loadIfExists(adapterPath, moduleStack, null); // if still no adapter found, then there is an issue if (!Adapter) { throw new Error('ServiceFactory could not find adapter ' + adapterName + ' paths ' + overridePath + ' and ' + adapterPath); } return new Adapter(resource); }
javascript
function getAdapter(serviceInfo, resource, moduleStack) { var adapterName = serviceInfo.adapterName; // if adapter name is 'service' and there is a default, switch to the default if (adapterName === 'service' && resource.adapters[this.injector.container]) { adapterName = serviceInfo.adapterName = resource.adapters[this.injector.container]; serviceInfo.adapterImpl = this.injector.adapterMap[adapterName]; serviceInfo.serviceName = utils.getCamelCase(serviceInfo.resourceName + '.' + serviceInfo.adapterName + '.service'); } // if that doesn't work, we will assume the adapter is in the current codebase, so go get it var overridePath = '/resources/' + serviceInfo.resourceName + '/' + serviceInfo.resourceName + '.' + (adapterName === 'service' ? adapterName : adapterName + '.service'); var adapterPath = '/adapters/' + adapterName + '/' + serviceInfo.adapterImpl + '.' + adapterName + '.adapter'; // if override exists, use that one, else use the lower level adapter var Adapter = this.loadIfExists(overridePath, moduleStack, null) || this.injector.adapters[serviceInfo.adapterImpl] || this.loadIfExists(adapterPath, moduleStack, null); // if still no adapter found, then there is an issue if (!Adapter) { throw new Error('ServiceFactory could not find adapter ' + adapterName + ' paths ' + overridePath + ' and ' + adapterPath); } return new Adapter(resource); }
[ "function", "getAdapter", "(", "serviceInfo", ",", "resource", ",", "moduleStack", ")", "{", "var", "adapterName", "=", "serviceInfo", ".", "adapterName", ";", "if", "(", "adapterName", "===", "'service'", "&&", "resource", ".", "adapters", "[", "this", ".", "injector", ".", "container", "]", ")", "{", "adapterName", "=", "serviceInfo", ".", "adapterName", "=", "resource", ".", "adapters", "[", "this", ".", "injector", ".", "container", "]", ";", "serviceInfo", ".", "adapterImpl", "=", "this", ".", "injector", ".", "adapterMap", "[", "adapterName", "]", ";", "serviceInfo", ".", "serviceName", "=", "utils", ".", "getCamelCase", "(", "serviceInfo", ".", "resourceName", "+", "'.'", "+", "serviceInfo", ".", "adapterName", "+", "'.service'", ")", ";", "}", "var", "overridePath", "=", "'/resources/'", "+", "serviceInfo", ".", "resourceName", "+", "'/'", "+", "serviceInfo", ".", "resourceName", "+", "'.'", "+", "(", "adapterName", "===", "'service'", "?", "adapterName", ":", "adapterName", "+", "'.service'", ")", ";", "var", "adapterPath", "=", "'/adapters/'", "+", "adapterName", "+", "'/'", "+", "serviceInfo", ".", "adapterImpl", "+", "'.'", "+", "adapterName", "+", "'.adapter'", ";", "var", "Adapter", "=", "this", ".", "loadIfExists", "(", "overridePath", ",", "moduleStack", ",", "null", ")", "||", "this", ".", "injector", ".", "adapters", "[", "serviceInfo", ".", "adapterImpl", "]", "||", "this", ".", "loadIfExists", "(", "adapterPath", ",", "moduleStack", ",", "null", ")", ";", "if", "(", "!", "Adapter", ")", "{", "throw", "new", "Error", "(", "'ServiceFactory could not find adapter '", "+", "adapterName", "+", "' paths '", "+", "overridePath", "+", "' and '", "+", "adapterPath", ")", ";", "}", "return", "new", "Adapter", "(", "resource", ")", ";", "}" ]
Get a adapter based on the service info and what exists on the file system @param serviceInfo @param resource @param moduleStack
[ "Get", "a", "adapter", "based", "on", "the", "service", "info", "and", "what", "exists", "on", "the", "file", "system" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L130-L160
train
gethuman/pancakes
lib/factories/service.factory.js
loadIfExists
function loadIfExists(path, moduleStack, errMsg) { var servicesDir = this.injector.servicesDir; var servicesFullPath = this.injector.rootDir + '/' + servicesDir; // if the file doesn't exist, either throw an error (if msg passed in), else just return null if (!fs.existsSync(p.join(servicesFullPath, path + '.js'))) { if (errMsg) { throw new Error(errMsg + ' ' + servicesFullPath + path + '.js'); } else { return null; } } // else load the module return this.injector.loadModule(servicesDir + path, moduleStack); }
javascript
function loadIfExists(path, moduleStack, errMsg) { var servicesDir = this.injector.servicesDir; var servicesFullPath = this.injector.rootDir + '/' + servicesDir; // if the file doesn't exist, either throw an error (if msg passed in), else just return null if (!fs.existsSync(p.join(servicesFullPath, path + '.js'))) { if (errMsg) { throw new Error(errMsg + ' ' + servicesFullPath + path + '.js'); } else { return null; } } // else load the module return this.injector.loadModule(servicesDir + path, moduleStack); }
[ "function", "loadIfExists", "(", "path", ",", "moduleStack", ",", "errMsg", ")", "{", "var", "servicesDir", "=", "this", ".", "injector", ".", "servicesDir", ";", "var", "servicesFullPath", "=", "this", ".", "injector", ".", "rootDir", "+", "'/'", "+", "servicesDir", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "p", ".", "join", "(", "servicesFullPath", ",", "path", "+", "'.js'", ")", ")", ")", "{", "if", "(", "errMsg", ")", "{", "throw", "new", "Error", "(", "errMsg", "+", "' '", "+", "servicesFullPath", "+", "path", "+", "'.js'", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", "return", "this", ".", "injector", ".", "loadModule", "(", "servicesDir", "+", "path", ",", "moduleStack", ")", ";", "}" ]
Load a module if it exists @param path @param moduleStack @param errMsg @returns {*}
[ "Load", "a", "module", "if", "it", "exists" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L169-L185
train
gethuman/pancakes
lib/factories/service.factory.js
putItAllTogether
function putItAllTogether(serviceInfo, resource, adapter) { var me = this; var debug = this.injector.debug; // loop through the methods _.each(resource.methods[serviceInfo.adapterName], function (method) { if (!adapter[method]) { return; } // we are going to monkey patch the target method on the adapter, so save the original method var origMethod = adapter[method].bind(adapter); var eventNameBase = { resource: serviceInfo.resourceName, adapter: serviceInfo.adapterName, method: method }; // create the new service function adapter[method] = function (req) { req = req || {}; // clean out request _.each(req, function (value, name) { if (value && value === 'undefined') { delete req[name]; } }); // add event for data before anything happens (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // first validate the request return me.validateRequestParams(req, resource, method, serviceInfo.adapterName) .then(function () { // add event before calling the original method (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // call the original target method on the adapter return origMethod(req); }) .then(function (res) { // emit event after origin method called; this is what most // reactors key off of (can be disabled with noemit flag) if (!req.noemit && !req.multi && method !== 'find') { var payload = { caller: req.caller, inputId: req._id, targetId: req.targetId, inputData: req.data, data: res }; me.emitEvent(payload, eventNameBase, null); } // return the response that will go back to the calling client return res; }); }; }); // so essentially the service is the adapter with each method bulked up with some extra stuff return adapter; }
javascript
function putItAllTogether(serviceInfo, resource, adapter) { var me = this; var debug = this.injector.debug; // loop through the methods _.each(resource.methods[serviceInfo.adapterName], function (method) { if (!adapter[method]) { return; } // we are going to monkey patch the target method on the adapter, so save the original method var origMethod = adapter[method].bind(adapter); var eventNameBase = { resource: serviceInfo.resourceName, adapter: serviceInfo.adapterName, method: method }; // create the new service function adapter[method] = function (req) { req = req || {}; // clean out request _.each(req, function (value, name) { if (value && value === 'undefined') { delete req[name]; } }); // add event for data before anything happens (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // first validate the request return me.validateRequestParams(req, resource, method, serviceInfo.adapterName) .then(function () { // add event before calling the original method (used only for debugging) if (debug) { me.emitEvent(req, eventNameBase, { type: 'service', timing: 'before' }); } // call the original target method on the adapter return origMethod(req); }) .then(function (res) { // emit event after origin method called; this is what most // reactors key off of (can be disabled with noemit flag) if (!req.noemit && !req.multi && method !== 'find') { var payload = { caller: req.caller, inputId: req._id, targetId: req.targetId, inputData: req.data, data: res }; me.emitEvent(payload, eventNameBase, null); } // return the response that will go back to the calling client return res; }); }; }); // so essentially the service is the adapter with each method bulked up with some extra stuff return adapter; }
[ "function", "putItAllTogether", "(", "serviceInfo", ",", "resource", ",", "adapter", ")", "{", "var", "me", "=", "this", ";", "var", "debug", "=", "this", ".", "injector", ".", "debug", ";", "_", ".", "each", "(", "resource", ".", "methods", "[", "serviceInfo", ".", "adapterName", "]", ",", "function", "(", "method", ")", "{", "if", "(", "!", "adapter", "[", "method", "]", ")", "{", "return", ";", "}", "var", "origMethod", "=", "adapter", "[", "method", "]", ".", "bind", "(", "adapter", ")", ";", "var", "eventNameBase", "=", "{", "resource", ":", "serviceInfo", ".", "resourceName", ",", "adapter", ":", "serviceInfo", ".", "adapterName", ",", "method", ":", "method", "}", ";", "adapter", "[", "method", "]", "=", "function", "(", "req", ")", "{", "req", "=", "req", "||", "{", "}", ";", "_", ".", "each", "(", "req", ",", "function", "(", "value", ",", "name", ")", "{", "if", "(", "value", "&&", "value", "===", "'undefined'", ")", "{", "delete", "req", "[", "name", "]", ";", "}", "}", ")", ";", "if", "(", "debug", ")", "{", "me", ".", "emitEvent", "(", "req", ",", "eventNameBase", ",", "{", "type", ":", "'service'", ",", "timing", ":", "'before'", "}", ")", ";", "}", "return", "me", ".", "validateRequestParams", "(", "req", ",", "resource", ",", "method", ",", "serviceInfo", ".", "adapterName", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "debug", ")", "{", "me", ".", "emitEvent", "(", "req", ",", "eventNameBase", ",", "{", "type", ":", "'service'", ",", "timing", ":", "'before'", "}", ")", ";", "}", "return", "origMethod", "(", "req", ")", ";", "}", ")", ".", "then", "(", "function", "(", "res", ")", "{", "if", "(", "!", "req", ".", "noemit", "&&", "!", "req", ".", "multi", "&&", "method", "!==", "'find'", ")", "{", "var", "payload", "=", "{", "caller", ":", "req", ".", "caller", ",", "inputId", ":", "req", ".", "_id", ",", "targetId", ":", "req", ".", "targetId", ",", "inputData", ":", "req", ".", "data", ",", "data", ":", "res", "}", ";", "me", ".", "emitEvent", "(", "payload", ",", "eventNameBase", ",", "null", ")", ";", "}", "return", "res", ";", "}", ")", ";", "}", ";", "}", ")", ";", "return", "adapter", ";", "}" ]
Take all the objects involved with a service and put them all together. The final service is really just an instance of an adapter with each method enhanced to have various filters added @param serviceInfo @param resource @param adapter @returns {{}}
[ "Take", "all", "the", "objects", "involved", "with", "a", "service", "and", "put", "them", "all", "together", ".", "The", "final", "service", "is", "really", "just", "an", "instance", "of", "an", "adapter", "with", "each", "method", "enhanced", "to", "have", "various", "filters", "added" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L196-L261
train
gethuman/pancakes
lib/factories/service.factory.js
emitEvent
function emitEvent(payload, eventNameBase, debugParams) { // create a copy of the payload so that nothing modifies the original object try { payload = JSON.parse(JSON.stringify(payload)); } catch (err) { /* eslint no-console:0 */ console.log('issue parsing during emit ' + JSON.stringify(eventNameBase)); } // we don't want to emit the potentially huge resource file if (payload && payload.resource) { delete payload.resource; } // create the event data and emit the event var name = _.extend({}, eventNameBase, debugParams); var eventData = { name: name, payload: payload }; var eventName = name.resource + '.' + name.adapter + '.' + name.method; eventName += debugParams ? '.' + name.type + '.' + name.timing : ''; eventBus.emit(eventName, eventData); }
javascript
function emitEvent(payload, eventNameBase, debugParams) { // create a copy of the payload so that nothing modifies the original object try { payload = JSON.parse(JSON.stringify(payload)); } catch (err) { /* eslint no-console:0 */ console.log('issue parsing during emit ' + JSON.stringify(eventNameBase)); } // we don't want to emit the potentially huge resource file if (payload && payload.resource) { delete payload.resource; } // create the event data and emit the event var name = _.extend({}, eventNameBase, debugParams); var eventData = { name: name, payload: payload }; var eventName = name.resource + '.' + name.adapter + '.' + name.method; eventName += debugParams ? '.' + name.type + '.' + name.timing : ''; eventBus.emit(eventName, eventData); }
[ "function", "emitEvent", "(", "payload", ",", "eventNameBase", ",", "debugParams", ")", "{", "try", "{", "payload", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "payload", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "'issue parsing during emit '", "+", "JSON", ".", "stringify", "(", "eventNameBase", ")", ")", ";", "}", "if", "(", "payload", "&&", "payload", ".", "resource", ")", "{", "delete", "payload", ".", "resource", ";", "}", "var", "name", "=", "_", ".", "extend", "(", "{", "}", ",", "eventNameBase", ",", "debugParams", ")", ";", "var", "eventData", "=", "{", "name", ":", "name", ",", "payload", ":", "payload", "}", ";", "var", "eventName", "=", "name", ".", "resource", "+", "'.'", "+", "name", ".", "adapter", "+", "'.'", "+", "name", ".", "method", ";", "eventName", "+=", "debugParams", "?", "'.'", "+", "name", ".", "type", "+", "'.'", "+", "name", ".", "timing", ":", "''", ";", "eventBus", ".", "emit", "(", "eventName", ",", "eventData", ")", ";", "}" ]
This is used to get an mock filter which will be sending out events @param payload @param eventNameBase @param debugParams
[ "This", "is", "used", "to", "get", "an", "mock", "filter", "which", "will", "be", "sending", "out", "events" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L269-L294
train
gethuman/pancakes
lib/factories/service.factory.js
validateRequestParams
function validateRequestParams(req, resource, method, adapter) { req = req || {}; var params = resource.params || {}; var methodParams = _.extend({}, params[method], params[adapter + '.' + method] ); var requiredParams = methodParams.required || []; var eitherorParams = methodParams.eitheror || []; var optional = methodParams.optional || []; var eitherorExists, param; var err, reqObj; // make sure all the required params are there for (var i = 0; i < requiredParams.length; i++) { param = requiredParams[i]; if (req[param] === undefined || req[param] === null) { reqObj = _.extend({}, req); delete reqObj.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' missing ' + param + '. Required params: ' + JSON.stringify(requiredParams) + ' req is: ' + JSON.stringify(reqObj); return Q.reject(err); } } // make sure at least one of the eitheror params are there if (eitherorParams.length) { eitherorExists = false; _.each(eitherorParams, function (eitherorParam) { if (req[eitherorParam]) { eitherorExists = true; } }); if (!eitherorExists) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' must have one of the following params: ' + JSON.stringify(eitherorParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } // now loop through the values and error if invalid param in there; also do JSON parsing if an object var validParams = requiredParams.concat(eitherorParams, optional, ['lang', 'caller', 'resource', 'method', 'auth', 'noemit']); for (var key in req) { if (req.hasOwnProperty(key)) { if (validParams.indexOf(key) < 0) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = 'For ' + resource.name + ' ' + method + ' the key ' + key + ' is not allowed. Valid params: ' + JSON.stringify(validParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } } // no errors, so return resolved promise return new Q(); }
javascript
function validateRequestParams(req, resource, method, adapter) { req = req || {}; var params = resource.params || {}; var methodParams = _.extend({}, params[method], params[adapter + '.' + method] ); var requiredParams = methodParams.required || []; var eitherorParams = methodParams.eitheror || []; var optional = methodParams.optional || []; var eitherorExists, param; var err, reqObj; // make sure all the required params are there for (var i = 0; i < requiredParams.length; i++) { param = requiredParams[i]; if (req[param] === undefined || req[param] === null) { reqObj = _.extend({}, req); delete reqObj.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' missing ' + param + '. Required params: ' + JSON.stringify(requiredParams) + ' req is: ' + JSON.stringify(reqObj); return Q.reject(err); } } // make sure at least one of the eitheror params are there if (eitherorParams.length) { eitherorExists = false; _.each(eitherorParams, function (eitherorParam) { if (req[eitherorParam]) { eitherorExists = true; } }); if (!eitherorExists) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = resource.name + ' ' + method + ' must have one of the following params: ' + JSON.stringify(eitherorParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } // now loop through the values and error if invalid param in there; also do JSON parsing if an object var validParams = requiredParams.concat(eitherorParams, optional, ['lang', 'caller', 'resource', 'method', 'auth', 'noemit']); for (var key in req) { if (req.hasOwnProperty(key)) { if (validParams.indexOf(key) < 0) { delete req.caller; delete req.resource; err = new Error('Invalid request'); err.code = 'invalid_request_error'; err.message = 'For ' + resource.name + ' ' + method + ' the key ' + key + ' is not allowed. Valid params: ' + JSON.stringify(validParams) + ' request is ' + JSON.stringify(req); return Q.reject(err); } } } // no errors, so return resolved promise return new Q(); }
[ "function", "validateRequestParams", "(", "req", ",", "resource", ",", "method", ",", "adapter", ")", "{", "req", "=", "req", "||", "{", "}", ";", "var", "params", "=", "resource", ".", "params", "||", "{", "}", ";", "var", "methodParams", "=", "_", ".", "extend", "(", "{", "}", ",", "params", "[", "method", "]", ",", "params", "[", "adapter", "+", "'.'", "+", "method", "]", ")", ";", "var", "requiredParams", "=", "methodParams", ".", "required", "||", "[", "]", ";", "var", "eitherorParams", "=", "methodParams", ".", "eitheror", "||", "[", "]", ";", "var", "optional", "=", "methodParams", ".", "optional", "||", "[", "]", ";", "var", "eitherorExists", ",", "param", ";", "var", "err", ",", "reqObj", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "requiredParams", ".", "length", ";", "i", "++", ")", "{", "param", "=", "requiredParams", "[", "i", "]", ";", "if", "(", "req", "[", "param", "]", "===", "undefined", "||", "req", "[", "param", "]", "===", "null", ")", "{", "reqObj", "=", "_", ".", "extend", "(", "{", "}", ",", "req", ")", ";", "delete", "reqObj", ".", "resource", ";", "err", "=", "new", "Error", "(", "'Invalid request'", ")", ";", "err", ".", "code", "=", "'invalid_request_error'", ";", "err", ".", "message", "=", "resource", ".", "name", "+", "' '", "+", "method", "+", "' missing '", "+", "param", "+", "'. Required params: '", "+", "JSON", ".", "stringify", "(", "requiredParams", ")", "+", "' req is: '", "+", "JSON", ".", "stringify", "(", "reqObj", ")", ";", "return", "Q", ".", "reject", "(", "err", ")", ";", "}", "}", "if", "(", "eitherorParams", ".", "length", ")", "{", "eitherorExists", "=", "false", ";", "_", ".", "each", "(", "eitherorParams", ",", "function", "(", "eitherorParam", ")", "{", "if", "(", "req", "[", "eitherorParam", "]", ")", "{", "eitherorExists", "=", "true", ";", "}", "}", ")", ";", "if", "(", "!", "eitherorExists", ")", "{", "delete", "req", ".", "caller", ";", "delete", "req", ".", "resource", ";", "err", "=", "new", "Error", "(", "'Invalid request'", ")", ";", "err", ".", "code", "=", "'invalid_request_error'", ";", "err", ".", "message", "=", "resource", ".", "name", "+", "' '", "+", "method", "+", "' must have one of the following params: '", "+", "JSON", ".", "stringify", "(", "eitherorParams", ")", "+", "' request is '", "+", "JSON", ".", "stringify", "(", "req", ")", ";", "return", "Q", ".", "reject", "(", "err", ")", ";", "}", "}", "var", "validParams", "=", "requiredParams", ".", "concat", "(", "eitherorParams", ",", "optional", ",", "[", "'lang'", ",", "'caller'", ",", "'resource'", ",", "'method'", ",", "'auth'", ",", "'noemit'", "]", ")", ";", "for", "(", "var", "key", "in", "req", ")", "{", "if", "(", "req", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "validParams", ".", "indexOf", "(", "key", ")", "<", "0", ")", "{", "delete", "req", ".", "caller", ";", "delete", "req", ".", "resource", ";", "err", "=", "new", "Error", "(", "'Invalid request'", ")", ";", "err", ".", "code", "=", "'invalid_request_error'", ";", "err", ".", "message", "=", "'For '", "+", "resource", ".", "name", "+", "' '", "+", "method", "+", "' the key '", "+", "key", "+", "' is not allowed. Valid params: '", "+", "JSON", ".", "stringify", "(", "validParams", ")", "+", "' request is '", "+", "JSON", ".", "stringify", "(", "req", ")", ";", "return", "Q", ".", "reject", "(", "err", ")", ";", "}", "}", "}", "return", "new", "Q", "(", ")", ";", "}" ]
Used within a service to validate the input params @param req @param resource @param method @param adapter @returns {*}
[ "Used", "within", "a", "service", "to", "validate", "the", "input", "params" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/service.factory.js#L304-L371
train
telefonicaid/logops
lib/logops.js
logWrap
function logWrap(level) { return function log() { let context, message, args, trace, err; if (arguments[0] instanceof Error) { // log.<level>(err, ...) context = API.getContext(); args = Array.prototype.slice.call(arguments, 1); if (!args.length) { // log.<level>(err) err = arguments[0]; message = err.name + ': ' + err.message; } else { // log.<level>(err, "More %s", "things") // Use the err as context information err = arguments[0]; message = arguments[1]; args = Array.prototype.slice.call(args, 1); } } else if (arguments[0] == null || (typeof (arguments[0]) !== 'object' && arguments[0] !== null) || Array.isArray(arguments[0])) { // log.<level>(msg, ...) context = API.getContext(); message = arguments[0]; args = Array.prototype.slice.call(arguments, 1); } else { // log.<level>(fields, msg, ...) context = merge(API.getContext(), arguments[0]); message = arguments[1]; args = Array.prototype.slice.call(arguments, 2); } trace = API.format(level, context || {}, message, args, err); API.stream.write(trace + '\n'); }; }
javascript
function logWrap(level) { return function log() { let context, message, args, trace, err; if (arguments[0] instanceof Error) { // log.<level>(err, ...) context = API.getContext(); args = Array.prototype.slice.call(arguments, 1); if (!args.length) { // log.<level>(err) err = arguments[0]; message = err.name + ': ' + err.message; } else { // log.<level>(err, "More %s", "things") // Use the err as context information err = arguments[0]; message = arguments[1]; args = Array.prototype.slice.call(args, 1); } } else if (arguments[0] == null || (typeof (arguments[0]) !== 'object' && arguments[0] !== null) || Array.isArray(arguments[0])) { // log.<level>(msg, ...) context = API.getContext(); message = arguments[0]; args = Array.prototype.slice.call(arguments, 1); } else { // log.<level>(fields, msg, ...) context = merge(API.getContext(), arguments[0]); message = arguments[1]; args = Array.prototype.slice.call(arguments, 2); } trace = API.format(level, context || {}, message, args, err); API.stream.write(trace + '\n'); }; }
[ "function", "logWrap", "(", "level", ")", "{", "return", "function", "log", "(", ")", "{", "let", "context", ",", "message", ",", "args", ",", "trace", ",", "err", ";", "if", "(", "arguments", "[", "0", "]", "instanceof", "Error", ")", "{", "context", "=", "API", ".", "getContext", "(", ")", ";", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "if", "(", "!", "args", ".", "length", ")", "{", "err", "=", "arguments", "[", "0", "]", ";", "message", "=", "err", ".", "name", "+", "': '", "+", "err", ".", "message", ";", "}", "else", "{", "err", "=", "arguments", "[", "0", "]", ";", "message", "=", "arguments", "[", "1", "]", ";", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ",", "1", ")", ";", "}", "}", "else", "if", "(", "arguments", "[", "0", "]", "==", "null", "||", "(", "typeof", "(", "arguments", "[", "0", "]", ")", "!==", "'object'", "&&", "arguments", "[", "0", "]", "!==", "null", ")", "||", "Array", ".", "isArray", "(", "arguments", "[", "0", "]", ")", ")", "{", "context", "=", "API", ".", "getContext", "(", ")", ";", "message", "=", "arguments", "[", "0", "]", ";", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "}", "else", "{", "context", "=", "merge", "(", "API", ".", "getContext", "(", ")", ",", "arguments", "[", "0", "]", ")", ";", "message", "=", "arguments", "[", "1", "]", ";", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ";", "}", "trace", "=", "API", ".", "format", "(", "level", ",", "context", "||", "{", "}", ",", "message", ",", "args", ",", "err", ")", ";", "API", ".", "stream", ".", "write", "(", "trace", "+", "'\\n'", ")", ";", "}", ";", "}" ]
Internal private function that implements a decorator to all the level functions. @param {String} level one of ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL']
[ "Internal", "private", "function", "that", "implements", "a", "decorator", "to", "all", "the", "level", "functions", "." ]
6023d75b3531ed1bb3abe171679234f9519be082
https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/logops.js#L45-L80
train
telefonicaid/logops
lib/logops.js
setLevel
function setLevel(level) { opts.level = level; let logLevelIndex = levels.indexOf(opts.level.toUpperCase()); levels.forEach((logLevel) => { let fn; if (logLevelIndex <= levels.indexOf(logLevel)) { fn = logWrap(logLevel); } else { fn = noop; } API[logLevel.toLowerCase()] = fn; }); }
javascript
function setLevel(level) { opts.level = level; let logLevelIndex = levels.indexOf(opts.level.toUpperCase()); levels.forEach((logLevel) => { let fn; if (logLevelIndex <= levels.indexOf(logLevel)) { fn = logWrap(logLevel); } else { fn = noop; } API[logLevel.toLowerCase()] = fn; }); }
[ "function", "setLevel", "(", "level", ")", "{", "opts", ".", "level", "=", "level", ";", "let", "logLevelIndex", "=", "levels", ".", "indexOf", "(", "opts", ".", "level", ".", "toUpperCase", "(", ")", ")", ";", "levels", ".", "forEach", "(", "(", "logLevel", ")", "=>", "{", "let", "fn", ";", "if", "(", "logLevelIndex", "<=", "levels", ".", "indexOf", "(", "logLevel", ")", ")", "{", "fn", "=", "logWrap", "(", "logLevel", ")", ";", "}", "else", "{", "fn", "=", "noop", ";", "}", "API", "[", "logLevel", ".", "toLowerCase", "(", ")", "]", "=", "fn", ";", "}", ")", ";", "}" ]
Sets the enabled logging level. All the disabled logging methods are replaced by a noop, so there is not any performance penalty at production using an undesired level @param {String} level
[ "Sets", "the", "enabled", "logging", "level", ".", "All", "the", "disabled", "logging", "methods", "are", "replaced", "by", "a", "noop", "so", "there", "is", "not", "any", "performance", "penalty", "at", "production", "using", "an", "undesired", "level" ]
6023d75b3531ed1bb3abe171679234f9519be082
https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/logops.js#L89-L102
train
telefonicaid/logops
lib/logops.js
merge
function merge(obj1, obj2) { var res = {}, attrname; for (attrname in obj1) { res[attrname] = obj1[attrname]; } for (attrname in obj2) { res[attrname] = obj2[attrname]; } return res; }
javascript
function merge(obj1, obj2) { var res = {}, attrname; for (attrname in obj1) { res[attrname] = obj1[attrname]; } for (attrname in obj2) { res[attrname] = obj2[attrname]; } return res; }
[ "function", "merge", "(", "obj1", ",", "obj2", ")", "{", "var", "res", "=", "{", "}", ",", "attrname", ";", "for", "(", "attrname", "in", "obj1", ")", "{", "res", "[", "attrname", "]", "=", "obj1", "[", "attrname", "]", ";", "}", "for", "(", "attrname", "in", "obj2", ")", "{", "res", "[", "attrname", "]", "=", "obj2", "[", "attrname", "]", ";", "}", "return", "res", ";", "}" ]
Merges accesible properties in two objects. obj2 takes precedence when common properties are found @param {Object} obj1 @param {Object} obj2 @returns {{}} The merged, new, object
[ "Merges", "accesible", "properties", "in", "two", "objects", ".", "obj2", "takes", "precedence", "when", "common", "properties", "are", "found" ]
6023d75b3531ed1bb3abe171679234f9519be082
https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/logops.js#L266-L276
train
gethuman/pancakes
lib/transformers/base.transformer.js
loadUIPart
function loadUIPart(appName, filePath) { var idx = filePath.indexOf(delim + appName + delim); var modulePath = filePath.substring(idx - 3); return this.pancakes.cook(modulePath); }
javascript
function loadUIPart(appName, filePath) { var idx = filePath.indexOf(delim + appName + delim); var modulePath = filePath.substring(idx - 3); return this.pancakes.cook(modulePath); }
[ "function", "loadUIPart", "(", "appName", ",", "filePath", ")", "{", "var", "idx", "=", "filePath", ".", "indexOf", "(", "delim", "+", "appName", "+", "delim", ")", ";", "var", "modulePath", "=", "filePath", ".", "substring", "(", "idx", "-", "3", ")", ";", "return", "this", ".", "pancakes", ".", "cook", "(", "modulePath", ")", ";", "}" ]
Load the UI part @param appName @param filePath @returns {injector.require|*|require}
[ "Load", "the", "UI", "part" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L24-L28
train
gethuman/pancakes
lib/transformers/base.transformer.js
setTemplate
function setTemplate(transformDir, templateName, clientType) { clientType = clientType ? (clientType + '.') : ''; if (templateCache[templateName]) { this.template = templateCache[templateName]; } else { var fileName = transformDir + '/' + clientType + templateName + '.template'; if (fs.existsSync(path.normalize(fileName))) { var file = fs.readFileSync(path.normalize(fileName)); this.template = templateCache[templateName] = dot.template(file); } else { throw new Error('No template at ' + fileName); } } }
javascript
function setTemplate(transformDir, templateName, clientType) { clientType = clientType ? (clientType + '.') : ''; if (templateCache[templateName]) { this.template = templateCache[templateName]; } else { var fileName = transformDir + '/' + clientType + templateName + '.template'; if (fs.existsSync(path.normalize(fileName))) { var file = fs.readFileSync(path.normalize(fileName)); this.template = templateCache[templateName] = dot.template(file); } else { throw new Error('No template at ' + fileName); } } }
[ "function", "setTemplate", "(", "transformDir", ",", "templateName", ",", "clientType", ")", "{", "clientType", "=", "clientType", "?", "(", "clientType", "+", "'.'", ")", ":", "''", ";", "if", "(", "templateCache", "[", "templateName", "]", ")", "{", "this", ".", "template", "=", "templateCache", "[", "templateName", "]", ";", "}", "else", "{", "var", "fileName", "=", "transformDir", "+", "'/'", "+", "clientType", "+", "templateName", "+", "'.template'", ";", "if", "(", "fs", ".", "existsSync", "(", "path", ".", "normalize", "(", "fileName", ")", ")", ")", "{", "var", "file", "=", "fs", ".", "readFileSync", "(", "path", ".", "normalize", "(", "fileName", ")", ")", ";", "this", ".", "template", "=", "templateCache", "[", "templateName", "]", "=", "dot", ".", "template", "(", "file", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'No template at '", "+", "fileName", ")", ";", "}", "}", "}" ]
Get a dot template @param transformDir @param templateName @param clientType
[ "Get", "a", "dot", "template" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L65-L82
train
gethuman/pancakes
lib/transformers/base.transformer.js
getParamInfo
function getParamInfo(params, aliases) { var paramInfo = { converted: [], list: [], ngrefs: [] }; _.each(params, function (param) { var mappedVal = aliases[param] || param; if (mappedVal === 'angular') { paramInfo.ngrefs.push(param); } else { paramInfo.list.push(param); paramInfo.converted.push(mappedVal); } }); return paramInfo; }
javascript
function getParamInfo(params, aliases) { var paramInfo = { converted: [], list: [], ngrefs: [] }; _.each(params, function (param) { var mappedVal = aliases[param] || param; if (mappedVal === 'angular') { paramInfo.ngrefs.push(param); } else { paramInfo.list.push(param); paramInfo.converted.push(mappedVal); } }); return paramInfo; }
[ "function", "getParamInfo", "(", "params", ",", "aliases", ")", "{", "var", "paramInfo", "=", "{", "converted", ":", "[", "]", ",", "list", ":", "[", "]", ",", "ngrefs", ":", "[", "]", "}", ";", "_", ".", "each", "(", "params", ",", "function", "(", "param", ")", "{", "var", "mappedVal", "=", "aliases", "[", "param", "]", "||", "param", ";", "if", "(", "mappedVal", "===", "'angular'", ")", "{", "paramInfo", ".", "ngrefs", ".", "push", "(", "param", ")", ";", "}", "else", "{", "paramInfo", ".", "list", ".", "push", "(", "param", ")", ";", "paramInfo", ".", "converted", ".", "push", "(", "mappedVal", ")", ";", "}", "}", ")", ";", "return", "paramInfo", ";", "}" ]
Take a list of params and create an object that contains the param list and converted values which will be used in templates @param params @param aliases @returns {{converted: Array, list: Array}}
[ "Take", "a", "list", "of", "params", "and", "create", "an", "object", "that", "contains", "the", "param", "list", "and", "converted", "values", "which", "will", "be", "used", "in", "templates" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L92-L107
train
gethuman/pancakes
lib/transformers/base.transformer.js
getFilteredParamInfo
function getFilteredParamInfo(flapjack, options) { if (!flapjack) { return {}; } var aliases = this.getClientAliases(flapjack, options); var params = this.getParameters(flapjack) || []; params = params.filter(function (param) { return ['$scope', 'defaults', 'initialModel'].indexOf(param) < 0; }); return this.getParamInfo(params, aliases) || {}; }
javascript
function getFilteredParamInfo(flapjack, options) { if (!flapjack) { return {}; } var aliases = this.getClientAliases(flapjack, options); var params = this.getParameters(flapjack) || []; params = params.filter(function (param) { return ['$scope', 'defaults', 'initialModel'].indexOf(param) < 0; }); return this.getParamInfo(params, aliases) || {}; }
[ "function", "getFilteredParamInfo", "(", "flapjack", ",", "options", ")", "{", "if", "(", "!", "flapjack", ")", "{", "return", "{", "}", ";", "}", "var", "aliases", "=", "this", ".", "getClientAliases", "(", "flapjack", ",", "options", ")", ";", "var", "params", "=", "this", ".", "getParameters", "(", "flapjack", ")", "||", "[", "]", ";", "params", "=", "params", ".", "filter", "(", "function", "(", "param", ")", "{", "return", "[", "'$scope'", ",", "'defaults'", ",", "'initialModel'", "]", ".", "indexOf", "(", "param", ")", "<", "0", ";", "}", ")", ";", "return", "this", ".", "getParamInfo", "(", "params", ",", "aliases", ")", "||", "{", "}", ";", "}" ]
Get the parameter info for a given flajack @param flapjack @param options @returns {*|{converted: Array, list: Array}|{}}
[ "Get", "the", "parameter", "info", "for", "a", "given", "flajack" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L115-L125
train
gethuman/pancakes
lib/transformers/base.transformer.js
getModuleBody
function getModuleBody(flapjack) { if (!flapjack) { return ''; } var str = flapjack.toString(); var openingCurly = str.indexOf('{'); var closingCurly = str.lastIndexOf('}'); // if can't find the opening or closing curly, just return the entire string if (openingCurly < 0 || closingCurly < 0) { return str; } var body = str.substring(openingCurly + 1, closingCurly); return body.replace(/\n/g, '\n\t'); }
javascript
function getModuleBody(flapjack) { if (!flapjack) { return ''; } var str = flapjack.toString(); var openingCurly = str.indexOf('{'); var closingCurly = str.lastIndexOf('}'); // if can't find the opening or closing curly, just return the entire string if (openingCurly < 0 || closingCurly < 0) { return str; } var body = str.substring(openingCurly + 1, closingCurly); return body.replace(/\n/g, '\n\t'); }
[ "function", "getModuleBody", "(", "flapjack", ")", "{", "if", "(", "!", "flapjack", ")", "{", "return", "''", ";", "}", "var", "str", "=", "flapjack", ".", "toString", "(", ")", ";", "var", "openingCurly", "=", "str", ".", "indexOf", "(", "'{'", ")", ";", "var", "closingCurly", "=", "str", ".", "lastIndexOf", "(", "'}'", ")", ";", "if", "(", "openingCurly", "<", "0", "||", "closingCurly", "<", "0", ")", "{", "return", "str", ";", "}", "var", "body", "=", "str", ".", "substring", "(", "openingCurly", "+", "1", ",", "closingCurly", ")", ";", "return", "body", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'\\n\\t'", ")", ";", "}" ]
Get the core logic within a module without the function declaration, parameters, etc. Essentially everything inside the curly brackets. @param flapjack The pancakes module @return {String}
[ "Get", "the", "core", "logic", "within", "a", "module", "without", "the", "function", "declaration", "parameters", "etc", ".", "Essentially", "everything", "inside", "the", "curly", "brackets", "." ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/transformers/base.transformer.js#L133-L147
train
kartotherian/core
lib/sources.js
updateInfo
function updateInfo(info, override, source, sourceId) { if (source) { if (source.minzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.minzoom = source.minzoom; } if (source.maxzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.maxzoom = source.maxzoom; } } if (sourceId !== undefined) { // eslint-disable-next-line no-param-reassign info.name = sourceId; } if (override) { _.each(override, (v, k) => { if (v === null) { // When override.key == null, delete that key // eslint-disable-next-line no-param-reassign delete info[k]; } else { // override info of the parent // eslint-disable-next-line no-param-reassign info[k] = v; } }); } }
javascript
function updateInfo(info, override, source, sourceId) { if (source) { if (source.minzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.minzoom = source.minzoom; } if (source.maxzoom !== undefined) { // eslint-disable-next-line no-param-reassign info.maxzoom = source.maxzoom; } } if (sourceId !== undefined) { // eslint-disable-next-line no-param-reassign info.name = sourceId; } if (override) { _.each(override, (v, k) => { if (v === null) { // When override.key == null, delete that key // eslint-disable-next-line no-param-reassign delete info[k]; } else { // override info of the parent // eslint-disable-next-line no-param-reassign info[k] = v; } }); } }
[ "function", "updateInfo", "(", "info", ",", "override", ",", "source", ",", "sourceId", ")", "{", "if", "(", "source", ")", "{", "if", "(", "source", ".", "minzoom", "!==", "undefined", ")", "{", "info", ".", "minzoom", "=", "source", ".", "minzoom", ";", "}", "if", "(", "source", ".", "maxzoom", "!==", "undefined", ")", "{", "info", ".", "maxzoom", "=", "source", ".", "maxzoom", ";", "}", "}", "if", "(", "sourceId", "!==", "undefined", ")", "{", "info", ".", "name", "=", "sourceId", ";", "}", "if", "(", "override", ")", "{", "_", ".", "each", "(", "override", ",", "(", "v", ",", "k", ")", "=>", "{", "if", "(", "v", "===", "null", ")", "{", "delete", "info", "[", "k", "]", ";", "}", "else", "{", "info", "[", "k", "]", "=", "v", ";", "}", "}", ")", ";", "}", "}" ]
Override top-level values in the info object with the ones from override object, or delete on null @param {object} info @param {object} override @param {object} [source] if given, sets min/max zoom @param {string} [sourceId]
[ "Override", "top", "-", "level", "values", "in", "the", "info", "object", "with", "the", "ones", "from", "override", "object", "or", "delete", "on", "null" ]
fb9f696816a08d782f5444364432f1fd79f4d56f
https://github.com/kartotherian/core/blob/fb9f696816a08d782f5444364432f1fd79f4d56f/lib/sources.js#L116-L144
train
querycert/qcert
doc/demo/evalWorker.js
qcertEval
function qcertEval(inputConfig) { console.log("qcertEval chosen"); var handler = function(result) { console.log("Compiler returned"); console.log(result); postMessage(result.eval); console.log("reply message posted"); // Each spawned worker is designed to be used once close(); } qcertWhiskDispatch(inputConfig, handler); }
javascript
function qcertEval(inputConfig) { console.log("qcertEval chosen"); var handler = function(result) { console.log("Compiler returned"); console.log(result); postMessage(result.eval); console.log("reply message posted"); // Each spawned worker is designed to be used once close(); } qcertWhiskDispatch(inputConfig, handler); }
[ "function", "qcertEval", "(", "inputConfig", ")", "{", "console", ".", "log", "(", "\"qcertEval chosen\"", ")", ";", "var", "handler", "=", "function", "(", "result", ")", "{", "console", ".", "log", "(", "\"Compiler returned\"", ")", ";", "console", ".", "log", "(", "result", ")", ";", "postMessage", "(", "result", ".", "eval", ")", ";", "console", ".", "log", "(", "\"reply message posted\"", ")", ";", "close", "(", ")", ";", "}", "qcertWhiskDispatch", "(", "inputConfig", ",", "handler", ")", ";", "}" ]
qcert intermediate language evaluation
[ "qcert", "intermediate", "language", "evaluation" ]
092ed55d08bf0f720fed9d07d172afc169e84576
https://github.com/querycert/qcert/blob/092ed55d08bf0f720fed9d07d172afc169e84576/doc/demo/evalWorker.js#L39-L51
train
gethuman/pancakes
lib/annotation.helper.js
getAnnotationInfo
function getAnnotationInfo(name, fn, isArray) { if (!fn) { return null; } var str = fn.toString(); var rgx = new RegExp('(?:@' + name + '\\()(.*)(?:\\))'); var matches = rgx.exec(str); if (!matches || matches.length < 2) { return null; } var annotation = matches[1]; if (isArray) { annotation = '{ "data": ' + annotation + '}'; } // we want all double quotes in our string annotation = annotation.replace(/'/g, '"'); // parse out the object from the string var obj = null; try { obj = JSON.parse(annotation); } catch (ex) { /* eslint no-console:0 */ console.log('Annotation parse error with ' + annotation); throw ex; } if (isArray) { obj = obj.data; } return obj; }
javascript
function getAnnotationInfo(name, fn, isArray) { if (!fn) { return null; } var str = fn.toString(); var rgx = new RegExp('(?:@' + name + '\\()(.*)(?:\\))'); var matches = rgx.exec(str); if (!matches || matches.length < 2) { return null; } var annotation = matches[1]; if (isArray) { annotation = '{ "data": ' + annotation + '}'; } // we want all double quotes in our string annotation = annotation.replace(/'/g, '"'); // parse out the object from the string var obj = null; try { obj = JSON.parse(annotation); } catch (ex) { /* eslint no-console:0 */ console.log('Annotation parse error with ' + annotation); throw ex; } if (isArray) { obj = obj.data; } return obj; }
[ "function", "getAnnotationInfo", "(", "name", ",", "fn", ",", "isArray", ")", "{", "if", "(", "!", "fn", ")", "{", "return", "null", ";", "}", "var", "str", "=", "fn", ".", "toString", "(", ")", ";", "var", "rgx", "=", "new", "RegExp", "(", "'(?:@'", "+", "name", "+", "'\\\\()(.*)(?:\\\\))'", ")", ";", "\\\\", "\\\\", "var", "matches", "=", "rgx", ".", "exec", "(", "str", ")", ";", "if", "(", "!", "matches", "||", "matches", ".", "length", "<", "2", ")", "{", "return", "null", ";", "}", "var", "annotation", "=", "matches", "[", "1", "]", ";", "if", "(", "isArray", ")", "{", "annotation", "=", "'{ \"data\": '", "+", "annotation", "+", "'}'", ";", "}", "annotation", "=", "annotation", ".", "replace", "(", "/", "'", "/", "g", ",", "'\"'", ")", ";", "var", "obj", "=", "null", ";", "try", "{", "obj", "=", "JSON", ".", "parse", "(", "annotation", ")", ";", "}", "catch", "(", "ex", ")", "{", "console", ".", "log", "(", "'Annotation parse error with '", "+", "annotation", ")", ";", "throw", "ex", ";", "}", "}" ]
Get any annotation that follows the same format @param name @param fn @param isArray @returns {*}
[ "Get", "any", "annotation", "that", "follows", "the", "same", "format" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/annotation.helper.js#L17-L54
train
gethuman/pancakes
lib/annotation.helper.js
getAliases
function getAliases(name, flapjack) { var moduleInfo = getModuleInfo(flapjack) || {}; var aliases = moduleInfo[name] || {}; return aliases === true ? {} : aliases; }
javascript
function getAliases(name, flapjack) { var moduleInfo = getModuleInfo(flapjack) || {}; var aliases = moduleInfo[name] || {}; return aliases === true ? {} : aliases; }
[ "function", "getAliases", "(", "name", ",", "flapjack", ")", "{", "var", "moduleInfo", "=", "getModuleInfo", "(", "flapjack", ")", "||", "{", "}", ";", "var", "aliases", "=", "moduleInfo", "[", "name", "]", "||", "{", "}", ";", "return", "aliases", "===", "true", "?", "{", "}", ":", "aliases", ";", "}" ]
Get either the client or server param mapping @param name [client|server] @param flapjack @return {{}}
[ "Get", "either", "the", "client", "or", "server", "param", "mapping" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/annotation.helper.js#L73-L77
train
gethuman/pancakes
lib/annotation.helper.js
getServerAliases
function getServerAliases(flapjack, options) { options = options || {}; var aliases = getAliases('server', flapjack); var serverAliases = options && options.serverAliases; return _.extend({}, aliases, serverAliases); }
javascript
function getServerAliases(flapjack, options) { options = options || {}; var aliases = getAliases('server', flapjack); var serverAliases = options && options.serverAliases; return _.extend({}, aliases, serverAliases); }
[ "function", "getServerAliases", "(", "flapjack", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "aliases", "=", "getAliases", "(", "'server'", ",", "flapjack", ")", ";", "var", "serverAliases", "=", "options", "&&", "options", ".", "serverAliases", ";", "return", "_", ".", "extend", "(", "{", "}", ",", "aliases", ",", "serverAliases", ")", ";", "}" ]
Get the Server param mappings @param flapjack @param options @return {{}}
[ "Get", "the", "Server", "param", "mappings" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/annotation.helper.js#L85-L90
train
gethuman/pancakes
lib/annotation.helper.js
getClientAliases
function getClientAliases(flapjack, options) { options = options || {}; var aliases = getAliases('client', flapjack); return _.extend({}, aliases, options.clientAliases); }
javascript
function getClientAliases(flapjack, options) { options = options || {}; var aliases = getAliases('client', flapjack); return _.extend({}, aliases, options.clientAliases); }
[ "function", "getClientAliases", "(", "flapjack", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "aliases", "=", "getAliases", "(", "'client'", ",", "flapjack", ")", ";", "return", "_", ".", "extend", "(", "{", "}", ",", "aliases", ",", "options", ".", "clientAliases", ")", ";", "}" ]
Get the client param mapping @param flapjack @param options @return {{}}
[ "Get", "the", "client", "param", "mapping" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/annotation.helper.js#L98-L102
train
gethuman/pancakes
lib/annotation.helper.js
getParameters
function getParameters(flapjack) { if (!_.isFunction(flapjack)) { throw new Error('Flapjack not a function ' + JSON.stringify(flapjack)); } var str = flapjack.toString(); var pattern = /(?:\()([^\)]*)(?:\))/; var matches = pattern.exec(str); if (matches === null || matches.length < 2) { throw new Error('Invalid flapjack: ' + str.substring(0, 200)); } var unfiltered = matches[1].replace(/\s/g, '').split(','); var params = [], i; for (i = 0; i < unfiltered.length; i++) { if (unfiltered[i]) { params.push(unfiltered[i]); } } return params; }
javascript
function getParameters(flapjack) { if (!_.isFunction(flapjack)) { throw new Error('Flapjack not a function ' + JSON.stringify(flapjack)); } var str = flapjack.toString(); var pattern = /(?:\()([^\)]*)(?:\))/; var matches = pattern.exec(str); if (matches === null || matches.length < 2) { throw new Error('Invalid flapjack: ' + str.substring(0, 200)); } var unfiltered = matches[1].replace(/\s/g, '').split(','); var params = [], i; for (i = 0; i < unfiltered.length; i++) { if (unfiltered[i]) { params.push(unfiltered[i]); } } return params; }
[ "function", "getParameters", "(", "flapjack", ")", "{", "if", "(", "!", "_", ".", "isFunction", "(", "flapjack", ")", ")", "{", "throw", "new", "Error", "(", "'Flapjack not a function '", "+", "JSON", ".", "stringify", "(", "flapjack", ")", ")", ";", "}", "var", "str", "=", "flapjack", ".", "toString", "(", ")", ";", "var", "pattern", "=", "/", "(?:\\()([^\\)]*)(?:\\))", "/", ";", "var", "matches", "=", "pattern", ".", "exec", "(", "str", ")", ";", "if", "(", "matches", "===", "null", "||", "matches", ".", "length", "<", "2", ")", "{", "throw", "new", "Error", "(", "'Invalid flapjack: '", "+", "str", ".", "substring", "(", "0", ",", "200", ")", ")", ";", "}", "var", "unfiltered", "=", "matches", "[", "1", "]", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ".", "split", "(", "','", ")", ";", "var", "params", "=", "[", "]", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "unfiltered", ".", "length", ";", "i", "++", ")", "{", "if", "(", "unfiltered", "[", "i", "]", ")", "{", "params", ".", "push", "(", "unfiltered", "[", "i", "]", ")", ";", "}", "}", "return", "params", ";", "}" ]
Get the function parameters for a given pancakes module @param flapjack The pancakes module @return {Array}
[ "Get", "the", "function", "parameters", "for", "a", "given", "pancakes", "module" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/annotation.helper.js#L110-L134
train
gethuman/pancakes
lib/factories/model.factory.js
getResourceNames
function getResourceNames() { var resourceNames = {}; var resourcesDir = this.injector.rootDir + '/' + this.injector.servicesDir + '/resources'; if (!fs.existsSync(path.normalize(resourcesDir))) { return resourceNames; } var names = fs.readdirSync(path.normalize(resourcesDir)); _.each(names, function (name) { if (name.substring(name.length - 3) !== '.js') { // only dirs, not js files resourceNames[utils.getPascalCase(name)] = utils.getCamelCase(name); } }); return resourceNames; }
javascript
function getResourceNames() { var resourceNames = {}; var resourcesDir = this.injector.rootDir + '/' + this.injector.servicesDir + '/resources'; if (!fs.existsSync(path.normalize(resourcesDir))) { return resourceNames; } var names = fs.readdirSync(path.normalize(resourcesDir)); _.each(names, function (name) { if (name.substring(name.length - 3) !== '.js') { // only dirs, not js files resourceNames[utils.getPascalCase(name)] = utils.getCamelCase(name); } }); return resourceNames; }
[ "function", "getResourceNames", "(", ")", "{", "var", "resourceNames", "=", "{", "}", ";", "var", "resourcesDir", "=", "this", ".", "injector", ".", "rootDir", "+", "'/'", "+", "this", ".", "injector", ".", "servicesDir", "+", "'/resources'", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "path", ".", "normalize", "(", "resourcesDir", ")", ")", ")", "{", "return", "resourceNames", ";", "}", "var", "names", "=", "fs", ".", "readdirSync", "(", "path", ".", "normalize", "(", "resourcesDir", ")", ")", ";", "_", ".", "each", "(", "names", ",", "function", "(", "name", ")", "{", "if", "(", "name", ".", "substring", "(", "name", ".", "length", "-", "3", ")", "!==", "'.js'", ")", "{", "resourceNames", "[", "utils", ".", "getPascalCase", "(", "name", ")", "]", "=", "utils", ".", "getCamelCase", "(", "name", ")", ";", "}", "}", ")", ";", "return", "resourceNames", ";", "}" ]
Get all the resources into memory @returns {{}}
[ "Get", "all", "the", "resources", "into", "memory" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/model.factory.js#L33-L49
train
gethuman/pancakes
lib/factories/model.factory.js
getModel
function getModel(service, mixins) { // model constructor takes in data and saves it along with the model mixins var Model = function (data) { _.extend(this, data, mixins); }; if (service.save) { Model.prototype.save = function () { if (this._id) { return service.save({ where: { _id: this._id }, data: this }); } else { return service.save({ data: this }); } }; } else if (service.create && service.update) { Model.prototype.save = function () { if (this._id) { return service.update({ where: { _id: this._id }, data: this }); } else { return service.create({ data: this }); } }; } if (service.remove) { Model.prototype.remove = function () { return service.remove({ where: { _id: this._id } }); }; } // the service methods are added as static references on the model _.each(service, function (method, methodName) { Model[methodName] = function () { return service[methodName].apply(service, arguments); }; }); return Model; }
javascript
function getModel(service, mixins) { // model constructor takes in data and saves it along with the model mixins var Model = function (data) { _.extend(this, data, mixins); }; if (service.save) { Model.prototype.save = function () { if (this._id) { return service.save({ where: { _id: this._id }, data: this }); } else { return service.save({ data: this }); } }; } else if (service.create && service.update) { Model.prototype.save = function () { if (this._id) { return service.update({ where: { _id: this._id }, data: this }); } else { return service.create({ data: this }); } }; } if (service.remove) { Model.prototype.remove = function () { return service.remove({ where: { _id: this._id } }); }; } // the service methods are added as static references on the model _.each(service, function (method, methodName) { Model[methodName] = function () { return service[methodName].apply(service, arguments); }; }); return Model; }
[ "function", "getModel", "(", "service", ",", "mixins", ")", "{", "var", "Model", "=", "function", "(", "data", ")", "{", "_", ".", "extend", "(", "this", ",", "data", ",", "mixins", ")", ";", "}", ";", "if", "(", "service", ".", "save", ")", "{", "Model", ".", "prototype", ".", "save", "=", "function", "(", ")", "{", "if", "(", "this", ".", "_id", ")", "{", "return", "service", ".", "save", "(", "{", "where", ":", "{", "_id", ":", "this", ".", "_id", "}", ",", "data", ":", "this", "}", ")", ";", "}", "else", "{", "return", "service", ".", "save", "(", "{", "data", ":", "this", "}", ")", ";", "}", "}", ";", "}", "else", "if", "(", "service", ".", "create", "&&", "service", ".", "update", ")", "{", "Model", ".", "prototype", ".", "save", "=", "function", "(", ")", "{", "if", "(", "this", ".", "_id", ")", "{", "return", "service", ".", "update", "(", "{", "where", ":", "{", "_id", ":", "this", ".", "_id", "}", ",", "data", ":", "this", "}", ")", ";", "}", "else", "{", "return", "service", ".", "create", "(", "{", "data", ":", "this", "}", ")", ";", "}", "}", ";", "}", "if", "(", "service", ".", "remove", ")", "{", "Model", ".", "prototype", ".", "remove", "=", "function", "(", ")", "{", "return", "service", ".", "remove", "(", "{", "where", ":", "{", "_id", ":", "this", ".", "_id", "}", "}", ")", ";", "}", ";", "}", "_", ".", "each", "(", "service", ",", "function", "(", "method", ",", "methodName", ")", "{", "Model", "[", "methodName", "]", "=", "function", "(", ")", "{", "return", "service", "[", "methodName", "]", ".", "apply", "(", "service", ",", "arguments", ")", ";", "}", ";", "}", ")", ";", "return", "Model", ";", "}" ]
Get a model based on a service and resource @param service @param mixins @returns {Model}
[ "Get", "a", "model", "based", "on", "a", "service", "and", "resource" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/model.factory.js#L73-L115
train
gethuman/pancakes
lib/factories/model.factory.js
create
function create(modulePath, moduleStack) { // first check the cache to see if we already loaded it if (this.cache[modulePath]) { return this.cache[modulePath]; } // try to get the resource for this module var resource; if (this.resources[modulePath]) { resource = this.resources[modulePath]; } else if (this.resourceNames[modulePath]) { resource = this.injector.loadModule(this.resourceNames[modulePath] + 'Resource'); } else { return null; } // get the service for this model var serviceName = modulePath.substring(0, 1).toLowerCase() + modulePath.substring(1) + 'Service'; var service = this.injector.loadModule(serviceName, moduleStack); // save the model to cache and return it var Model = this.getModel(service, resource.mixins); this.cache[modulePath] = Model; return Model; }
javascript
function create(modulePath, moduleStack) { // first check the cache to see if we already loaded it if (this.cache[modulePath]) { return this.cache[modulePath]; } // try to get the resource for this module var resource; if (this.resources[modulePath]) { resource = this.resources[modulePath]; } else if (this.resourceNames[modulePath]) { resource = this.injector.loadModule(this.resourceNames[modulePath] + 'Resource'); } else { return null; } // get the service for this model var serviceName = modulePath.substring(0, 1).toLowerCase() + modulePath.substring(1) + 'Service'; var service = this.injector.loadModule(serviceName, moduleStack); // save the model to cache and return it var Model = this.getModel(service, resource.mixins); this.cache[modulePath] = Model; return Model; }
[ "function", "create", "(", "modulePath", ",", "moduleStack", ")", "{", "if", "(", "this", ".", "cache", "[", "modulePath", "]", ")", "{", "return", "this", ".", "cache", "[", "modulePath", "]", ";", "}", "var", "resource", ";", "if", "(", "this", ".", "resources", "[", "modulePath", "]", ")", "{", "resource", "=", "this", ".", "resources", "[", "modulePath", "]", ";", "}", "else", "if", "(", "this", ".", "resourceNames", "[", "modulePath", "]", ")", "{", "resource", "=", "this", ".", "injector", ".", "loadModule", "(", "this", ".", "resourceNames", "[", "modulePath", "]", "+", "'Resource'", ")", ";", "}", "else", "{", "return", "null", ";", "}", "var", "serviceName", "=", "modulePath", ".", "substring", "(", "0", ",", "1", ")", ".", "toLowerCase", "(", ")", "+", "modulePath", ".", "substring", "(", "1", ")", "+", "'Service'", ";", "var", "service", "=", "this", ".", "injector", ".", "loadModule", "(", "serviceName", ",", "moduleStack", ")", ";", "var", "Model", "=", "this", ".", "getModel", "(", "service", ",", "resource", ".", "mixins", ")", ";", "this", ".", "cache", "[", "modulePath", "]", "=", "Model", ";", "return", "Model", ";", "}" ]
Create a model @param modulePath @param moduleStack
[ "Create", "a", "model" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/model.factory.js#L122-L149
train
gethuman/pancakes
lib/factories/internal.object.factory.js
InternalObjectFactory
function InternalObjectFactory(injector) { this.injector = injector; this.internalObjects = { resources: true, reactors: true, adapters: true, appConfigs: true, eventBus: eventBus, chainPromises: utils.chainPromises }; }
javascript
function InternalObjectFactory(injector) { this.injector = injector; this.internalObjects = { resources: true, reactors: true, adapters: true, appConfigs: true, eventBus: eventBus, chainPromises: utils.chainPromises }; }
[ "function", "InternalObjectFactory", "(", "injector", ")", "{", "this", ".", "injector", "=", "injector", ";", "this", ".", "internalObjects", "=", "{", "resources", ":", "true", ",", "reactors", ":", "true", ",", "adapters", ":", "true", ",", "appConfigs", ":", "true", ",", "eventBus", ":", "eventBus", ",", "chainPromises", ":", "utils", ".", "chainPromises", "}", ";", "}" ]
Constructor doesn't currently do anything @constructor
[ "Constructor", "doesn", "t", "currently", "do", "anything" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/internal.object.factory.js#L18-L28
train
gethuman/pancakes
lib/factories/internal.object.factory.js
loadResources
function loadResources() { var resources = {}; var resourcesDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/resources'); if (!fs.existsSync(resourcesDir)) { return resources; } var me = this; var resourceNames = fs.readdirSync(resourcesDir); _.each(resourceNames, function (resourceName) { if (resourceName.substring(resourceName.length - 3) !== '.js') { // only dirs, not js files resources[resourceName] = me.injector.loadModule(utils.getCamelCase(resourceName + '.resource')); } }); return resources; }
javascript
function loadResources() { var resources = {}; var resourcesDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/resources'); if (!fs.existsSync(resourcesDir)) { return resources; } var me = this; var resourceNames = fs.readdirSync(resourcesDir); _.each(resourceNames, function (resourceName) { if (resourceName.substring(resourceName.length - 3) !== '.js') { // only dirs, not js files resources[resourceName] = me.injector.loadModule(utils.getCamelCase(resourceName + '.resource')); } }); return resources; }
[ "function", "loadResources", "(", ")", "{", "var", "resources", "=", "{", "}", ";", "var", "resourcesDir", "=", "path", ".", "join", "(", "this", ".", "injector", ".", "rootDir", ",", "this", ".", "injector", ".", "servicesDir", "+", "'/resources'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "resourcesDir", ")", ")", "{", "return", "resources", ";", "}", "var", "me", "=", "this", ";", "var", "resourceNames", "=", "fs", ".", "readdirSync", "(", "resourcesDir", ")", ";", "_", ".", "each", "(", "resourceNames", ",", "function", "(", "resourceName", ")", "{", "if", "(", "resourceName", ".", "substring", "(", "resourceName", ".", "length", "-", "3", ")", "!==", "'.js'", ")", "{", "resources", "[", "resourceName", "]", "=", "me", ".", "injector", ".", "loadModule", "(", "utils", ".", "getCamelCase", "(", "resourceName", "+", "'.resource'", ")", ")", ";", "}", "}", ")", ";", "return", "resources", ";", "}" ]
Load all resources into an object that can be injected @returns {{}}
[ "Load", "all", "resources", "into", "an", "object", "that", "can", "be", "injected" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/internal.object.factory.js#L36-L55
train
gethuman/pancakes
lib/factories/internal.object.factory.js
loadAdapters
function loadAdapters() { var adapters = {}; var adaptersDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/adapters'); if (!fs.existsSync(adaptersDir)) { return this.injector.adapters || {}; } var me = this; var adapterNames = fs.readdirSync(adaptersDir); _.each(adapterNames, function (adapterName) { if (adapterName.substring(adapterName.length - 3) !== '.js') { // only dirs, not js files var adapterImpl = me.injector.adapterMap[adapterName]; adapterName = utils.getPascalCase(adapterImpl + '.' + adapterName + '.adapter'); adapters[adapterName] = me.injector.loadModule(adapterName); } }); // add the adapters that come from plugins to the list _.extend(adapters, this.injector.adapters); // return the adapters return adapters; }
javascript
function loadAdapters() { var adapters = {}; var adaptersDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/adapters'); if (!fs.existsSync(adaptersDir)) { return this.injector.adapters || {}; } var me = this; var adapterNames = fs.readdirSync(adaptersDir); _.each(adapterNames, function (adapterName) { if (adapterName.substring(adapterName.length - 3) !== '.js') { // only dirs, not js files var adapterImpl = me.injector.adapterMap[adapterName]; adapterName = utils.getPascalCase(adapterImpl + '.' + adapterName + '.adapter'); adapters[adapterName] = me.injector.loadModule(adapterName); } }); // add the adapters that come from plugins to the list _.extend(adapters, this.injector.adapters); // return the adapters return adapters; }
[ "function", "loadAdapters", "(", ")", "{", "var", "adapters", "=", "{", "}", ";", "var", "adaptersDir", "=", "path", ".", "join", "(", "this", ".", "injector", ".", "rootDir", ",", "this", ".", "injector", ".", "servicesDir", "+", "'/adapters'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "adaptersDir", ")", ")", "{", "return", "this", ".", "injector", ".", "adapters", "||", "{", "}", ";", "}", "var", "me", "=", "this", ";", "var", "adapterNames", "=", "fs", ".", "readdirSync", "(", "adaptersDir", ")", ";", "_", ".", "each", "(", "adapterNames", ",", "function", "(", "adapterName", ")", "{", "if", "(", "adapterName", ".", "substring", "(", "adapterName", ".", "length", "-", "3", ")", "!==", "'.js'", ")", "{", "var", "adapterImpl", "=", "me", ".", "injector", ".", "adapterMap", "[", "adapterName", "]", ";", "adapterName", "=", "utils", ".", "getPascalCase", "(", "adapterImpl", "+", "'.'", "+", "adapterName", "+", "'.adapter'", ")", ";", "adapters", "[", "adapterName", "]", "=", "me", ".", "injector", ".", "loadModule", "(", "adapterName", ")", ";", "}", "}", ")", ";", "_", ".", "extend", "(", "adapters", ",", "this", ".", "injector", ".", "adapters", ")", ";", "return", "adapters", ";", "}" ]
Load all adapters into an object that can be injected @returns {{}}
[ "Load", "all", "adapters", "into", "an", "object", "that", "can", "be", "injected" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/internal.object.factory.js#L61-L85
train
gethuman/pancakes
lib/factories/internal.object.factory.js
loadReactors
function loadReactors() { var reactors = {}; var reactorsDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/reactors'); if (!fs.existsSync(reactorsDir)) { return reactors; } var me = this; var reactorNames = fs.readdirSync(reactorsDir); _.each(reactorNames, function (reactorName) { reactorName = reactorName.substring(0, reactorName.length - 3); reactors[reactorName] = me.injector.loadModule(utils.getCamelCase(reactorName)); }); // add the reactors that come from plugins to the list _.extend(reactors, this.injector.reactors); return reactors; }
javascript
function loadReactors() { var reactors = {}; var reactorsDir = path.join(this.injector.rootDir, this.injector.servicesDir + '/reactors'); if (!fs.existsSync(reactorsDir)) { return reactors; } var me = this; var reactorNames = fs.readdirSync(reactorsDir); _.each(reactorNames, function (reactorName) { reactorName = reactorName.substring(0, reactorName.length - 3); reactors[reactorName] = me.injector.loadModule(utils.getCamelCase(reactorName)); }); // add the reactors that come from plugins to the list _.extend(reactors, this.injector.reactors); return reactors; }
[ "function", "loadReactors", "(", ")", "{", "var", "reactors", "=", "{", "}", ";", "var", "reactorsDir", "=", "path", ".", "join", "(", "this", ".", "injector", ".", "rootDir", ",", "this", ".", "injector", ".", "servicesDir", "+", "'/reactors'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "reactorsDir", ")", ")", "{", "return", "reactors", ";", "}", "var", "me", "=", "this", ";", "var", "reactorNames", "=", "fs", ".", "readdirSync", "(", "reactorsDir", ")", ";", "_", ".", "each", "(", "reactorNames", ",", "function", "(", "reactorName", ")", "{", "reactorName", "=", "reactorName", ".", "substring", "(", "0", ",", "reactorName", ".", "length", "-", "3", ")", ";", "reactors", "[", "reactorName", "]", "=", "me", ".", "injector", ".", "loadModule", "(", "utils", ".", "getCamelCase", "(", "reactorName", ")", ")", ";", "}", ")", ";", "_", ".", "extend", "(", "reactors", ",", "this", ".", "injector", ".", "reactors", ")", ";", "return", "reactors", ";", "}" ]
Load all reactors into an object that can be injected @returns {{}}
[ "Load", "all", "reactors", "into", "an", "object", "that", "can", "be", "injected" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/internal.object.factory.js#L91-L111
train
gethuman/pancakes
lib/factories/internal.object.factory.js
loadAppConfigs
function loadAppConfigs() { var appConfigs = {}; var appDir = path.join(this.injector.rootDir, '/app'); if (!fs.existsSync(appDir)) { return appConfigs; } var me = this; var appNames = fs.readdirSync(appDir); _.each(appNames, function (appName) { appConfigs[appName] = me.injector.loadModule('app/' + appName + '/' + appName + '.app'); }); return appConfigs; }
javascript
function loadAppConfigs() { var appConfigs = {}; var appDir = path.join(this.injector.rootDir, '/app'); if (!fs.existsSync(appDir)) { return appConfigs; } var me = this; var appNames = fs.readdirSync(appDir); _.each(appNames, function (appName) { appConfigs[appName] = me.injector.loadModule('app/' + appName + '/' + appName + '.app'); }); return appConfigs; }
[ "function", "loadAppConfigs", "(", ")", "{", "var", "appConfigs", "=", "{", "}", ";", "var", "appDir", "=", "path", ".", "join", "(", "this", ".", "injector", ".", "rootDir", ",", "'/app'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "appDir", ")", ")", "{", "return", "appConfigs", ";", "}", "var", "me", "=", "this", ";", "var", "appNames", "=", "fs", ".", "readdirSync", "(", "appDir", ")", ";", "_", ".", "each", "(", "appNames", ",", "function", "(", "appName", ")", "{", "appConfigs", "[", "appName", "]", "=", "me", ".", "injector", ".", "loadModule", "(", "'app/'", "+", "appName", "+", "'/'", "+", "appName", "+", "'.app'", ")", ";", "}", ")", ";", "return", "appConfigs", ";", "}" ]
Load all app configs into an object that can be injected @returns {{}}
[ "Load", "all", "app", "configs", "into", "an", "object", "that", "can", "be", "injected" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/internal.object.factory.js#L117-L133
train
gethuman/pancakes
lib/factories/internal.object.factory.js
create
function create(objectName) { // for resources we need to load them the first time they are referenced if (objectName === 'resources' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadResources(); } // for reactors we need to load them the first time they are referenced else if (objectName === 'reactors' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadReactors(); } // for reactors we need to load them the first time they are referenced else if (objectName === 'appConfigs' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadAppConfigs(); } // for adapters we need to load them the first time they are referenced else if (objectName === 'adapters' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadAdapters(); } return this.internalObjects[objectName]; }
javascript
function create(objectName) { // for resources we need to load them the first time they are referenced if (objectName === 'resources' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadResources(); } // for reactors we need to load them the first time they are referenced else if (objectName === 'reactors' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadReactors(); } // for reactors we need to load them the first time they are referenced else if (objectName === 'appConfigs' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadAppConfigs(); } // for adapters we need to load them the first time they are referenced else if (objectName === 'adapters' && this.internalObjects[objectName] === true) { this.internalObjects[objectName] = this.loadAdapters(); } return this.internalObjects[objectName]; }
[ "function", "create", "(", "objectName", ")", "{", "if", "(", "objectName", "===", "'resources'", "&&", "this", ".", "internalObjects", "[", "objectName", "]", "===", "true", ")", "{", "this", ".", "internalObjects", "[", "objectName", "]", "=", "this", ".", "loadResources", "(", ")", ";", "}", "else", "if", "(", "objectName", "===", "'reactors'", "&&", "this", ".", "internalObjects", "[", "objectName", "]", "===", "true", ")", "{", "this", ".", "internalObjects", "[", "objectName", "]", "=", "this", ".", "loadReactors", "(", ")", ";", "}", "else", "if", "(", "objectName", "===", "'appConfigs'", "&&", "this", ".", "internalObjects", "[", "objectName", "]", "===", "true", ")", "{", "this", ".", "internalObjects", "[", "objectName", "]", "=", "this", ".", "loadAppConfigs", "(", ")", ";", "}", "else", "if", "(", "objectName", "===", "'adapters'", "&&", "this", ".", "internalObjects", "[", "objectName", "]", "===", "true", ")", "{", "this", ".", "internalObjects", "[", "objectName", "]", "=", "this", ".", "loadAdapters", "(", ")", ";", "}", "return", "this", ".", "internalObjects", "[", "objectName", "]", ";", "}" ]
Very simply use require to get the object @param objectName @returns {{}}
[ "Very", "simply", "use", "require", "to", "get", "the", "object" ]
86b89ae2f0ac68f86cd5ff66421677b3aa290857
https://github.com/gethuman/pancakes/blob/86b89ae2f0ac68f86cd5ff66421677b3aa290857/lib/factories/internal.object.factory.js#L154-L177
train
telefonicaid/logops
lib/formatters.js
formatDevTrace
function formatDevTrace(level, context, message, args, err) { var str, mainMessage = util.format.apply(global, [message].concat(args)), printStack = API.stacktracesWith.indexOf(level) > -1, errCommomMessage = err && (err.name + ': ' + err.message), isErrorLoggingWithoutMessage = mainMessage === errCommomMessage; switch (level) { case 'DEBUG': str = colors.grey(level); break; case 'INFO': str = colors.blue(level) + ' '; // Pad to 5 chars break; case 'WARN': str = colors.yellow(level) + ' '; // Pad to 5 chars break; case 'ERROR': str = colors.red(level); break; case 'FATAL': str = colors.red.bold(level); break; } str += ' ' + mainMessage; if (isErrorLoggingWithoutMessage) { str += colorize(colors.gray, serializeErr(err).toString(printStack).substr(mainMessage.length)); } else if (err) { str += '\n' + colorize(colors.gray, serializeErr(err).toString(printStack)); } var localContext = _.omit(context, formatDevTrace.omit); str += Object.keys(localContext).length ? ' ' + colorize(colors.gray, util.inspect(localContext)) : ''; // pad all subsequent lines with as much spaces as "DEBUG " or "INFO " have return str.replace(new RegExp('\r?\n','g'), '\n '); }
javascript
function formatDevTrace(level, context, message, args, err) { var str, mainMessage = util.format.apply(global, [message].concat(args)), printStack = API.stacktracesWith.indexOf(level) > -1, errCommomMessage = err && (err.name + ': ' + err.message), isErrorLoggingWithoutMessage = mainMessage === errCommomMessage; switch (level) { case 'DEBUG': str = colors.grey(level); break; case 'INFO': str = colors.blue(level) + ' '; // Pad to 5 chars break; case 'WARN': str = colors.yellow(level) + ' '; // Pad to 5 chars break; case 'ERROR': str = colors.red(level); break; case 'FATAL': str = colors.red.bold(level); break; } str += ' ' + mainMessage; if (isErrorLoggingWithoutMessage) { str += colorize(colors.gray, serializeErr(err).toString(printStack).substr(mainMessage.length)); } else if (err) { str += '\n' + colorize(colors.gray, serializeErr(err).toString(printStack)); } var localContext = _.omit(context, formatDevTrace.omit); str += Object.keys(localContext).length ? ' ' + colorize(colors.gray, util.inspect(localContext)) : ''; // pad all subsequent lines with as much spaces as "DEBUG " or "INFO " have return str.replace(new RegExp('\r?\n','g'), '\n '); }
[ "function", "formatDevTrace", "(", "level", ",", "context", ",", "message", ",", "args", ",", "err", ")", "{", "var", "str", ",", "mainMessage", "=", "util", ".", "format", ".", "apply", "(", "global", ",", "[", "message", "]", ".", "concat", "(", "args", ")", ")", ",", "printStack", "=", "API", ".", "stacktracesWith", ".", "indexOf", "(", "level", ")", ">", "-", "1", ",", "errCommomMessage", "=", "err", "&&", "(", "err", ".", "name", "+", "': '", "+", "err", ".", "message", ")", ",", "isErrorLoggingWithoutMessage", "=", "mainMessage", "===", "errCommomMessage", ";", "switch", "(", "level", ")", "{", "case", "'DEBUG'", ":", "str", "=", "colors", ".", "grey", "(", "level", ")", ";", "break", ";", "case", "'INFO'", ":", "str", "=", "colors", ".", "blue", "(", "level", ")", "+", "' '", ";", "break", ";", "case", "'WARN'", ":", "str", "=", "colors", ".", "yellow", "(", "level", ")", "+", "' '", ";", "break", ";", "case", "'ERROR'", ":", "str", "=", "colors", ".", "red", "(", "level", ")", ";", "break", ";", "case", "'FATAL'", ":", "str", "=", "colors", ".", "red", ".", "bold", "(", "level", ")", ";", "break", ";", "}", "str", "+=", "' '", "+", "mainMessage", ";", "if", "(", "isErrorLoggingWithoutMessage", ")", "{", "str", "+=", "colorize", "(", "colors", ".", "gray", ",", "serializeErr", "(", "err", ")", ".", "toString", "(", "printStack", ")", ".", "substr", "(", "mainMessage", ".", "length", ")", ")", ";", "}", "else", "if", "(", "err", ")", "{", "str", "+=", "'\\n'", "+", "\\n", ";", "}", "colorize", "(", "colors", ".", "gray", ",", "serializeErr", "(", "err", ")", ".", "toString", "(", "printStack", ")", ")", "var", "localContext", "=", "_", ".", "omit", "(", "context", ",", "formatDevTrace", ".", "omit", ")", ";", "str", "+=", "Object", ".", "keys", "(", "localContext", ")", ".", "length", "?", "' '", "+", "colorize", "(", "colors", ".", "gray", ",", "util", ".", "inspect", "(", "localContext", ")", ")", ":", "''", ";", "}" ]
Formats a trace message with some nice TTY colors @param {String} level One of the following values ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'] @param {Object} context Additional information to add to the trace @param {String} message The main message to be added to the trace @param {Array} args More arguments provided to the log function @param {Error|undefined} err A cause error used to log extra information @return {String} The trace formatted
[ "Formats", "a", "trace", "message", "with", "some", "nice", "TTY", "colors" ]
6023d75b3531ed1bb3abe171679234f9519be082
https://github.com/telefonicaid/logops/blob/6023d75b3531ed1bb3abe171679234f9519be082/lib/formatters.js#L68-L107
train