repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
mthadley/magnet-plugin-sass
src/index.js
serveSassFiles
function serveSassFiles(magnet, outputDir) { if (!isServingSassFiles) { magnet.getServer() .getEngine() .use('/css', express.static(outputDir)); } isServingSassFiles = true; }
javascript
function serveSassFiles(magnet, outputDir) { if (!isServingSassFiles) { magnet.getServer() .getEngine() .use('/css', express.static(outputDir)); } isServingSassFiles = true; }
[ "function", "serveSassFiles", "(", "magnet", ",", "outputDir", ")", "{", "if", "(", "!", "isServingSassFiles", ")", "{", "magnet", ".", "getServer", "(", ")", ".", "getEngine", "(", ")", ".", "use", "(", "'/css'", ",", "express", ".", "static", "(", "outputDir", ")", ")", ";", "}", "isServingSassFiles", "=", "true", ";", "}" ]
Serves built sass files using magnet server instance @param {!Magnet} magnet @param {!string} outputDir
[ "Serves", "built", "sass", "files", "using", "magnet", "server", "instance" ]
60323a1e590534954d813a13a08046eb3c12265f
https://github.com/mthadley/magnet-plugin-sass/blob/60323a1e590534954d813a13a08046eb3c12265f/src/index.js#L22-L29
train
mthadley/magnet-plugin-sass
src/index.js
getOutputFile
function getOutputFile(file, outputDir) { const fileName = path.basename(file).replace('.scss', '.css'); return path.join(outputDir, fileName); }
javascript
function getOutputFile(file, outputDir) { const fileName = path.basename(file).replace('.scss', '.css'); return path.join(outputDir, fileName); }
[ "function", "getOutputFile", "(", "file", ",", "outputDir", ")", "{", "const", "fileName", "=", "path", ".", "basename", "(", "file", ")", ".", "replace", "(", "'.scss'", ",", "'.css'", ")", ";", "return", "path", ".", "join", "(", "outputDir", ",", "fileName", ")", ";", "}" ]
Gets the output file path for a file and a given output directory. @param {!string} file @param {!string} outputDir @return {!string}
[ "Gets", "the", "output", "file", "path", "for", "a", "file", "and", "a", "given", "output", "directory", "." ]
60323a1e590534954d813a13a08046eb3c12265f
https://github.com/mthadley/magnet-plugin-sass/blob/60323a1e590534954d813a13a08046eb3c12265f/src/index.js#L38-L41
train
mthadley/magnet-plugin-sass
src/index.js
writeFile
function writeFile(file, css) { return new Promise((resolve, reject) => { fs.writeFile(file, css, err => { if (err) { return reject(err); } resolve(); }) }); }
javascript
function writeFile(file, css) { return new Promise((resolve, reject) => { fs.writeFile(file, css, err => { if (err) { return reject(err); } resolve(); }) }); }
[ "function", "writeFile", "(", "file", ",", "css", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "writeFile", "(", "file", ",", "css", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", ")", ";", "}", ")", "}", ")", ";", "}" ]
Writes css to file @param {!string} file @param {!string} css @return {!Promise}
[ "Writes", "css", "to", "file" ]
60323a1e590534954d813a13a08046eb3c12265f
https://github.com/mthadley/magnet-plugin-sass/blob/60323a1e590534954d813a13a08046eb3c12265f/src/index.js#L49-L58
train
mthadley/magnet-plugin-sass
src/index.js
renderFile
function renderFile(file, config) { const options = Object.assign({file}, config); return new Promise((resolve, reject) => { sass.render(options, (err, result) => { if (err) { return reject(err); } resolve(result.css); }); }); }
javascript
function renderFile(file, config) { const options = Object.assign({file}, config); return new Promise((resolve, reject) => { sass.render(options, (err, result) => { if (err) { return reject(err); } resolve(result.css); }); }); }
[ "function", "renderFile", "(", "file", ",", "config", ")", "{", "const", "options", "=", "Object", ".", "assign", "(", "{", "file", "}", ",", "config", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "sass", ".", "render", "(", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "result", ".", "css", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Renders a single sass file @param {!string} file @param {!object} config @return {!Promise.<string>} The resulting css
[ "Renders", "a", "single", "sass", "file" ]
60323a1e590534954d813a13a08046eb3c12265f
https://github.com/mthadley/magnet-plugin-sass/blob/60323a1e590534954d813a13a08046eb3c12265f/src/index.js#L66-L77
train
mthadley/magnet-plugin-sass
src/index.js
buildSassFiles
async function buildSassFiles(files, outputDir, config) { const renderedFiles = await Promise.all(files.map(async file => { const css = await renderFile(file, config); return {file, css}; })); await fs.ensureDir(outputDir); return Promise.all(renderedFiles.map(({file, css}) => { const outputFile = getOutputFile(file, outputDir); return writeFile(outputFile, css); })); }
javascript
async function buildSassFiles(files, outputDir, config) { const renderedFiles = await Promise.all(files.map(async file => { const css = await renderFile(file, config); return {file, css}; })); await fs.ensureDir(outputDir); return Promise.all(renderedFiles.map(({file, css}) => { const outputFile = getOutputFile(file, outputDir); return writeFile(outputFile, css); })); }
[ "async", "function", "buildSassFiles", "(", "files", ",", "outputDir", ",", "config", ")", "{", "const", "renderedFiles", "=", "await", "Promise", ".", "all", "(", "files", ".", "map", "(", "async", "file", "=>", "{", "const", "css", "=", "await", "renderFile", "(", "file", ",", "config", ")", ";", "return", "{", "file", ",", "css", "}", ";", "}", ")", ")", ";", "await", "fs", ".", "ensureDir", "(", "outputDir", ")", ";", "return", "Promise", ".", "all", "(", "renderedFiles", ".", "map", "(", "(", "{", "file", ",", "css", "}", ")", "=>", "{", "const", "outputFile", "=", "getOutputFile", "(", "file", ",", "outputDir", ")", ";", "return", "writeFile", "(", "outputFile", ",", "css", ")", ";", "}", ")", ")", ";", "}" ]
Builds sass files to output dir @param {!Array.<string>} files @param {!string} outputDir @param {!Object} config @return {!Promise}
[ "Builds", "sass", "files", "to", "output", "dir" ]
60323a1e590534954d813a13a08046eb3c12265f
https://github.com/mthadley/magnet-plugin-sass/blob/60323a1e590534954d813a13a08046eb3c12265f/src/index.js#L86-L98
train
Julien-Cousineau/util
src/index.js
range
function range(n,type) { n = (typeof n !== 'undefined') ? n : 0; if (!(Number.isInteger(n))) throw Error("Error in range: Value must be an integer"); let array; if(type=='Uint8') array = new Uint8Array(n); if(type=='Uint16') array = new Uint16Array(n); if(type=='Uint32') array = new Uint32Array(n); if(type=='Int8') array = new Int8Array(n); if(type=='Int16') array = new Int16Array(n); if(type=='Int32') array = new Int32Array(n); if(type=='Float32') array = new Float32Array(n); if((typeof type === 'undefined') || !array)array = new Array(n); for(let i=0;i<n;i++)array[i]=i; return array; }
javascript
function range(n,type) { n = (typeof n !== 'undefined') ? n : 0; if (!(Number.isInteger(n))) throw Error("Error in range: Value must be an integer"); let array; if(type=='Uint8') array = new Uint8Array(n); if(type=='Uint16') array = new Uint16Array(n); if(type=='Uint32') array = new Uint32Array(n); if(type=='Int8') array = new Int8Array(n); if(type=='Int16') array = new Int16Array(n); if(type=='Int32') array = new Int32Array(n); if(type=='Float32') array = new Float32Array(n); if((typeof type === 'undefined') || !array)array = new Array(n); for(let i=0;i<n;i++)array[i]=i; return array; }
[ "function", "range", "(", "n", ",", "type", ")", "{", "n", "=", "(", "typeof", "n", "!==", "'undefined'", ")", "?", "n", ":", "0", ";", "if", "(", "!", "(", "Number", ".", "isInteger", "(", "n", ")", ")", ")", "throw", "Error", "(", "\"Error in range: Value must be an integer\"", ")", ";", "let", "array", ";", "if", "(", "type", "==", "'Uint8'", ")", "array", "=", "new", "Uint8Array", "(", "n", ")", ";", "if", "(", "type", "==", "'Uint16'", ")", "array", "=", "new", "Uint16Array", "(", "n", ")", ";", "if", "(", "type", "==", "'Uint32'", ")", "array", "=", "new", "Uint32Array", "(", "n", ")", ";", "if", "(", "type", "==", "'Int8'", ")", "array", "=", "new", "Int8Array", "(", "n", ")", ";", "if", "(", "type", "==", "'Int16'", ")", "array", "=", "new", "Int16Array", "(", "n", ")", ";", "if", "(", "type", "==", "'Int32'", ")", "array", "=", "new", "Int32Array", "(", "n", ")", ";", "if", "(", "type", "==", "'Float32'", ")", "array", "=", "new", "Float32Array", "(", "n", ")", ";", "if", "(", "(", "typeof", "type", "===", "'undefined'", ")", "||", "!", "array", ")", "array", "=", "new", "Array", "(", "n", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "array", "[", "i", "]", "=", "i", ";", "return", "array", ";", "}" ]
module.exports.quickSort = quickSort; module.exports.quickSortIndices = quickSortIndices;
[ "module", ".", "exports", ".", "quickSort", "=", "quickSort", ";", "module", ".", "exports", ".", "quickSortIndices", "=", "quickSortIndices", ";" ]
b52b841288a1d5eb5fd185a42664a75fba42e2da
https://github.com/Julien-Cousineau/util/blob/b52b841288a1d5eb5fd185a42664a75fba42e2da/src/index.js#L291-L307
train
Psychopoulet/simplessl
lib/wrapperStdToString.js
_execution
function _execution (spawn, data, options) { const match = data.match(WATING_STDIN); if (match) { if (-1 < match[1].indexOf("Country Name")) { if (!options.country) { options.country = match[2] ? match[2] : "."; } spawn.stdin.write(options.country + "\n"); } else if (-1 < match[1].indexOf("Locality Name")) { if (!options.locality) { options.locality = match[2] ? match[2] : "."; } spawn.stdin.write(options.locality + "\n"); } else if (-1 < match[1].indexOf("State or Province Name")) { if (!options.state) { options.state = match[2] ? match[2] : "."; } spawn.stdin.write(options.state + "\n"); } else if (-1 < match[1].indexOf("Organization Name")) { if (!options.organization) { options.organization = match[2] ? match[2] : "."; } spawn.stdin.write(options.organization + "\n"); } else if (-1 < match[1].indexOf("Common Name")) { if (!options.common) { options.common = match[2] ? match[2] : "."; } spawn.stdin.write(options.common + "\n"); } else if (-1 < match[1].indexOf("Email Address")) { if (!options.email) { options.email = match[2] ? match[2] : "."; } spawn.stdin.write(options.email + "\n"); } else { spawn.stdin.write(".\n"); } return ""; } else { return data; } }
javascript
function _execution (spawn, data, options) { const match = data.match(WATING_STDIN); if (match) { if (-1 < match[1].indexOf("Country Name")) { if (!options.country) { options.country = match[2] ? match[2] : "."; } spawn.stdin.write(options.country + "\n"); } else if (-1 < match[1].indexOf("Locality Name")) { if (!options.locality) { options.locality = match[2] ? match[2] : "."; } spawn.stdin.write(options.locality + "\n"); } else if (-1 < match[1].indexOf("State or Province Name")) { if (!options.state) { options.state = match[2] ? match[2] : "."; } spawn.stdin.write(options.state + "\n"); } else if (-1 < match[1].indexOf("Organization Name")) { if (!options.organization) { options.organization = match[2] ? match[2] : "."; } spawn.stdin.write(options.organization + "\n"); } else if (-1 < match[1].indexOf("Common Name")) { if (!options.common) { options.common = match[2] ? match[2] : "."; } spawn.stdin.write(options.common + "\n"); } else if (-1 < match[1].indexOf("Email Address")) { if (!options.email) { options.email = match[2] ? match[2] : "."; } spawn.stdin.write(options.email + "\n"); } else { spawn.stdin.write(".\n"); } return ""; } else { return data; } }
[ "function", "_execution", "(", "spawn", ",", "data", ",", "options", ")", "{", "const", "match", "=", "data", ".", "match", "(", "WATING_STDIN", ")", ";", "if", "(", "match", ")", "{", "if", "(", "-", "1", "<", "match", "[", "1", "]", ".", "indexOf", "(", "\"Country Name\"", ")", ")", "{", "if", "(", "!", "options", ".", "country", ")", "{", "options", ".", "country", "=", "match", "[", "2", "]", "?", "match", "[", "2", "]", ":", "\".\"", ";", "}", "spawn", ".", "stdin", ".", "write", "(", "options", ".", "country", "+", "\"\\n\"", ")", ";", "}", "else", "\\n", "if", "(", "-", "1", "<", "match", "[", "1", "]", ".", "indexOf", "(", "\"Locality Name\"", ")", ")", "{", "if", "(", "!", "options", ".", "locality", ")", "{", "options", ".", "locality", "=", "match", "[", "2", "]", "?", "match", "[", "2", "]", ":", "\".\"", ";", "}", "spawn", ".", "stdin", ".", "write", "(", "options", ".", "locality", "+", "\"\\n\"", ")", ";", "}", "else", "\\n", "}", "else", "if", "(", "-", "1", "<", "match", "[", "1", "]", ".", "indexOf", "(", "\"State or Province Name\"", ")", ")", "{", "if", "(", "!", "options", ".", "state", ")", "{", "options", ".", "state", "=", "match", "[", "2", "]", "?", "match", "[", "2", "]", ":", "\".\"", ";", "}", "spawn", ".", "stdin", ".", "write", "(", "options", ".", "state", "+", "\"\\n\"", ")", ";", "}", "else", "\\n", "}" ]
methods Execute method @param {child_process} spawn : std process @param {string} data : data to check @param {object} options : options for execution @returns {any} Cloned data
[ "methods", "Execute", "method" ]
22872f3429510a45260ba73158dfdcc44df80700
https://github.com/Psychopoulet/simplessl/blob/22872f3429510a45260ba73158dfdcc44df80700/lib/wrapperStdToString.js#L27-L98
train
panarch/famous-mig
surfaces/CanvasSurface.js
CanvasSurface
function CanvasSurface(options) { if (options) options.useTarget = true; else options = { useTarget: true }; if (options.canvasSize) this._canvasSize = options.canvasSize; Surface.apply(this, arguments); if (!this._canvasSize) this._canvasSize = this.getSize(); this._backBuffer = document.createElement('canvas'); if (this._canvasSize) { this._backBuffer.width = this._canvasSize[0]; this._backBuffer.height = this._canvasSize[1]; } this._contextId = undefined; }
javascript
function CanvasSurface(options) { if (options) options.useTarget = true; else options = { useTarget: true }; if (options.canvasSize) this._canvasSize = options.canvasSize; Surface.apply(this, arguments); if (!this._canvasSize) this._canvasSize = this.getSize(); this._backBuffer = document.createElement('canvas'); if (this._canvasSize) { this._backBuffer.width = this._canvasSize[0]; this._backBuffer.height = this._canvasSize[1]; } this._contextId = undefined; }
[ "function", "CanvasSurface", "(", "options", ")", "{", "if", "(", "options", ")", "options", ".", "useTarget", "=", "true", ";", "else", "options", "=", "{", "useTarget", ":", "true", "}", ";", "if", "(", "options", ".", "canvasSize", ")", "this", ".", "_canvasSize", "=", "options", ".", "canvasSize", ";", "Surface", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "!", "this", ".", "_canvasSize", ")", "this", ".", "_canvasSize", "=", "this", ".", "getSize", "(", ")", ";", "this", ".", "_backBuffer", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "if", "(", "this", ".", "_canvasSize", ")", "{", "this", ".", "_backBuffer", ".", "width", "=", "this", ".", "_canvasSize", "[", "0", "]", ";", "this", ".", "_backBuffer", ".", "height", "=", "this", ".", "_canvasSize", "[", "1", "]", ";", "}", "this", ".", "_contextId", "=", "undefined", ";", "}" ]
A surface containing an HTML5 Canvas element. This extends the Surface class. @class CanvasSurface @extends Surface @constructor @param {Object} [options] overrides of default options @param {Array.Number} [options.canvasSize] [width, height] for document element
[ "A", "surface", "containing", "an", "HTML5", "Canvas", "element", ".", "This", "extends", "the", "Surface", "class", "." ]
a241d9955d20ceb0fe3ce0a1fb13e9961e1c6878
https://github.com/panarch/famous-mig/blob/a241d9955d20ceb0fe3ce0a1fb13e9961e1c6878/surfaces/CanvasSurface.js#L17-L32
train
melvincarvalho/rdf-shell
lib/cat.js
cat
function cat(uri, callback) { if (!uri) { callback(new Error('URI is required')) } util.get(uri, function(err, val, uri) { callback(null, val, uri) }) }
javascript
function cat(uri, callback) { if (!uri) { callback(new Error('URI is required')) } util.get(uri, function(err, val, uri) { callback(null, val, uri) }) }
[ "function", "cat", "(", "uri", ",", "callback", ")", "{", "if", "(", "!", "uri", ")", "{", "callback", "(", "new", "Error", "(", "'URI is required'", ")", ")", "}", "util", ".", "get", "(", "uri", ",", "function", "(", "err", ",", "val", ",", "uri", ")", "{", "callback", "(", "null", ",", "val", ",", "uri", ")", "}", ")", "}" ]
cat gets the turtle for a uri @param {string} uri The URI to get @param {Function} callback Callback with text and uri
[ "cat", "gets", "the", "turtle", "for", "a", "uri" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/cat.js#L10-L17
train
nightshiftjs/nightshift-core
src/utils/functions.js
getParamNames
function getParamNames(fn) { var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var fnString = fn.toString().replace(STRIP_COMMENTS, ''); var result = fnString.slice(fnString.indexOf('(') + 1, fnString.indexOf(')')).match(/([^\s,]+)/g); return result || []; }
javascript
function getParamNames(fn) { var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var fnString = fn.toString().replace(STRIP_COMMENTS, ''); var result = fnString.slice(fnString.indexOf('(') + 1, fnString.indexOf(')')).match(/([^\s,]+)/g); return result || []; }
[ "function", "getParamNames", "(", "fn", ")", "{", "var", "STRIP_COMMENTS", "=", "/", "((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))", "/", "mg", ";", "var", "fnString", "=", "fn", ".", "toString", "(", ")", ".", "replace", "(", "STRIP_COMMENTS", ",", "''", ")", ";", "var", "result", "=", "fnString", ".", "slice", "(", "fnString", ".", "indexOf", "(", "'('", ")", "+", "1", ",", "fnString", ".", "indexOf", "(", "')'", ")", ")", ".", "match", "(", "/", "([^\\s,]+)", "/", "g", ")", ";", "return", "result", "||", "[", "]", ";", "}" ]
This method returns an array listing the names of the parameters of the given function. The array is empty if the function does not expect any parameter. @param {function} fn the function to retrieve the parameters names for @returns {Array|{index: number, input: string}} an array listing the names of the parameters of the given function, or an empty array if the function does not expect any parameter
[ "This", "method", "returns", "an", "array", "listing", "the", "names", "of", "the", "parameters", "of", "the", "given", "function", ".", "The", "array", "is", "empty", "if", "the", "function", "does", "not", "expect", "any", "parameter", "." ]
e1dc28b4d551c71dfb09d5b1e939a44d922a89d7
https://github.com/nightshiftjs/nightshift-core/blob/e1dc28b4d551c71dfb09d5b1e939a44d922a89d7/src/utils/functions.js#L33-L38
train
aashay/node-bart
lib/bart.js
merge_objects
function merge_objects(obj1,obj2){ var obj3 = {}; for (var attrname1 in obj1) { obj3[attrname1] = obj1[attrname1]; } for (var attrname2 in obj2) { obj3[attrname2] = obj2[attrname2]; } return obj3; }
javascript
function merge_objects(obj1,obj2){ var obj3 = {}; for (var attrname1 in obj1) { obj3[attrname1] = obj1[attrname1]; } for (var attrname2 in obj2) { obj3[attrname2] = obj2[attrname2]; } return obj3; }
[ "function", "merge_objects", "(", "obj1", ",", "obj2", ")", "{", "var", "obj3", "=", "{", "}", ";", "for", "(", "var", "attrname1", "in", "obj1", ")", "{", "obj3", "[", "attrname1", "]", "=", "obj1", "[", "attrname1", "]", ";", "}", "for", "(", "var", "attrname2", "in", "obj2", ")", "{", "obj3", "[", "attrname2", "]", "=", "obj2", "[", "attrname2", "]", ";", "}", "return", "obj3", ";", "}" ]
Convenience function to smash two objects together. @param obj1 @param obj2 @returns obj3, a merged object
[ "Convenience", "function", "to", "smash", "two", "objects", "together", "." ]
a9fea7e7adb59d44628c05b54547c347c1accd6e
https://github.com/aashay/node-bart/blob/a9fea7e7adb59d44628c05b54547c347c1accd6e/lib/bart.js#L20-L25
train
assemble/assemble-fs
index.js
toFiles
function toFiles(app, options) { let opts = Object.assign({ collection: null }, options); let name = opts.collection; let collection = app.collections ? name && app[name] : app; let view; if (!collection && name) { collection = app.create(name, opts); } return utils.through.obj(async (file, enc, next) => { if (!app.File.isFile(file)) { file = app.file(file.path, file); } if (file.isNull()) { next(null, file); return; } if (collection && isCollection(collection)) { try { view = await collection.set(file.path, file); } catch (err) { next(err); return; } next(null, view); return; } view = !app.File.isFile(file) ? app.file(file.path, file) : file; app.handle('onLoad', view) .then(() => next(null, view)) .catch(next); }); }
javascript
function toFiles(app, options) { let opts = Object.assign({ collection: null }, options); let name = opts.collection; let collection = app.collections ? name && app[name] : app; let view; if (!collection && name) { collection = app.create(name, opts); } return utils.through.obj(async (file, enc, next) => { if (!app.File.isFile(file)) { file = app.file(file.path, file); } if (file.isNull()) { next(null, file); return; } if (collection && isCollection(collection)) { try { view = await collection.set(file.path, file); } catch (err) { next(err); return; } next(null, view); return; } view = !app.File.isFile(file) ? app.file(file.path, file) : file; app.handle('onLoad', view) .then(() => next(null, view)) .catch(next); }); }
[ "function", "toFiles", "(", "app", ",", "options", ")", "{", "let", "opts", "=", "Object", ".", "assign", "(", "{", "collection", ":", "null", "}", ",", "options", ")", ";", "let", "name", "=", "opts", ".", "collection", ";", "let", "collection", "=", "app", ".", "collections", "?", "name", "&&", "app", "[", "name", "]", ":", "app", ";", "let", "view", ";", "if", "(", "!", "collection", "&&", "name", ")", "{", "collection", "=", "app", ".", "create", "(", "name", ",", "opts", ")", ";", "}", "return", "utils", ".", "through", ".", "obj", "(", "async", "(", "file", ",", "enc", ",", "next", ")", "=>", "{", "if", "(", "!", "app", ".", "File", ".", "isFile", "(", "file", ")", ")", "{", "file", "=", "app", ".", "file", "(", "file", ".", "path", ",", "file", ")", ";", "}", "if", "(", "file", ".", "isNull", "(", ")", ")", "{", "next", "(", "null", ",", "file", ")", ";", "return", ";", "}", "if", "(", "collection", "&&", "isCollection", "(", "collection", ")", ")", "{", "try", "{", "view", "=", "await", "collection", ".", "set", "(", "file", ".", "path", ",", "file", ")", ";", "}", "catch", "(", "err", ")", "{", "next", "(", "err", ")", ";", "return", ";", "}", "next", "(", "null", ",", "view", ")", ";", "return", ";", "}", "view", "=", "!", "app", ".", "File", ".", "isFile", "(", "file", ")", "?", "app", ".", "file", "(", "file", ".", "path", ",", "file", ")", ":", "file", ";", "app", ".", "handle", "(", "'onLoad'", ",", "view", ")", ".", "then", "(", "(", ")", "=>", "next", "(", "null", ",", "view", ")", ")", ".", "catch", "(", "next", ")", ";", "}", ")", ";", "}" ]
Make sure vinyl files are assemble files, and add them to a collection, if specified.
[ "Make", "sure", "vinyl", "files", "are", "assemble", "files", "and", "add", "them", "to", "a", "collection", "if", "specified", "." ]
708e393935d52bf75659905ca1d658f92c362d7c
https://github.com/assemble/assemble-fs/blob/708e393935d52bf75659905ca1d658f92c362d7c/index.js#L129-L166
train
EpiphanySoft/assertly
inspect.js
inspect
function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments[2] !== undefined) ctx.depth = arguments[2]; if (arguments[3] !== undefined) ctx.colors = arguments[3]; if (typeof opts === 'boolean') { // legacy... ctx.showHidden = opts; } // Set default and user-specified options ctx = Object.assign({}, inspect.defaultOptions, ctx, opts); if (ctx.colors) ctx.stylize = stylizeWithColor; if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity; return formatValue(ctx, obj, ctx.depth); }
javascript
function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments[2] !== undefined) ctx.depth = arguments[2]; if (arguments[3] !== undefined) ctx.colors = arguments[3]; if (typeof opts === 'boolean') { // legacy... ctx.showHidden = opts; } // Set default and user-specified options ctx = Object.assign({}, inspect.defaultOptions, ctx, opts); if (ctx.colors) ctx.stylize = stylizeWithColor; if (ctx.maxArrayLength === null) ctx.maxArrayLength = Infinity; return formatValue(ctx, obj, ctx.depth); }
[ "function", "inspect", "(", "obj", ",", "opts", ")", "{", "var", "ctx", "=", "{", "seen", ":", "[", "]", ",", "stylize", ":", "stylizeNoColor", "}", ";", "if", "(", "arguments", "[", "2", "]", "!==", "undefined", ")", "ctx", ".", "depth", "=", "arguments", "[", "2", "]", ";", "if", "(", "arguments", "[", "3", "]", "!==", "undefined", ")", "ctx", ".", "colors", "=", "arguments", "[", "3", "]", ";", "if", "(", "typeof", "opts", "===", "'boolean'", ")", "{", "ctx", ".", "showHidden", "=", "opts", ";", "}", "ctx", "=", "Object", ".", "assign", "(", "{", "}", ",", "inspect", ".", "defaultOptions", ",", "ctx", ",", "opts", ")", ";", "if", "(", "ctx", ".", "colors", ")", "ctx", ".", "stylize", "=", "stylizeWithColor", ";", "if", "(", "ctx", ".", "maxArrayLength", "===", "null", ")", "ctx", ".", "maxArrayLength", "=", "Infinity", ";", "return", "formatValue", "(", "ctx", ",", "obj", ",", "ctx", ".", "depth", ")", ";", "}" ]
Echos the value of a value. Tries to print the value out in the best way possible given the different types. @param {Object} obj The object to print out. @param {Object} opts Optional options object that alters the output. /* legacy: obj, showHidden, depth, colors
[ "Echos", "the", "value", "of", "a", "value", ".", "Tries", "to", "print", "the", "value", "out", "in", "the", "best", "way", "possible", "given", "the", "different", "types", "." ]
04a62335eb0ebba5308a9b5d2059ee38bcaf1444
https://github.com/EpiphanySoft/assertly/blob/04a62335eb0ebba5308a9b5d2059ee38bcaf1444/inspect.js#L176-L194
train
jtheriault/code-copter-analyzer-jscs
src/index.js
getJscsrc
function getJscsrc () { var jscsrcPath = process.cwd() + '/.jscsrc'; try { return JSON.parse(fs.readFileSync(jscsrcPath, 'utf8')); } catch (error) { throw new Error(`Expected to find JSCS configuration ${jscsrcPath}; saw error "${error.message}". Cannot run JSCS analysis.`, error); } }
javascript
function getJscsrc () { var jscsrcPath = process.cwd() + '/.jscsrc'; try { return JSON.parse(fs.readFileSync(jscsrcPath, 'utf8')); } catch (error) { throw new Error(`Expected to find JSCS configuration ${jscsrcPath}; saw error "${error.message}". Cannot run JSCS analysis.`, error); } }
[ "function", "getJscsrc", "(", ")", "{", "var", "jscsrcPath", "=", "process", ".", "cwd", "(", ")", "+", "'/.jscsrc'", ";", "try", "{", "return", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "jscsrcPath", ",", "'utf8'", ")", ")", ";", "}", "catch", "(", "error", ")", "{", "throw", "new", "Error", "(", "`", "${", "jscsrcPath", "}", "${", "error", ".", "message", "}", "`", ",", "error", ")", ";", "}", "}" ]
Get the object representation of the configuration in .jscsrc in the project root.
[ "Get", "the", "object", "representation", "of", "the", "configuration", "in", ".", "jscsrc", "in", "the", "project", "root", "." ]
81ee8300c1e6017e7e2f3b4ac880bca6f124d601
https://github.com/jtheriault/code-copter-analyzer-jscs/blob/81ee8300c1e6017e7e2f3b4ac880bca6f124d601/src/index.js#L50-L59
train
allanmboyd/formaterrors
lib/formatErrors.js
filterMatch
function filterMatch(s, regExps) { if (!regExps) { return false; } var match = false; for (var i = 0; i < regExps.length && !match; i++) { match = s.match(regExps[i]) !== null; } return match; }
javascript
function filterMatch(s, regExps) { if (!regExps) { return false; } var match = false; for (var i = 0; i < regExps.length && !match; i++) { match = s.match(regExps[i]) !== null; } return match; }
[ "function", "filterMatch", "(", "s", ",", "regExps", ")", "{", "if", "(", "!", "regExps", ")", "{", "return", "false", ";", "}", "var", "match", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "regExps", ".", "length", "&&", "!", "match", ";", "i", "++", ")", "{", "match", "=", "s", ".", "match", "(", "regExps", "[", "i", "]", ")", "!==", "null", ";", "}", "return", "match", ";", "}" ]
Determine if a provided array of regular expressions includes a match for a provided String. @method filterMatch @private @param {String} s the String @param {String[]} regExps an array of reg. exp. Strings @return {Boolean} true if a match is found; false otherwise
[ "Determine", "if", "a", "provided", "array", "of", "regular", "expressions", "includes", "a", "match", "for", "a", "provided", "String", "." ]
83c6f0c9d6334e706549db848174fc901e6ce5c3
https://github.com/allanmboyd/formaterrors/blob/83c6f0c9d6334e706549db848174fc901e6ce5c3/lib/formatErrors.js#L323-L333
train
allanmboyd/formaterrors
lib/formatErrors.js
isError
function isError(error) { return error && (Object.prototype.toString.call(error).slice(8, -1) === "Error" || (typeof error.stack !== "undefined" && typeof error.name !== "undefined")); }
javascript
function isError(error) { return error && (Object.prototype.toString.call(error).slice(8, -1) === "Error" || (typeof error.stack !== "undefined" && typeof error.name !== "undefined")); }
[ "function", "isError", "(", "error", ")", "{", "return", "error", "&&", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "error", ")", ".", "slice", "(", "8", ",", "-", "1", ")", "===", "\"Error\"", "||", "(", "typeof", "error", ".", "stack", "!==", "\"undefined\"", "&&", "typeof", "error", ".", "name", "!==", "\"undefined\"", ")", ")", ";", "}" ]
Determine if a given parameter is an Error. @method isError @private @param {Error} error the prospective Error @return {Boolean} true is 'error' is an Error; false otherwise
[ "Determine", "if", "a", "given", "parameter", "is", "an", "Error", "." ]
83c6f0c9d6334e706549db848174fc901e6ce5c3
https://github.com/allanmboyd/formaterrors/blob/83c6f0c9d6334e706549db848174fc901e6ce5c3/lib/formatErrors.js#L402-L405
train
allanmboyd/formaterrors
lib/formatErrors.js
diffToMessage
function diffToMessage(diffedAssertionError) { var diff = diffedAssertionError.diff; var actual = ""; var expected = ""; for (var i = 0; i < diff.length; i++) { var diffType = diff[i][0]; if (diffType === 1) { if (actual.length > 0) { actual += ", "; } actual += "\"" + diff[i][1] + "\""; } else if (diffType === -1) { if (expected.length > 0) { expected += ", "; } expected += "\"" + diff[i][1] + "\""; } } var message = "Differences: "; if (expected.length > 0) { message += "'expected': " + expected; } if (actual.length > 0) { if (expected.length > 0) { message += ", "; } message += "'actual': " + actual; } message += "\n"; return getMessages(diffedAssertionError).join(" ") + "\n" + message; }
javascript
function diffToMessage(diffedAssertionError) { var diff = diffedAssertionError.diff; var actual = ""; var expected = ""; for (var i = 0; i < diff.length; i++) { var diffType = diff[i][0]; if (diffType === 1) { if (actual.length > 0) { actual += ", "; } actual += "\"" + diff[i][1] + "\""; } else if (diffType === -1) { if (expected.length > 0) { expected += ", "; } expected += "\"" + diff[i][1] + "\""; } } var message = "Differences: "; if (expected.length > 0) { message += "'expected': " + expected; } if (actual.length > 0) { if (expected.length > 0) { message += ", "; } message += "'actual': " + actual; } message += "\n"; return getMessages(diffedAssertionError).join(" ") + "\n" + message; }
[ "function", "diffToMessage", "(", "diffedAssertionError", ")", "{", "var", "diff", "=", "diffedAssertionError", ".", "diff", ";", "var", "actual", "=", "\"\"", ";", "var", "expected", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "diff", ".", "length", ";", "i", "++", ")", "{", "var", "diffType", "=", "diff", "[", "i", "]", "[", "0", "]", ";", "if", "(", "diffType", "===", "1", ")", "{", "if", "(", "actual", ".", "length", ">", "0", ")", "{", "actual", "+=", "\", \"", ";", "}", "actual", "+=", "\"\\\"\"", "+", "\\\"", "+", "diff", "[", "i", "]", "[", "1", "]", ";", "}", "else", "\"\\\"\"", "}", "\\\"", "if", "(", "diffType", "===", "-", "1", ")", "{", "if", "(", "expected", ".", "length", ">", "0", ")", "{", "expected", "+=", "\", \"", ";", "}", "expected", "+=", "\"\\\"\"", "+", "\\\"", "+", "diff", "[", "i", "]", "[", "1", "]", ";", "}", "\"\\\"\"", "\\\"", "var", "message", "=", "\"Differences: \"", ";", "}" ]
Given an AssertionError that has had diffs applied - and that means it has a diff property - provide the message for the AssertionError including details of the diffs. @method diffToMessage @private @param {AssertionError} diffedAssertionError an AssertionError that has a diff property containing diffs between the expected and actual values @return {String} the message that includes diff details
[ "Given", "an", "AssertionError", "that", "has", "had", "diffs", "applied", "-", "and", "that", "means", "it", "has", "a", "diff", "property", "-", "provide", "the", "message", "for", "the", "AssertionError", "including", "details", "of", "the", "diffs", "." ]
83c6f0c9d6334e706549db848174fc901e6ce5c3
https://github.com/allanmboyd/formaterrors/blob/83c6f0c9d6334e706549db848174fc901e6ce5c3/lib/formatErrors.js#L547-L578
train
greggman/hft-sample-ui
src/hft/scripts/commonui.js
function() { if (!fullScreen.isFullScreen()) { touchStartElement.removeEventListener('touchstart', requestFullScreen, false); touchStartElement.style.display = "none"; fullScreen.requestFullScreen(document.body); } }
javascript
function() { if (!fullScreen.isFullScreen()) { touchStartElement.removeEventListener('touchstart', requestFullScreen, false); touchStartElement.style.display = "none"; fullScreen.requestFullScreen(document.body); } }
[ "function", "(", ")", "{", "if", "(", "!", "fullScreen", ".", "isFullScreen", "(", ")", ")", "{", "touchStartElement", ".", "removeEventListener", "(", "'touchstart'", ",", "requestFullScreen", ",", "false", ")", ";", "touchStartElement", ".", "style", ".", "display", "=", "\"none\"", ";", "fullScreen", ".", "requestFullScreen", "(", "document", ".", "body", ")", ";", "}", "}" ]
setup full screen support
[ "setup", "full", "screen", "support" ]
b9e20afd5183db73522bcfae48225c87e01f68c0
https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/commonui.js#L220-L226
train
huafu/ember-dev-fixtures
private/utils/dev-fixtures/adapter.js
function (name) { if (!this.instances[name]) { this.instances[name] = DevFixturesAdapter.create({name: name}); } return this.instances[name]; }
javascript
function (name) { if (!this.instances[name]) { this.instances[name] = DevFixturesAdapter.create({name: name}); } return this.instances[name]; }
[ "function", "(", "name", ")", "{", "if", "(", "!", "this", ".", "instances", "[", "name", "]", ")", "{", "this", ".", "instances", "[", "name", "]", "=", "DevFixturesAdapter", ".", "create", "(", "{", "name", ":", "name", "}", ")", ";", "}", "return", "this", ".", "instances", "[", "name", "]", ";", "}" ]
Get or create the singleton instance for given adapter name @method for @param {string} name @return {DevFixturesAdapter}
[ "Get", "or", "create", "the", "singleton", "instance", "for", "given", "adapter", "name" ]
811ed4d339c2dc840d5b297b5b244726cf1339ca
https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/adapter.js#L131-L136
train
altshift/altshift
lib/altshift/core/base.js
format
function format(string, args) { if ( string.length === 0 || !args || Object.keys(args).length === 0 ) { return string; } var matchVar = '[0-9a-zA-Z_$\\.]+', matchBrackets = '\\[[^\\]]*\\]', matchParsing = new RegExp( //"^" + "((" + matchVar + "|" + matchBrackets + ")*)" + //Match arg path "(!([rsa]))?" + //Conversion "(:([^\\?\\!]+))?" //spec //"$" ), matchCount = 0; return string.replace(FORMAT_EXPRESSION, function (_, match) { var parts = match.match(matchParsing), argName = parts[1] || matchCount, conversion = parts[4] || 's', //Default is string conversion formatSpec = parts[6], value = formatArgGet(args, argName); matchCount += 1; if (value === undefined) { return FORMAT_EXPRESSION_START + match + FORMAT_EXPRESSION_STOP;//Replace unchanged } if (formatSpec && formatSpec.length > 0) { value = formatValueSpec(value, formatSpec); } //Conversion s, r or a switch (conversion) { case 's': return '' + value; case 'r': return inspect(value); case 'a': throw new Error('Not yet implemented conversion "' + conversion + '"'); default: throw new Error('Invalid conversion "' + conversion + '"'); } }); }
javascript
function format(string, args) { if ( string.length === 0 || !args || Object.keys(args).length === 0 ) { return string; } var matchVar = '[0-9a-zA-Z_$\\.]+', matchBrackets = '\\[[^\\]]*\\]', matchParsing = new RegExp( //"^" + "((" + matchVar + "|" + matchBrackets + ")*)" + //Match arg path "(!([rsa]))?" + //Conversion "(:([^\\?\\!]+))?" //spec //"$" ), matchCount = 0; return string.replace(FORMAT_EXPRESSION, function (_, match) { var parts = match.match(matchParsing), argName = parts[1] || matchCount, conversion = parts[4] || 's', //Default is string conversion formatSpec = parts[6], value = formatArgGet(args, argName); matchCount += 1; if (value === undefined) { return FORMAT_EXPRESSION_START + match + FORMAT_EXPRESSION_STOP;//Replace unchanged } if (formatSpec && formatSpec.length > 0) { value = formatValueSpec(value, formatSpec); } //Conversion s, r or a switch (conversion) { case 's': return '' + value; case 'r': return inspect(value); case 'a': throw new Error('Not yet implemented conversion "' + conversion + '"'); default: throw new Error('Invalid conversion "' + conversion + '"'); } }); }
[ "function", "format", "(", "string", ",", "args", ")", "{", "if", "(", "string", ".", "length", "===", "0", "||", "!", "args", "||", "Object", ".", "keys", "(", "args", ")", ".", "length", "===", "0", ")", "{", "return", "string", ";", "}", "var", "matchVar", "=", "'[0-9a-zA-Z_$\\\\.]+'", ",", "\\\\", ",", "matchBrackets", "=", "'\\\\[[^\\\\]]*\\\\]'", ",", "\\\\", ";", "\\\\", "}" ]
Format string with `args` @see http://docs.python.org/release/3.1.3/library/string.html#format-string-syntax @param {string} string @param {Array|Object} args @return {string}
[ "Format", "string", "with", "args" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L133-L182
train
altshift/altshift
lib/altshift/core/base.js
mixin
function mixin(obj, props) { var argi = 1, argc = arguments.length, source, property, value; if (!obj) { obj = {}; } while (argi < argc) { source = arguments[argi]; for (property in source) { if (source.hasOwnProperty(property)) { value = source[property]; if (obj[property] !== value) { obj[property] = value; } } } argi += 1; } return obj; // Object }
javascript
function mixin(obj, props) { var argi = 1, argc = arguments.length, source, property, value; if (!obj) { obj = {}; } while (argi < argc) { source = arguments[argi]; for (property in source) { if (source.hasOwnProperty(property)) { value = source[property]; if (obj[property] !== value) { obj[property] = value; } } } argi += 1; } return obj; // Object }
[ "function", "mixin", "(", "obj", ",", "props", ")", "{", "var", "argi", "=", "1", ",", "argc", "=", "arguments", ".", "length", ",", "source", ",", "property", ",", "value", ";", "if", "(", "!", "obj", ")", "{", "obj", "=", "{", "}", ";", "}", "while", "(", "argi", "<", "argc", ")", "{", "source", "=", "arguments", "[", "argi", "]", ";", "for", "(", "property", "in", "source", ")", "{", "if", "(", "source", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "value", "=", "source", "[", "property", "]", ";", "if", "(", "obj", "[", "property", "]", "!==", "value", ")", "{", "obj", "[", "property", "]", "=", "value", ";", "}", "}", "}", "argi", "+=", "1", ";", "}", "return", "obj", ";", "}" ]
Mix all props, ... into `obj` @param {Object} obj @param {Object} props @return {Object}
[ "Mix", "all", "props", "...", "into", "obj" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L191-L213
train
altshift/altshift
lib/altshift/core/base.js
isObject
function isObject(obj) { return obj !== undefined && (obj === null || typeof obj === "object" || typeof obj === "array" || obj instanceof Array || Object.prototype.toString.call(obj) === "[object Function]" ); }
javascript
function isObject(obj) { return obj !== undefined && (obj === null || typeof obj === "object" || typeof obj === "array" || obj instanceof Array || Object.prototype.toString.call(obj) === "[object Function]" ); }
[ "function", "isObject", "(", "obj", ")", "{", "return", "obj", "!==", "undefined", "&&", "(", "obj", "===", "null", "||", "typeof", "obj", "===", "\"object\"", "||", "typeof", "obj", "===", "\"array\"", "||", "obj", "instanceof", "Array", "||", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "obj", ")", "===", "\"[object Function]\"", ")", ";", "}" ]
Return true if `obj` is an Object @param {*} obj @return {boolean}
[ "Return", "true", "if", "obj", "is", "an", "Object" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L251-L257
train
altshift/altshift
lib/altshift/core/base.js
isScalar
function isScalar(obj) { var type = typeof obj; return (type !== 'undefined' && ( obj === null || type === 'string' || type === 'number' || type === 'boolean' )); }
javascript
function isScalar(obj) { var type = typeof obj; return (type !== 'undefined' && ( obj === null || type === 'string' || type === 'number' || type === 'boolean' )); }
[ "function", "isScalar", "(", "obj", ")", "{", "var", "type", "=", "typeof", "obj", ";", "return", "(", "type", "!==", "'undefined'", "&&", "(", "obj", "===", "null", "||", "type", "===", "'string'", "||", "type", "===", "'number'", "||", "type", "===", "'boolean'", ")", ")", ";", "}" ]
Return true if `obj` is a scalar @param {*} obj @return {boolean}
[ "Return", "true", "if", "obj", "is", "a", "scalar" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L265-L273
train
altshift/altshift
lib/altshift/core/base.js
destroy
function destroy(object) { if (isObject(object)) { if (isFunction(object.finalize)) { object.finalize(); } for (var property in object) { if (true) {//For lint delete object[property]; } } } }
javascript
function destroy(object) { if (isObject(object)) { if (isFunction(object.finalize)) { object.finalize(); } for (var property in object) { if (true) {//For lint delete object[property]; } } } }
[ "function", "destroy", "(", "object", ")", "{", "if", "(", "isObject", "(", "object", ")", ")", "{", "if", "(", "isFunction", "(", "object", ".", "finalize", ")", ")", "{", "object", ".", "finalize", "(", ")", ";", "}", "for", "(", "var", "property", "in", "object", ")", "{", "if", "(", "true", ")", "{", "delete", "object", "[", "property", "]", ";", "}", "}", "}", "}" ]
Will destroy object @param {Object} object @return undefined
[ "Will", "destroy", "object" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L281-L292
train
altshift/altshift
lib/altshift/core/base.js
clone
function clone(obj, deep) { if (!obj || typeof obj !== "object" || isFunction(obj)) { // null, undefined, any non-object, or function return obj; // anything } if (obj instanceof Date) { // Date return new Date(obj.getTime()); // Date } var result, index, length, value; if (isArray(obj)) { // array result = []; if (deep) { for (index = 0, length = obj.length; index < length; index += 1) { if (index in obj) { value = obj[index]; value = value.clone ? value.clone(true) : clone(value); result.push(clone(value)); } } } else { for (index = 0, length = obj.length; index < length; index += 1) { if (index in obj) { result.push(value); } } } return result; } //Default implementation if (obj.clone) { return obj.clone(obj, deep); } // generic objects result = obj.constructor ? new obj.constructor() : {}; for (index in obj) { if (true) {//jslint validation value = obj[index]; if ( !(index in result) || (result[index] !== value && (!(index in EMPTY) || EMPTY[index] !== value)) ) { result[index] = clone(value); } } } return result; // Object }
javascript
function clone(obj, deep) { if (!obj || typeof obj !== "object" || isFunction(obj)) { // null, undefined, any non-object, or function return obj; // anything } if (obj instanceof Date) { // Date return new Date(obj.getTime()); // Date } var result, index, length, value; if (isArray(obj)) { // array result = []; if (deep) { for (index = 0, length = obj.length; index < length; index += 1) { if (index in obj) { value = obj[index]; value = value.clone ? value.clone(true) : clone(value); result.push(clone(value)); } } } else { for (index = 0, length = obj.length; index < length; index += 1) { if (index in obj) { result.push(value); } } } return result; } //Default implementation if (obj.clone) { return obj.clone(obj, deep); } // generic objects result = obj.constructor ? new obj.constructor() : {}; for (index in obj) { if (true) {//jslint validation value = obj[index]; if ( !(index in result) || (result[index] !== value && (!(index in EMPTY) || EMPTY[index] !== value)) ) { result[index] = clone(value); } } } return result; // Object }
[ "function", "clone", "(", "obj", ",", "deep", ")", "{", "if", "(", "!", "obj", "||", "typeof", "obj", "!==", "\"object\"", "||", "isFunction", "(", "obj", ")", ")", "{", "return", "obj", ";", "}", "if", "(", "obj", "instanceof", "Date", ")", "{", "return", "new", "Date", "(", "obj", ".", "getTime", "(", ")", ")", ";", "}", "var", "result", ",", "index", ",", "length", ",", "value", ";", "if", "(", "isArray", "(", "obj", ")", ")", "{", "result", "=", "[", "]", ";", "if", "(", "deep", ")", "{", "for", "(", "index", "=", "0", ",", "length", "=", "obj", ".", "length", ";", "index", "<", "length", ";", "index", "+=", "1", ")", "{", "if", "(", "index", "in", "obj", ")", "{", "value", "=", "obj", "[", "index", "]", ";", "value", "=", "value", ".", "clone", "?", "value", ".", "clone", "(", "true", ")", ":", "clone", "(", "value", ")", ";", "result", ".", "push", "(", "clone", "(", "value", ")", ")", ";", "}", "}", "}", "else", "{", "for", "(", "index", "=", "0", ",", "length", "=", "obj", ".", "length", ";", "index", "<", "length", ";", "index", "+=", "1", ")", "{", "if", "(", "index", "in", "obj", ")", "{", "result", ".", "push", "(", "value", ")", ";", "}", "}", "}", "return", "result", ";", "}", "if", "(", "obj", ".", "clone", ")", "{", "return", "obj", ".", "clone", "(", "obj", ",", "deep", ")", ";", "}", "result", "=", "obj", ".", "constructor", "?", "new", "obj", ".", "constructor", "(", ")", ":", "{", "}", ";", "for", "(", "index", "in", "obj", ")", "{", "if", "(", "true", ")", "{", "value", "=", "obj", "[", "index", "]", ";", "if", "(", "!", "(", "index", "in", "result", ")", "||", "(", "result", "[", "index", "]", "!==", "value", "&&", "(", "!", "(", "index", "in", "EMPTY", ")", "||", "EMPTY", "[", "index", "]", "!==", "value", ")", ")", ")", "{", "result", "[", "index", "]", "=", "clone", "(", "value", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Clone an object @param {*} obj @return {*}
[ "Clone", "an", "object" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L301-L354
train
altshift/altshift
lib/altshift/core/base.js
forEach
function forEach(object, iterator, thisp) { if (object) { if (object.forEach) { object.forEach(iterator, thisp); return; } //Default implementation if (! (iterator instanceof Function)) { throw new TypeError('iterator should be a Function'); } var key, length; if (isString(object)) { length = object.length; for (key = 0; key < length; key += 1) { iterator.call(thisp, object[key], key, object); } return; } for (key in object) { if (object.hasOwnProperty(key)) { iterator.call(thisp, object[key], key, object); } } } }
javascript
function forEach(object, iterator, thisp) { if (object) { if (object.forEach) { object.forEach(iterator, thisp); return; } //Default implementation if (! (iterator instanceof Function)) { throw new TypeError('iterator should be a Function'); } var key, length; if (isString(object)) { length = object.length; for (key = 0; key < length; key += 1) { iterator.call(thisp, object[key], key, object); } return; } for (key in object) { if (object.hasOwnProperty(key)) { iterator.call(thisp, object[key], key, object); } } } }
[ "function", "forEach", "(", "object", ",", "iterator", ",", "thisp", ")", "{", "if", "(", "object", ")", "{", "if", "(", "object", ".", "forEach", ")", "{", "object", ".", "forEach", "(", "iterator", ",", "thisp", ")", ";", "return", ";", "}", "if", "(", "!", "(", "iterator", "instanceof", "Function", ")", ")", "{", "throw", "new", "TypeError", "(", "'iterator should be a Function'", ")", ";", "}", "var", "key", ",", "length", ";", "if", "(", "isString", "(", "object", ")", ")", "{", "length", "=", "object", ".", "length", ";", "for", "(", "key", "=", "0", ";", "key", "<", "length", ";", "key", "+=", "1", ")", "{", "iterator", ".", "call", "(", "thisp", ",", "object", "[", "key", "]", ",", "key", ",", "object", ")", ";", "}", "return", ";", "}", "for", "(", "key", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "iterator", ".", "call", "(", "thisp", ",", "object", "[", "key", "]", ",", "key", ",", "object", ")", ";", "}", "}", "}", "}" ]
Iterate on object @param {*} object @param {Function} iterator @param {*} thisp @return undefined
[ "Iterate", "on", "object" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L364-L391
train
altshift/altshift
lib/altshift/core/base.js
hash
function hash(object) { if (object === undefined || isScalar(object)) { return '' + object; } if (object.hash) { return object.hash(); } //Default implementation var hashes = [], value, key, hashKey, hashValue; for (key in object) { if (object.hasOwnProperty(key)) { value = object[key]; hashKey = String(key); hashValue = hash(value); hashValue = (hashKey > hashValue) ? hashValue + hashKey : hashKey + hashValue; hashes.push(hashValue); } } return hashes.sort().join(''); }
javascript
function hash(object) { if (object === undefined || isScalar(object)) { return '' + object; } if (object.hash) { return object.hash(); } //Default implementation var hashes = [], value, key, hashKey, hashValue; for (key in object) { if (object.hasOwnProperty(key)) { value = object[key]; hashKey = String(key); hashValue = hash(value); hashValue = (hashKey > hashValue) ? hashValue + hashKey : hashKey + hashValue; hashes.push(hashValue); } } return hashes.sort().join(''); }
[ "function", "hash", "(", "object", ")", "{", "if", "(", "object", "===", "undefined", "||", "isScalar", "(", "object", ")", ")", "{", "return", "''", "+", "object", ";", "}", "if", "(", "object", ".", "hash", ")", "{", "return", "object", ".", "hash", "(", ")", ";", "}", "var", "hashes", "=", "[", "]", ",", "value", ",", "key", ",", "hashKey", ",", "hashValue", ";", "for", "(", "key", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "value", "=", "object", "[", "key", "]", ";", "hashKey", "=", "String", "(", "key", ")", ";", "hashValue", "=", "hash", "(", "value", ")", ";", "hashValue", "=", "(", "hashKey", ">", "hashValue", ")", "?", "hashValue", "+", "hashKey", ":", "hashKey", "+", "hashValue", ";", "hashes", ".", "push", "(", "hashValue", ")", ";", "}", "}", "return", "hashes", ".", "sort", "(", ")", ".", "join", "(", "''", ")", ";", "}" ]
Return a hash string for the object @param {*} object @return {String}
[ "Return", "a", "hash", "string", "for", "the", "object" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/base.js#L399-L423
train
dazeus/dazeus-nodejs
dazeus.js
function (options, onConnect) { var self = this; EventEmitter.call(this); this.options = options; // debugging this.debug_enabled = options.debug; this.handshook = false; // received data which could not be parsed into messages yet this.data = ''; // determine correct call of net.connect var cb = function () { connected.call(self); onConnect.call(self); }; if (options.path) { this.debug("Trying to establish connection to unix socket %s", options.path); this.client = net.connect(options.path, cb); } else { this.debug("Trying to establish connection to %s on port %s", options.host, options.port); this.client = net.connect(options.port, options.host, cb); } // when data is received this.client.on('data', function (data) { var obj = dezeusify.call(self, data.toString('utf8')); obj.forEach(function (item) { received.call(self, item); }); }); // when the connection is closed this.client.on('end', function () { disconnected.call(self); }); this.client.on('error', function (err) { self.debug("Whoops, an error occurred: %s", err.message); throw new Error(util.format("A connection error occurred: %s", err.message)); }); // when a new listener is added to this object, we'll want to check if we should notify the server this.on('newListener', function (evt) { this.debug("A new event listener was added"); if (evt.toUpperCase() === evt && !this.subscribedEvents.indexOf(evt) !== -1) { subscribeServerEvent.call(self, evt); } }); this.subscribedEvents = []; this.waitingCallbacks = []; }
javascript
function (options, onConnect) { var self = this; EventEmitter.call(this); this.options = options; // debugging this.debug_enabled = options.debug; this.handshook = false; // received data which could not be parsed into messages yet this.data = ''; // determine correct call of net.connect var cb = function () { connected.call(self); onConnect.call(self); }; if (options.path) { this.debug("Trying to establish connection to unix socket %s", options.path); this.client = net.connect(options.path, cb); } else { this.debug("Trying to establish connection to %s on port %s", options.host, options.port); this.client = net.connect(options.port, options.host, cb); } // when data is received this.client.on('data', function (data) { var obj = dezeusify.call(self, data.toString('utf8')); obj.forEach(function (item) { received.call(self, item); }); }); // when the connection is closed this.client.on('end', function () { disconnected.call(self); }); this.client.on('error', function (err) { self.debug("Whoops, an error occurred: %s", err.message); throw new Error(util.format("A connection error occurred: %s", err.message)); }); // when a new listener is added to this object, we'll want to check if we should notify the server this.on('newListener', function (evt) { this.debug("A new event listener was added"); if (evt.toUpperCase() === evt && !this.subscribedEvents.indexOf(evt) !== -1) { subscribeServerEvent.call(self, evt); } }); this.subscribedEvents = []; this.waitingCallbacks = []; }
[ "function", "(", "options", ",", "onConnect", ")", "{", "var", "self", "=", "this", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "options", "=", "options", ";", "this", ".", "debug_enabled", "=", "options", ".", "debug", ";", "this", ".", "handshook", "=", "false", ";", "this", ".", "data", "=", "''", ";", "var", "cb", "=", "function", "(", ")", "{", "connected", ".", "call", "(", "self", ")", ";", "onConnect", ".", "call", "(", "self", ")", ";", "}", ";", "if", "(", "options", ".", "path", ")", "{", "this", ".", "debug", "(", "\"Trying to establish connection to unix socket %s\"", ",", "options", ".", "path", ")", ";", "this", ".", "client", "=", "net", ".", "connect", "(", "options", ".", "path", ",", "cb", ")", ";", "}", "else", "{", "this", ".", "debug", "(", "\"Trying to establish connection to %s on port %s\"", ",", "options", ".", "host", ",", "options", ".", "port", ")", ";", "this", ".", "client", "=", "net", ".", "connect", "(", "options", ".", "port", ",", "options", ".", "host", ",", "cb", ")", ";", "}", "this", ".", "client", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "var", "obj", "=", "dezeusify", ".", "call", "(", "self", ",", "data", ".", "toString", "(", "'utf8'", ")", ")", ";", "obj", ".", "forEach", "(", "function", "(", "item", ")", "{", "received", ".", "call", "(", "self", ",", "item", ")", ";", "}", ")", ";", "}", ")", ";", "this", ".", "client", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "disconnected", ".", "call", "(", "self", ")", ";", "}", ")", ";", "this", ".", "client", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "debug", "(", "\"Whoops, an error occurred: %s\"", ",", "err", ".", "message", ")", ";", "throw", "new", "Error", "(", "util", ".", "format", "(", "\"A connection error occurred: %s\"", ",", "err", ".", "message", ")", ")", ";", "}", ")", ";", "this", ".", "on", "(", "'newListener'", ",", "function", "(", "evt", ")", "{", "this", ".", "debug", "(", "\"A new event listener was added\"", ")", ";", "if", "(", "evt", ".", "toUpperCase", "(", ")", "===", "evt", "&&", "!", "this", ".", "subscribedEvents", ".", "indexOf", "(", "evt", ")", "!==", "-", "1", ")", "{", "subscribeServerEvent", ".", "call", "(", "self", ",", "evt", ")", ";", "}", "}", ")", ";", "this", ".", "subscribedEvents", "=", "[", "]", ";", "this", ".", "waitingCallbacks", "=", "[", "]", ";", "}" ]
DaZeus client connection object @param {Object} options @param {Function} onConnect Function to be executed when the connection is established
[ "DaZeus", "client", "connection", "object" ]
d62347378bb4cd5939fdabec7e0922548178222c
https://github.com/dazeus/dazeus-nodejs/blob/d62347378bb4cd5939fdabec7e0922548178222c/dazeus.js#L23-L78
train
dazeus/dazeus-nodejs
dazeus.js
function (data, callback) { this.debug("Sending: %s", JSON.stringify(data)); var message = dazeusify.call(this, data); this.client.write(message, callback); }
javascript
function (data, callback) { this.debug("Sending: %s", JSON.stringify(data)); var message = dazeusify.call(this, data); this.client.write(message, callback); }
[ "function", "(", "data", ",", "callback", ")", "{", "this", ".", "debug", "(", "\"Sending: %s\"", ",", "JSON", ".", "stringify", "(", "data", ")", ")", ";", "var", "message", "=", "dazeusify", ".", "call", "(", "this", ",", "data", ")", ";", "this", ".", "client", ".", "write", "(", "message", ",", "callback", ")", ";", "}" ]
Sends some data to the server and calls a callback as soon as that is done. @param {Object} data Message to be sent @param {Function} callback Callback to be executed when sending is finished
[ "Sends", "some", "data", "to", "the", "server", "and", "calls", "a", "callback", "as", "soon", "as", "that", "is", "done", "." ]
d62347378bb4cd5939fdabec7e0922548178222c
https://github.com/dazeus/dazeus-nodejs/blob/d62347378bb4cd5939fdabec7e0922548178222c/dazeus.js#L592-L596
train
dazeus/dazeus-nodejs
dazeus.js
function (data, callback) { if (typeof callback !== 'function') { this.debug("Registering dummy callback, because a response message is expected"); } else { this.debug("Registering callback"); } this.waitingCallbacks.push(callback); send.call(this, data); }
javascript
function (data, callback) { if (typeof callback !== 'function') { this.debug("Registering dummy callback, because a response message is expected"); } else { this.debug("Registering callback"); } this.waitingCallbacks.push(callback); send.call(this, data); }
[ "function", "(", "data", ",", "callback", ")", "{", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "this", ".", "debug", "(", "\"Registering dummy callback, because a response message is expected\"", ")", ";", "}", "else", "{", "this", ".", "debug", "(", "\"Registering callback\"", ")", ";", "}", "this", ".", "waitingCallbacks", ".", "push", "(", "callback", ")", ";", "send", ".", "call", "(", "this", ",", "data", ")", ";", "}" ]
Send a message and register a callback @param {Object} data Message to be sent @param {Function} callback Callback function to be registered
[ "Send", "a", "message", "and", "register", "a", "callback" ]
d62347378bb4cd5939fdabec7e0922548178222c
https://github.com/dazeus/dazeus-nodejs/blob/d62347378bb4cd5939fdabec7e0922548178222c/dazeus.js#L603-L611
train
dazeus/dazeus-nodejs
dazeus.js
function (event) { this.debug("Requesting subscription for " + event); sendReceive.call(this, {'do': 'subscribe', params: [event]}, function (result) { if (result.success) { this.debug("Succesfully subscribed to %s", event); } else { this.debug("Subscription request for %s failed", event); } }); this.subscribedEvents.push(event); }
javascript
function (event) { this.debug("Requesting subscription for " + event); sendReceive.call(this, {'do': 'subscribe', params: [event]}, function (result) { if (result.success) { this.debug("Succesfully subscribed to %s", event); } else { this.debug("Subscription request for %s failed", event); } }); this.subscribedEvents.push(event); }
[ "function", "(", "event", ")", "{", "this", ".", "debug", "(", "\"Requesting subscription for \"", "+", "event", ")", ";", "sendReceive", ".", "call", "(", "this", ",", "{", "'do'", ":", "'subscribe'", ",", "params", ":", "[", "event", "]", "}", ",", "function", "(", "result", ")", "{", "if", "(", "result", ".", "success", ")", "{", "this", ".", "debug", "(", "\"Succesfully subscribed to %s\"", ",", "event", ")", ";", "}", "else", "{", "this", ".", "debug", "(", "\"Subscription request for %s failed\"", ",", "event", ")", ";", "}", "}", ")", ";", "this", ".", "subscribedEvents", ".", "push", "(", "event", ")", ";", "}" ]
Request DaZeus to be notified of a certain type of event @param {String} event Type of event to subscribe to
[ "Request", "DaZeus", "to", "be", "notified", "of", "a", "certain", "type", "of", "event" ]
d62347378bb4cd5939fdabec7e0922548178222c
https://github.com/dazeus/dazeus-nodejs/blob/d62347378bb4cd5939fdabec7e0922548178222c/dazeus.js#L617-L627
train
dazeus/dazeus-nodejs
dazeus.js
function (obj) { this.debug("Received: %s", JSON.stringify(obj)); if (typeof obj.event !== 'undefined') { this.debug("Received an event-based message, sending off to listeners"); handleEvent.call(this, obj.event, obj.params); } else { if (this.waitingCallbacks.length > 0) { var callback = this.waitingCallbacks.shift(); if (typeof callback === 'function') { this.debug("Calling previously registered callback with message"); callback.call(this, obj); } else { this.debug("Callback was a dummy, not calling"); } } else { this.debug("No callbacks remaining, still received a response"); } } }
javascript
function (obj) { this.debug("Received: %s", JSON.stringify(obj)); if (typeof obj.event !== 'undefined') { this.debug("Received an event-based message, sending off to listeners"); handleEvent.call(this, obj.event, obj.params); } else { if (this.waitingCallbacks.length > 0) { var callback = this.waitingCallbacks.shift(); if (typeof callback === 'function') { this.debug("Calling previously registered callback with message"); callback.call(this, obj); } else { this.debug("Callback was a dummy, not calling"); } } else { this.debug("No callbacks remaining, still received a response"); } } }
[ "function", "(", "obj", ")", "{", "this", ".", "debug", "(", "\"Received: %s\"", ",", "JSON", ".", "stringify", "(", "obj", ")", ")", ";", "if", "(", "typeof", "obj", ".", "event", "!==", "'undefined'", ")", "{", "this", ".", "debug", "(", "\"Received an event-based message, sending off to listeners\"", ")", ";", "handleEvent", ".", "call", "(", "this", ",", "obj", ".", "event", ",", "obj", ".", "params", ")", ";", "}", "else", "{", "if", "(", "this", ".", "waitingCallbacks", ".", "length", ">", "0", ")", "{", "var", "callback", "=", "this", ".", "waitingCallbacks", ".", "shift", "(", ")", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "this", ".", "debug", "(", "\"Calling previously registered callback with message\"", ")", ";", "callback", ".", "call", "(", "this", ",", "obj", ")", ";", "}", "else", "{", "this", ".", "debug", "(", "\"Callback was a dummy, not calling\"", ")", ";", "}", "}", "else", "{", "this", ".", "debug", "(", "\"No callbacks remaining, still received a response\"", ")", ";", "}", "}", "}" ]
Receive a new message object from the server. Either we pass it off to the event-handler if it is an event-based object, or we look for a corresponding callback that is waiting for a response. @param {Object} obj The received message as a javascript object
[ "Receive", "a", "new", "message", "object", "from", "the", "server", ".", "Either", "we", "pass", "it", "off", "to", "the", "event", "-", "handler", "if", "it", "is", "an", "event", "-", "based", "object", "or", "we", "look", "for", "a", "corresponding", "callback", "that", "is", "waiting", "for", "a", "response", "." ]
d62347378bb4cd5939fdabec7e0922548178222c
https://github.com/dazeus/dazeus-nodejs/blob/d62347378bb4cd5939fdabec7e0922548178222c/dazeus.js#L635-L653
train
dazeus/dazeus-nodejs
dazeus.js
function (event, parameters) { if (event === 'COMMAND') { event = 'command_' + parameters[3]; } parameters.unshift(event); this.emit.apply(this, parameters); }
javascript
function (event, parameters) { if (event === 'COMMAND') { event = 'command_' + parameters[3]; } parameters.unshift(event); this.emit.apply(this, parameters); }
[ "function", "(", "event", ",", "parameters", ")", "{", "if", "(", "event", "===", "'COMMAND'", ")", "{", "event", "=", "'command_'", "+", "parameters", "[", "3", "]", ";", "}", "parameters", ".", "unshift", "(", "event", ")", ";", "this", ".", "emit", ".", "apply", "(", "this", ",", "parameters", ")", ";", "}" ]
For event-type messages, this calls the correct event handlers. @param {String} event Event type name @param {Array} parameters Parameters for the event
[ "For", "event", "-", "type", "messages", "this", "calls", "the", "correct", "event", "handlers", "." ]
d62347378bb4cd5939fdabec7e0922548178222c
https://github.com/dazeus/dazeus-nodejs/blob/d62347378bb4cd5939fdabec7e0922548178222c/dazeus.js#L660-L666
train
dazeus/dazeus-nodejs
dazeus.js
function (message) { var objs = [], collector = '', chr, msglen, data; this.data += message; data = new Buffer(this.data, 'utf8'); for (var i = 0; i < data.length; i += 1) { chr = data[i]; if (chr > 47 && chr < 58) { collector += String.fromCharCode(chr); } else if (chr !== 10 && chr !== 13) { msglen = parseInt(collector, 10); if (msglen + i <= data.length) { objs.push(JSON.parse(data.toString('utf8', i, msglen + i))); data = data.slice(i + msglen); collector = ''; i = 0; } else { break; } } } this.data = data.toString('utf8'); return objs; }
javascript
function (message) { var objs = [], collector = '', chr, msglen, data; this.data += message; data = new Buffer(this.data, 'utf8'); for (var i = 0; i < data.length; i += 1) { chr = data[i]; if (chr > 47 && chr < 58) { collector += String.fromCharCode(chr); } else if (chr !== 10 && chr !== 13) { msglen = parseInt(collector, 10); if (msglen + i <= data.length) { objs.push(JSON.parse(data.toString('utf8', i, msglen + i))); data = data.slice(i + msglen); collector = ''; i = 0; } else { break; } } } this.data = data.toString('utf8'); return objs; }
[ "function", "(", "message", ")", "{", "var", "objs", "=", "[", "]", ",", "collector", "=", "''", ",", "chr", ",", "msglen", ",", "data", ";", "this", ".", "data", "+=", "message", ";", "data", "=", "new", "Buffer", "(", "this", ".", "data", ",", "'utf8'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "+=", "1", ")", "{", "chr", "=", "data", "[", "i", "]", ";", "if", "(", "chr", ">", "47", "&&", "chr", "<", "58", ")", "{", "collector", "+=", "String", ".", "fromCharCode", "(", "chr", ")", ";", "}", "else", "if", "(", "chr", "!==", "10", "&&", "chr", "!==", "13", ")", "{", "msglen", "=", "parseInt", "(", "collector", ",", "10", ")", ";", "if", "(", "msglen", "+", "i", "<=", "data", ".", "length", ")", "{", "objs", ".", "push", "(", "JSON", ".", "parse", "(", "data", ".", "toString", "(", "'utf8'", ",", "i", ",", "msglen", "+", "i", ")", ")", ")", ";", "data", "=", "data", ".", "slice", "(", "i", "+", "msglen", ")", ";", "collector", "=", "''", ";", "i", "=", "0", ";", "}", "else", "{", "break", ";", "}", "}", "}", "this", ".", "data", "=", "data", ".", "toString", "(", "'utf8'", ")", ";", "return", "objs", ";", "}" ]
Transform a string retrieved from DaZeus to it's javascript-object-equivalents. @param {String} message @return {Array} Array of parsed messages
[ "Transform", "a", "string", "retrieved", "from", "DaZeus", "to", "it", "s", "javascript", "-", "object", "-", "equivalents", "." ]
d62347378bb4cd5939fdabec7e0922548178222c
https://github.com/dazeus/dazeus-nodejs/blob/d62347378bb4cd5939fdabec7e0922548178222c/dazeus.js#L698-L723
train
sebpiq/node-validation-pod
index.js
function(err) { var validationErrMsg = self.handleError(err) if (!validationErrMsg) return false else { self._merge(validationErrors, validationErrMsg, prefix) isValid = false return true } }
javascript
function(err) { var validationErrMsg = self.handleError(err) if (!validationErrMsg) return false else { self._merge(validationErrors, validationErrMsg, prefix) isValid = false return true } }
[ "function", "(", "err", ")", "{", "var", "validationErrMsg", "=", "self", ".", "handleError", "(", "err", ")", "if", "(", "!", "validationErrMsg", ")", "return", "false", "else", "{", "self", ".", "_merge", "(", "validationErrors", ",", "validationErrMsg", ",", "prefix", ")", "isValid", "=", "false", "return", "true", "}", "}" ]
Returns true if `err` was handled as a validation error, false otherwise
[ "Returns", "true", "if", "err", "was", "handled", "as", "a", "validation", "error", "false", "otherwise" ]
c9a75c94c219a41fa877157a2df102c8fa24efbf
https://github.com/sebpiq/node-validation-pod/blob/c9a75c94c219a41fa877157a2df102c8fa24efbf/index.js#L34-L42
train
ugate/releasebot
tasks/release.js
genTemplateData
function genTemplateData() { var templateData = { data : { process : process, commit : commit, env : commitTask.commitOpts, options : options } }; var rtn = {}; var arr = Array.prototype.slice.call(arguments, 0); arr.forEach(function genIntMsgs(s) { rtn[s] = options[s] ? rbot.processTemplate(options[s], templateData) : ''; if (rtn[s]) { rbot.log.verbose(s + ' = ' + rtn[s]); } }); return rtn; }
javascript
function genTemplateData() { var templateData = { data : { process : process, commit : commit, env : commitTask.commitOpts, options : options } }; var rtn = {}; var arr = Array.prototype.slice.call(arguments, 0); arr.forEach(function genIntMsgs(s) { rtn[s] = options[s] ? rbot.processTemplate(options[s], templateData) : ''; if (rtn[s]) { rbot.log.verbose(s + ' = ' + rtn[s]); } }); return rtn; }
[ "function", "genTemplateData", "(", ")", "{", "var", "templateData", "=", "{", "data", ":", "{", "process", ":", "process", ",", "commit", ":", "commit", ",", "env", ":", "commitTask", ".", "commitOpts", ",", "options", ":", "options", "}", "}", ";", "var", "rtn", "=", "{", "}", ";", "var", "arr", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "arr", ".", "forEach", "(", "function", "genIntMsgs", "(", "s", ")", "{", "rtn", "[", "s", "]", "=", "options", "[", "s", "]", "?", "rbot", ".", "processTemplate", "(", "options", "[", "s", "]", ",", "templateData", ")", ":", "''", ";", "if", "(", "rtn", "[", "s", "]", ")", "{", "rbot", ".", "log", ".", "verbose", "(", "s", "+", "' = '", "+", "rtn", "[", "s", "]", ")", ";", "}", "}", ")", ";", "return", "rtn", ";", "}" ]
Generates an object that contains each of the passed arguments as a property with a value of an option with the same name. Each property will have a value for that option that is parsed using the template processor. @returns the parsed template data
[ "Generates", "an", "object", "that", "contains", "each", "of", "the", "passed", "arguments", "as", "a", "property", "with", "a", "value", "of", "an", "option", "with", "the", "same", "name", ".", "Each", "property", "will", "have", "a", "value", "for", "that", "option", "that", "is", "parsed", "using", "the", "template", "processor", "." ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/tasks/release.js#L123-L141
train
ugate/releasebot
tasks/release.js
remoteSetup
function remoteSetup() { var link = '${GH_TOKEN}@' + options.gitHostname + '/' + commit.slug + '.git'; cmd('git config --global user.email "' + options.repoEmail + '"'); cmd('git config --global user.name "' + options.repoUser + '"'); cmd('git remote rm ' + options.repoName); cmd('git remote add ' + options.repoName + ' https://' + commit.username + ':' + link); }
javascript
function remoteSetup() { var link = '${GH_TOKEN}@' + options.gitHostname + '/' + commit.slug + '.git'; cmd('git config --global user.email "' + options.repoEmail + '"'); cmd('git config --global user.name "' + options.repoUser + '"'); cmd('git remote rm ' + options.repoName); cmd('git remote add ' + options.repoName + ' https://' + commit.username + ':' + link); }
[ "function", "remoteSetup", "(", ")", "{", "var", "link", "=", "'${GH_TOKEN}@'", "+", "options", ".", "gitHostname", "+", "'/'", "+", "commit", ".", "slug", "+", "'.git'", ";", "cmd", "(", "'git config --global user.email \"'", "+", "options", ".", "repoEmail", "+", "'\"'", ")", ";", "cmd", "(", "'git config --global user.name \"'", "+", "options", ".", "repoUser", "+", "'\"'", ")", ";", "cmd", "(", "'git remote rm '", "+", "options", ".", "repoName", ")", ";", "cmd", "(", "'git remote add '", "+", "options", ".", "repoName", "+", "' https://'", "+", "commit", ".", "username", "+", "':'", "+", "link", ")", ";", "}" ]
Remote Git setup to permit pushes
[ "Remote", "Git", "setup", "to", "permit", "pushes" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/tasks/release.js#L146-L152
train
ugate/releasebot
tasks/release.js
gitRelease
function gitRelease() { // Tag release rbot.log.info('Tagging release ' + commit.versionTag + ' via ' + options.gitHostname); cmd('git tag -f -a ' + commit.versionTag + ' -m "' + (chgLogRtn ? chgLogRtn.replace(coopt.regexLines, '$1 \\') : commit.message) + '"'); cmd('git push -f ' + options.repoName + ' ' + commit.versionTag); commit.releaseId = commit.versionTag; // TODO : upload asset? rollCall.addRollback(rollbackTag); rollCall.then(publish); }
javascript
function gitRelease() { // Tag release rbot.log.info('Tagging release ' + commit.versionTag + ' via ' + options.gitHostname); cmd('git tag -f -a ' + commit.versionTag + ' -m "' + (chgLogRtn ? chgLogRtn.replace(coopt.regexLines, '$1 \\') : commit.message) + '"'); cmd('git push -f ' + options.repoName + ' ' + commit.versionTag); commit.releaseId = commit.versionTag; // TODO : upload asset? rollCall.addRollback(rollbackTag); rollCall.then(publish); }
[ "function", "gitRelease", "(", ")", "{", "rbot", ".", "log", ".", "info", "(", "'Tagging release '", "+", "commit", ".", "versionTag", "+", "' via '", "+", "options", ".", "gitHostname", ")", ";", "cmd", "(", "'git tag -f -a '", "+", "commit", ".", "versionTag", "+", "' -m \"'", "+", "(", "chgLogRtn", "?", "chgLogRtn", ".", "replace", "(", "coopt", ".", "regexLines", ",", "'$1 \\\\'", ")", ":", "\\\\", ")", "+", "commit", ".", "message", ")", ";", "'\"'", "cmd", "(", "'git push -f '", "+", "options", ".", "repoName", "+", "' '", "+", "commit", ".", "versionTag", ")", ";", "commit", ".", "releaseId", "=", "commit", ".", "versionTag", ";", "rollCall", ".", "addRollback", "(", "rollbackTag", ")", ";", "}" ]
Tags release via standard Git CLI
[ "Tags", "release", "via", "standard", "Git", "CLI" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/tasks/release.js#L335-L345
train
ugate/releasebot
tasks/release.js
gitHubRelease
function gitHubRelease() { rbot.log.info('Releasing ' + commit.versionTag + ' via ' + options.gitHostname); // GitHub Release API will not remove the tag when removing a // release github.releaseAndUploadAsset(distAssets, coopt.regexLines, commit, tmpltData.name, chgLogRtn || commit.message, options, rollCall, rollbackTag, function() { rollCall.then(publish); }); }
javascript
function gitHubRelease() { rbot.log.info('Releasing ' + commit.versionTag + ' via ' + options.gitHostname); // GitHub Release API will not remove the tag when removing a // release github.releaseAndUploadAsset(distAssets, coopt.regexLines, commit, tmpltData.name, chgLogRtn || commit.message, options, rollCall, rollbackTag, function() { rollCall.then(publish); }); }
[ "function", "gitHubRelease", "(", ")", "{", "rbot", ".", "log", ".", "info", "(", "'Releasing '", "+", "commit", ".", "versionTag", "+", "' via '", "+", "options", ".", "gitHostname", ")", ";", "github", ".", "releaseAndUploadAsset", "(", "distAssets", ",", "coopt", ".", "regexLines", ",", "commit", ",", "tmpltData", ".", "name", ",", "chgLogRtn", "||", "commit", ".", "message", ",", "options", ",", "rollCall", ",", "rollbackTag", ",", "function", "(", ")", "{", "rollCall", ".", "then", "(", "publish", ")", ";", "}", ")", ";", "}" ]
Calls the GitHub Release API to tag release and upload optional distribution asset
[ "Calls", "the", "GitHub", "Release", "API", "to", "tag", "release", "and", "upload", "optional", "distribution", "asset" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/tasks/release.js#L351-L359
train
ugate/releasebot
tasks/release.js
rollbackPublish
function rollbackPublish() { try { chkoutRun(options.distBranch, function() { var cph = cmd('git rev-parse HEAD'); if (pubHash && pubHash !== cph) { cmd('git checkout -qf ' + pubHash); cmd('git commit -q -m "Rollback: ' + tmpltData.distBranchPubMsg + '"'); cmd('git push -f ' + options.repoName + ' ' + options.distBranch); } else if (!pubHash) { cmd('git push ' + options.repoName + ' --delete ' + options.distBranch); } else { rbot.log.verbose('Skipping rollback for ' + options.distBranch + ' for hash "' + pubHash + '" (current hash: "' + cph + '")'); } }); } catch (e) { var msg = 'Failed to rollback publish branch changes!'; rollCall.error(msg, e); } }
javascript
function rollbackPublish() { try { chkoutRun(options.distBranch, function() { var cph = cmd('git rev-parse HEAD'); if (pubHash && pubHash !== cph) { cmd('git checkout -qf ' + pubHash); cmd('git commit -q -m "Rollback: ' + tmpltData.distBranchPubMsg + '"'); cmd('git push -f ' + options.repoName + ' ' + options.distBranch); } else if (!pubHash) { cmd('git push ' + options.repoName + ' --delete ' + options.distBranch); } else { rbot.log.verbose('Skipping rollback for ' + options.distBranch + ' for hash "' + pubHash + '" (current hash: "' + cph + '")'); } }); } catch (e) { var msg = 'Failed to rollback publish branch changes!'; rollCall.error(msg, e); } }
[ "function", "rollbackPublish", "(", ")", "{", "try", "{", "chkoutRun", "(", "options", ".", "distBranch", ",", "function", "(", ")", "{", "var", "cph", "=", "cmd", "(", "'git rev-parse HEAD'", ")", ";", "if", "(", "pubHash", "&&", "pubHash", "!==", "cph", ")", "{", "cmd", "(", "'git checkout -qf '", "+", "pubHash", ")", ";", "cmd", "(", "'git commit -q -m \"Rollback: '", "+", "tmpltData", ".", "distBranchPubMsg", "+", "'\"'", ")", ";", "cmd", "(", "'git push -f '", "+", "options", ".", "repoName", "+", "' '", "+", "options", ".", "distBranch", ")", ";", "}", "else", "if", "(", "!", "pubHash", ")", "{", "cmd", "(", "'git push '", "+", "options", ".", "repoName", "+", "' --delete '", "+", "options", ".", "distBranch", ")", ";", "}", "else", "{", "rbot", ".", "log", ".", "verbose", "(", "'Skipping rollback for '", "+", "options", ".", "distBranch", "+", "' for hash \"'", "+", "pubHash", "+", "'\" (current hash: \"'", "+", "cph", "+", "'\")'", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "var", "msg", "=", "'Failed to rollback publish branch changes!'", ";", "rollCall", ".", "error", "(", "msg", ",", "e", ")", ";", "}", "}" ]
Reverts published branch
[ "Reverts", "published", "branch" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/tasks/release.js#L428-L447
train
d-mon-/typeof--
index.js
getObjectToStringValue
function getObjectToStringValue(value) { var result = objectToString.call(value); switch (result) { case '[object Undefined]': return '#Undefined'; case '[object Null]': return '#Null'; case '[object Object]': return 'Object'; case '[object Function]': return 'Function'; case '[object String]': return 'String'; case '[object Number]': return (value != +value) ? '#NaN' : 'Number'; case '[object Array]': return 'Array'; case '[object Boolean]': return 'Boolean'; case '[object RegExp]': return 'RegExp'; case '[object Symbol]': return 'Symbol'; case '[object Map]': return 'Map'; case '[object WeakMap]': return 'WeakMap'; case '[object Set]': return 'Set'; case '[object WeakSet]': return 'WeakSet'; case '[object Int8Array]': return 'Int8Array'; case '[object Uint8Array]': return 'Uint8Array'; case '[object Uint8ClampedArray]': return 'Uint8ClampedArray'; case '[object Int16Array]': return 'Int16Array'; case '[object Uint16Array]': return 'Uint16Array'; case '[object Int32Array]': return 'Int32Array'; case '[object Uint32Array]': return 'Uint32Array'; case '[object Float32Array]': return 'Float32Array'; case '[object Float64Array]': return 'Float64Array'; case '[object ArrayBuffer]': return 'ArrayBuffer'; case '[object DataView]': return 'DataView'; case '[object Error]': return 'Error'; case '[object Arguments]': return 'Arguments'; case '[object JSON]': return 'JSON'; case '[object Math]': return 'Math'; case '[object Date]': return 'Date'; default: //handle the rest (HTML element, future global objects,...) return result.slice(8, -1); } }
javascript
function getObjectToStringValue(value) { var result = objectToString.call(value); switch (result) { case '[object Undefined]': return '#Undefined'; case '[object Null]': return '#Null'; case '[object Object]': return 'Object'; case '[object Function]': return 'Function'; case '[object String]': return 'String'; case '[object Number]': return (value != +value) ? '#NaN' : 'Number'; case '[object Array]': return 'Array'; case '[object Boolean]': return 'Boolean'; case '[object RegExp]': return 'RegExp'; case '[object Symbol]': return 'Symbol'; case '[object Map]': return 'Map'; case '[object WeakMap]': return 'WeakMap'; case '[object Set]': return 'Set'; case '[object WeakSet]': return 'WeakSet'; case '[object Int8Array]': return 'Int8Array'; case '[object Uint8Array]': return 'Uint8Array'; case '[object Uint8ClampedArray]': return 'Uint8ClampedArray'; case '[object Int16Array]': return 'Int16Array'; case '[object Uint16Array]': return 'Uint16Array'; case '[object Int32Array]': return 'Int32Array'; case '[object Uint32Array]': return 'Uint32Array'; case '[object Float32Array]': return 'Float32Array'; case '[object Float64Array]': return 'Float64Array'; case '[object ArrayBuffer]': return 'ArrayBuffer'; case '[object DataView]': return 'DataView'; case '[object Error]': return 'Error'; case '[object Arguments]': return 'Arguments'; case '[object JSON]': return 'JSON'; case '[object Math]': return 'Math'; case '[object Date]': return 'Date'; default: //handle the rest (HTML element, future global objects,...) return result.slice(8, -1); } }
[ "function", "getObjectToStringValue", "(", "value", ")", "{", "var", "result", "=", "objectToString", ".", "call", "(", "value", ")", ";", "switch", "(", "result", ")", "{", "case", "'[object Undefined]'", ":", "return", "'#Undefined'", ";", "case", "'[object Null]'", ":", "return", "'#Null'", ";", "case", "'[object Object]'", ":", "return", "'Object'", ";", "case", "'[object Function]'", ":", "return", "'Function'", ";", "case", "'[object String]'", ":", "return", "'String'", ";", "case", "'[object Number]'", ":", "return", "(", "value", "!=", "+", "value", ")", "?", "'#NaN'", ":", "'Number'", ";", "case", "'[object Array]'", ":", "return", "'Array'", ";", "case", "'[object Boolean]'", ":", "return", "'Boolean'", ";", "case", "'[object RegExp]'", ":", "return", "'RegExp'", ";", "case", "'[object Symbol]'", ":", "return", "'Symbol'", ";", "case", "'[object Map]'", ":", "return", "'Map'", ";", "case", "'[object WeakMap]'", ":", "return", "'WeakMap'", ";", "case", "'[object Set]'", ":", "return", "'Set'", ";", "case", "'[object WeakSet]'", ":", "return", "'WeakSet'", ";", "case", "'[object Int8Array]'", ":", "return", "'Int8Array'", ";", "case", "'[object Uint8Array]'", ":", "return", "'Uint8Array'", ";", "case", "'[object Uint8ClampedArray]'", ":", "return", "'Uint8ClampedArray'", ";", "case", "'[object Int16Array]'", ":", "return", "'Int16Array'", ";", "case", "'[object Uint16Array]'", ":", "return", "'Uint16Array'", ";", "case", "'[object Int32Array]'", ":", "return", "'Int32Array'", ";", "case", "'[object Uint32Array]'", ":", "return", "'Uint32Array'", ";", "case", "'[object Float32Array]'", ":", "return", "'Float32Array'", ";", "case", "'[object Float64Array]'", ":", "return", "'Float64Array'", ";", "case", "'[object ArrayBuffer]'", ":", "return", "'ArrayBuffer'", ";", "case", "'[object DataView]'", ":", "return", "'DataView'", ";", "case", "'[object Error]'", ":", "return", "'Error'", ";", "case", "'[object Arguments]'", ":", "return", "'Arguments'", ";", "case", "'[object JSON]'", ":", "return", "'JSON'", ";", "case", "'[object Math]'", ":", "return", "'Math'", ";", "case", "'[object Date]'", ":", "return", "'Date'", ";", "default", ":", "return", "result", ".", "slice", "(", "8", ",", "-", "1", ")", ";", "}", "}" ]
retrieve type of value after calling Object.prototype.toString @param value @returns {String}
[ "retrieve", "type", "of", "value", "after", "calling", "Object", ".", "prototype", ".", "toString" ]
9749072fec62b42a0b35dc00f87c6169f5d93855
https://github.com/d-mon-/typeof--/blob/9749072fec62b42a0b35dc00f87c6169f5d93855/index.js#L27-L93
train
d-mon-/typeof--
index.js
typeOf
function typeOf(value, options) { if (value === undefined) return '#Undefined'; if (value === null) return '#Null'; if (options !== 'forceObjectToString') { var constructor = getConstructor(value); if (constructor !== null) { var type = getFunctionName(constructor); if (type === 'Object') { return getObjectToStringValue(value); } return (type === 'Number' && value != +value) ? '#NaN' : type; } } return getObjectToStringValue(value); }
javascript
function typeOf(value, options) { if (value === undefined) return '#Undefined'; if (value === null) return '#Null'; if (options !== 'forceObjectToString') { var constructor = getConstructor(value); if (constructor !== null) { var type = getFunctionName(constructor); if (type === 'Object') { return getObjectToStringValue(value); } return (type === 'Number' && value != +value) ? '#NaN' : type; } } return getObjectToStringValue(value); }
[ "function", "typeOf", "(", "value", ",", "options", ")", "{", "if", "(", "value", "===", "undefined", ")", "return", "'#Undefined'", ";", "if", "(", "value", "===", "null", ")", "return", "'#Null'", ";", "if", "(", "options", "!==", "'forceObjectToString'", ")", "{", "var", "constructor", "=", "getConstructor", "(", "value", ")", ";", "if", "(", "constructor", "!==", "null", ")", "{", "var", "type", "=", "getFunctionName", "(", "constructor", ")", ";", "if", "(", "type", "===", "'Object'", ")", "{", "return", "getObjectToStringValue", "(", "value", ")", ";", "}", "return", "(", "type", "===", "'Number'", "&&", "value", "!=", "+", "value", ")", "?", "'#NaN'", ":", "type", ";", "}", "}", "return", "getObjectToStringValue", "(", "value", ")", ";", "}" ]
return the constructor name if "defined" and "valid" of the value, otherwise return Object.prototype.toString @param {*} value @returns {String}
[ "return", "the", "constructor", "name", "if", "defined", "and", "valid", "of", "the", "value", "otherwise", "return", "Object", ".", "prototype", ".", "toString" ]
9749072fec62b42a0b35dc00f87c6169f5d93855
https://github.com/d-mon-/typeof--/blob/9749072fec62b42a0b35dc00f87c6169f5d93855/index.js#L100-L114
train
gahlotnikhil/bower-component-files
lib/main.js
fetchComponents
function fetchComponents(filter, options) { console.log('Fetching dependencies...'); var componentList = []; if (_.isObject(filter) || _.isArray(filter)) { var dependencies = fetchBowerComponents(); _.each(dependencies, function(dep) { var bowerObj = getBower(dep); if (bowerObj) { var mainFiles = fetchMainFiles(bowerObj); var componentFiles = []; _.each(filter, function(destDir, expression) { var expressionObj = {}; expressionObj[expression] = destDir; var filteredValues = filterByExpression(mainFiles, expressionObj, options); Array.prototype.push.apply(componentFiles, filteredValues); }); // create Component class and encapsulate Component // related info in that. componentList.push(new Component(bowerObj, componentFiles)); console.log(componentFiles.length + ' file(s) found for ' + dep); } }); console.log('##### Total dependencie(s) found ' + componentList.length); } return componentList; }
javascript
function fetchComponents(filter, options) { console.log('Fetching dependencies...'); var componentList = []; if (_.isObject(filter) || _.isArray(filter)) { var dependencies = fetchBowerComponents(); _.each(dependencies, function(dep) { var bowerObj = getBower(dep); if (bowerObj) { var mainFiles = fetchMainFiles(bowerObj); var componentFiles = []; _.each(filter, function(destDir, expression) { var expressionObj = {}; expressionObj[expression] = destDir; var filteredValues = filterByExpression(mainFiles, expressionObj, options); Array.prototype.push.apply(componentFiles, filteredValues); }); // create Component class and encapsulate Component // related info in that. componentList.push(new Component(bowerObj, componentFiles)); console.log(componentFiles.length + ' file(s) found for ' + dep); } }); console.log('##### Total dependencie(s) found ' + componentList.length); } return componentList; }
[ "function", "fetchComponents", "(", "filter", ",", "options", ")", "{", "console", ".", "log", "(", "'Fetching dependencies...'", ")", ";", "var", "componentList", "=", "[", "]", ";", "if", "(", "_", ".", "isObject", "(", "filter", ")", "||", "_", ".", "isArray", "(", "filter", ")", ")", "{", "var", "dependencies", "=", "fetchBowerComponents", "(", ")", ";", "_", ".", "each", "(", "dependencies", ",", "function", "(", "dep", ")", "{", "var", "bowerObj", "=", "getBower", "(", "dep", ")", ";", "if", "(", "bowerObj", ")", "{", "var", "mainFiles", "=", "fetchMainFiles", "(", "bowerObj", ")", ";", "var", "componentFiles", "=", "[", "]", ";", "_", ".", "each", "(", "filter", ",", "function", "(", "destDir", ",", "expression", ")", "{", "var", "expressionObj", "=", "{", "}", ";", "expressionObj", "[", "expression", "]", "=", "destDir", ";", "var", "filteredValues", "=", "filterByExpression", "(", "mainFiles", ",", "expressionObj", ",", "options", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "componentFiles", ",", "filteredValues", ")", ";", "}", ")", ";", "componentList", ".", "push", "(", "new", "Component", "(", "bowerObj", ",", "componentFiles", ")", ")", ";", "console", ".", "log", "(", "componentFiles", ".", "length", "+", "' file(s) found for '", "+", "dep", ")", ";", "}", "}", ")", ";", "console", ".", "log", "(", "'##### Total dependencie(s) found '", "+", "componentList", ".", "length", ")", ";", "}", "return", "componentList", ";", "}" ]
Get components from bower.json @param {Object}/{Array} filter @param {Object} options @return {Array<Component>} List of components
[ "Get", "components", "from", "bower", ".", "json" ]
f57111e2718517d2c86995975be0d862dc83c7bd
https://github.com/gahlotnikhil/bower-component-files/blob/f57111e2718517d2c86995975be0d862dc83c7bd/lib/main.js#L188-L223
train
gahlotnikhil/bower-component-files
lib/main.js
fetchComponent
function fetchComponent(compName, filter, options) { var componentFiles = []; _.each(filter, function(destDir, expression) { var fileInfo = path.parse(path.resolve(BOWER_DIRECTORY, compName, expression)); var sourceDir = fileInfo.dir; var dirContent = fs.readdirSync(sourceDir); var expressionObj = {}; expressionObj[expression] = destDir; dirContent = dirContent.map(function(file) { return path.resolve(BOWER_DIRECTORY, compName, file); }); Array.prototype.push.apply(componentFiles, filterByExpression(dirContent, expressionObj, options)); }); console.log(componentFiles.length + ' file(s) found for ' + compName); var bowerObj = getBower(compName); return new Component(bowerObj, componentFiles); }
javascript
function fetchComponent(compName, filter, options) { var componentFiles = []; _.each(filter, function(destDir, expression) { var fileInfo = path.parse(path.resolve(BOWER_DIRECTORY, compName, expression)); var sourceDir = fileInfo.dir; var dirContent = fs.readdirSync(sourceDir); var expressionObj = {}; expressionObj[expression] = destDir; dirContent = dirContent.map(function(file) { return path.resolve(BOWER_DIRECTORY, compName, file); }); Array.prototype.push.apply(componentFiles, filterByExpression(dirContent, expressionObj, options)); }); console.log(componentFiles.length + ' file(s) found for ' + compName); var bowerObj = getBower(compName); return new Component(bowerObj, componentFiles); }
[ "function", "fetchComponent", "(", "compName", ",", "filter", ",", "options", ")", "{", "var", "componentFiles", "=", "[", "]", ";", "_", ".", "each", "(", "filter", ",", "function", "(", "destDir", ",", "expression", ")", "{", "var", "fileInfo", "=", "path", ".", "parse", "(", "path", ".", "resolve", "(", "BOWER_DIRECTORY", ",", "compName", ",", "expression", ")", ")", ";", "var", "sourceDir", "=", "fileInfo", ".", "dir", ";", "var", "dirContent", "=", "fs", ".", "readdirSync", "(", "sourceDir", ")", ";", "var", "expressionObj", "=", "{", "}", ";", "expressionObj", "[", "expression", "]", "=", "destDir", ";", "dirContent", "=", "dirContent", ".", "map", "(", "function", "(", "file", ")", "{", "return", "path", ".", "resolve", "(", "BOWER_DIRECTORY", ",", "compName", ",", "file", ")", ";", "}", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "componentFiles", ",", "filterByExpression", "(", "dirContent", ",", "expressionObj", ",", "options", ")", ")", ";", "}", ")", ";", "console", ".", "log", "(", "componentFiles", ".", "length", "+", "' file(s) found for '", "+", "compName", ")", ";", "var", "bowerObj", "=", "getBower", "(", "compName", ")", ";", "return", "new", "Component", "(", "bowerObj", ",", "componentFiles", ")", ";", "}" ]
Constructs a Component object @param {String} compName @param {Object} filter @param {Object} options @return {Component}
[ "Constructs", "a", "Component", "object" ]
f57111e2718517d2c86995975be0d862dc83c7bd
https://github.com/gahlotnikhil/bower-component-files/blob/f57111e2718517d2c86995975be0d862dc83c7bd/lib/main.js#L232-L253
train
MiguelCastillo/dis-isa
src/index.js
typeName
function typeName(item) { if (isNull(item)) { return "null"; } else if (isUndefined(item)) { return "undefined"; } return /\[.+ ([^\]]+)/.exec(toString(item))[1].toLowerCase(); }
javascript
function typeName(item) { if (isNull(item)) { return "null"; } else if (isUndefined(item)) { return "undefined"; } return /\[.+ ([^\]]+)/.exec(toString(item))[1].toLowerCase(); }
[ "function", "typeName", "(", "item", ")", "{", "if", "(", "isNull", "(", "item", ")", ")", "{", "return", "\"null\"", ";", "}", "else", "if", "(", "isUndefined", "(", "item", ")", ")", "{", "return", "\"undefined\"", ";", "}", "return", "/", "\\[.+ ([^\\]]+)", "/", ".", "exec", "(", "toString", "(", "item", ")", ")", "[", "1", "]", ".", "toLowerCase", "(", ")", ";", "}" ]
Extract the type name. This uses Object.prototype.toString to get the type name. @param {*} item - Item to get the type for @returns {string} type of the object
[ "Extract", "the", "type", "name", ".", "This", "uses", "Object", ".", "prototype", ".", "toString", "to", "get", "the", "type", "name", "." ]
11ed2ba864ad8c50b11ce025d345242dd62e4f65
https://github.com/MiguelCastillo/dis-isa/blob/11ed2ba864ad8c50b11ce025d345242dd62e4f65/src/index.js#L148-L157
train
edinella/ploud
public/audiojs/audio.js
function(wrapper, audio) { if (!audio.settings.createPlayer) return; var player = audio.settings.createPlayer, playPause = getByClass(player.playPauseClass, wrapper), scrubber = getByClass(player.scrubberClass, wrapper), leftPos = function(elem) { var curleft = 0; if (elem.offsetParent) { do { curleft += elem.offsetLeft; } while (elem = elem.offsetParent); } return curleft; }; container[audiojs].events.addListener(playPause, 'click', function(e) { audio.playPause.apply(audio); }); container[audiojs].events.addListener(scrubber, 'click', function(e) { var relativeLeft = e.clientX - leftPos(this); audio.skipTo(relativeLeft / scrubber.offsetWidth); }); // _If flash is being used, then the following handlers don't need to be registered._ if (audio.settings.useFlash) return; // Start tracking the load progress of the track. container[audiojs].events.trackLoadProgress(audio); container[audiojs].events.addListener(audio.element, 'timeupdate', function(e) { audio.updatePlayhead.apply(audio); }); container[audiojs].events.addListener(audio.element, 'ended', function(e) { audio.trackEnded.apply(audio); }); container[audiojs].events.addListener(audio.source, 'error', function(e) { // on error, cancel any load timers that are running. clearInterval(audio.readyTimer); clearInterval(audio.loadTimer); audio.settings.loadError.apply(audio); }); }
javascript
function(wrapper, audio) { if (!audio.settings.createPlayer) return; var player = audio.settings.createPlayer, playPause = getByClass(player.playPauseClass, wrapper), scrubber = getByClass(player.scrubberClass, wrapper), leftPos = function(elem) { var curleft = 0; if (elem.offsetParent) { do { curleft += elem.offsetLeft; } while (elem = elem.offsetParent); } return curleft; }; container[audiojs].events.addListener(playPause, 'click', function(e) { audio.playPause.apply(audio); }); container[audiojs].events.addListener(scrubber, 'click', function(e) { var relativeLeft = e.clientX - leftPos(this); audio.skipTo(relativeLeft / scrubber.offsetWidth); }); // _If flash is being used, then the following handlers don't need to be registered._ if (audio.settings.useFlash) return; // Start tracking the load progress of the track. container[audiojs].events.trackLoadProgress(audio); container[audiojs].events.addListener(audio.element, 'timeupdate', function(e) { audio.updatePlayhead.apply(audio); }); container[audiojs].events.addListener(audio.element, 'ended', function(e) { audio.trackEnded.apply(audio); }); container[audiojs].events.addListener(audio.source, 'error', function(e) { // on error, cancel any load timers that are running. clearInterval(audio.readyTimer); clearInterval(audio.loadTimer); audio.settings.loadError.apply(audio); }); }
[ "function", "(", "wrapper", ",", "audio", ")", "{", "if", "(", "!", "audio", ".", "settings", ".", "createPlayer", ")", "return", ";", "var", "player", "=", "audio", ".", "settings", ".", "createPlayer", ",", "playPause", "=", "getByClass", "(", "player", ".", "playPauseClass", ",", "wrapper", ")", ",", "scrubber", "=", "getByClass", "(", "player", ".", "scrubberClass", ",", "wrapper", ")", ",", "leftPos", "=", "function", "(", "elem", ")", "{", "var", "curleft", "=", "0", ";", "if", "(", "elem", ".", "offsetParent", ")", "{", "do", "{", "curleft", "+=", "elem", ".", "offsetLeft", ";", "}", "while", "(", "elem", "=", "elem", ".", "offsetParent", ")", ";", "}", "return", "curleft", ";", "}", ";", "container", "[", "audiojs", "]", ".", "events", ".", "addListener", "(", "playPause", ",", "'click'", ",", "function", "(", "e", ")", "{", "audio", ".", "playPause", ".", "apply", "(", "audio", ")", ";", "}", ")", ";", "container", "[", "audiojs", "]", ".", "events", ".", "addListener", "(", "scrubber", ",", "'click'", ",", "function", "(", "e", ")", "{", "var", "relativeLeft", "=", "e", ".", "clientX", "-", "leftPos", "(", "this", ")", ";", "audio", ".", "skipTo", "(", "relativeLeft", "/", "scrubber", ".", "offsetWidth", ")", ";", "}", ")", ";", "if", "(", "audio", ".", "settings", ".", "useFlash", ")", "return", ";", "container", "[", "audiojs", "]", ".", "events", ".", "trackLoadProgress", "(", "audio", ")", ";", "container", "[", "audiojs", "]", ".", "events", ".", "addListener", "(", "audio", ".", "element", ",", "'timeupdate'", ",", "function", "(", "e", ")", "{", "audio", ".", "updatePlayhead", ".", "apply", "(", "audio", ")", ";", "}", ")", ";", "container", "[", "audiojs", "]", ".", "events", ".", "addListener", "(", "audio", ".", "element", ",", "'ended'", ",", "function", "(", "e", ")", "{", "audio", ".", "trackEnded", ".", "apply", "(", "audio", ")", ";", "}", ")", ";", "container", "[", "audiojs", "]", ".", "events", ".", "addListener", "(", "audio", ".", "source", ",", "'error'", ",", "function", "(", "e", ")", "{", "clearInterval", "(", "audio", ".", "readyTimer", ")", ";", "clearInterval", "(", "audio", ".", "loadTimer", ")", ";", "audio", ".", "settings", ".", "loadError", ".", "apply", "(", "audio", ")", ";", "}", ")", ";", "}" ]
Attaches useful event callbacks to an `audiojs` instance.
[ "Attaches", "useful", "event", "callbacks", "to", "an", "audiojs", "instance", "." ]
ccf01fd213482b320a0a804f100eaae007103b6d
https://github.com/edinella/ploud/blob/ccf01fd213482b320a0a804f100eaae007103b6d/public/audiojs/audio.js#L240-L283
train
cli-kit/cli-property
lib/exec.js
exec
function exec(ptn, source, opts) { opts = opts || {}; var list = [] , flat = opts.flat = opts.flat !== undefined ? opts.flat : false , keys = opts.keys = opts.keys !== undefined ? opts.keys : true , values = opts.values = opts.values !== undefined ? opts.values : false if(flat) { source = flatten(source); } //console.dir(source); function match(k, v, p) { var re = recopy(ptn) , res = {key: k, value: v, parent: p, match: {key: false, value: false}}; res.match.key = keys && re.test(k); res.match.value = values && re.test('' + v); //console.log('matches %s %s %s', matches, re, k); if(res.match.key || res.match.value) { res.pattern = ptn; list.push(res); } } function lookup(source) { var k, v; for(k in source) { v = source[k]; match(k, v, source); if(!flat && v && typeof v === 'object' && Object.keys(v).length) { lookup(v); } } } lookup(source); return list; }
javascript
function exec(ptn, source, opts) { opts = opts || {}; var list = [] , flat = opts.flat = opts.flat !== undefined ? opts.flat : false , keys = opts.keys = opts.keys !== undefined ? opts.keys : true , values = opts.values = opts.values !== undefined ? opts.values : false if(flat) { source = flatten(source); } //console.dir(source); function match(k, v, p) { var re = recopy(ptn) , res = {key: k, value: v, parent: p, match: {key: false, value: false}}; res.match.key = keys && re.test(k); res.match.value = values && re.test('' + v); //console.log('matches %s %s %s', matches, re, k); if(res.match.key || res.match.value) { res.pattern = ptn; list.push(res); } } function lookup(source) { var k, v; for(k in source) { v = source[k]; match(k, v, source); if(!flat && v && typeof v === 'object' && Object.keys(v).length) { lookup(v); } } } lookup(source); return list; }
[ "function", "exec", "(", "ptn", ",", "source", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "list", "=", "[", "]", ",", "flat", "=", "opts", ".", "flat", "=", "opts", ".", "flat", "!==", "undefined", "?", "opts", ".", "flat", ":", "false", ",", "keys", "=", "opts", ".", "keys", "=", "opts", ".", "keys", "!==", "undefined", "?", "opts", ".", "keys", ":", "true", ",", "values", "=", "opts", ".", "values", "=", "opts", ".", "values", "!==", "undefined", "?", "opts", ".", "values", ":", "false", "if", "(", "flat", ")", "{", "source", "=", "flatten", "(", "source", ")", ";", "}", "function", "match", "(", "k", ",", "v", ",", "p", ")", "{", "var", "re", "=", "recopy", "(", "ptn", ")", ",", "res", "=", "{", "key", ":", "k", ",", "value", ":", "v", ",", "parent", ":", "p", ",", "match", ":", "{", "key", ":", "false", ",", "value", ":", "false", "}", "}", ";", "res", ".", "match", ".", "key", "=", "keys", "&&", "re", ".", "test", "(", "k", ")", ";", "res", ".", "match", ".", "value", "=", "values", "&&", "re", ".", "test", "(", "''", "+", "v", ")", ";", "if", "(", "res", ".", "match", ".", "key", "||", "res", ".", "match", ".", "value", ")", "{", "res", ".", "pattern", "=", "ptn", ";", "list", ".", "push", "(", "res", ")", ";", "}", "}", "function", "lookup", "(", "source", ")", "{", "var", "k", ",", "v", ";", "for", "(", "k", "in", "source", ")", "{", "v", "=", "source", "[", "k", "]", ";", "match", "(", "k", ",", "v", ",", "source", ")", ";", "if", "(", "!", "flat", "&&", "v", "&&", "typeof", "v", "===", "'object'", "&&", "Object", ".", "keys", "(", "v", ")", ".", "length", ")", "{", "lookup", "(", "v", ")", ";", "}", "}", "}", "lookup", "(", "source", ")", ";", "return", "list", ";", "}" ]
Execute a regular expression pattern against an object finding all values that match the pattern. Returns an array of result object. @param ptn The regular expression to execute. @param source The source object to search. @param opts Processing options. @param opts.flat Compare against flattened object keys. @param opts.keys Match against keys. @param opts.values Match against values.
[ "Execute", "a", "regular", "expression", "pattern", "against", "an", "object", "finding", "all", "values", "that", "match", "the", "pattern", "." ]
de6f727af1f8fc1f613fe42200c5e070aa6b0b21
https://github.com/cli-kit/cli-property/blob/de6f727af1f8fc1f613fe42200c5e070aa6b0b21/lib/exec.js#L18-L55
train
mrjoelkemp/ya
helpers/GruntHelper.js
generateGruntfile
function generateGruntfile (generatedConfig) { return function(grunt) { var path = require('path'), fs = require('fs'); require('load-grunt-tasks')(grunt); grunt.initConfig(generatedConfig); grunt.registerTask('default', ['watch']); // Handle new files with that have a new, supported preprocessor grunt.event.on('watch', function(action, filepath) { var ext = path.extname(filepath); // Ignore directories if (fs.lstatSync(filepath).isDirectory()) return; if (action === 'added') { // This is a special message that's parsed by YA // to determine if support for an additional preprocessor is necessary // Note: this allows us to avoid controlling grunt manually within YA console.log('EXTADDED:' + ext); // Note: we don't do anything for newly added .js files // A new js file can't be the root unless it's changed to require // the current root and saved/changed } else if (action === 'changed' || action === 'deleted') { if (ext === '.js') { // Ignore bundles if (/.+bundle.js/g.test(filepath)) return; // Notify YA to recompute the roots and // generate a configuration console.log('JSCHANGED:' + filepath); } } }); // For watching entire directories but allowing // the grunt.event binding to take care of it grunt.registerTask('noop', function () {}); }; }
javascript
function generateGruntfile (generatedConfig) { return function(grunt) { var path = require('path'), fs = require('fs'); require('load-grunt-tasks')(grunt); grunt.initConfig(generatedConfig); grunt.registerTask('default', ['watch']); // Handle new files with that have a new, supported preprocessor grunt.event.on('watch', function(action, filepath) { var ext = path.extname(filepath); // Ignore directories if (fs.lstatSync(filepath).isDirectory()) return; if (action === 'added') { // This is a special message that's parsed by YA // to determine if support for an additional preprocessor is necessary // Note: this allows us to avoid controlling grunt manually within YA console.log('EXTADDED:' + ext); // Note: we don't do anything for newly added .js files // A new js file can't be the root unless it's changed to require // the current root and saved/changed } else if (action === 'changed' || action === 'deleted') { if (ext === '.js') { // Ignore bundles if (/.+bundle.js/g.test(filepath)) return; // Notify YA to recompute the roots and // generate a configuration console.log('JSCHANGED:' + filepath); } } }); // For watching entire directories but allowing // the grunt.event binding to take care of it grunt.registerTask('noop', function () {}); }; }
[ "function", "generateGruntfile", "(", "generatedConfig", ")", "{", "return", "function", "(", "grunt", ")", "{", "var", "path", "=", "require", "(", "'path'", ")", ",", "fs", "=", "require", "(", "'fs'", ")", ";", "require", "(", "'load-grunt-tasks'", ")", "(", "grunt", ")", ";", "grunt", ".", "initConfig", "(", "generatedConfig", ")", ";", "grunt", ".", "registerTask", "(", "'default'", ",", "[", "'watch'", "]", ")", ";", "grunt", ".", "event", ".", "on", "(", "'watch'", ",", "function", "(", "action", ",", "filepath", ")", "{", "var", "ext", "=", "path", ".", "extname", "(", "filepath", ")", ";", "if", "(", "fs", ".", "lstatSync", "(", "filepath", ")", ".", "isDirectory", "(", ")", ")", "return", ";", "if", "(", "action", "===", "'added'", ")", "{", "console", ".", "log", "(", "'EXTADDED:'", "+", "ext", ")", ";", "}", "else", "if", "(", "action", "===", "'changed'", "||", "action", "===", "'deleted'", ")", "{", "if", "(", "ext", "===", "'.js'", ")", "{", "if", "(", "/", ".+bundle.js", "/", "g", ".", "test", "(", "filepath", ")", ")", "return", ";", "console", ".", "log", "(", "'JSCHANGED:'", "+", "filepath", ")", ";", "}", "}", "}", ")", ";", "grunt", ".", "registerTask", "(", "'noop'", ",", "function", "(", ")", "{", "}", ")", ";", "}", ";", "}" ]
Helper that returns a function whose body represents a gruntfile definition
[ "Helper", "that", "returns", "a", "function", "whose", "body", "represents", "a", "gruntfile", "definition" ]
6cb44f31902daaed32b2d72168b15eebfb7fbfbb
https://github.com/mrjoelkemp/ya/blob/6cb44f31902daaed32b2d72168b15eebfb7fbfbb/helpers/GruntHelper.js#L167-L210
train
mrjoelkemp/ya
helpers/GruntHelper.js
getMatches
function getMatches(source, pattern) { var matches = [], match; // Grab all added extensions while (match = pattern.exec(source)) { matches.push(match[2]); } return matches; }
javascript
function getMatches(source, pattern) { var matches = [], match; // Grab all added extensions while (match = pattern.exec(source)) { matches.push(match[2]); } return matches; }
[ "function", "getMatches", "(", "source", ",", "pattern", ")", "{", "var", "matches", "=", "[", "]", ",", "match", ";", "while", "(", "match", "=", "pattern", ".", "exec", "(", "source", ")", ")", "{", "matches", ".", "push", "(", "match", "[", "2", "]", ")", ";", "}", "return", "matches", ";", "}" ]
Returns a list of pattern matches against the source string
[ "Returns", "a", "list", "of", "pattern", "matches", "against", "the", "source", "string" ]
6cb44f31902daaed32b2d72168b15eebfb7fbfbb
https://github.com/mrjoelkemp/ya/blob/6cb44f31902daaed32b2d72168b15eebfb7fbfbb/helpers/GruntHelper.js#L308-L318
train
t9md/atom-outlet
lib/index.js
link
function link (outlet, editor) { if (getLocationForItem(editor) === 'center') { outlet.element.setAttribute('outlet-linked-editor-id', editor.id) } else { outlet.element.removeAttribute('outlet-linked-editor-id') } }
javascript
function link (outlet, editor) { if (getLocationForItem(editor) === 'center') { outlet.element.setAttribute('outlet-linked-editor-id', editor.id) } else { outlet.element.removeAttribute('outlet-linked-editor-id') } }
[ "function", "link", "(", "outlet", ",", "editor", ")", "{", "if", "(", "getLocationForItem", "(", "editor", ")", "===", "'center'", ")", "{", "outlet", ".", "element", ".", "setAttribute", "(", "'outlet-linked-editor-id'", ",", "editor", ".", "id", ")", "}", "else", "{", "outlet", ".", "element", ".", "removeAttribute", "(", "'outlet-linked-editor-id'", ")", "}", "}" ]
When outlet was created from an editor. Call this function to link outlet to that editor. Linked editor will not be hidden while outlet relocation. Only editor in center container can be linked.
[ "When", "outlet", "was", "created", "from", "an", "editor", ".", "Call", "this", "function", "to", "link", "outlet", "to", "that", "editor", ".", "Linked", "editor", "will", "not", "be", "hidden", "while", "outlet", "relocation", ".", "Only", "editor", "in", "center", "container", "can", "be", "linked", "." ]
6098828c54dbb0b64b14e89c449a04ea1ed069b1
https://github.com/t9md/atom-outlet/blob/6098828c54dbb0b64b14e89c449a04ea1ed069b1/lib/index.js#L198-L204
train
zappan/connect-spa-request-filter
lib/requestFilter.js
_isVoidFilterRoute
function _isVoidFilterRoute(req) { var reqPathRegex = new RegExp(['^', req.path.replace(/\/$/, ''), '$'].join(''), 'i') , voidRoute , i; for (i=0; i<voidFilterRoutes.length; i++) { if (reqPathRegex.test(voidFilterRoutes[i])) { return true; } } return false; }
javascript
function _isVoidFilterRoute(req) { var reqPathRegex = new RegExp(['^', req.path.replace(/\/$/, ''), '$'].join(''), 'i') , voidRoute , i; for (i=0; i<voidFilterRoutes.length; i++) { if (reqPathRegex.test(voidFilterRoutes[i])) { return true; } } return false; }
[ "function", "_isVoidFilterRoute", "(", "req", ")", "{", "var", "reqPathRegex", "=", "new", "RegExp", "(", "[", "'^'", ",", "req", ".", "path", ".", "replace", "(", "/", "\\/$", "/", ",", "''", ")", ",", "'$'", "]", ".", "join", "(", "''", ")", ",", "'i'", ")", ",", "voidRoute", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "voidFilterRoutes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "reqPathRegex", ".", "test", "(", "voidFilterRoutes", "[", "i", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether the route is in the list of routes to void filtering on @param {http.ServerRequest} req Node.js HTTP Server request @return true if request headers match 'application/json', false otherwise @return {Boolean} true if route (path) in the list of routes to void filtering on, false otherwise @author Tomislav Capan
[ "Checks", "whether", "the", "route", "is", "in", "the", "list", "of", "routes", "to", "void", "filtering", "on" ]
52a497dd8c4b315410322d698089a43ccdb938bc
https://github.com/zappan/connect-spa-request-filter/blob/52a497dd8c4b315410322d698089a43ccdb938bc/lib/requestFilter.js#L28-L37
train
zappan/connect-spa-request-filter
lib/requestFilter.js
_renderAppShell
function _renderAppShell(res) { res.render(appShell.view, { layout : appShell.layout , appTitle : appConfig.appTitle , appConfig : JSON.stringify(appConfig) , appData : JSON.stringify(appData) }); }
javascript
function _renderAppShell(res) { res.render(appShell.view, { layout : appShell.layout , appTitle : appConfig.appTitle , appConfig : JSON.stringify(appConfig) , appData : JSON.stringify(appData) }); }
[ "function", "_renderAppShell", "(", "res", ")", "{", "res", ".", "render", "(", "appShell", ".", "view", ",", "{", "layout", ":", "appShell", ".", "layout", ",", "appTitle", ":", "appConfig", ".", "appTitle", ",", "appConfig", ":", "JSON", ".", "stringify", "(", "appConfig", ")", ",", "appData", ":", "JSON", ".", "stringify", "(", "appData", ")", "}", ")", ";", "}" ]
Default method to render app shell, could be overriden through init options @return _void_ @author Tomislav Capan
[ "Default", "method", "to", "render", "app", "shell", "could", "be", "overriden", "through", "init", "options" ]
52a497dd8c4b315410322d698089a43ccdb938bc
https://github.com/zappan/connect-spa-request-filter/blob/52a497dd8c4b315410322d698089a43ccdb938bc/lib/requestFilter.js#L45-L52
train
zappan/connect-spa-request-filter
lib/requestFilter.js
configure
function configure(options) { options = options || {}; var assertErrTemplate = '[connect-spa-request-filter middleware :: configure()] Fatal error! Missing parameter:'; assert(options.appConfig, util.format(assertErrTemplate, 'options.appConfig')); assert(options.appConfig.appTitle, util.format(assertErrTemplate, 'options.appConfig.appTitle')); appConfig = options.appConfig; appData = options.appData || {}; appShell = options.appShell || {}; voidFilterRoutes = options.voidFilterRoutes || []; appShell.view = appShell.view || 'index'; appShell.layout = appShell.layout || false; // Publicly expose the module interface after initialized return requestFilter; }
javascript
function configure(options) { options = options || {}; var assertErrTemplate = '[connect-spa-request-filter middleware :: configure()] Fatal error! Missing parameter:'; assert(options.appConfig, util.format(assertErrTemplate, 'options.appConfig')); assert(options.appConfig.appTitle, util.format(assertErrTemplate, 'options.appConfig.appTitle')); appConfig = options.appConfig; appData = options.appData || {}; appShell = options.appShell || {}; voidFilterRoutes = options.voidFilterRoutes || []; appShell.view = appShell.view || 'index'; appShell.layout = appShell.layout || false; // Publicly expose the module interface after initialized return requestFilter; }
[ "function", "configure", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "assertErrTemplate", "=", "'[connect-spa-request-filter middleware :: configure()] Fatal error! Missing parameter:'", ";", "assert", "(", "options", ".", "appConfig", ",", "util", ".", "format", "(", "assertErrTemplate", ",", "'options.appConfig'", ")", ")", ";", "assert", "(", "options", ".", "appConfig", ".", "appTitle", ",", "util", ".", "format", "(", "assertErrTemplate", ",", "'options.appConfig.appTitle'", ")", ")", ";", "appConfig", "=", "options", ".", "appConfig", ";", "appData", "=", "options", ".", "appData", "||", "{", "}", ";", "appShell", "=", "options", ".", "appShell", "||", "{", "}", ";", "voidFilterRoutes", "=", "options", ".", "voidFilterRoutes", "||", "[", "]", ";", "appShell", ".", "view", "=", "appShell", ".", "view", "||", "'index'", ";", "appShell", ".", "layout", "=", "appShell", ".", "layout", "||", "false", ";", "return", "requestFilter", ";", "}" ]
Initializes the middleware by setting the required options for it to run and exposing the filtering interface @param {object} options Options object containing the following: * app: A reference to the Express app object * voidFilterRoutes: an array of routes (paths) to void filtering on @return {function} The requestFilter function doing the filtering @author Tomislav Capan
[ "Initializes", "the", "middleware", "by", "setting", "the", "required", "options", "for", "it", "to", "run", "and", "exposing", "the", "filtering", "interface" ]
52a497dd8c4b315410322d698089a43ccdb938bc
https://github.com/zappan/connect-spa-request-filter/blob/52a497dd8c4b315410322d698089a43ccdb938bc/lib/requestFilter.js#L80-L98
train
crysalead-js/expand-flatten
expand.js
expand
function expand(object, options) { var expanded = {}; var options = options || {}; var separator = options.separator || '.'; var affix = options.affix ? separator + options.affix + separator : separator; for (var path in object) { var value = object[path]; var pointer = expanded; if (path.indexOf('[') >= 0) { path = path.replace(/\[/g, '[.').replace(/]/g, ''); } var parts = path.split(separator).join(affix).split('.'); while (parts.length - 1) { var key = parts.shift(); if (key.slice(-1) === '[') { key = key.slice(0, - 1); pointer[key] = Array.isArray(pointer[key]) ? pointer[key] : []; } else { pointer[key] = (pointer[key] !== null && typeof pointer[key] === 'object' && pointer[key].constructor === Object) ? pointer[key] : {}; } pointer = pointer[key]; } pointer[parts.shift()] = value; } return expanded; }
javascript
function expand(object, options) { var expanded = {}; var options = options || {}; var separator = options.separator || '.'; var affix = options.affix ? separator + options.affix + separator : separator; for (var path in object) { var value = object[path]; var pointer = expanded; if (path.indexOf('[') >= 0) { path = path.replace(/\[/g, '[.').replace(/]/g, ''); } var parts = path.split(separator).join(affix).split('.'); while (parts.length - 1) { var key = parts.shift(); if (key.slice(-1) === '[') { key = key.slice(0, - 1); pointer[key] = Array.isArray(pointer[key]) ? pointer[key] : []; } else { pointer[key] = (pointer[key] !== null && typeof pointer[key] === 'object' && pointer[key].constructor === Object) ? pointer[key] : {}; } pointer = pointer[key]; } pointer[parts.shift()] = value; } return expanded; }
[ "function", "expand", "(", "object", ",", "options", ")", "{", "var", "expanded", "=", "{", "}", ";", "var", "options", "=", "options", "||", "{", "}", ";", "var", "separator", "=", "options", ".", "separator", "||", "'.'", ";", "var", "affix", "=", "options", ".", "affix", "?", "separator", "+", "options", ".", "affix", "+", "separator", ":", "separator", ";", "for", "(", "var", "path", "in", "object", ")", "{", "var", "value", "=", "object", "[", "path", "]", ";", "var", "pointer", "=", "expanded", ";", "if", "(", "path", ".", "indexOf", "(", "'['", ")", ">=", "0", ")", "{", "path", "=", "path", ".", "replace", "(", "/", "\\[", "/", "g", ",", "'[.'", ")", ".", "replace", "(", "/", "]", "/", "g", ",", "''", ")", ";", "}", "var", "parts", "=", "path", ".", "split", "(", "separator", ")", ".", "join", "(", "affix", ")", ".", "split", "(", "'.'", ")", ";", "while", "(", "parts", ".", "length", "-", "1", ")", "{", "var", "key", "=", "parts", ".", "shift", "(", ")", ";", "if", "(", "key", ".", "slice", "(", "-", "1", ")", "===", "'['", ")", "{", "key", "=", "key", ".", "slice", "(", "0", ",", "-", "1", ")", ";", "pointer", "[", "key", "]", "=", "Array", ".", "isArray", "(", "pointer", "[", "key", "]", ")", "?", "pointer", "[", "key", "]", ":", "[", "]", ";", "}", "else", "{", "pointer", "[", "key", "]", "=", "(", "pointer", "[", "key", "]", "!==", "null", "&&", "typeof", "pointer", "[", "key", "]", "===", "'object'", "&&", "pointer", "[", "key", "]", ".", "constructor", "===", "Object", ")", "?", "pointer", "[", "key", "]", ":", "{", "}", ";", "}", "pointer", "=", "pointer", "[", "key", "]", ";", "}", "pointer", "[", "parts", ".", "shift", "(", ")", "]", "=", "value", ";", "}", "return", "expanded", ";", "}" ]
Expands a "hash" object an object. @param Object object The object to expand. @param Object options The options. @return Object The expanded object.
[ "Expands", "a", "hash", "object", "an", "object", "." ]
dd298e70509a11219603f7eccecd2b0d963da904
https://github.com/crysalead-js/expand-flatten/blob/dd298e70509a11219603f7eccecd2b0d963da904/expand.js#L8-L36
train
melvincarvalho/rdf-shell
lib/touch.js
touch
function touch(argv, callback) { util.patch(argv[2], 'DELETE {} .', function(err, val) { if (!err) { console.log('touch to : ' + argv[2]); } }); }
javascript
function touch(argv, callback) { util.patch(argv[2], 'DELETE {} .', function(err, val) { if (!err) { console.log('touch to : ' + argv[2]); } }); }
[ "function", "touch", "(", "argv", ",", "callback", ")", "{", "util", ".", "patch", "(", "argv", "[", "2", "]", ",", "'DELETE {} .'", ",", "function", "(", "err", ",", "val", ")", "{", "if", "(", "!", "err", ")", "{", "console", ".", "log", "(", "'touch to : '", "+", "argv", "[", "2", "]", ")", ";", "}", "}", ")", ";", "}" ]
touch gets list of files for a given container @param {String} argv[2] url @param {String} argv[3] data @callback {bin~cb} callback
[ "touch", "gets", "list", "of", "files", "for", "a", "given", "container" ]
bf2015f6f333855e69a18ce3ec9e917bbddfb425
https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/touch.js#L13-L19
train
tomek-f/auto-elems-from-dom
autoElemsFromDOM.js
getDocumentFragmentFromString
function getDocumentFragmentFromString(html) { // return document.createRange().createContextualFragment(html); // FU safari var range = document.createRange(); range.selectNode(document.body);// safari return range.createContextualFragment(html); }
javascript
function getDocumentFragmentFromString(html) { // return document.createRange().createContextualFragment(html); // FU safari var range = document.createRange(); range.selectNode(document.body);// safari return range.createContextualFragment(html); }
[ "function", "getDocumentFragmentFromString", "(", "html", ")", "{", "var", "range", "=", "document", ".", "createRange", "(", ")", ";", "range", ".", "selectNode", "(", "document", ".", "body", ")", ";", "return", "range", ".", "createContextualFragment", "(", "html", ")", ";", "}" ]
Array.from without additional div
[ "Array", ".", "from", "without", "additional", "div" ]
1852d0a3d2d3b5ecb5d0f66c8fbf753e71e699af
https://github.com/tomek-f/auto-elems-from-dom/blob/1852d0a3d2d3b5ecb5d0f66c8fbf753e71e699af/autoElemsFromDOM.js#L4-L9
train
AndreasMadsen/immortal
lib/module.js
checkPath
function checkPath(name, path) { helpers.exists(path, function (exist) { if (!exist) { callback(new Error(name + ' was not found (' + path + ')')); return; } progress.set(name); }); }
javascript
function checkPath(name, path) { helpers.exists(path, function (exist) { if (!exist) { callback(new Error(name + ' was not found (' + path + ')')); return; } progress.set(name); }); }
[ "function", "checkPath", "(", "name", ",", "path", ")", "{", "helpers", ".", "exists", "(", "path", ",", "function", "(", "exist", ")", "{", "if", "(", "!", "exist", ")", "{", "callback", "(", "new", "Error", "(", "name", "+", "' was not found ('", "+", "path", "+", "')'", ")", ")", ";", "return", ";", "}", "progress", ".", "set", "(", "name", ")", ";", "}", ")", ";", "}" ]
check file paths
[ "check", "file", "paths" ]
c1ab5a4287a543fdfd980604a9e9927d663a9ef2
https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/module.js#L104-L111
train
AndreasMadsen/immortal
lib/module.js
execFile
function execFile() { var child; if (options.strategy === 'development') { child = core.spawnPump(options, false, false); if (options.relay) child.pump(process); } else if (options.strategy === 'unattached') { child = core.spawnPump(options, true, false); } else if (options.strategy === 'daemon') { child = core.spawnDaemon(options, true); } // start child child.spawn(); child.on('start', function () { callback(null); }); }
javascript
function execFile() { var child; if (options.strategy === 'development') { child = core.spawnPump(options, false, false); if (options.relay) child.pump(process); } else if (options.strategy === 'unattached') { child = core.spawnPump(options, true, false); } else if (options.strategy === 'daemon') { child = core.spawnDaemon(options, true); } // start child child.spawn(); child.on('start', function () { callback(null); }); }
[ "function", "execFile", "(", ")", "{", "var", "child", ";", "if", "(", "options", ".", "strategy", "===", "'development'", ")", "{", "child", "=", "core", ".", "spawnPump", "(", "options", ",", "false", ",", "false", ")", ";", "if", "(", "options", ".", "relay", ")", "child", ".", "pump", "(", "process", ")", ";", "}", "else", "if", "(", "options", ".", "strategy", "===", "'unattached'", ")", "{", "child", "=", "core", ".", "spawnPump", "(", "options", ",", "true", ",", "false", ")", ";", "}", "else", "if", "(", "options", ".", "strategy", "===", "'daemon'", ")", "{", "child", "=", "core", ".", "spawnDaemon", "(", "options", ",", "true", ")", ";", "}", "child", ".", "spawn", "(", ")", ";", "child", ".", "on", "(", "'start'", ",", "function", "(", ")", "{", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
this will execute when all tests are made
[ "this", "will", "execute", "when", "all", "tests", "are", "made" ]
c1ab5a4287a543fdfd980604a9e9927d663a9ef2
https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/module.js#L140-L158
train
sreenaths/em-tgraph
addon/utils/graph-view.js
function (mx, my, q1x1, q1y1, q1x, q1y, q2x1, q2y1, q2x, q2y ) { return `M ${mx} ${my} Q ${q1x1} ${q1y1} ${q1x} ${q1y} Q ${q2x1} ${q2y1} ${q2x} ${q2y}`; }
javascript
function (mx, my, q1x1, q1y1, q1x, q1y, q2x1, q2y1, q2x, q2y ) { return `M ${mx} ${my} Q ${q1x1} ${q1y1} ${q1x} ${q1y} Q ${q2x1} ${q2y1} ${q2x} ${q2y}`; }
[ "function", "(", "mx", ",", "my", ",", "q1x1", ",", "q1y1", ",", "q1x", ",", "q1y", ",", "q2x1", ",", "q2y1", ",", "q2x", ",", "q2y", ")", "{", "return", "`", "${", "mx", "}", "${", "my", "}", "${", "q1x1", "}", "${", "q1y1", "}", "${", "q1x", "}", "${", "q1y", "}", "${", "q2x1", "}", "${", "q2y1", "}", "${", "q2x", "}", "${", "q2y", "}", "`", ";", "}" ]
Defines how path between nodes are drawn
[ "Defines", "how", "path", "between", "nodes", "are", "drawn" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L86-L88
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_addTaskBubble
function _addTaskBubble(node, d) { var group = node.append('g'); group.attr('class', 'task-bubble'); group.append('use').attr('xlink:href', '#task-bubble'); translateIfIE(group.append('text') .text(_trimText(d.get('data.totalTasks') || 0, 3)), 0, 4); translateIfIE(group, 38, -15); }
javascript
function _addTaskBubble(node, d) { var group = node.append('g'); group.attr('class', 'task-bubble'); group.append('use').attr('xlink:href', '#task-bubble'); translateIfIE(group.append('text') .text(_trimText(d.get('data.totalTasks') || 0, 3)), 0, 4); translateIfIE(group, 38, -15); }
[ "function", "_addTaskBubble", "(", "node", ",", "d", ")", "{", "var", "group", "=", "node", ".", "append", "(", "'g'", ")", ";", "group", ".", "attr", "(", "'class'", ",", "'task-bubble'", ")", ";", "group", ".", "append", "(", "'use'", ")", ".", "attr", "(", "'xlink:href'", ",", "'#task-bubble'", ")", ";", "translateIfIE", "(", "group", ".", "append", "(", "'text'", ")", ".", "text", "(", "_trimText", "(", "d", ".", "get", "(", "'data.totalTasks'", ")", "||", "0", ",", "3", ")", ")", ",", "0", ",", "4", ")", ";", "translateIfIE", "(", "group", ",", "38", ",", "-", "15", ")", ";", "}" ]
Add task bubble to a vertex node @param node {SVG DOM element} Vertex node @param d {VertexDataNode}
[ "Add", "task", "bubble", "to", "a", "vertex", "node" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L171-L179
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_addVertexGroupBubble
function _addVertexGroupBubble(node, d) { var group; if(d.vertexGroup) { group = node.append('g'); group.attr('class', 'group-bubble'); group.append('use').attr('xlink:href', '#group-bubble'); translateIfIE(group.append('text') .text(_trimText(d.get('vertexGroup.groupMembers.length'), 2)), 0, 4); translateIfIE(group, 38, 15); } }
javascript
function _addVertexGroupBubble(node, d) { var group; if(d.vertexGroup) { group = node.append('g'); group.attr('class', 'group-bubble'); group.append('use').attr('xlink:href', '#group-bubble'); translateIfIE(group.append('text') .text(_trimText(d.get('vertexGroup.groupMembers.length'), 2)), 0, 4); translateIfIE(group, 38, 15); } }
[ "function", "_addVertexGroupBubble", "(", "node", ",", "d", ")", "{", "var", "group", ";", "if", "(", "d", ".", "vertexGroup", ")", "{", "group", "=", "node", ".", "append", "(", "'g'", ")", ";", "group", ".", "attr", "(", "'class'", ",", "'group-bubble'", ")", ";", "group", ".", "append", "(", "'use'", ")", ".", "attr", "(", "'xlink:href'", ",", "'#group-bubble'", ")", ";", "translateIfIE", "(", "group", ".", "append", "(", "'text'", ")", ".", "text", "(", "_trimText", "(", "d", ".", "get", "(", "'vertexGroup.groupMembers.length'", ")", ",", "2", ")", ")", ",", "0", ",", "4", ")", ";", "translateIfIE", "(", "group", ",", "38", ",", "15", ")", ";", "}", "}" ]
Add vertex group bubble to a vertex node @param node {SVG DOM element} Vertex node @param d {VertexDataNode}
[ "Add", "vertex", "group", "bubble", "to", "a", "vertex", "node" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L205-L217
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_addStatusBar
function _addStatusBar(node, d) { var group = node.append('g'); group.attr('class', 'status-bar'); group.append('foreignObject') .attr("class", "status") .attr("width", 70) .attr("height", 15) .html('<span class="msg-container">' + d.get('data.status') + '</span>' ); }
javascript
function _addStatusBar(node, d) { var group = node.append('g'); group.attr('class', 'status-bar'); group.append('foreignObject') .attr("class", "status") .attr("width", 70) .attr("height", 15) .html('<span class="msg-container">' + d.get('data.status') + '</span>' ); }
[ "function", "_addStatusBar", "(", "node", ",", "d", ")", "{", "var", "group", "=", "node", ".", "append", "(", "'g'", ")", ";", "group", ".", "attr", "(", "'class'", ",", "'status-bar'", ")", ";", "group", ".", "append", "(", "'foreignObject'", ")", ".", "attr", "(", "\"class\"", ",", "\"status\"", ")", ".", "attr", "(", "\"width\"", ",", "70", ")", ".", "attr", "(", "\"height\"", ",", "15", ")", ".", "html", "(", "'<span class=\"msg-container\">'", "+", "d", ".", "get", "(", "'data.status'", ")", "+", "'</span>'", ")", ";", "}" ]
Add status bar to a vertex node @param node {SVG DOM element} Vertex node @param d {VertexDataNode}
[ "Add", "status", "bar", "to", "a", "vertex", "node" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L223-L235
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_addBasicContents
function _addBasicContents(node, d, titleProperty, maxTitleLength) { var className = d.type; node.attr('class', `node ${className}`); node.append('use').attr('xlink:href', `#${className}-bg`); translateIfIE(node.append('text') .attr('class', 'title') .text(_trimText(d.get(titleProperty || 'name'), maxTitleLength || 12)), 0, 4); }
javascript
function _addBasicContents(node, d, titleProperty, maxTitleLength) { var className = d.type; node.attr('class', `node ${className}`); node.append('use').attr('xlink:href', `#${className}-bg`); translateIfIE(node.append('text') .attr('class', 'title') .text(_trimText(d.get(titleProperty || 'name'), maxTitleLength || 12)), 0, 4); }
[ "function", "_addBasicContents", "(", "node", ",", "d", ",", "titleProperty", ",", "maxTitleLength", ")", "{", "var", "className", "=", "d", ".", "type", ";", "node", ".", "attr", "(", "'class'", ",", "`", "${", "className", "}", "`", ")", ";", "node", ".", "append", "(", "'use'", ")", ".", "attr", "(", "'xlink:href'", ",", "`", "${", "className", "}", "`", ")", ";", "translateIfIE", "(", "node", ".", "append", "(", "'text'", ")", ".", "attr", "(", "'class'", ",", "'title'", ")", ".", "text", "(", "_trimText", "(", "d", ".", "get", "(", "titleProperty", "||", "'name'", ")", ",", "maxTitleLength", "||", "12", ")", ")", ",", "0", ",", "4", ")", ";", "}" ]
Creates a base SVG DOM node, with bg and title based on the type of DataNode @param node {SVG DOM element} Vertex node @param d {DataNode} @param titleProperty {String} d's property who's value is the title to be displayed. By default 'name'. @param maxTitleLength {Number} Title would be trimmed beyond maxTitleLength. By default 3 chars
[ "Creates", "a", "base", "SVG", "DOM", "node", "with", "bg", "and", "title", "based", "on", "the", "type", "of", "DataNode" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L244-L252
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_addContent
function _addContent(d) { var node = d3.select(this); switch(d.type) { case 'vertex': _addBasicContents(node, d, 'vertexName'); _addStatusBar(node, d); _addTaskBubble(node, d); _addIOBubble(node, d); _addVertexGroupBubble(node, d); break; case 'input': case 'output': _addBasicContents(node, d); break; } }
javascript
function _addContent(d) { var node = d3.select(this); switch(d.type) { case 'vertex': _addBasicContents(node, d, 'vertexName'); _addStatusBar(node, d); _addTaskBubble(node, d); _addIOBubble(node, d); _addVertexGroupBubble(node, d); break; case 'input': case 'output': _addBasicContents(node, d); break; } }
[ "function", "_addContent", "(", "d", ")", "{", "var", "node", "=", "d3", ".", "select", "(", "this", ")", ";", "switch", "(", "d", ".", "type", ")", "{", "case", "'vertex'", ":", "_addBasicContents", "(", "node", ",", "d", ",", "'vertexName'", ")", ";", "_addStatusBar", "(", "node", ",", "d", ")", ";", "_addTaskBubble", "(", "node", ",", "d", ")", ";", "_addIOBubble", "(", "node", ",", "d", ")", ";", "_addVertexGroupBubble", "(", "node", ",", "d", ")", ";", "break", ";", "case", "'input'", ":", "case", "'output'", ":", "_addBasicContents", "(", "node", ",", "d", ")", ";", "break", ";", "}", "}" ]
Populates the calling node with the required content. @param s {DataNode}
[ "Populates", "the", "calling", "node", "with", "the", "required", "content", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L257-L273
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_getLinks
function _getLinks(nodes) { var links = [], nodeHash; nodeHash = nodes.reduce(function (obj, node) { obj[node.id] = node; return obj; }, {}); _data.links.forEach(function (link) { var source = nodeHash[link.sourceId], target = nodeHash[link.targetId]; if(source && target) { link.setProperties({ source: source, target: target, isBackwardLink: source.isSelfOrAncestor(target) }); links.push(link); } }); return links; }
javascript
function _getLinks(nodes) { var links = [], nodeHash; nodeHash = nodes.reduce(function (obj, node) { obj[node.id] = node; return obj; }, {}); _data.links.forEach(function (link) { var source = nodeHash[link.sourceId], target = nodeHash[link.targetId]; if(source && target) { link.setProperties({ source: source, target: target, isBackwardLink: source.isSelfOrAncestor(target) }); links.push(link); } }); return links; }
[ "function", "_getLinks", "(", "nodes", ")", "{", "var", "links", "=", "[", "]", ",", "nodeHash", ";", "nodeHash", "=", "nodes", ".", "reduce", "(", "function", "(", "obj", ",", "node", ")", "{", "obj", "[", "node", ".", "id", "]", "=", "node", ";", "return", "obj", ";", "}", ",", "{", "}", ")", ";", "_data", ".", "links", ".", "forEach", "(", "function", "(", "link", ")", "{", "var", "source", "=", "nodeHash", "[", "link", ".", "sourceId", "]", ",", "target", "=", "nodeHash", "[", "link", ".", "targetId", "]", ";", "if", "(", "source", "&&", "target", ")", "{", "link", ".", "setProperties", "(", "{", "source", ":", "source", ",", "target", ":", "target", ",", "isBackwardLink", ":", "source", ".", "isSelfOrAncestor", "(", "target", ")", "}", ")", ";", "links", ".", "push", "(", "link", ")", ";", "}", "}", ")", ";", "return", "links", ";", "}" ]
Create a list of all links connecting nodes in the given array. @param nodes {Array} A list of d3 nodes created by tree layout @return links {Array} All links between nodes in the current DAG
[ "Create", "a", "list", "of", "all", "links", "connecting", "nodes", "in", "the", "given", "array", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L280-L303
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_normalize
function _normalize(nodes) { // Set layout var farthestY = 0; nodes.forEach(function (d) { d.y = d.depth * -_layout.depthSpacing; if(d.y < farthestY) { farthestY = d.y; } }); farthestY -= PADDING; nodes.forEach(function (d) { d.y -= farthestY; }); //Remove space occupied by dummy var rootChildren = _treeData.get('children'), rootChildCount = rootChildren.length, dummyIndex, i; if(rootChildCount % 2 === 0) { dummyIndex = rootChildren.indexOf(_treeData.get('dummy')); if(dummyIndex >= rootChildCount / 2) { for(i = 0; i < dummyIndex; i++) { rootChildren[i].x = rootChildren[i + 1].x; rootChildren[i].y = rootChildren[i + 1].y; } } else { for(i = rootChildCount - 1; i > dummyIndex; i--) { rootChildren[i].x = rootChildren[i - 1].x; rootChildren[i].y = rootChildren[i - 1].y; } } } // Put all single vertex outputs in-line with the vertex node // So that they are directly below the respective vertex in vertical layout nodes.forEach(function (node) { if(node.type === DataProcessor.types.OUTPUT && node.get('vertex.outputs.length') === 1 && !node.get('vertex.outEdgeIds.length') && node.get('treeParent.x') !== node.get('x') ) { node.x = node.get('vertex.x'); } }); }
javascript
function _normalize(nodes) { // Set layout var farthestY = 0; nodes.forEach(function (d) { d.y = d.depth * -_layout.depthSpacing; if(d.y < farthestY) { farthestY = d.y; } }); farthestY -= PADDING; nodes.forEach(function (d) { d.y -= farthestY; }); //Remove space occupied by dummy var rootChildren = _treeData.get('children'), rootChildCount = rootChildren.length, dummyIndex, i; if(rootChildCount % 2 === 0) { dummyIndex = rootChildren.indexOf(_treeData.get('dummy')); if(dummyIndex >= rootChildCount / 2) { for(i = 0; i < dummyIndex; i++) { rootChildren[i].x = rootChildren[i + 1].x; rootChildren[i].y = rootChildren[i + 1].y; } } else { for(i = rootChildCount - 1; i > dummyIndex; i--) { rootChildren[i].x = rootChildren[i - 1].x; rootChildren[i].y = rootChildren[i - 1].y; } } } // Put all single vertex outputs in-line with the vertex node // So that they are directly below the respective vertex in vertical layout nodes.forEach(function (node) { if(node.type === DataProcessor.types.OUTPUT && node.get('vertex.outputs.length') === 1 && !node.get('vertex.outEdgeIds.length') && node.get('treeParent.x') !== node.get('x') ) { node.x = node.get('vertex.x'); } }); }
[ "function", "_normalize", "(", "nodes", ")", "{", "var", "farthestY", "=", "0", ";", "nodes", ".", "forEach", "(", "function", "(", "d", ")", "{", "d", ".", "y", "=", "d", ".", "depth", "*", "-", "_layout", ".", "depthSpacing", ";", "if", "(", "d", ".", "y", "<", "farthestY", ")", "{", "farthestY", "=", "d", ".", "y", ";", "}", "}", ")", ";", "farthestY", "-=", "PADDING", ";", "nodes", ".", "forEach", "(", "function", "(", "d", ")", "{", "d", ".", "y", "-=", "farthestY", ";", "}", ")", ";", "var", "rootChildren", "=", "_treeData", ".", "get", "(", "'children'", ")", ",", "rootChildCount", "=", "rootChildren", ".", "length", ",", "dummyIndex", ",", "i", ";", "if", "(", "rootChildCount", "%", "2", "===", "0", ")", "{", "dummyIndex", "=", "rootChildren", ".", "indexOf", "(", "_treeData", ".", "get", "(", "'dummy'", ")", ")", ";", "if", "(", "dummyIndex", ">=", "rootChildCount", "/", "2", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "dummyIndex", ";", "i", "++", ")", "{", "rootChildren", "[", "i", "]", ".", "x", "=", "rootChildren", "[", "i", "+", "1", "]", ".", "x", ";", "rootChildren", "[", "i", "]", ".", "y", "=", "rootChildren", "[", "i", "+", "1", "]", ".", "y", ";", "}", "}", "else", "{", "for", "(", "i", "=", "rootChildCount", "-", "1", ";", "i", ">", "dummyIndex", ";", "i", "--", ")", "{", "rootChildren", "[", "i", "]", ".", "x", "=", "rootChildren", "[", "i", "-", "1", "]", ".", "x", ";", "rootChildren", "[", "i", "]", ".", "y", "=", "rootChildren", "[", "i", "-", "1", "]", ".", "y", ";", "}", "}", "}", "nodes", ".", "forEach", "(", "function", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "DataProcessor", ".", "types", ".", "OUTPUT", "&&", "node", ".", "get", "(", "'vertex.outputs.length'", ")", "===", "1", "&&", "!", "node", ".", "get", "(", "'vertex.outEdgeIds.length'", ")", "&&", "node", ".", "get", "(", "'treeParent.x'", ")", "!==", "node", ".", "get", "(", "'x'", ")", ")", "{", "node", ".", "x", "=", "node", ".", "get", "(", "'vertex.x'", ")", ";", "}", "}", ")", ";", "}" ]
Apply proper depth spacing and remove the space occupied by dummy node if the number of other nodes are odd. @param nodes {Array} A list of d3 nodes created by tree layout
[ "Apply", "proper", "depth", "spacing", "and", "remove", "the", "space", "occupied", "by", "dummy", "node", "if", "the", "number", "of", "other", "nodes", "are", "odd", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L310-L358
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_scheduledClick
function _scheduledClick(d, node) { node = node.correspondingUseElement || node; _component.sendAction('entityClicked', { type: _getType(node), d: d }); _tip.hide(); _scheduledClickId = 0; }
javascript
function _scheduledClick(d, node) { node = node.correspondingUseElement || node; _component.sendAction('entityClicked', { type: _getType(node), d: d }); _tip.hide(); _scheduledClickId = 0; }
[ "function", "_scheduledClick", "(", "d", ",", "node", ")", "{", "node", "=", "node", ".", "correspondingUseElement", "||", "node", ";", "_component", ".", "sendAction", "(", "'entityClicked'", ",", "{", "type", ":", "_getType", "(", "node", ")", ",", "d", ":", "d", "}", ")", ";", "_tip", ".", "hide", "(", ")", ";", "_scheduledClickId", "=", "0", ";", "}" ]
onclick handler scheduled using setTimeout @params d {DataNode} data of the clicked element @param node {D3 element} Element that was clicked
[ "onclick", "handler", "scheduled", "using", "setTimeout" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L518-L528
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_onClick
function _onClick(d) { if(!_scheduledClickId) { _scheduledClickId = setTimeout(_scheduledClick.bind(this, d, d3.event.target), 200); } }
javascript
function _onClick(d) { if(!_scheduledClickId) { _scheduledClickId = setTimeout(_scheduledClick.bind(this, d, d3.event.target), 200); } }
[ "function", "_onClick", "(", "d", ")", "{", "if", "(", "!", "_scheduledClickId", ")", "{", "_scheduledClickId", "=", "setTimeout", "(", "_scheduledClick", ".", "bind", "(", "this", ",", "d", ",", "d3", ".", "event", ".", "target", ")", ",", "200", ")", ";", "}", "}" ]
Schedules an onclick handler. If double click event is not triggered the handler will be called in 200ms. @param d {DataNode} Data of the clicked element
[ "Schedules", "an", "onclick", "handler", ".", "If", "double", "click", "event", "is", "not", "triggered", "the", "handler", "will", "be", "called", "in", "200ms", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L535-L539
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_onDblclick
function _onDblclick(d) { var event = d3.event, node = event.target; node = node.correspondingUseElement || node; if(_scheduledClickId) { clearTimeout(_scheduledClickId); _scheduledClickId = 0; } switch(_getType(node)) { case "io": d.toggleAdditionalInclusion(); _update(); break; } }
javascript
function _onDblclick(d) { var event = d3.event, node = event.target; node = node.correspondingUseElement || node; if(_scheduledClickId) { clearTimeout(_scheduledClickId); _scheduledClickId = 0; } switch(_getType(node)) { case "io": d.toggleAdditionalInclusion(); _update(); break; } }
[ "function", "_onDblclick", "(", "d", ")", "{", "var", "event", "=", "d3", ".", "event", ",", "node", "=", "event", ".", "target", ";", "node", "=", "node", ".", "correspondingUseElement", "||", "node", ";", "if", "(", "_scheduledClickId", ")", "{", "clearTimeout", "(", "_scheduledClickId", ")", ";", "_scheduledClickId", "=", "0", ";", "}", "switch", "(", "_getType", "(", "node", ")", ")", "{", "case", "\"io\"", ":", "d", ".", "toggleAdditionalInclusion", "(", ")", ";", "_update", "(", ")", ";", "break", ";", "}", "}" ]
Double click event handler. @param d {DataNode} Data of the clicked element
[ "Double", "click", "event", "handler", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L553-L570
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_createPathData
function _createPathData(d) { var sX = d.source.y, sY = d.source.x, tX = d.target.y, tY = d.target.x, mX = (sX + tX)/2, mY = (sY + tY)/2, sH = Math.abs(sX - tX) * 0.35, sV = 0; // strength if(d.isBackwardLink) { if(sY === tY) { sV = 45; mY -= 50; if(sX === tX) { sX += _layout.linkDelta; tX -= _layout.linkDelta; } } sH = Math.abs(sX - tX) * 1.1; } return _layout.pathFormatter( sX, sY, sX + sH, sY - sV, mX, mY, tX - sH, tY - sV, tX, tY ); }
javascript
function _createPathData(d) { var sX = d.source.y, sY = d.source.x, tX = d.target.y, tY = d.target.x, mX = (sX + tX)/2, mY = (sY + tY)/2, sH = Math.abs(sX - tX) * 0.35, sV = 0; // strength if(d.isBackwardLink) { if(sY === tY) { sV = 45; mY -= 50; if(sX === tX) { sX += _layout.linkDelta; tX -= _layout.linkDelta; } } sH = Math.abs(sX - tX) * 1.1; } return _layout.pathFormatter( sX, sY, sX + sH, sY - sV, mX, mY, tX - sH, tY - sV, tX, tY ); }
[ "function", "_createPathData", "(", "d", ")", "{", "var", "sX", "=", "d", ".", "source", ".", "y", ",", "sY", "=", "d", ".", "source", ".", "x", ",", "tX", "=", "d", ".", "target", ".", "y", ",", "tY", "=", "d", ".", "target", ".", "x", ",", "mX", "=", "(", "sX", "+", "tX", ")", "/", "2", ",", "mY", "=", "(", "sY", "+", "tY", ")", "/", "2", ",", "sH", "=", "Math", ".", "abs", "(", "sX", "-", "tX", ")", "*", "0.35", ",", "sV", "=", "0", ";", "if", "(", "d", ".", "isBackwardLink", ")", "{", "if", "(", "sY", "===", "tY", ")", "{", "sV", "=", "45", ";", "mY", "-=", "50", ";", "if", "(", "sX", "===", "tX", ")", "{", "sX", "+=", "_layout", ".", "linkDelta", ";", "tX", "-=", "_layout", ".", "linkDelta", ";", "}", "}", "sH", "=", "Math", ".", "abs", "(", "sX", "-", "tX", ")", "*", "1.1", ";", "}", "return", "_layout", ".", "pathFormatter", "(", "sX", ",", "sY", ",", "sX", "+", "sH", ",", "sY", "-", "sV", ",", "mX", ",", "mY", ",", "tX", "-", "sH", ",", "tY", "-", "sV", ",", "tX", ",", "tY", ")", ";", "}" ]
Creates a path data string for the given link. Google SVG path data to learn what it is. @param d {Object} Must contain source and target properties with the start and end positions. @return pathData {String} Path data string based on the current layout
[ "Creates", "a", "path", "data", "string", "for", "the", "given", "link", ".", "Google", "SVG", "path", "data", "to", "learn", "what", "it", "is", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L577-L609
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_updateNodes
function _updateNodes(nodes, source) { // Enter any new nodes at the parent's previous position. nodes.enter().append('g') .attr('transform', function(d) { var node = _getVertexNode(d, "x0") || source; node = _layout.projector(node.x0, node.y0); return 'translate(' + node.x + ',' + node.y + ')'; }) .on({ mouseover: _onMouseOver, mouseout: _tip.hide, mousedown: _onMouse, mousemove: _onMouse, dblclick: _onDblclick }) .style('opacity', 1e-6) .each(_addContent); // Transition nodes to their new position. nodes.transition() .duration(DURATION) .attr('transform', function(d) { d = _layout.projector(d.x, d.y); return 'translate(' + d.x + ',' + d.y + ')'; }) .style('opacity', 1); // Transition exiting nodes to the parent's new position. nodes.exit().transition() .duration(DURATION) .attr('transform', function(d) { var node = _getVertexNode(d, "x") || source; node = _layout.projector(node.x, node.y); return 'translate(' + node.x + ',' + node.y + ')'; }) .style('opacity', 1e-6) .remove(); }
javascript
function _updateNodes(nodes, source) { // Enter any new nodes at the parent's previous position. nodes.enter().append('g') .attr('transform', function(d) { var node = _getVertexNode(d, "x0") || source; node = _layout.projector(node.x0, node.y0); return 'translate(' + node.x + ',' + node.y + ')'; }) .on({ mouseover: _onMouseOver, mouseout: _tip.hide, mousedown: _onMouse, mousemove: _onMouse, dblclick: _onDblclick }) .style('opacity', 1e-6) .each(_addContent); // Transition nodes to their new position. nodes.transition() .duration(DURATION) .attr('transform', function(d) { d = _layout.projector(d.x, d.y); return 'translate(' + d.x + ',' + d.y + ')'; }) .style('opacity', 1); // Transition exiting nodes to the parent's new position. nodes.exit().transition() .duration(DURATION) .attr('transform', function(d) { var node = _getVertexNode(d, "x") || source; node = _layout.projector(node.x, node.y); return 'translate(' + node.x + ',' + node.y + ')'; }) .style('opacity', 1e-6) .remove(); }
[ "function", "_updateNodes", "(", "nodes", ",", "source", ")", "{", "nodes", ".", "enter", "(", ")", ".", "append", "(", "'g'", ")", ".", "attr", "(", "'transform'", ",", "function", "(", "d", ")", "{", "var", "node", "=", "_getVertexNode", "(", "d", ",", "\"x0\"", ")", "||", "source", ";", "node", "=", "_layout", ".", "projector", "(", "node", ".", "x0", ",", "node", ".", "y0", ")", ";", "return", "'translate('", "+", "node", ".", "x", "+", "','", "+", "node", ".", "y", "+", "')'", ";", "}", ")", ".", "on", "(", "{", "mouseover", ":", "_onMouseOver", ",", "mouseout", ":", "_tip", ".", "hide", ",", "mousedown", ":", "_onMouse", ",", "mousemove", ":", "_onMouse", ",", "dblclick", ":", "_onDblclick", "}", ")", ".", "style", "(", "'opacity'", ",", "1e-6", ")", ".", "each", "(", "_addContent", ")", ";", "nodes", ".", "transition", "(", ")", ".", "duration", "(", "DURATION", ")", ".", "attr", "(", "'transform'", ",", "function", "(", "d", ")", "{", "d", "=", "_layout", ".", "projector", "(", "d", ".", "x", ",", "d", ".", "y", ")", ";", "return", "'translate('", "+", "d", ".", "x", "+", "','", "+", "d", ".", "y", "+", "')'", ";", "}", ")", ".", "style", "(", "'opacity'", ",", "1", ")", ";", "nodes", ".", "exit", "(", ")", ".", "transition", "(", ")", ".", "duration", "(", "DURATION", ")", ".", "attr", "(", "'transform'", ",", "function", "(", "d", ")", "{", "var", "node", "=", "_getVertexNode", "(", "d", ",", "\"x\"", ")", "||", "source", ";", "node", "=", "_layout", ".", "projector", "(", "node", ".", "x", ",", "node", ".", "y", ")", ";", "return", "'translate('", "+", "node", ".", "x", "+", "','", "+", "node", ".", "y", "+", "')'", ";", "}", ")", ".", "style", "(", "'opacity'", ",", "1e-6", ")", ".", "remove", "(", ")", ";", "}" ]
Update position of all nodes in the list and preform required transitions. @param nodes {Array} Nodes to be updated @param source {d3 element} Node that trigged the update, in first update source will be root.
[ "Update", "position", "of", "all", "nodes", "in", "the", "list", "and", "preform", "required", "transitions", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L627-L664
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_updateLinks
function _updateLinks(links, source) { // Enter any new links at the parent's previous position. links.enter().insert('path', 'g') .attr('class', function (d) { var type = d.get('dataMovementType') || ""; return 'link ' + type.toLowerCase(); }) /** * IE11 rendering does not work for svg path element with marker set. * See https://connect.microsoft.com/IE/feedback/details/801938 * This can be removed once the bug is fixed in all supported IE versions */ .attr("style", isIE ? "" : Ember.String.htmlSafe("marker-mid: url(" + window.location.pathname + "#arrow-marker);")) .attr('d', function(d) { var node = _getTargetNode(d, "x0") || source; var o = {x: node.x0, y: node.y0}; return _createPathData({source: o, target: o}); }) .on({ mouseover: _onMouseOver, mouseout: _tip.hide }); // Transition links to their new position. links.transition() .duration(DURATION) .attr('d', _createPathData); // Transition exiting nodes to the parent's new position. links.exit().transition() .duration(DURATION) .attr('d', function(d) { var node = _getTargetNode(d, "x") || source; var o = {x: node.x, y: node.y}; return _createPathData({source: o, target: o}); }) .remove(); }
javascript
function _updateLinks(links, source) { // Enter any new links at the parent's previous position. links.enter().insert('path', 'g') .attr('class', function (d) { var type = d.get('dataMovementType') || ""; return 'link ' + type.toLowerCase(); }) /** * IE11 rendering does not work for svg path element with marker set. * See https://connect.microsoft.com/IE/feedback/details/801938 * This can be removed once the bug is fixed in all supported IE versions */ .attr("style", isIE ? "" : Ember.String.htmlSafe("marker-mid: url(" + window.location.pathname + "#arrow-marker);")) .attr('d', function(d) { var node = _getTargetNode(d, "x0") || source; var o = {x: node.x0, y: node.y0}; return _createPathData({source: o, target: o}); }) .on({ mouseover: _onMouseOver, mouseout: _tip.hide }); // Transition links to their new position. links.transition() .duration(DURATION) .attr('d', _createPathData); // Transition exiting nodes to the parent's new position. links.exit().transition() .duration(DURATION) .attr('d', function(d) { var node = _getTargetNode(d, "x") || source; var o = {x: node.x, y: node.y}; return _createPathData({source: o, target: o}); }) .remove(); }
[ "function", "_updateLinks", "(", "links", ",", "source", ")", "{", "links", ".", "enter", "(", ")", ".", "insert", "(", "'path'", ",", "'g'", ")", ".", "attr", "(", "'class'", ",", "function", "(", "d", ")", "{", "var", "type", "=", "d", ".", "get", "(", "'dataMovementType'", ")", "||", "\"\"", ";", "return", "'link '", "+", "type", ".", "toLowerCase", "(", ")", ";", "}", ")", ".", "attr", "(", "\"style\"", ",", "isIE", "?", "\"\"", ":", "Ember", ".", "String", ".", "htmlSafe", "(", "\"marker-mid: url(\"", "+", "window", ".", "location", ".", "pathname", "+", "\"#arrow-marker);\"", ")", ")", ".", "attr", "(", "'d'", ",", "function", "(", "d", ")", "{", "var", "node", "=", "_getTargetNode", "(", "d", ",", "\"x0\"", ")", "||", "source", ";", "var", "o", "=", "{", "x", ":", "node", ".", "x0", ",", "y", ":", "node", ".", "y0", "}", ";", "return", "_createPathData", "(", "{", "source", ":", "o", ",", "target", ":", "o", "}", ")", ";", "}", ")", ".", "on", "(", "{", "mouseover", ":", "_onMouseOver", ",", "mouseout", ":", "_tip", ".", "hide", "}", ")", ";", "links", ".", "transition", "(", ")", ".", "duration", "(", "DURATION", ")", ".", "attr", "(", "'d'", ",", "_createPathData", ")", ";", "links", ".", "exit", "(", ")", ".", "transition", "(", ")", ".", "duration", "(", "DURATION", ")", ".", "attr", "(", "'d'", ",", "function", "(", "d", ")", "{", "var", "node", "=", "_getTargetNode", "(", "d", ",", "\"x\"", ")", "||", "source", ";", "var", "o", "=", "{", "x", ":", "node", ".", "x", ",", "y", ":", "node", ".", "y", "}", ";", "return", "_createPathData", "(", "{", "source", ":", "o", ",", "target", ":", "o", "}", ")", ";", "}", ")", ".", "remove", "(", ")", ";", "}" ]
Update position of all links in the list and preform required transitions. @param links {Array} Links to be updated @param source {d3 element} Node that trigged the update, in first update source will be root.
[ "Update", "position", "of", "all", "links", "in", "the", "list", "and", "preform", "required", "transitions", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L685-L722
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_update
function _update() { var nodesData = _treeLayout.nodes(_treeData), linksData = _getLinks(nodesData); _normalize(nodesData); var nodes = _g.selectAll('g.node') .data(nodesData, _getNodeId); _updateNodes(nodes, _treeData); var links = _g.selectAll('path.link') .data(linksData, _getLinkId); _updateLinks(links, _treeData); nodesData.forEach(_stashOldPositions); }
javascript
function _update() { var nodesData = _treeLayout.nodes(_treeData), linksData = _getLinks(nodesData); _normalize(nodesData); var nodes = _g.selectAll('g.node') .data(nodesData, _getNodeId); _updateNodes(nodes, _treeData); var links = _g.selectAll('path.link') .data(linksData, _getLinkId); _updateLinks(links, _treeData); nodesData.forEach(_stashOldPositions); }
[ "function", "_update", "(", ")", "{", "var", "nodesData", "=", "_treeLayout", ".", "nodes", "(", "_treeData", ")", ",", "linksData", "=", "_getLinks", "(", "nodesData", ")", ";", "_normalize", "(", "nodesData", ")", ";", "var", "nodes", "=", "_g", ".", "selectAll", "(", "'g.node'", ")", ".", "data", "(", "nodesData", ",", "_getNodeId", ")", ";", "_updateNodes", "(", "nodes", ",", "_treeData", ")", ";", "var", "links", "=", "_g", ".", "selectAll", "(", "'path.link'", ")", ".", "data", "(", "linksData", ",", "_getLinkId", ")", ";", "_updateLinks", "(", "links", ",", "_treeData", ")", ";", "nodesData", ".", "forEach", "(", "_stashOldPositions", ")", ";", "}" ]
Updates position of nodes and links based on changes in _treeData.
[ "Updates", "position", "of", "nodes", "and", "links", "based", "on", "changes", "in", "_treeData", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L738-L753
train
sreenaths/em-tgraph
addon/utils/graph-view.js
transform
function transform(animate) { var base = animate ? g.transition().duration(DURATION) : g; base.attr('transform', `translate(${panX}, ${panY}) scale(${scale})`); }
javascript
function transform(animate) { var base = animate ? g.transition().duration(DURATION) : g; base.attr('transform', `translate(${panX}, ${panY}) scale(${scale})`); }
[ "function", "transform", "(", "animate", ")", "{", "var", "base", "=", "animate", "?", "g", ".", "transition", "(", ")", ".", "duration", "(", "DURATION", ")", ":", "g", ";", "base", ".", "attr", "(", "'transform'", ",", "`", "${", "panX", "}", "${", "panY", "}", "${", "scale", "}", "`", ")", ";", "}" ]
Transform g to current panX, panY and scale. @param animate {Boolean} Animate the transformation in DURATION time.
[ "Transform", "g", "to", "current", "panX", "panY", "and", "scale", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L778-L781
train
sreenaths/em-tgraph
addon/utils/graph-view.js
visibilityCheck
function visibilityCheck() { var graphBound = g.node().getBoundingClientRect(), containerBound = container[0].getBoundingClientRect(); if(graphBound.right < containerBound.left || graphBound.bottom < containerBound.top || graphBound.left > containerBound.right || graphBound.top > containerBound.bottom) { panX = PADDING; panY = PADDING; scale = 1; transform(true); } }
javascript
function visibilityCheck() { var graphBound = g.node().getBoundingClientRect(), containerBound = container[0].getBoundingClientRect(); if(graphBound.right < containerBound.left || graphBound.bottom < containerBound.top || graphBound.left > containerBound.right || graphBound.top > containerBound.bottom) { panX = PADDING; panY = PADDING; scale = 1; transform(true); } }
[ "function", "visibilityCheck", "(", ")", "{", "var", "graphBound", "=", "g", ".", "node", "(", ")", ".", "getBoundingClientRect", "(", ")", ",", "containerBound", "=", "container", "[", "0", "]", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "graphBound", ".", "right", "<", "containerBound", ".", "left", "||", "graphBound", ".", "bottom", "<", "containerBound", ".", "top", "||", "graphBound", ".", "left", ">", "containerBound", ".", "right", "||", "graphBound", ".", "top", ">", "containerBound", ".", "bottom", ")", "{", "panX", "=", "PADDING", ";", "panY", "=", "PADDING", ";", "scale", "=", "1", ";", "transform", "(", "true", ")", ";", "}", "}" ]
Check if the item have moved out of the visible area, and reset if required
[ "Check", "if", "the", "item", "have", "moved", "out", "of", "the", "visible", "area", "and", "reset", "if", "required" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L786-L799
train
sreenaths/em-tgraph
addon/utils/graph-view.js
onMouseMove
function onMouseMove(event) { panX += event.pageX - prevX; panY += event.pageY - prevY; transform(); prevX = event.pageX; prevY = event.pageY; }
javascript
function onMouseMove(event) { panX += event.pageX - prevX; panY += event.pageY - prevY; transform(); prevX = event.pageX; prevY = event.pageY; }
[ "function", "onMouseMove", "(", "event", ")", "{", "panX", "+=", "event", ".", "pageX", "-", "prevX", ";", "panY", "+=", "event", ".", "pageY", "-", "prevY", ";", "transform", "(", ")", ";", "prevX", "=", "event", ".", "pageX", ";", "prevY", "=", "event", ".", "pageY", ";", "}" ]
Set pan values
[ "Set", "pan", "values" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L815-L823
train
sreenaths/em-tgraph
addon/utils/graph-view.js
onWheel
function onWheel(event) { var prevScale = scale, offset = container.offset(), mouseX = event.pageX - offset.left, mouseY = event.pageY - offset.top, factor = 0; scale += event.deltaY * SCALE_TUNER; if(scale < MIN_SCALE) { scale = MIN_SCALE; } else if(scale > MAX_SCALE) { scale = MAX_SCALE; } factor = 1 - scale / prevScale; panX += (mouseX - panX) * factor; panY += (mouseY - panY) * factor; transform(); scheduleVisibilityCheck(); _tip.reposition(); event.preventDefault(); }
javascript
function onWheel(event) { var prevScale = scale, offset = container.offset(), mouseX = event.pageX - offset.left, mouseY = event.pageY - offset.top, factor = 0; scale += event.deltaY * SCALE_TUNER; if(scale < MIN_SCALE) { scale = MIN_SCALE; } else if(scale > MAX_SCALE) { scale = MAX_SCALE; } factor = 1 - scale / prevScale; panX += (mouseX - panX) * factor; panY += (mouseY - panY) * factor; transform(); scheduleVisibilityCheck(); _tip.reposition(); event.preventDefault(); }
[ "function", "onWheel", "(", "event", ")", "{", "var", "prevScale", "=", "scale", ",", "offset", "=", "container", ".", "offset", "(", ")", ",", "mouseX", "=", "event", ".", "pageX", "-", "offset", ".", "left", ",", "mouseY", "=", "event", ".", "pageY", "-", "offset", ".", "top", ",", "factor", "=", "0", ";", "scale", "+=", "event", ".", "deltaY", "*", "SCALE_TUNER", ";", "if", "(", "scale", "<", "MIN_SCALE", ")", "{", "scale", "=", "MIN_SCALE", ";", "}", "else", "if", "(", "scale", ">", "MAX_SCALE", ")", "{", "scale", "=", "MAX_SCALE", ";", "}", "factor", "=", "1", "-", "scale", "/", "prevScale", ";", "panX", "+=", "(", "mouseX", "-", "panX", ")", "*", "factor", ";", "panY", "+=", "(", "mouseY", "-", "panY", ")", "*", "factor", ";", "transform", "(", ")", ";", "scheduleVisibilityCheck", "(", ")", ";", "_tip", ".", "reposition", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}" ]
Set zoom values, pan also would change as we are zooming with mouse position as pivote.
[ "Set", "zoom", "values", "pan", "also", "would", "change", "as", "we", "are", "zooming", "with", "mouse", "position", "as", "pivote", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L827-L852
train
sreenaths/em-tgraph
addon/utils/graph-view.js
_setLayout
function _setLayout(layout) { var leafCount = _data.leafCount, dimention; // If count is even dummy will be replaced by output, so output would no more be leaf if(_data.tree.get('children.length') % 2 === 0) { leafCount--; } dimention = layout.projector(leafCount, _data.maxDepth - 1); _layout = layout; _width = dimention.x *= _layout.hSpacing; _height = dimention.y *= _layout.vSpacing; dimention = _layout.projector(dimention.x, dimention.y); // Because tree is always top to bottom _treeLayout = d3.layout.tree().size([dimention.x, dimention.y]); _update(); }
javascript
function _setLayout(layout) { var leafCount = _data.leafCount, dimention; // If count is even dummy will be replaced by output, so output would no more be leaf if(_data.tree.get('children.length') % 2 === 0) { leafCount--; } dimention = layout.projector(leafCount, _data.maxDepth - 1); _layout = layout; _width = dimention.x *= _layout.hSpacing; _height = dimention.y *= _layout.vSpacing; dimention = _layout.projector(dimention.x, dimention.y); // Because tree is always top to bottom _treeLayout = d3.layout.tree().size([dimention.x, dimention.y]); _update(); }
[ "function", "_setLayout", "(", "layout", ")", "{", "var", "leafCount", "=", "_data", ".", "leafCount", ",", "dimention", ";", "if", "(", "_data", ".", "tree", ".", "get", "(", "'children.length'", ")", "%", "2", "===", "0", ")", "{", "leafCount", "--", ";", "}", "dimention", "=", "layout", ".", "projector", "(", "leafCount", ",", "_data", ".", "maxDepth", "-", "1", ")", ";", "_layout", "=", "layout", ";", "_width", "=", "dimention", ".", "x", "*=", "_layout", ".", "hSpacing", ";", "_height", "=", "dimention", ".", "y", "*=", "_layout", ".", "vSpacing", ";", "dimention", "=", "_layout", ".", "projector", "(", "dimention", ".", "x", ",", "dimention", ".", "y", ")", ";", "_treeLayout", "=", "d3", ".", "layout", ".", "tree", "(", ")", ".", "size", "(", "[", "dimention", ".", "x", ",", "dimention", ".", "y", "]", ")", ";", "_update", "(", ")", ";", "}" ]
Sets the layout and update the display. @param layout {Object} One of the values defined in LAYOUTS object
[ "Sets", "the", "layout", "and", "update", "the", "display", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L898-L917
train
sreenaths/em-tgraph
addon/utils/graph-view.js
function (component, element, data) { var svg = d3.select(element).select('svg'); _component = component; _data = data; _g = svg.append('g').attr('transform', `translate(${PADDING},${PADDING})`); _svg = Ember.$(svg.node()); _tip = Tip; _tip.init(Ember.$(element).find('.tool-tip'), _svg); _treeData = data.tree; _treeData.x0 = 0; _treeData.y0 = 0; _panZoom = _attachPanZoom(_svg, _g, element); _setLayout(LAYOUTS.topToBottom); }
javascript
function (component, element, data) { var svg = d3.select(element).select('svg'); _component = component; _data = data; _g = svg.append('g').attr('transform', `translate(${PADDING},${PADDING})`); _svg = Ember.$(svg.node()); _tip = Tip; _tip.init(Ember.$(element).find('.tool-tip'), _svg); _treeData = data.tree; _treeData.x0 = 0; _treeData.y0 = 0; _panZoom = _attachPanZoom(_svg, _g, element); _setLayout(LAYOUTS.topToBottom); }
[ "function", "(", "component", ",", "element", ",", "data", ")", "{", "var", "svg", "=", "d3", ".", "select", "(", "element", ")", ".", "select", "(", "'svg'", ")", ";", "_component", "=", "component", ";", "_data", "=", "data", ";", "_g", "=", "svg", ".", "append", "(", "'g'", ")", ".", "attr", "(", "'transform'", ",", "`", "${", "PADDING", "}", "${", "PADDING", "}", "`", ")", ";", "_svg", "=", "Ember", ".", "$", "(", "svg", ".", "node", "(", ")", ")", ";", "_tip", "=", "Tip", ";", "_tip", ".", "init", "(", "Ember", ".", "$", "(", "element", ")", ".", "find", "(", "'.tool-tip'", ")", ",", "_svg", ")", ";", "_treeData", "=", "data", ".", "tree", ";", "_treeData", ".", "x0", "=", "0", ";", "_treeData", ".", "y0", "=", "0", ";", "_panZoom", "=", "_attachPanZoom", "(", "_svg", ",", "_g", ",", "element", ")", ";", "_setLayout", "(", "LAYOUTS", ".", "topToBottom", ")", ";", "}" ]
Creates a DAG view in the given element based on the data @param component {DagViewComponent} Parent ember component, to sendAction @param element {HTML DOM Element} HTML element in which the view will be created @param data {Object} Created by data processor
[ "Creates", "a", "DAG", "view", "in", "the", "given", "element", "based", "on", "the", "data" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L926-L944
train
sreenaths/em-tgraph
addon/utils/graph-view.js
function (){ var scale = Math.min( (_svg.width() - PADDING * 2) / _width, (_svg.height() - PADDING * 2) / _height ), panZoomValues = _panZoom(); if( panZoomValues.panX !== PADDING || panZoomValues.panY !== PADDING || panZoomValues.scale !== scale ) { _panZoomValues = _panZoom(PADDING, PADDING, scale); } else { _panZoomValues = _panZoom( _panZoomValues.panX, _panZoomValues.panY, _panZoomValues.scale); } }
javascript
function (){ var scale = Math.min( (_svg.width() - PADDING * 2) / _width, (_svg.height() - PADDING * 2) / _height ), panZoomValues = _panZoom(); if( panZoomValues.panX !== PADDING || panZoomValues.panY !== PADDING || panZoomValues.scale !== scale ) { _panZoomValues = _panZoom(PADDING, PADDING, scale); } else { _panZoomValues = _panZoom( _panZoomValues.panX, _panZoomValues.panY, _panZoomValues.scale); } }
[ "function", "(", ")", "{", "var", "scale", "=", "Math", ".", "min", "(", "(", "_svg", ".", "width", "(", ")", "-", "PADDING", "*", "2", ")", "/", "_width", ",", "(", "_svg", ".", "height", "(", ")", "-", "PADDING", "*", "2", ")", "/", "_height", ")", ",", "panZoomValues", "=", "_panZoom", "(", ")", ";", "if", "(", "panZoomValues", ".", "panX", "!==", "PADDING", "||", "panZoomValues", ".", "panY", "!==", "PADDING", "||", "panZoomValues", ".", "scale", "!==", "scale", ")", "{", "_panZoomValues", "=", "_panZoom", "(", "PADDING", ",", "PADDING", ",", "scale", ")", ";", "}", "else", "{", "_panZoomValues", "=", "_panZoom", "(", "_panZoomValues", ".", "panX", ",", "_panZoomValues", ".", "panY", ",", "_panZoomValues", ".", "scale", ")", ";", "}", "}" ]
Calling this function would fit the graph to the available space.
[ "Calling", "this", "function", "would", "fit", "the", "graph", "to", "the", "available", "space", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L949-L969
train
sreenaths/em-tgraph
addon/utils/graph-view.js
function (hide) { if(hide) { _g.attr('class', 'hide-io'); _treeData.recursivelyCall('excludeAdditionals'); } else { _treeData.recursivelyCall('includeAdditionals'); _g.attr('class', null); } _update(); }
javascript
function (hide) { if(hide) { _g.attr('class', 'hide-io'); _treeData.recursivelyCall('excludeAdditionals'); } else { _treeData.recursivelyCall('includeAdditionals'); _g.attr('class', null); } _update(); }
[ "function", "(", "hide", ")", "{", "if", "(", "hide", ")", "{", "_g", ".", "attr", "(", "'class'", ",", "'hide-io'", ")", ";", "_treeData", ".", "recursivelyCall", "(", "'excludeAdditionals'", ")", ";", "}", "else", "{", "_treeData", ".", "recursivelyCall", "(", "'includeAdditionals'", ")", ";", "_g", ".", "attr", "(", "'class'", ",", "null", ")", ";", "}", "_update", "(", ")", ";", "}" ]
Control display of additionals or sources and sinks. @param hide {Boolean} If true the additionals will be excluded, else included in the display
[ "Control", "display", "of", "additionals", "or", "sources", "and", "sinks", "." ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L975-L985
train
sreenaths/em-tgraph
addon/utils/graph-view.js
function () { _setLayout(_layout === LAYOUTS.topToBottom ? LAYOUTS.leftToRight : LAYOUTS.topToBottom); return _layout === LAYOUTS.topToBottom; }
javascript
function () { _setLayout(_layout === LAYOUTS.topToBottom ? LAYOUTS.leftToRight : LAYOUTS.topToBottom); return _layout === LAYOUTS.topToBottom; }
[ "function", "(", ")", "{", "_setLayout", "(", "_layout", "===", "LAYOUTS", ".", "topToBottom", "?", "LAYOUTS", ".", "leftToRight", ":", "LAYOUTS", ".", "topToBottom", ")", ";", "return", "_layout", "===", "LAYOUTS", ".", "topToBottom", ";", "}" ]
Toggle graph layouts between the available options
[ "Toggle", "graph", "layouts", "between", "the", "available", "options" ]
8d6a8f46b911a165ac16561731735ab762954996
https://github.com/sreenaths/em-tgraph/blob/8d6a8f46b911a165ac16561731735ab762954996/addon/utils/graph-view.js#L990-L995
train
timkuijsten/node-mongo-bcrypt-user
index.js
User
function User(coll, username, opts) { if (typeof coll !== 'object') { throw new TypeError('coll must be an object'); } if (typeof username !== 'string') { throw new TypeError('username must be a string'); } // setup a resolver var db = { find: coll.findOne.bind(coll), insert: coll.insert.bind(coll), updateHash: function(lookup, hash, cb) { coll.update(lookup, { $set: { password: hash } }, function(err, updated) { if (err) { cb(err); return; } if (updated !== 1) { cb(new Error('failed to update password')); return; } cb(null); }); } }; BcryptUser.call(this, db, username, opts || {}); }
javascript
function User(coll, username, opts) { if (typeof coll !== 'object') { throw new TypeError('coll must be an object'); } if (typeof username !== 'string') { throw new TypeError('username must be a string'); } // setup a resolver var db = { find: coll.findOne.bind(coll), insert: coll.insert.bind(coll), updateHash: function(lookup, hash, cb) { coll.update(lookup, { $set: { password: hash } }, function(err, updated) { if (err) { cb(err); return; } if (updated !== 1) { cb(new Error('failed to update password')); return; } cb(null); }); } }; BcryptUser.call(this, db, username, opts || {}); }
[ "function", "User", "(", "coll", ",", "username", ",", "opts", ")", "{", "if", "(", "typeof", "coll", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'coll must be an object'", ")", ";", "}", "if", "(", "typeof", "username", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'username must be a string'", ")", ";", "}", "var", "db", "=", "{", "find", ":", "coll", ".", "findOne", ".", "bind", "(", "coll", ")", ",", "insert", ":", "coll", ".", "insert", ".", "bind", "(", "coll", ")", ",", "updateHash", ":", "function", "(", "lookup", ",", "hash", ",", "cb", ")", "{", "coll", ".", "update", "(", "lookup", ",", "{", "$set", ":", "{", "password", ":", "hash", "}", "}", ",", "function", "(", "err", ",", "updated", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "return", ";", "}", "if", "(", "updated", "!==", "1", ")", "{", "cb", "(", "new", "Error", "(", "'failed to update password'", ")", ")", ";", "return", ";", "}", "cb", "(", "null", ")", ";", "}", ")", ";", "}", "}", ";", "BcryptUser", ".", "call", "(", "this", ",", "db", ",", "username", ",", "opts", "||", "{", "}", ")", ";", "}" ]
Store and verify users with bcrypt passwords located in a mongodb collection. @param {Object} coll the database that contains all user accounts @param {String} username the name of the user to bind this instance to @param {Object} [opts] object containing optional parameters opts: realm {String, default "_default"} optional realm the user belongs to debug {Boolean, default false} whether to do extra console logging or not hide {Boolean, default false} whether to suppress errors or not (for testing)
[ "Store", "and", "verify", "users", "with", "bcrypt", "passwords", "located", "in", "a", "mongodb", "collection", "." ]
2a110a07cf474bca486bf70350c828b47decae52
https://github.com/timkuijsten/node-mongo-bcrypt-user/blob/2a110a07cf474bca486bf70350c828b47decae52/index.js#L34-L54
train
airbrite/muni
model.js
function(options) { return function(err, resp) { if (err) { options.error(err); } else { options.success(resp); } }; }
javascript
function(options) { return function(err, resp) { if (err) { options.error(err); } else { options.success(resp); } }; }
[ "function", "(", "options", ")", "{", "return", "function", "(", "err", ",", "resp", ")", "{", "if", "(", "err", ")", "{", "options", ".", "error", "(", "err", ")", ";", "}", "else", "{", "options", ".", "success", "(", "resp", ")", ";", "}", "}", ";", "}" ]
Responsible for setting attributes after a database call Takes the mongodb response and calls the Backbone success method @param {Object} options @return {Function}
[ "Responsible", "for", "setting", "attributes", "after", "a", "database", "call", "Takes", "the", "mongodb", "response", "and", "calls", "the", "Backbone", "success", "method" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L52-L60
train
airbrite/muni
model.js
function(attrs, attrsToRemove) { _.forEach(attrs, function(val, key) { // shouldRemove is either an object or a boolean var shouldRemove = attrsToRemove[key]; if (_.isUndefined(shouldRemove)) { return; } // Support nested object if (_.isPlainObject(val) && !_.isArray(val) && _.isPlainObject(shouldRemove)) { return this._removeExpandableAttributes(val, shouldRemove); } // Make sure attribute is an object // Strip all nested properties except for `_id` if (_.isPlainObject(attrs[key]) && shouldRemove) { attrs[key] = _.pick(attrs[key], ['_id']); } }.bind(this)); }
javascript
function(attrs, attrsToRemove) { _.forEach(attrs, function(val, key) { // shouldRemove is either an object or a boolean var shouldRemove = attrsToRemove[key]; if (_.isUndefined(shouldRemove)) { return; } // Support nested object if (_.isPlainObject(val) && !_.isArray(val) && _.isPlainObject(shouldRemove)) { return this._removeExpandableAttributes(val, shouldRemove); } // Make sure attribute is an object // Strip all nested properties except for `_id` if (_.isPlainObject(attrs[key]) && shouldRemove) { attrs[key] = _.pick(attrs[key], ['_id']); } }.bind(this)); }
[ "function", "(", "attrs", ",", "attrsToRemove", ")", "{", "_", ".", "forEach", "(", "attrs", ",", "function", "(", "val", ",", "key", ")", "{", "var", "shouldRemove", "=", "attrsToRemove", "[", "key", "]", ";", "if", "(", "_", ".", "isUndefined", "(", "shouldRemove", ")", ")", "{", "return", ";", "}", "if", "(", "_", ".", "isPlainObject", "(", "val", ")", "&&", "!", "_", ".", "isArray", "(", "val", ")", "&&", "_", ".", "isPlainObject", "(", "shouldRemove", ")", ")", "{", "return", "this", ".", "_removeExpandableAttributes", "(", "val", ",", "shouldRemove", ")", ";", "}", "if", "(", "_", ".", "isPlainObject", "(", "attrs", "[", "key", "]", ")", "&&", "shouldRemove", ")", "{", "attrs", "[", "key", "]", "=", "_", ".", "pick", "(", "attrs", "[", "key", "]", ",", "[", "'_id'", "]", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Remove expandable attributes Does not work for objects embedded inside arrays @param {Object} attrs @param {Object} attrsToRemove
[ "Remove", "expandable", "attributes" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L99-L118
train
airbrite/muni
model.js
function(schemaType, schemaDefault) { if (!_.isUndefined(schemaDefault)) { return schemaDefault; } switch (schemaType) { case 'integer': case 'uinteger': case 'float': case 'ufloat': return 0; case 'boolean': return false; case 'timestamp': return new Date().getTime(); // ms case 'date': return new Date(); // iso default: return null; } }
javascript
function(schemaType, schemaDefault) { if (!_.isUndefined(schemaDefault)) { return schemaDefault; } switch (schemaType) { case 'integer': case 'uinteger': case 'float': case 'ufloat': return 0; case 'boolean': return false; case 'timestamp': return new Date().getTime(); // ms case 'date': return new Date(); // iso default: return null; } }
[ "function", "(", "schemaType", ",", "schemaDefault", ")", "{", "if", "(", "!", "_", ".", "isUndefined", "(", "schemaDefault", ")", ")", "{", "return", "schemaDefault", ";", "}", "switch", "(", "schemaType", ")", "{", "case", "'integer'", ":", "case", "'uinteger'", ":", "case", "'float'", ":", "case", "'ufloat'", ":", "return", "0", ";", "case", "'boolean'", ":", "return", "false", ";", "case", "'timestamp'", ":", "return", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "case", "'date'", ":", "return", "new", "Date", "(", ")", ";", "default", ":", "return", "null", ";", "}", "}" ]
Return the default value for a schema type @param {string} schemaType @param {*} schemaDefault @return {*}
[ "Return", "the", "default", "value", "for", "a", "schema", "type" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L311-L330
train
airbrite/muni
model.js
function(def, withArray) { def = def ? def : _.result(this, 'definition'); return _.reduce(def, function(defaults, attr, key) { if (attr.computed) { return defaults; } if (attr.default !== undefined) { defaults[key] = _.result(attr, 'default'); } else if (attr.type === 'object') { defaults[key] = this.defaults(attr.fields || {}); } else if (attr.type === 'array') { // withArray to populate nested array values for _validateAttributes defaults[key] = withArray ? [this.defaults(attr.fields || {})] : []; } else { defaults[key] = this._defaultVal(attr.type); } return defaults; }.bind(this), {}); }
javascript
function(def, withArray) { def = def ? def : _.result(this, 'definition'); return _.reduce(def, function(defaults, attr, key) { if (attr.computed) { return defaults; } if (attr.default !== undefined) { defaults[key] = _.result(attr, 'default'); } else if (attr.type === 'object') { defaults[key] = this.defaults(attr.fields || {}); } else if (attr.type === 'array') { // withArray to populate nested array values for _validateAttributes defaults[key] = withArray ? [this.defaults(attr.fields || {})] : []; } else { defaults[key] = this._defaultVal(attr.type); } return defaults; }.bind(this), {}); }
[ "function", "(", "def", ",", "withArray", ")", "{", "def", "=", "def", "?", "def", ":", "_", ".", "result", "(", "this", ",", "'definition'", ")", ";", "return", "_", ".", "reduce", "(", "def", ",", "function", "(", "defaults", ",", "attr", ",", "key", ")", "{", "if", "(", "attr", ".", "computed", ")", "{", "return", "defaults", ";", "}", "if", "(", "attr", ".", "default", "!==", "undefined", ")", "{", "defaults", "[", "key", "]", "=", "_", ".", "result", "(", "attr", ",", "'default'", ")", ";", "}", "else", "if", "(", "attr", ".", "type", "===", "'object'", ")", "{", "defaults", "[", "key", "]", "=", "this", ".", "defaults", "(", "attr", ".", "fields", "||", "{", "}", ")", ";", "}", "else", "if", "(", "attr", ".", "type", "===", "'array'", ")", "{", "defaults", "[", "key", "]", "=", "withArray", "?", "[", "this", ".", "defaults", "(", "attr", ".", "fields", "||", "{", "}", ")", "]", ":", "[", "]", ";", "}", "else", "{", "defaults", "[", "key", "]", "=", "this", ".", "_defaultVal", "(", "attr", ".", "type", ")", ";", "}", "return", "defaults", ";", "}", ".", "bind", "(", "this", ")", ",", "{", "}", ")", ";", "}" ]
Get the default attribute values for your model. When creating an instance of the model, any unspecified attributes will be set to their default value. Define defaults as a function. @param {Object} def @param {boolean} withArray @return {Object}
[ "Get", "the", "default", "attribute", "values", "for", "your", "model", ".", "When", "creating", "an", "instance", "of", "the", "model", "any", "unspecified", "attributes", "will", "be", "set", "to", "their", "default", "value", "." ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L344-L363
train
airbrite/muni
model.js
function(def) { def = def ? def : _.result(this, 'definition'); return _.reduce(def, function(schema, attr, key) { if (attr.type === 'object') { schema[key] = this.schema(attr.fields || {}); } else if (attr.type === 'array') { if (attr.value_type === 'object') { schema[key] = [this.schema(attr.fields || {})]; } else if (attr.value_type) { schema[key] = [attr.value_type]; } else { schema[key] = []; } } else { schema[key] = attr.type; } return schema; }.bind(this), {}); }
javascript
function(def) { def = def ? def : _.result(this, 'definition'); return _.reduce(def, function(schema, attr, key) { if (attr.type === 'object') { schema[key] = this.schema(attr.fields || {}); } else if (attr.type === 'array') { if (attr.value_type === 'object') { schema[key] = [this.schema(attr.fields || {})]; } else if (attr.value_type) { schema[key] = [attr.value_type]; } else { schema[key] = []; } } else { schema[key] = attr.type; } return schema; }.bind(this), {}); }
[ "function", "(", "def", ")", "{", "def", "=", "def", "?", "def", ":", "_", ".", "result", "(", "this", ",", "'definition'", ")", ";", "return", "_", ".", "reduce", "(", "def", ",", "function", "(", "schema", ",", "attr", ",", "key", ")", "{", "if", "(", "attr", ".", "type", "===", "'object'", ")", "{", "schema", "[", "key", "]", "=", "this", ".", "schema", "(", "attr", ".", "fields", "||", "{", "}", ")", ";", "}", "else", "if", "(", "attr", ".", "type", "===", "'array'", ")", "{", "if", "(", "attr", ".", "value_type", "===", "'object'", ")", "{", "schema", "[", "key", "]", "=", "[", "this", ".", "schema", "(", "attr", ".", "fields", "||", "{", "}", ")", "]", ";", "}", "else", "if", "(", "attr", ".", "value_type", ")", "{", "schema", "[", "key", "]", "=", "[", "attr", ".", "value_type", "]", ";", "}", "else", "{", "schema", "[", "key", "]", "=", "[", "]", ";", "}", "}", "else", "{", "schema", "[", "key", "]", "=", "attr", ".", "type", ";", "}", "return", "schema", ";", "}", ".", "bind", "(", "this", ")", ",", "{", "}", ")", ";", "}" ]
Get the types of each attribute. Define schema as a function. See `model.spec.js` for how to use @param {Object} def @return {Object}
[ "Get", "the", "types", "of", "each", "attribute", "." ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L376-L395
train
airbrite/muni
model.js
function(prop, def) { def = def ? def : _.result(this, 'definition'); return _.reduce(def, function(attrs, attr, key) { if (attr.type === 'object') { var nested = this.findAttributes(prop, attr.fields || {}); if (!_.isEmpty(nested)) { attrs[key] = nested; } } if (attr[prop]) { attrs[key] = true; } return attrs; }.bind(this), {}); }
javascript
function(prop, def) { def = def ? def : _.result(this, 'definition'); return _.reduce(def, function(attrs, attr, key) { if (attr.type === 'object') { var nested = this.findAttributes(prop, attr.fields || {}); if (!_.isEmpty(nested)) { attrs[key] = nested; } } if (attr[prop]) { attrs[key] = true; } return attrs; }.bind(this), {}); }
[ "function", "(", "prop", ",", "def", ")", "{", "def", "=", "def", "?", "def", ":", "_", ".", "result", "(", "this", ",", "'definition'", ")", ";", "return", "_", ".", "reduce", "(", "def", ",", "function", "(", "attrs", ",", "attr", ",", "key", ")", "{", "if", "(", "attr", ".", "type", "===", "'object'", ")", "{", "var", "nested", "=", "this", ".", "findAttributes", "(", "prop", ",", "attr", ".", "fields", "||", "{", "}", ")", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "nested", ")", ")", "{", "attrs", "[", "key", "]", "=", "nested", ";", "}", "}", "if", "(", "attr", "[", "prop", "]", ")", "{", "attrs", "[", "key", "]", "=", "true", ";", "}", "return", "attrs", ";", "}", ".", "bind", "(", "this", ")", ",", "{", "}", ")", ";", "}" ]
Define attributes that are not settable from the request @param {String} prop @param {Object} def @return {Object}
[ "Define", "attributes", "that", "are", "not", "settable", "from", "the", "request" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L404-L418
train
airbrite/muni
model.js
function(resp, options) { // Mongodb sometimes returns an array of one document if (_.isArray(resp)) { resp = resp[0]; } resp = _.defaultsDeep({}, resp, this.defaults()); return resp; }
javascript
function(resp, options) { // Mongodb sometimes returns an array of one document if (_.isArray(resp)) { resp = resp[0]; } resp = _.defaultsDeep({}, resp, this.defaults()); return resp; }
[ "function", "(", "resp", ",", "options", ")", "{", "if", "(", "_", ".", "isArray", "(", "resp", ")", ")", "{", "resp", "=", "resp", "[", "0", "]", ";", "}", "resp", "=", "_", ".", "defaultsDeep", "(", "{", "}", ",", "resp", ",", "this", ".", "defaults", "(", ")", ")", ";", "return", "resp", ";", "}" ]
Backbone `parse` extended with support for defaults @param {Object|Array} resp @param {Object} options @return {Object}
[ "Backbone", "parse", "extended", "with", "support", "for", "defaults" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L472-L479
train
airbrite/muni
model.js
function(key, val, options) { var attrs; if (key === null) return this; if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Don't override unset if (options.unset) { return Backbone.Model.prototype.set.apply(this, arguments); } // Apply schema this._validateAttributes(attrs, this._schema, this._defaults); return Backbone.Model.prototype.set.call(this, attrs, options); }
javascript
function(key, val, options) { var attrs; if (key === null) return this; if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Don't override unset if (options.unset) { return Backbone.Model.prototype.set.apply(this, arguments); } // Apply schema this._validateAttributes(attrs, this._schema, this._defaults); return Backbone.Model.prototype.set.call(this, attrs, options); }
[ "function", "(", "key", ",", "val", ",", "options", ")", "{", "var", "attrs", ";", "if", "(", "key", "===", "null", ")", "return", "this", ";", "if", "(", "typeof", "key", "===", "'object'", ")", "{", "attrs", "=", "key", ";", "options", "=", "val", ";", "}", "else", "{", "(", "attrs", "=", "{", "}", ")", "[", "key", "]", "=", "val", ";", "}", "options", "||", "(", "options", "=", "{", "}", ")", ";", "if", "(", "options", ".", "unset", ")", "{", "return", "Backbone", ".", "Model", ".", "prototype", ".", "set", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "this", ".", "_validateAttributes", "(", "attrs", ",", "this", ".", "_schema", ",", "this", ".", "_defaults", ")", ";", "return", "Backbone", ".", "Model", ".", "prototype", ".", "set", ".", "call", "(", "this", ",", "attrs", ",", "options", ")", ";", "}" ]
Backbone `set` extended with support for schema TODO @ptshih Extend with lodash `set` (nested/deep) @return {*}
[ "Backbone", "set", "extended", "with", "support", "for", "schema" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L489-L511
train
airbrite/muni
model.js
function(attrs, attr) { if (!_.isString(attr)) { return undefined; } var keys = attr.split('.'); var key; var val = attrs; var context = this; for (var i = 0, n = keys.length; i < n; i++) { // get key key = keys[i]; // Hold reference to the context when diving deep into nested keys if (i > 0) { context = val; } // get value for key val = val[key]; // value for key does not exist // break out of loop early if (_.isUndefined(val) || _.isNull(val)) { break; } } // Eval computed properties that are functions if (_.isFunction(val)) { // Call it with the proper context (see above) val = val.call(context); } return val; }
javascript
function(attrs, attr) { if (!_.isString(attr)) { return undefined; } var keys = attr.split('.'); var key; var val = attrs; var context = this; for (var i = 0, n = keys.length; i < n; i++) { // get key key = keys[i]; // Hold reference to the context when diving deep into nested keys if (i > 0) { context = val; } // get value for key val = val[key]; // value for key does not exist // break out of loop early if (_.isUndefined(val) || _.isNull(val)) { break; } } // Eval computed properties that are functions if (_.isFunction(val)) { // Call it with the proper context (see above) val = val.call(context); } return val; }
[ "function", "(", "attrs", ",", "attr", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "attr", ")", ")", "{", "return", "undefined", ";", "}", "var", "keys", "=", "attr", ".", "split", "(", "'.'", ")", ";", "var", "key", ";", "var", "val", "=", "attrs", ";", "var", "context", "=", "this", ";", "for", "(", "var", "i", "=", "0", ",", "n", "=", "keys", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "i", ">", "0", ")", "{", "context", "=", "val", ";", "}", "val", "=", "val", "[", "key", "]", ";", "if", "(", "_", ".", "isUndefined", "(", "val", ")", "||", "_", ".", "isNull", "(", "val", ")", ")", "{", "break", ";", "}", "}", "if", "(", "_", ".", "isFunction", "(", "val", ")", ")", "{", "val", "=", "val", ".", "call", "(", "context", ")", ";", "}", "return", "val", ";", "}" ]
DEPRECATED 2015-05-08 Soon `get` will use lodash `get` instead of `getDeep`
[ "DEPRECATED", "2015", "-", "05", "-", "08", "Soon", "get", "will", "use", "lodash", "get", "instead", "of", "getDeep" ]
ea8b26aa94836514374907c325a0d79f28838e2e
https://github.com/airbrite/muni/blob/ea8b26aa94836514374907c325a0d79f28838e2e/model.js#L540-L576
train
stadt-bielefeld/wms-capabilities-tools
index.js
determineVersion
function determineVersion(json) { var version = 'unknown'; if (json) { if (json.WMS_Capabilities) { if (json.WMS_Capabilities.$) { if (json.WMS_Capabilities.$.version) { version = json.WMS_Capabilities.$.version; } } } else { if (json.WMT_MS_Capabilities) { if (json.WMT_MS_Capabilities.$) { if (json.WMT_MS_Capabilities.$.version) { version = json.WMT_MS_Capabilities.$.version; } } } } } return version; }
javascript
function determineVersion(json) { var version = 'unknown'; if (json) { if (json.WMS_Capabilities) { if (json.WMS_Capabilities.$) { if (json.WMS_Capabilities.$.version) { version = json.WMS_Capabilities.$.version; } } } else { if (json.WMT_MS_Capabilities) { if (json.WMT_MS_Capabilities.$) { if (json.WMT_MS_Capabilities.$.version) { version = json.WMT_MS_Capabilities.$.version; } } } } } return version; }
[ "function", "determineVersion", "(", "json", ")", "{", "var", "version", "=", "'unknown'", ";", "if", "(", "json", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "$", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "$", ".", "version", ")", "{", "version", "=", "json", ".", "WMS_Capabilities", ".", "$", ".", "version", ";", "}", "}", "}", "else", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "$", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "$", ".", "version", ")", "{", "version", "=", "json", ".", "WMT_MS_Capabilities", ".", "$", ".", "version", ";", "}", "}", "}", "}", "}", "return", "version", ";", "}" ]
It determines the version of GetCapabilities document. @param json {object} GetCapabilities document as JSON. @returns {String} Version of GetCapabilities document. If the version can't determined, it will return 'unknown'.
[ "It", "determines", "the", "version", "of", "GetCapabilities", "document", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L43-L63
train
stadt-bielefeld/wms-capabilities-tools
index.js
determineJSON
function determineJSON(xml) { var json = null; parseString(xml, function(err, result) { if (err) { // TODO console.log(err); } else { json = result; } }); return json; }
javascript
function determineJSON(xml) { var json = null; parseString(xml, function(err, result) { if (err) { // TODO console.log(err); } else { json = result; } }); return json; }
[ "function", "determineJSON", "(", "xml", ")", "{", "var", "json", "=", "null", ";", "parseString", "(", "xml", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ")", ";", "}", "else", "{", "json", "=", "result", ";", "}", "}", ")", ";", "return", "json", ";", "}" ]
It determines the JSON object from XML. @param xml {string} GetCapabilities document as XML. @returns {object} GetCapabilities document as JSON.
[ "It", "determines", "the", "JSON", "object", "from", "XML", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L72-L83
train
stadt-bielefeld/wms-capabilities-tools
index.js
determineLayers
function determineLayers(json, version) { var layers = []; if (version == '1.3.0') { if (json.WMS_Capabilities.Capability) { if (json.WMS_Capabilities.Capability[0]) { if (json.WMS_Capabilities.Capability[0].Layer) { layers = buildLayers(json.WMS_Capabilities.Capability[0].Layer); } } } } else { if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') { if (json.WMT_MS_Capabilities.Capability) { if (json.WMT_MS_Capabilities.Capability[0]) { if (json.WMT_MS_Capabilities.Capability[0].Layer) { layers = buildLayers(json.WMT_MS_Capabilities.Capability[0].Layer); } } } } } return layers; }
javascript
function determineLayers(json, version) { var layers = []; if (version == '1.3.0') { if (json.WMS_Capabilities.Capability) { if (json.WMS_Capabilities.Capability[0]) { if (json.WMS_Capabilities.Capability[0].Layer) { layers = buildLayers(json.WMS_Capabilities.Capability[0].Layer); } } } } else { if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') { if (json.WMT_MS_Capabilities.Capability) { if (json.WMT_MS_Capabilities.Capability[0]) { if (json.WMT_MS_Capabilities.Capability[0].Layer) { layers = buildLayers(json.WMT_MS_Capabilities.Capability[0].Layer); } } } } } return layers; }
[ "function", "determineLayers", "(", "json", ",", "version", ")", "{", "var", "layers", "=", "[", "]", ";", "if", "(", "version", "==", "'1.3.0'", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Capability", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Capability", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Capability", "[", "0", "]", ".", "Layer", ")", "{", "layers", "=", "buildLayers", "(", "json", ".", "WMS_Capabilities", ".", "Capability", "[", "0", "]", ".", "Layer", ")", ";", "}", "}", "}", "}", "else", "{", "if", "(", "version", "==", "'1.1.1'", "||", "version", "==", "'1.1.0'", "||", "version", "==", "'1.0.0'", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Capability", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Capability", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Capability", "[", "0", "]", ".", "Layer", ")", "{", "layers", "=", "buildLayers", "(", "json", ".", "WMT_MS_Capabilities", ".", "Capability", "[", "0", "]", ".", "Layer", ")", ";", "}", "}", "}", "}", "}", "return", "layers", ";", "}" ]
It determines the layer JSON from original XML GetCapabilities document. @param json {object} GetCapabilities document as JSON. @param version {string} Version of GetCapabilities document. @returns {object} JSON object with layers from original XML GetCapabilities.
[ "It", "determines", "the", "layer", "JSON", "from", "original", "XML", "GetCapabilities", "document", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L94-L117
train
stadt-bielefeld/wms-capabilities-tools
index.js
determineLayerName
function determineLayerName(layer) { var name = ''; // Layer name available if (layer.Name) { return layer.Name; } else { // Layer name not available // Layer name will be building from sublayers for (var int = 0; int < layer.Layer.length; int++) { name += determineLayerName(layer.Layer[int]) + ','; } } // Remove last comma if (name.substring(name.length - 1, name.length) == ',') { name = name.substring(0, name.length - 1); } return name; }
javascript
function determineLayerName(layer) { var name = ''; // Layer name available if (layer.Name) { return layer.Name; } else { // Layer name not available // Layer name will be building from sublayers for (var int = 0; int < layer.Layer.length; int++) { name += determineLayerName(layer.Layer[int]) + ','; } } // Remove last comma if (name.substring(name.length - 1, name.length) == ',') { name = name.substring(0, name.length - 1); } return name; }
[ "function", "determineLayerName", "(", "layer", ")", "{", "var", "name", "=", "''", ";", "if", "(", "layer", ".", "Name", ")", "{", "return", "layer", ".", "Name", ";", "}", "else", "{", "for", "(", "var", "int", "=", "0", ";", "int", "<", "layer", ".", "Layer", ".", "length", ";", "int", "++", ")", "{", "name", "+=", "determineLayerName", "(", "layer", ".", "Layer", "[", "int", "]", ")", "+", "','", ";", "}", "}", "if", "(", "name", ".", "substring", "(", "name", ".", "length", "-", "1", ",", "name", ".", "length", ")", "==", "','", ")", "{", "name", "=", "name", ".", "substring", "(", "0", ",", "name", ".", "length", "-", "1", ")", ";", "}", "return", "name", ";", "}" ]
It determines the name of a layer. If the layer name is not set, it will generate from the sublayers. @param {object} layer Layer object like {"Name": "LayerName", "Layer": [{"Name": "SubLayerName1"},{"Name": "SubLayerName2"}]} @returns {string} Name of layer
[ "It", "determines", "the", "name", "of", "a", "layer", ".", "If", "the", "layer", "name", "is", "not", "set", "it", "will", "generate", "from", "the", "sublayers", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L128-L148
train
stadt-bielefeld/wms-capabilities-tools
index.js
buildLayers
function buildLayers(layersObject) { // Array of layers var layers = []; if (layersObject) { // Iterate over all layers for (var int = 0; int < layersObject.length; int++) { // One layer var singleLayer = layersObject[int]; // Build a new layer object var layer = {}; // Determine name from GetCapabilities document if (singleLayer.Name) { if (singleLayer.Name[0]) { layer.Name = singleLayer.Name[0]; } } // Determine title from GetCapabilities document if (singleLayer.Title) { if (singleLayer.Title[0]) { layer.Title = singleLayer.Title[0]; } } // Determine abstract from GetCapabilities document if (singleLayer.Abstract) { if (singleLayer.Abstract[0]) { layer.Abstract = singleLayer.Abstract[0]; } } layer.Layer = buildLayers(singleLayer.Layer); // Determine layer name if not available layer.Name = determineLayerName(layer); // Determine layer title if not available if (!(layer.Title)) { layer.Title = layer.Name; } // Add layer to the array layers.push(layer); } } return layers; }
javascript
function buildLayers(layersObject) { // Array of layers var layers = []; if (layersObject) { // Iterate over all layers for (var int = 0; int < layersObject.length; int++) { // One layer var singleLayer = layersObject[int]; // Build a new layer object var layer = {}; // Determine name from GetCapabilities document if (singleLayer.Name) { if (singleLayer.Name[0]) { layer.Name = singleLayer.Name[0]; } } // Determine title from GetCapabilities document if (singleLayer.Title) { if (singleLayer.Title[0]) { layer.Title = singleLayer.Title[0]; } } // Determine abstract from GetCapabilities document if (singleLayer.Abstract) { if (singleLayer.Abstract[0]) { layer.Abstract = singleLayer.Abstract[0]; } } layer.Layer = buildLayers(singleLayer.Layer); // Determine layer name if not available layer.Name = determineLayerName(layer); // Determine layer title if not available if (!(layer.Title)) { layer.Title = layer.Name; } // Add layer to the array layers.push(layer); } } return layers; }
[ "function", "buildLayers", "(", "layersObject", ")", "{", "var", "layers", "=", "[", "]", ";", "if", "(", "layersObject", ")", "{", "for", "(", "var", "int", "=", "0", ";", "int", "<", "layersObject", ".", "length", ";", "int", "++", ")", "{", "var", "singleLayer", "=", "layersObject", "[", "int", "]", ";", "var", "layer", "=", "{", "}", ";", "if", "(", "singleLayer", ".", "Name", ")", "{", "if", "(", "singleLayer", ".", "Name", "[", "0", "]", ")", "{", "layer", ".", "Name", "=", "singleLayer", ".", "Name", "[", "0", "]", ";", "}", "}", "if", "(", "singleLayer", ".", "Title", ")", "{", "if", "(", "singleLayer", ".", "Title", "[", "0", "]", ")", "{", "layer", ".", "Title", "=", "singleLayer", ".", "Title", "[", "0", "]", ";", "}", "}", "if", "(", "singleLayer", ".", "Abstract", ")", "{", "if", "(", "singleLayer", ".", "Abstract", "[", "0", "]", ")", "{", "layer", ".", "Abstract", "=", "singleLayer", ".", "Abstract", "[", "0", "]", ";", "}", "}", "layer", ".", "Layer", "=", "buildLayers", "(", "singleLayer", ".", "Layer", ")", ";", "layer", ".", "Name", "=", "determineLayerName", "(", "layer", ")", ";", "if", "(", "!", "(", "layer", ".", "Title", ")", ")", "{", "layer", ".", "Title", "=", "layer", ".", "Name", ";", "}", "layers", ".", "push", "(", "layer", ")", ";", "}", "}", "return", "layers", ";", "}" ]
It builds a simple array with layer information. @param {object} layersObject Object with layers from JSON. That JSON have to converted by the original XML GetCapabilities document. @returns {array} Array with layers and sublayers
[ "It", "builds", "a", "simple", "array", "with", "layer", "information", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L158-L208
train
stadt-bielefeld/wms-capabilities-tools
index.js
determineMaxWidth
function determineMaxWidth(json, version) { var maxWidth = 0; // Only available in WMS 1.3.0 if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].MaxWidth) { if (json.WMS_Capabilities.Service[0].MaxWidth[0]) { maxWidth = json.WMS_Capabilities.Service[0].MaxWidth[0]; } } } } } return maxWidth; }
javascript
function determineMaxWidth(json, version) { var maxWidth = 0; // Only available in WMS 1.3.0 if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].MaxWidth) { if (json.WMS_Capabilities.Service[0].MaxWidth[0]) { maxWidth = json.WMS_Capabilities.Service[0].MaxWidth[0]; } } } } } return maxWidth; }
[ "function", "determineMaxWidth", "(", "json", ",", "version", ")", "{", "var", "maxWidth", "=", "0", ";", "if", "(", "version", "==", "'1.3.0'", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "MaxWidth", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "MaxWidth", "[", "0", "]", ")", "{", "maxWidth", "=", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "MaxWidth", "[", "0", "]", ";", "}", "}", "}", "}", "}", "return", "maxWidth", ";", "}" ]
It determines the max width of a GetMap request in pixels. @param json {object} GetCapabilities document as JSON. @param version {string} Version of GetCapabilities document. @returns {integer} Max width of a GetMap request in pixels. It returns 0, if no value is available.
[ "It", "determines", "the", "max", "width", "of", "a", "GetMap", "request", "in", "pixels", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L220-L237
train
stadt-bielefeld/wms-capabilities-tools
index.js
determineMaxHeight
function determineMaxHeight(json, version) { var maxHeight = 0; // Only available in WMS 1.3.0 if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].MaxHeight) { if (json.WMS_Capabilities.Service[0].MaxHeight[0]) { maxHeight = json.WMS_Capabilities.Service[0].MaxHeight[0]; } } } } } return maxHeight; }
javascript
function determineMaxHeight(json, version) { var maxHeight = 0; // Only available in WMS 1.3.0 if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].MaxHeight) { if (json.WMS_Capabilities.Service[0].MaxHeight[0]) { maxHeight = json.WMS_Capabilities.Service[0].MaxHeight[0]; } } } } } return maxHeight; }
[ "function", "determineMaxHeight", "(", "json", ",", "version", ")", "{", "var", "maxHeight", "=", "0", ";", "if", "(", "version", "==", "'1.3.0'", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "MaxHeight", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "MaxHeight", "[", "0", "]", ")", "{", "maxHeight", "=", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "MaxHeight", "[", "0", "]", ";", "}", "}", "}", "}", "}", "return", "maxHeight", ";", "}" ]
It determines the max height of a GetMap request in pixels. @param json {object} GetCapabilities document as JSON. @param version {string} Version of GetCapabilities document. @returns {integer} Max height of a GetMap request in pixels. It returns 0, if no value is available.
[ "It", "determines", "the", "max", "height", "of", "a", "GetMap", "request", "in", "pixels", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L249-L266
train
stadt-bielefeld/wms-capabilities-tools
index.js
determineWMSTitle
function determineWMSTitle(json, version) { var ret = ''; if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].Title) { if (json.WMS_Capabilities.Service[0].Title[0]) { ret = json.WMS_Capabilities.Service[0].Title[0]; } } } } } else { if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') { if (json.WMT_MS_Capabilities.Service) { if (json.WMT_MS_Capabilities.Service[0]) { if (json.WMT_MS_Capabilities.Service[0].Title) { if (json.WMT_MS_Capabilities.Service[0].Title[0]) { ret = json.WMT_MS_Capabilities.Service[0].Title[0]; } } } } } } return ret; }
javascript
function determineWMSTitle(json, version) { var ret = ''; if (version == '1.3.0') { if (json.WMS_Capabilities.Service) { if (json.WMS_Capabilities.Service[0]) { if (json.WMS_Capabilities.Service[0].Title) { if (json.WMS_Capabilities.Service[0].Title[0]) { ret = json.WMS_Capabilities.Service[0].Title[0]; } } } } } else { if (version == '1.1.1' || version == '1.1.0' || version == '1.0.0') { if (json.WMT_MS_Capabilities.Service) { if (json.WMT_MS_Capabilities.Service[0]) { if (json.WMT_MS_Capabilities.Service[0].Title) { if (json.WMT_MS_Capabilities.Service[0].Title[0]) { ret = json.WMT_MS_Capabilities.Service[0].Title[0]; } } } } } } return ret; }
[ "function", "determineWMSTitle", "(", "json", ",", "version", ")", "{", "var", "ret", "=", "''", ";", "if", "(", "version", "==", "'1.3.0'", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "Title", ")", "{", "if", "(", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "Title", "[", "0", "]", ")", "{", "ret", "=", "json", ".", "WMS_Capabilities", ".", "Service", "[", "0", "]", ".", "Title", "[", "0", "]", ";", "}", "}", "}", "}", "}", "else", "{", "if", "(", "version", "==", "'1.1.1'", "||", "version", "==", "'1.1.0'", "||", "version", "==", "'1.0.0'", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ".", "Title", ")", "{", "if", "(", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ".", "Title", "[", "0", "]", ")", "{", "ret", "=", "json", ".", "WMT_MS_Capabilities", ".", "Service", "[", "0", "]", ".", "Title", "[", "0", "]", ";", "}", "}", "}", "}", "}", "}", "return", "ret", ";", "}" ]
It determines the WMS title. @param {object} json GetCapabilities document as JSON. @param {string} version Version of GetCapabilities document. @returns {string} WMS title.
[ "It", "determines", "the", "WMS", "title", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/index.js#L399-L427
train