id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
52,600
statticjs/stattic-parseurl
index.js
Get
function Get(url) { //Initialize the output var out = {"path": "", "file": "", "ext": "", "query": {}, "hashtag": ""}; //Save the file path out.path = url; //Find if exists a ? or # var p1 = out.path.indexOf('?'); var p2 = out.path.indexOf('#'); //Check for hashtag if(p2 != -1) { //Get the hashtag value out.hashtag = out.path.substring(p2 + 1); //Reset the file path out.path = out.path.substring(0, p2); } //Check for query if(p1 != -1) { //Get the query value var query = out.path.substring(p1 + 1); //Split the query value query = query.split('&'); //Insert into the output for(var i = 0; i < query.length; i++) { //Get the item var item = query[i].split('='); //Save to the output out.query[item[0]] = item[1]; } //Reset the file path out.path = out.path.substring(0, p1); } //Get the file name out.file = out.path.substring(out.path.lastIndexOf('/') + 1); //Get the extension out.ext = path.extname(out.file).replace('.', ''); //Return return out; }
javascript
function Get(url) { //Initialize the output var out = {"path": "", "file": "", "ext": "", "query": {}, "hashtag": ""}; //Save the file path out.path = url; //Find if exists a ? or # var p1 = out.path.indexOf('?'); var p2 = out.path.indexOf('#'); //Check for hashtag if(p2 != -1) { //Get the hashtag value out.hashtag = out.path.substring(p2 + 1); //Reset the file path out.path = out.path.substring(0, p2); } //Check for query if(p1 != -1) { //Get the query value var query = out.path.substring(p1 + 1); //Split the query value query = query.split('&'); //Insert into the output for(var i = 0; i < query.length; i++) { //Get the item var item = query[i].split('='); //Save to the output out.query[item[0]] = item[1]; } //Reset the file path out.path = out.path.substring(0, p1); } //Get the file name out.file = out.path.substring(out.path.lastIndexOf('/') + 1); //Get the extension out.ext = path.extname(out.file).replace('.', ''); //Return return out; }
[ "function", "Get", "(", "url", ")", "{", "//Initialize the output", "var", "out", "=", "{", "\"path\"", ":", "\"\"", ",", "\"file\"", ":", "\"\"", ",", "\"ext\"", ":", "\"\"", ",", "\"query\"", ":", "{", "}", ",", "\"hashtag\"", ":", "\"\"", "}", ";", "//Save the file path", "out", ".", "path", "=", "url", ";", "//Find if exists a ? or #", "var", "p1", "=", "out", ".", "path", ".", "indexOf", "(", "'?'", ")", ";", "var", "p2", "=", "out", ".", "path", ".", "indexOf", "(", "'#'", ")", ";", "//Check for hashtag", "if", "(", "p2", "!=", "-", "1", ")", "{", "//Get the hashtag value", "out", ".", "hashtag", "=", "out", ".", "path", ".", "substring", "(", "p2", "+", "1", ")", ";", "//Reset the file path", "out", ".", "path", "=", "out", ".", "path", ".", "substring", "(", "0", ",", "p2", ")", ";", "}", "//Check for query", "if", "(", "p1", "!=", "-", "1", ")", "{", "//Get the query value", "var", "query", "=", "out", ".", "path", ".", "substring", "(", "p1", "+", "1", ")", ";", "//Split the query value", "query", "=", "query", ".", "split", "(", "'&'", ")", ";", "//Insert into the output", "for", "(", "var", "i", "=", "0", ";", "i", "<", "query", ".", "length", ";", "i", "++", ")", "{", "//Get the item", "var", "item", "=", "query", "[", "i", "]", ".", "split", "(", "'='", ")", ";", "//Save to the output", "out", ".", "query", "[", "item", "[", "0", "]", "]", "=", "item", "[", "1", "]", ";", "}", "//Reset the file path", "out", ".", "path", "=", "out", ".", "path", ".", "substring", "(", "0", ",", "p1", ")", ";", "}", "//Get the file name", "out", ".", "file", "=", "out", ".", "path", ".", "substring", "(", "out", ".", "path", ".", "lastIndexOf", "(", "'/'", ")", "+", "1", ")", ";", "//Get the extension", "out", ".", "ext", "=", "path", ".", "extname", "(", "out", ".", "file", ")", ".", "replace", "(", "'.'", ",", "''", ")", ";", "//Return", "return", "out", ";", "}" ]
Get the ext name sync
[ "Get", "the", "ext", "name", "sync" ]
b479a413c94a8d11af7bed9f95a2f1c3029600e8
https://github.com/statticjs/stattic-parseurl/blob/b479a413c94a8d11af7bed9f95a2f1c3029600e8/index.js#L5-L58
52,601
Psychopoulet/node-promfs
lib/extends/_directoryToFile.js
_directoryToFile
function _directoryToFile (directory, target, separator, callback) { if ("undefined" === typeof directory) { throw new ReferenceError("missing \"directory\" argument"); } else if ("string" !== typeof directory) { throw new TypeError("\"directory\" argument is not a string"); } else if ("" === directory.trim()) { throw new Error("\"directory\" argument is empty"); } else if ("undefined" === typeof target) { throw new ReferenceError("missing \"target\" argument"); } else if ("string" !== typeof target) { throw new TypeError("\"target\" argument is not a string"); } else if ("" === target.trim()) { throw new Error("\"target\" argument is empty"); } else if ("undefined" === typeof callback && "undefined" === typeof separator) { throw new ReferenceError("missing \"callback\" argument"); } else if ("function" !== typeof callback && "function" !== typeof separator) { throw new TypeError("\"callback\" argument is not a function"); } else { let _callback = callback; let _separator = separator; if ("undefined" === typeof _callback) { _callback = separator; _separator = " "; } extractFiles(directory, (err, files) => { return err ? _callback(err) : filesToFile(files, target, _separator, _callback); }); } }
javascript
function _directoryToFile (directory, target, separator, callback) { if ("undefined" === typeof directory) { throw new ReferenceError("missing \"directory\" argument"); } else if ("string" !== typeof directory) { throw new TypeError("\"directory\" argument is not a string"); } else if ("" === directory.trim()) { throw new Error("\"directory\" argument is empty"); } else if ("undefined" === typeof target) { throw new ReferenceError("missing \"target\" argument"); } else if ("string" !== typeof target) { throw new TypeError("\"target\" argument is not a string"); } else if ("" === target.trim()) { throw new Error("\"target\" argument is empty"); } else if ("undefined" === typeof callback && "undefined" === typeof separator) { throw new ReferenceError("missing \"callback\" argument"); } else if ("function" !== typeof callback && "function" !== typeof separator) { throw new TypeError("\"callback\" argument is not a function"); } else { let _callback = callback; let _separator = separator; if ("undefined" === typeof _callback) { _callback = separator; _separator = " "; } extractFiles(directory, (err, files) => { return err ? _callback(err) : filesToFile(files, target, _separator, _callback); }); } }
[ "function", "_directoryToFile", "(", "directory", ",", "target", ",", "separator", ",", "callback", ")", "{", "if", "(", "\"undefined\"", "===", "typeof", "directory", ")", "{", "throw", "new", "ReferenceError", "(", "\"missing \\\"directory\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"string\"", "!==", "typeof", "directory", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"directory\\\" argument is not a string\"", ")", ";", "}", "else", "if", "(", "\"\"", "===", "directory", ".", "trim", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"\\\"directory\\\" argument is empty\"", ")", ";", "}", "else", "if", "(", "\"undefined\"", "===", "typeof", "target", ")", "{", "throw", "new", "ReferenceError", "(", "\"missing \\\"target\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"string\"", "!==", "typeof", "target", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"target\\\" argument is not a string\"", ")", ";", "}", "else", "if", "(", "\"\"", "===", "target", ".", "trim", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"\\\"target\\\" argument is empty\"", ")", ";", "}", "else", "if", "(", "\"undefined\"", "===", "typeof", "callback", "&&", "\"undefined\"", "===", "typeof", "separator", ")", "{", "throw", "new", "ReferenceError", "(", "\"missing \\\"callback\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"function\"", "!==", "typeof", "callback", "&&", "\"function\"", "!==", "typeof", "separator", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"callback\\\" argument is not a function\"", ")", ";", "}", "else", "{", "let", "_callback", "=", "callback", ";", "let", "_separator", "=", "separator", ";", "if", "(", "\"undefined\"", "===", "typeof", "_callback", ")", "{", "_callback", "=", "separator", ";", "_separator", "=", "\" \"", ";", "}", "extractFiles", "(", "directory", ",", "(", "err", ",", "files", ")", "=>", "{", "return", "err", "?", "_callback", "(", "err", ")", ":", "filesToFile", "(", "files", ",", "target", ",", "_separator", ",", "_callback", ")", ";", "}", ")", ";", "}", "}" ]
methods Async directoryToFile @param {string} directory : directory to work with @param {string} target : file to write in @param {string} separator : used to separate content (can be "") @param {function|null} callback : operation's result @returns {void}
[ "methods", "Async", "directoryToFile" ]
016e272fc58c6ef6eae5ea551a0e8873f0ac20cc
https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/lib/extends/_directoryToFile.js#L24-L66
52,602
AndCake/glassbil
src/store.js
deepFreeze
function deepFreeze(obj) { // if it's already frozen, don't bother going deep into it... if (obj === null || typeof obj === 'undefined' || typeof obj.toJS === 'function' || typeof obj !== 'object') { return obj; } // Retrieve the property names defined on obj let propNames = Object.getOwnPropertyNames(obj); let properties = {toJS: {value: mirror.bind(obj)}}; if (Array.isArray(obj)) { // create a copy and deep freeze all entries obj = obj.slice(0).map(deepFreeze); // re-attach some important methods ['map', 'forEach', 'find', 'indexOf', 'filter', 'some', 'every', 'lastIndexOf', 'slice'].forEach(fn => { properties[fn] = {value: function () { return deepFreeze(Array.prototype[fn].apply(obj, arguments));}}; }); } // Freeze properties before freezing self for (let index = 0, prop; prop = obj[propNames[index]], index < propNames.length; index += 1) { // Freeze prop if it is an object properties[propNames[index]] = { enumerable: true, get () { return deepFreeze(prop); }, set (newValue) { throw new Error('Cannot change property "' + propNames[index] + '" to "' + newValue + '" of an immutable object'); } } } // Freeze self (no-op if already frozen) return Object.freeze(Object.create(Object.getPrototypeOf(obj), properties)); }
javascript
function deepFreeze(obj) { // if it's already frozen, don't bother going deep into it... if (obj === null || typeof obj === 'undefined' || typeof obj.toJS === 'function' || typeof obj !== 'object') { return obj; } // Retrieve the property names defined on obj let propNames = Object.getOwnPropertyNames(obj); let properties = {toJS: {value: mirror.bind(obj)}}; if (Array.isArray(obj)) { // create a copy and deep freeze all entries obj = obj.slice(0).map(deepFreeze); // re-attach some important methods ['map', 'forEach', 'find', 'indexOf', 'filter', 'some', 'every', 'lastIndexOf', 'slice'].forEach(fn => { properties[fn] = {value: function () { return deepFreeze(Array.prototype[fn].apply(obj, arguments));}}; }); } // Freeze properties before freezing self for (let index = 0, prop; prop = obj[propNames[index]], index < propNames.length; index += 1) { // Freeze prop if it is an object properties[propNames[index]] = { enumerable: true, get () { return deepFreeze(prop); }, set (newValue) { throw new Error('Cannot change property "' + propNames[index] + '" to "' + newValue + '" of an immutable object'); } } } // Freeze self (no-op if already frozen) return Object.freeze(Object.create(Object.getPrototypeOf(obj), properties)); }
[ "function", "deepFreeze", "(", "obj", ")", "{", "// if it's already frozen, don't bother going deep into it...", "if", "(", "obj", "===", "null", "||", "typeof", "obj", "===", "'undefined'", "||", "typeof", "obj", ".", "toJS", "===", "'function'", "||", "typeof", "obj", "!==", "'object'", ")", "{", "return", "obj", ";", "}", "// Retrieve the property names defined on obj", "let", "propNames", "=", "Object", ".", "getOwnPropertyNames", "(", "obj", ")", ";", "let", "properties", "=", "{", "toJS", ":", "{", "value", ":", "mirror", ".", "bind", "(", "obj", ")", "}", "}", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "// create a copy and deep freeze all entries", "obj", "=", "obj", ".", "slice", "(", "0", ")", ".", "map", "(", "deepFreeze", ")", ";", "// re-attach some important methods", "[", "'map'", ",", "'forEach'", ",", "'find'", ",", "'indexOf'", ",", "'filter'", ",", "'some'", ",", "'every'", ",", "'lastIndexOf'", ",", "'slice'", "]", ".", "forEach", "(", "fn", "=>", "{", "properties", "[", "fn", "]", "=", "{", "value", ":", "function", "(", ")", "{", "return", "deepFreeze", "(", "Array", ".", "prototype", "[", "fn", "]", ".", "apply", "(", "obj", ",", "arguments", ")", ")", ";", "}", "}", ";", "}", ")", ";", "}", "// Freeze properties before freezing self", "for", "(", "let", "index", "=", "0", ",", "prop", ";", "prop", "=", "obj", "[", "propNames", "[", "index", "]", "]", ",", "index", "<", "propNames", ".", "length", ";", "index", "+=", "1", ")", "{", "// Freeze prop if it is an object", "properties", "[", "propNames", "[", "index", "]", "]", "=", "{", "enumerable", ":", "true", ",", "get", "(", ")", "{", "return", "deepFreeze", "(", "prop", ")", ";", "}", ",", "set", "(", "newValue", ")", "{", "throw", "new", "Error", "(", "'Cannot change property \"'", "+", "propNames", "[", "index", "]", "+", "'\" to \"'", "+", "newValue", "+", "'\" of an immutable object'", ")", ";", "}", "}", "}", "// Freeze self (no-op if already frozen)", "return", "Object", ".", "freeze", "(", "Object", ".", "create", "(", "Object", ".", "getPrototypeOf", "(", "obj", ")", ",", "properties", ")", ")", ";", "}" ]
Create an immutable object lazily. @param {Object} obj @returns {Object} the immutable object created
[ "Create", "an", "immutable", "object", "lazily", "." ]
4fec5179d61e86ba32dac136ebe966de0c224844
https://github.com/AndCake/glassbil/blob/4fec5179d61e86ba32dac136ebe966de0c224844/src/store.js#L28-L63
52,603
hotosm/oam-browser-filters
index.js
getCombination
function getCombination (dateFilter, resolutionFilter, dataTypeFilter) { var c = { date: getFilter(date, dateFilter), resolution: getFilter(resolution, resolutionFilter), dataType: getFilter(dataType, dataTypeFilter), searchParameters: getSearchParameters(dateFilter, resolutionFilter, dataTypeFilter) }; c.key = [c.date.key, c.resolution.key, c.dataType.key].join('_'); return c; }
javascript
function getCombination (dateFilter, resolutionFilter, dataTypeFilter) { var c = { date: getFilter(date, dateFilter), resolution: getFilter(resolution, resolutionFilter), dataType: getFilter(dataType, dataTypeFilter), searchParameters: getSearchParameters(dateFilter, resolutionFilter, dataTypeFilter) }; c.key = [c.date.key, c.resolution.key, c.dataType.key].join('_'); return c; }
[ "function", "getCombination", "(", "dateFilter", ",", "resolutionFilter", ",", "dataTypeFilter", ")", "{", "var", "c", "=", "{", "date", ":", "getFilter", "(", "date", ",", "dateFilter", ")", ",", "resolution", ":", "getFilter", "(", "resolution", ",", "resolutionFilter", ")", ",", "dataType", ":", "getFilter", "(", "dataType", ",", "dataTypeFilter", ")", ",", "searchParameters", ":", "getSearchParameters", "(", "dateFilter", ",", "resolutionFilter", ",", "dataTypeFilter", ")", "}", ";", "c", ".", "key", "=", "[", "c", ".", "date", ".", "key", ",", "c", ".", "resolution", ".", "key", ",", "c", ".", "dataType", ".", "key", "]", ".", "join", "(", "'_'", ")", ";", "return", "c", ";", "}" ]
Get the combination of the given dateFilter, resolutionFilter, dataTypeFilter combination.
[ "Get", "the", "combination", "of", "the", "given", "dateFilter", "resolutionFilter", "dataTypeFilter", "combination", "." ]
c3086925d2d198c1d7c2426eb7e0790e37a46013
https://github.com/hotosm/oam-browser-filters/blob/c3086925d2d198c1d7c2426eb7e0790e37a46013/index.js#L56-L66
52,604
hotosm/oam-browser-filters
index.js
getAllCombinations
function getAllCombinations () { var combinations = []; date.forEach(function (tf) { resolution.forEach(function (rf) { dataType.forEach(function (sf) { combinations.push(getCombination(tf, rf, sf)); }); }); }); return combinations; }
javascript
function getAllCombinations () { var combinations = []; date.forEach(function (tf) { resolution.forEach(function (rf) { dataType.forEach(function (sf) { combinations.push(getCombination(tf, rf, sf)); }); }); }); return combinations; }
[ "function", "getAllCombinations", "(", ")", "{", "var", "combinations", "=", "[", "]", ";", "date", ".", "forEach", "(", "function", "(", "tf", ")", "{", "resolution", ".", "forEach", "(", "function", "(", "rf", ")", "{", "dataType", ".", "forEach", "(", "function", "(", "sf", ")", "{", "combinations", ".", "push", "(", "getCombination", "(", "tf", ",", "rf", ",", "sf", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "combinations", ";", "}" ]
Get an array of all possible filter combinations.
[ "Get", "an", "array", "of", "all", "possible", "filter", "combinations", "." ]
c3086925d2d198c1d7c2426eb7e0790e37a46013
https://github.com/hotosm/oam-browser-filters/blob/c3086925d2d198c1d7c2426eb7e0790e37a46013/index.js#L101-L112
52,605
meltmedia/node-usher
lib/decider/tasks/while-loop.js
WhileLoop
function WhileLoop(name, deps, fragment, doneFn, options) { if (!(this instanceof WhileLoop)) { return new WhileLoop(name, deps, fragment, doneFn, options); } Task.apply(this, Array.prototype.slice.call(arguments)); this.fragment = fragment; if (!_.isFunction(doneFn)) { throw new Error('You must provide a function to indicate when the loop is complete'); } this.doneFn = doneFn; this.options = options || {}; }
javascript
function WhileLoop(name, deps, fragment, doneFn, options) { if (!(this instanceof WhileLoop)) { return new WhileLoop(name, deps, fragment, doneFn, options); } Task.apply(this, Array.prototype.slice.call(arguments)); this.fragment = fragment; if (!_.isFunction(doneFn)) { throw new Error('You must provide a function to indicate when the loop is complete'); } this.doneFn = doneFn; this.options = options || {}; }
[ "function", "WhileLoop", "(", "name", ",", "deps", ",", "fragment", ",", "doneFn", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "WhileLoop", ")", ")", "{", "return", "new", "WhileLoop", "(", "name", ",", "deps", ",", "fragment", ",", "doneFn", ",", "options", ")", ";", "}", "Task", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "this", ".", "fragment", "=", "fragment", ";", "if", "(", "!", "_", ".", "isFunction", "(", "doneFn", ")", ")", "{", "throw", "new", "Error", "(", "'You must provide a function to indicate when the loop is complete'", ")", ";", "}", "this", ".", "doneFn", "=", "doneFn", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
The loop executes the `fragment` until the `doneFn` returns a truthy value @constructor
[ "The", "loop", "executes", "the", "fragment", "until", "the", "doneFn", "returns", "a", "truthy", "value" ]
fe6183bf7097f84bef935e8d9c19463accc08ad6
https://github.com/meltmedia/node-usher/blob/fe6183bf7097f84bef935e8d9c19463accc08ad6/lib/decider/tasks/while-loop.js#L24-L39
52,606
jmendiara/gitftw
src/gitftw.js
readStream
function readStream(stream) { return new Promise(function(resolve) { stream.pipe(concat(function(data) { resolve(data.toString().trim()); })); }); }
javascript
function readStream(stream) { return new Promise(function(resolve) { stream.pipe(concat(function(data) { resolve(data.toString().trim()); })); }); }
[ "function", "readStream", "(", "stream", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "stream", ".", "pipe", "(", "concat", "(", "function", "(", "data", ")", "{", "resolve", "(", "data", ".", "toString", "(", ")", ".", "trim", "(", ")", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
Reads an stream @private @param {Stream} stream @returns {Promise} resolves with the value
[ "Reads", "an", "stream" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/gitftw.js#L51-L57
52,607
jmendiara/gitftw
src/gitftw.js
createGitCmdPromise
function createGitCmdPromise(args) { return new Promise(function(resolve, reject) { //Remove null values from the final git arguments args = args.filter(function(arg) { /*jshint eqnull:true */ return arg != null; }); /** * @name git#command * @event * @param {String} String the command issued */ events.emit('command', [gitCmd].concat(args).join(' ')); var proc = spawn(gitCmd, args); var output = Promise.join(readStream(proc.stdout), readStream(proc.stderr), function(stdout, stderr) { //Some warnings (like code === 1) are in stdout //fatal are in stderr. So try both return stdout || stderr; }).tap(function(output) { /** * @name git#result * @event * @param {String} String the captured output */ events.emit('result', output); }); proc.on('close', function(code) { //Some weird behaviours can arise with stdout and stderr values //cause writting to then is sync in *nix and async in windows. //Also, excessive treatment or long outputs that cause a drain //in the stderr & stdout streams, could lead us to having this proc //closed (and this callback called), and no complete values captured //in an eventual closure variable set then we emit the 'result' event //So using promises solves this syncronization output.then(function(output) { if (code !== 0) { var error = new Error('git exited with an error'); error.code = code; error.output = output; reject(error); } else { resolve(output); } }); }); proc.on('error', function(error) { reject(new Error(error)); }); }); }
javascript
function createGitCmdPromise(args) { return new Promise(function(resolve, reject) { //Remove null values from the final git arguments args = args.filter(function(arg) { /*jshint eqnull:true */ return arg != null; }); /** * @name git#command * @event * @param {String} String the command issued */ events.emit('command', [gitCmd].concat(args).join(' ')); var proc = spawn(gitCmd, args); var output = Promise.join(readStream(proc.stdout), readStream(proc.stderr), function(stdout, stderr) { //Some warnings (like code === 1) are in stdout //fatal are in stderr. So try both return stdout || stderr; }).tap(function(output) { /** * @name git#result * @event * @param {String} String the captured output */ events.emit('result', output); }); proc.on('close', function(code) { //Some weird behaviours can arise with stdout and stderr values //cause writting to then is sync in *nix and async in windows. //Also, excessive treatment or long outputs that cause a drain //in the stderr & stdout streams, could lead us to having this proc //closed (and this callback called), and no complete values captured //in an eventual closure variable set then we emit the 'result' event //So using promises solves this syncronization output.then(function(output) { if (code !== 0) { var error = new Error('git exited with an error'); error.code = code; error.output = output; reject(error); } else { resolve(output); } }); }); proc.on('error', function(error) { reject(new Error(error)); }); }); }
[ "function", "createGitCmdPromise", "(", "args", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "//Remove null values from the final git arguments", "args", "=", "args", ".", "filter", "(", "function", "(", "arg", ")", "{", "/*jshint eqnull:true */", "return", "arg", "!=", "null", ";", "}", ")", ";", "/**\n * @name git#command\n * @event\n * @param {String} String the command issued\n */", "events", ".", "emit", "(", "'command'", ",", "[", "gitCmd", "]", ".", "concat", "(", "args", ")", ".", "join", "(", "' '", ")", ")", ";", "var", "proc", "=", "spawn", "(", "gitCmd", ",", "args", ")", ";", "var", "output", "=", "Promise", ".", "join", "(", "readStream", "(", "proc", ".", "stdout", ")", ",", "readStream", "(", "proc", ".", "stderr", ")", ",", "function", "(", "stdout", ",", "stderr", ")", "{", "//Some warnings (like code === 1) are in stdout", "//fatal are in stderr. So try both", "return", "stdout", "||", "stderr", ";", "}", ")", ".", "tap", "(", "function", "(", "output", ")", "{", "/**\n * @name git#result\n * @event\n * @param {String} String the captured output\n */", "events", ".", "emit", "(", "'result'", ",", "output", ")", ";", "}", ")", ";", "proc", ".", "on", "(", "'close'", ",", "function", "(", "code", ")", "{", "//Some weird behaviours can arise with stdout and stderr values", "//cause writting to then is sync in *nix and async in windows.", "//Also, excessive treatment or long outputs that cause a drain", "//in the stderr & stdout streams, could lead us to having this proc", "//closed (and this callback called), and no complete values captured", "//in an eventual closure variable set then we emit the 'result' event", "//So using promises solves this syncronization", "output", ".", "then", "(", "function", "(", "output", ")", "{", "if", "(", "code", "!==", "0", ")", "{", "var", "error", "=", "new", "Error", "(", "'git exited with an error'", ")", ";", "error", ".", "code", "=", "code", ";", "error", ".", "output", "=", "output", ";", "reject", "(", "error", ")", ";", "}", "else", "{", "resolve", "(", "output", ")", ";", "}", "}", ")", ";", "}", ")", ";", "proc", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "reject", "(", "new", "Error", "(", "error", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates a promise for a Git Execution @private @param {Resolvable|Array<String|null>} args The arguments to pass to git command @returns {Promise}
[ "Creates", "a", "promise", "for", "a", "Git", "Execution" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/gitftw.js#L66-L120
52,608
jmendiara/gitftw
src/gitftw.js
spawnGit
function spawnGit(args) { //don't bother with throws, they are catched by promises gitCmd = gitCmd || which('git'); assert.ok(args, 'arguments to git is mandatory'); executionCount++; if (executionPromise) { executionPromise = executionPromise.then( createGitCmdPromise.bind(null, args), createGitCmdPromise.bind(null, args) ); } else { executionPromise = createGitCmdPromise(args); } return executionPromise.finally(function() { if (--executionCount === 0) { executionPromise = null; } }); }
javascript
function spawnGit(args) { //don't bother with throws, they are catched by promises gitCmd = gitCmd || which('git'); assert.ok(args, 'arguments to git is mandatory'); executionCount++; if (executionPromise) { executionPromise = executionPromise.then( createGitCmdPromise.bind(null, args), createGitCmdPromise.bind(null, args) ); } else { executionPromise = createGitCmdPromise(args); } return executionPromise.finally(function() { if (--executionCount === 0) { executionPromise = null; } }); }
[ "function", "spawnGit", "(", "args", ")", "{", "//don't bother with throws, they are catched by promises", "gitCmd", "=", "gitCmd", "||", "which", "(", "'git'", ")", ";", "assert", ".", "ok", "(", "args", ",", "'arguments to git is mandatory'", ")", ";", "executionCount", "++", ";", "if", "(", "executionPromise", ")", "{", "executionPromise", "=", "executionPromise", ".", "then", "(", "createGitCmdPromise", ".", "bind", "(", "null", ",", "args", ")", ",", "createGitCmdPromise", ".", "bind", "(", "null", ",", "args", ")", ")", ";", "}", "else", "{", "executionPromise", "=", "createGitCmdPromise", "(", "args", ")", ";", "}", "return", "executionPromise", ".", "finally", "(", "function", "(", ")", "{", "if", "(", "--", "executionCount", "===", "0", ")", "{", "executionPromise", "=", "null", ";", "}", "}", ")", ";", "}" ]
Spawns a git process with the provider arguments This function is called when you call directly the require of `gitftw` If you provide a second parameter DISCLAIMER: I've not found any way to document this in jsdoc and this template in a proper way. Sorry for the possible missunderstanding @example var git = require('gitftw'); //executes a `git version` git(['version'], function(err, data) { console.log(data);}); //or git(['version']).then(console.log); @fires command the git command executed @fires result the result from the command line @param {Resolvable|Array<String|null>} args The arguments to pass to git command @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with the git output Rejects with an invalid/not found git cmd Rejects with an error with the git cmd spawn Rejects with git exits with an error
[ "Spawns", "a", "git", "process", "with", "the", "provider", "arguments", "This", "function", "is", "called", "when", "you", "call", "directly", "the", "require", "of", "gitftw" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/gitftw.js#L149-L169
52,609
jmendiara/gitftw
src/gitftw.js
decorator
function decorator(fn, options, cb) { if (typeof options === 'function') { cb = options; options = null; } return resolvable(options) .then(fn) .nodeify(cb); }
javascript
function decorator(fn, options, cb) { if (typeof options === 'function') { cb = options; options = null; } return resolvable(options) .then(fn) .nodeify(cb); }
[ "function", "decorator", "(", "fn", ",", "options", ",", "cb", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "cb", "=", "options", ";", "options", "=", "null", ";", "}", "return", "resolvable", "(", "options", ")", ".", "then", "(", "fn", ")", ".", "nodeify", "(", "cb", ")", ";", "}" ]
Decorates a function resolving its resolvables before calling it, adding node callback api @private @param {Function} fn The function to decorate @param {Object} [options] The options object passed to the command @param {callback} [cb] Callback used when in callback mode @returns {Promise|undefined} A promise when in promise API
[ "Decorates", "a", "function", "resolving", "its", "resolvables", "before", "calling", "it", "adding", "node", "callback", "api" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/gitftw.js#L181-L190
52,610
zland/zland-map
actions/MapActionCreators.js
function(projection, map) { Dispatcher.dispatch({ type: Constants.MAP_PROJECTION, projection: projection, map: map }); }
javascript
function(projection, map) { Dispatcher.dispatch({ type: Constants.MAP_PROJECTION, projection: projection, map: map }); }
[ "function", "(", "projection", ",", "map", ")", "{", "Dispatcher", ".", "dispatch", "(", "{", "type", ":", "Constants", ".", "MAP_PROJECTION", ",", "projection", ":", "projection", ",", "map", ":", "map", "}", ")", ";", "}" ]
when goole map is rendered the stores need to get the projection to convert positions from pixels to latlng and vice versa @param {Object} projection google map projection @param {Object} map google map object
[ "when", "goole", "map", "is", "rendered", "the", "stores", "need", "to", "get", "the", "projection", "to", "convert", "positions", "from", "pixels", "to", "latlng", "and", "vice", "versa" ]
adff5510e3c267ce87e166f0a0354c7a85db8752
https://github.com/zland/zland-map/blob/adff5510e3c267ce87e166f0a0354c7a85db8752/actions/MapActionCreators.js#L33-L39
52,611
inviqa/deck-task-registry
src/assets/buildFonts.js
buildFonts
function buildFonts(conf, undertaker) { const fontSrc = path.join(conf.themeConfig.root, conf.themeConfig.fonts.src, '**', '*.{eot,ttf,woff,woff2,otf,svg}'); const fontDest = path.join(conf.themeConfig.root, conf.themeConfig.fonts.dest); return undertaker.src(fontSrc) .pipe(undertaker.dest(fontDest)); }
javascript
function buildFonts(conf, undertaker) { const fontSrc = path.join(conf.themeConfig.root, conf.themeConfig.fonts.src, '**', '*.{eot,ttf,woff,woff2,otf,svg}'); const fontDest = path.join(conf.themeConfig.root, conf.themeConfig.fonts.dest); return undertaker.src(fontSrc) .pipe(undertaker.dest(fontDest)); }
[ "function", "buildFonts", "(", "conf", ",", "undertaker", ")", "{", "const", "fontSrc", "=", "path", ".", "join", "(", "conf", ".", "themeConfig", ".", "root", ",", "conf", ".", "themeConfig", ".", "fonts", ".", "src", ",", "'**'", ",", "'*.{eot,ttf,woff,woff2,otf,svg}'", ")", ";", "const", "fontDest", "=", "path", ".", "join", "(", "conf", ".", "themeConfig", ".", "root", ",", "conf", ".", "themeConfig", ".", "fonts", ".", "dest", ")", ";", "return", "undertaker", ".", "src", "(", "fontSrc", ")", ".", "pipe", "(", "undertaker", ".", "dest", "(", "fontDest", ")", ")", ";", "}" ]
Build project fonts. @param {ConfigParser} conf A configuration parser object. @param {Undertaker} undertaker An Undertaker instance. @returns {Stream} A stream of files.
[ "Build", "project", "fonts", "." ]
4c31787b978e9d99a47052e090d4589a50cd3015
https://github.com/inviqa/deck-task-registry/blob/4c31787b978e9d99a47052e090d4589a50cd3015/src/assets/buildFonts.js#L13-L21
52,612
konfirm/gulp-chain
lib/chain.js
chain
function chain() { let arg = Array.from(arguments), pipe = arg.length > 0 ? arg.shift() : stream => stream; return function() { let writer = through.obj(); return duplexer( {objectMode: true}, writer, pipe.apply(null, [writer].concat(merge(arguments, arg))) ); }; }
javascript
function chain() { let arg = Array.from(arguments), pipe = arg.length > 0 ? arg.shift() : stream => stream; return function() { let writer = through.obj(); return duplexer( {objectMode: true}, writer, pipe.apply(null, [writer].concat(merge(arguments, arg))) ); }; }
[ "function", "chain", "(", ")", "{", "let", "arg", "=", "Array", ".", "from", "(", "arguments", ")", ",", "pipe", "=", "arg", ".", "length", ">", "0", "?", "arg", ".", "shift", "(", ")", ":", "stream", "=>", "stream", ";", "return", "function", "(", ")", "{", "let", "writer", "=", "through", ".", "obj", "(", ")", ";", "return", "duplexer", "(", "{", "objectMode", ":", "true", "}", ",", "writer", ",", "pipe", ".", "apply", "(", "null", ",", "[", "writer", "]", ".", "concat", "(", "merge", "(", "arguments", ",", "arg", ")", ")", ")", ")", ";", "}", ";", "}" ]
Prepare a gulp-plugin like chain function @name chain @access internal @param variadic ... @return function
[ "Prepare", "a", "gulp", "-", "plugin", "like", "chain", "function" ]
69e604ea85352a5910885ee0a62c9812d208109e
https://github.com/konfirm/gulp-chain/blob/69e604ea85352a5910885ee0a62c9812d208109e/lib/chain.js#L34-L47
52,613
mcax/reporter
lib/reporter.js
coordinates
function coordinates(index, source) { if (!index || !source) return void 0; var lines = source .slice(0, index) .split('\n'); return lines.length + ':' + lines.pop().length; }
javascript
function coordinates(index, source) { if (!index || !source) return void 0; var lines = source .slice(0, index) .split('\n'); return lines.length + ':' + lines.pop().length; }
[ "function", "coordinates", "(", "index", ",", "source", ")", "{", "if", "(", "!", "index", "||", "!", "source", ")", "return", "void", "0", ";", "var", "lines", "=", "source", ".", "slice", "(", "0", ",", "index", ")", ".", "split", "(", "'\\n'", ")", ";", "return", "lines", ".", "length", "+", "':'", "+", "lines", ".", "pop", "(", ")", ".", "length", ";", "}" ]
Get row and column number in given string at given index. @param {Number} index @param {String} source @return {String} @api private
[ "Get", "row", "and", "column", "number", "in", "given", "string", "at", "given", "index", "." ]
11b70b80001cb6d339561c4efbaef97e11022438
https://github.com/mcax/reporter/blob/11b70b80001cb6d339561c4efbaef97e11022438/lib/reporter.js#L32-L41
52,614
MakerCollider/node-red-contrib-smartnode-hook
html/scripts/RGraph/RGraph.common.effects.js
iterator
function iterator () { // Begin by clearing the canvas RG.clear(obj.canvas, color); obj.context.save(); // First draw the circle and clip to it obj.context.beginPath(); obj.context.arc(centerx, centery, currentRadius, 0, RG.TWOPI, false); obj.context.clip(); // Clear the canvas to a white color if (opt.background) { RG.clear(obj.canvas, opt.background); } // Now draw the chart obj.Draw(); obj.context.restore(); // Increment the radius if (currentRadius < targetRadius) { currentRadius += step; RG.Effects.updateCanvas(iterator); } else { callback(obj); } }
javascript
function iterator () { // Begin by clearing the canvas RG.clear(obj.canvas, color); obj.context.save(); // First draw the circle and clip to it obj.context.beginPath(); obj.context.arc(centerx, centery, currentRadius, 0, RG.TWOPI, false); obj.context.clip(); // Clear the canvas to a white color if (opt.background) { RG.clear(obj.canvas, opt.background); } // Now draw the chart obj.Draw(); obj.context.restore(); // Increment the radius if (currentRadius < targetRadius) { currentRadius += step; RG.Effects.updateCanvas(iterator); } else { callback(obj); } }
[ "function", "iterator", "(", ")", "{", "// Begin by clearing the canvas", "RG", ".", "clear", "(", "obj", ".", "canvas", ",", "color", ")", ";", "obj", ".", "context", ".", "save", "(", ")", ";", "// First draw the circle and clip to it", "obj", ".", "context", ".", "beginPath", "(", ")", ";", "obj", ".", "context", ".", "arc", "(", "centerx", ",", "centery", ",", "currentRadius", ",", "0", ",", "RG", ".", "TWOPI", ",", "false", ")", ";", "obj", ".", "context", ".", "clip", "(", ")", ";", "// Clear the canvas to a white color", "if", "(", "opt", ".", "background", ")", "{", "RG", ".", "clear", "(", "obj", ".", "canvas", ",", "opt", ".", "background", ")", ";", "}", "// Now draw the chart", "obj", ".", "Draw", "(", ")", ";", "obj", ".", "context", ".", "restore", "(", ")", ";", "// Increment the radius", "if", "(", "currentRadius", "<", "targetRadius", ")", "{", "currentRadius", "+=", "step", ";", "RG", ".", "Effects", ".", "updateCanvas", "(", "iterator", ")", ";", "}", "else", "{", "callback", "(", "obj", ")", ";", "}", "}" ]
This is the iterator function which gradually increases the radius of the clip circle
[ "This", "is", "the", "iterator", "function", "which", "gradually", "increases", "the", "radius", "of", "the", "clip", "circle" ]
245c267e832968bad880ca009929043e82c7bc25
https://github.com/MakerCollider/node-red-contrib-smartnode-hook/blob/245c267e832968bad880ca009929043e82c7bc25/html/scripts/RGraph/RGraph.common.effects.js#L773-L802
52,615
shaozilee/tufu
lib/tufu.js
Tufu
function Tufu(src){ if(!(this instanceof Tufu)){ return new Tufu(src); } this.src = src; var bufferData = fs.readFileSync(this.src); this.codec = Tufu.adaptCodec(bufferData); this.imageData = this.codec.decode(bufferData); //set image quality 100% this.quality = 100; }
javascript
function Tufu(src){ if(!(this instanceof Tufu)){ return new Tufu(src); } this.src = src; var bufferData = fs.readFileSync(this.src); this.codec = Tufu.adaptCodec(bufferData); this.imageData = this.codec.decode(bufferData); //set image quality 100% this.quality = 100; }
[ "function", "Tufu", "(", "src", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Tufu", ")", ")", "{", "return", "new", "Tufu", "(", "src", ")", ";", "}", "this", ".", "src", "=", "src", ";", "var", "bufferData", "=", "fs", ".", "readFileSync", "(", "this", ".", "src", ")", ";", "this", ".", "codec", "=", "Tufu", ".", "adaptCodec", "(", "bufferData", ")", ";", "this", ".", "imageData", "=", "this", ".", "codec", ".", "decode", "(", "bufferData", ")", ";", "//set image quality 100%", "this", ".", "quality", "=", "100", ";", "}" ]
start of Tufu @param {[String]} filePath @return {[Tufu]} new instance Tufu
[ "start", "of", "Tufu" ]
06ae6c7bb0f32a1c186545366dac1dde2fd6d84e
https://github.com/shaozilee/tufu/blob/06ae6c7bb0f32a1c186545366dac1dde2fd6d84e/lib/tufu.js#L35-L45
52,616
nathanhood/postcss-js-mixins
index.js
castArgument
function castArgument(arg) { if (isNumber(arg)) { return parseFloat(arg); } if (helpers.isFraction(arg)) { arg = arg.split('/'); return arg[0] / arg[1]; } if (arg === 'false' || arg === 'true') { return arg === 'true'; } return arg.length ? arg : undefined; }
javascript
function castArgument(arg) { if (isNumber(arg)) { return parseFloat(arg); } if (helpers.isFraction(arg)) { arg = arg.split('/'); return arg[0] / arg[1]; } if (arg === 'false' || arg === 'true') { return arg === 'true'; } return arg.length ? arg : undefined; }
[ "function", "castArgument", "(", "arg", ")", "{", "if", "(", "isNumber", "(", "arg", ")", ")", "{", "return", "parseFloat", "(", "arg", ")", ";", "}", "if", "(", "helpers", ".", "isFraction", "(", "arg", ")", ")", "{", "arg", "=", "arg", ".", "split", "(", "'/'", ")", ";", "return", "arg", "[", "0", "]", "/", "arg", "[", "1", "]", ";", "}", "if", "(", "arg", "===", "'false'", "||", "arg", "===", "'true'", ")", "{", "return", "arg", "===", "'true'", ";", "}", "return", "arg", ".", "length", "?", "arg", ":", "undefined", ";", "}" ]
Convert argument to proper type @param {string} arg @returns {*}
[ "Convert", "argument", "to", "proper", "type" ]
b43e94b5eaa4b1f169d34ee98c65b8c94bee30b5
https://github.com/nathanhood/postcss-js-mixins/blob/b43e94b5eaa4b1f169d34ee98c65b8c94bee30b5/index.js#L28-L44
52,617
nathanhood/postcss-js-mixins
index.js
getArguments
function getArguments(name, mixin, obj) { let named = obj.named, ordered = obj.ordered, args = [], parameters; // Cache function parameter names if (! mixinArguments[name]) { mixinArguments[name] = mixin.toString() // Strip out quoted strings (stripping possible commas from parameters) .replace(/'((?:[^'\\])*)'|"((?:[^"\\])*)"/g, '') // Pull out parameters from function .match(/(?:function)?\s?.*?\s?\(([^)]*)\)/)[1] .split(',') .map(function(arg) { return arg.split('=')[0].trim(); }); } parameters = mixinArguments[name]; Object.keys(named).forEach(key => { parameters.forEach((param, i) => { if (key === param) { args[i] = castArgument(named[key]); } }); }); ordered.forEach((arg, i) => { args[i] = castArgument(arg); }); return args; }
javascript
function getArguments(name, mixin, obj) { let named = obj.named, ordered = obj.ordered, args = [], parameters; // Cache function parameter names if (! mixinArguments[name]) { mixinArguments[name] = mixin.toString() // Strip out quoted strings (stripping possible commas from parameters) .replace(/'((?:[^'\\])*)'|"((?:[^"\\])*)"/g, '') // Pull out parameters from function .match(/(?:function)?\s?.*?\s?\(([^)]*)\)/)[1] .split(',') .map(function(arg) { return arg.split('=')[0].trim(); }); } parameters = mixinArguments[name]; Object.keys(named).forEach(key => { parameters.forEach((param, i) => { if (key === param) { args[i] = castArgument(named[key]); } }); }); ordered.forEach((arg, i) => { args[i] = castArgument(arg); }); return args; }
[ "function", "getArguments", "(", "name", ",", "mixin", ",", "obj", ")", "{", "let", "named", "=", "obj", ".", "named", ",", "ordered", "=", "obj", ".", "ordered", ",", "args", "=", "[", "]", ",", "parameters", ";", "// Cache function parameter names", "if", "(", "!", "mixinArguments", "[", "name", "]", ")", "{", "mixinArguments", "[", "name", "]", "=", "mixin", ".", "toString", "(", ")", "// Strip out quoted strings (stripping possible commas from parameters)", ".", "replace", "(", "/", "'((?:[^'\\\\])*)'|\"((?:[^\"\\\\])*)\"", "/", "g", ",", "''", ")", "// Pull out parameters from function", ".", "match", "(", "/", "(?:function)?\\s?.*?\\s?\\(([^)]*)\\)", "/", ")", "[", "1", "]", ".", "split", "(", "','", ")", ".", "map", "(", "function", "(", "arg", ")", "{", "return", "arg", ".", "split", "(", "'='", ")", "[", "0", "]", ".", "trim", "(", ")", ";", "}", ")", ";", "}", "parameters", "=", "mixinArguments", "[", "name", "]", ";", "Object", ".", "keys", "(", "named", ")", ".", "forEach", "(", "key", "=>", "{", "parameters", ".", "forEach", "(", "(", "param", ",", "i", ")", "=>", "{", "if", "(", "key", "===", "param", ")", "{", "args", "[", "i", "]", "=", "castArgument", "(", "named", "[", "key", "]", ")", ";", "}", "}", ")", ";", "}", ")", ";", "ordered", ".", "forEach", "(", "(", "arg", ",", "i", ")", "=>", "{", "args", "[", "i", "]", "=", "castArgument", "(", "arg", ")", ";", "}", ")", ";", "return", "args", ";", "}" ]
Generate arguments array @param {string} name @param {function} mixin @param {object} obj - mixin arguments property @returns {Array}
[ "Generate", "arguments", "array" ]
b43e94b5eaa4b1f169d34ee98c65b8c94bee30b5
https://github.com/nathanhood/postcss-js-mixins/blob/b43e94b5eaa4b1f169d34ee98c65b8c94bee30b5/index.js#L54-L88
52,618
gethuman/pancakes-recipe
services/adapters/apiclient/apiclient.adapter.js
ApiclientAdapter
function ApiclientAdapter(resource) { this.admin = admin; this.resource = resource || {}; // loop through API interface for resource to get methods to expose var me = this; _.each(resource.api, function (methodInfo, httpMethod) { _.each(methodInfo, function (operation, path) { me[operation] = function (req) { return me.send(httpMethod, path, req); }; }); }); }
javascript
function ApiclientAdapter(resource) { this.admin = admin; this.resource = resource || {}; // loop through API interface for resource to get methods to expose var me = this; _.each(resource.api, function (methodInfo, httpMethod) { _.each(methodInfo, function (operation, path) { me[operation] = function (req) { return me.send(httpMethod, path, req); }; }); }); }
[ "function", "ApiclientAdapter", "(", "resource", ")", "{", "this", ".", "admin", "=", "admin", ";", "this", ".", "resource", "=", "resource", "||", "{", "}", ";", "// loop through API interface for resource to get methods to expose", "var", "me", "=", "this", ";", "_", ".", "each", "(", "resource", ".", "api", ",", "function", "(", "methodInfo", ",", "httpMethod", ")", "{", "_", ".", "each", "(", "methodInfo", ",", "function", "(", "operation", ",", "path", ")", "{", "me", "[", "operation", "]", "=", "function", "(", "req", ")", "{", "return", "me", ".", "send", "(", "httpMethod", ",", "path", ",", "req", ")", ";", "}", ";", "}", ")", ";", "}", ")", ";", "}" ]
Initialize the methods for this interface using the resource. This will loop through the routes defined in the api section of the resource file and auto generate method interfaces which all end up make REST API calls. @param resource @constructor
[ "Initialize", "the", "methods", "for", "this", "interface", "using", "the", "resource", ".", "This", "will", "loop", "through", "the", "routes", "defined", "in", "the", "api", "section", "of", "the", "resource", "file", "and", "auto", "generate", "method", "interfaces", "which", "all", "end", "up", "make", "REST", "API", "calls", "." ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/services/adapters/apiclient/apiclient.adapter.js#L23-L36
52,619
gethuman/pancakes-recipe
services/adapters/apiclient/apiclient.adapter.js
init
function init(config) { var tokenConfig = config.security.token || {}; var privateKey = tokenConfig.privateKey; var decryptedToken = { _id: tokenConfig.webserverId, authToken: tokenConfig.webserverToken }; var jwt = jsonwebtoken.sign(decryptedToken, privateKey); headers = { 'Authorization': 'Bearer ' + jwt }; admin._id = mongo.newObjectId('000000000000000000000000'); admin.name = 'systemAdmin'; admin.type = 'user'; admin.role = 'admin'; var apiConfig = config.api || {}; var host = apiConfig.internalHost || apiConfig.host; // from web server to api use internalHost name var useSSL = apiConfig.serverUseSSL !== undefined ? apiConfig.serverUseSSL : config.useSSL; baseUrl = (useSSL ? 'https://' : 'http://') + host; var port = config.api.port; if (port !== 80 && port !== 443) { baseUrl += ':' + port; } baseUrl += '/' + config.api.version; return config; }
javascript
function init(config) { var tokenConfig = config.security.token || {}; var privateKey = tokenConfig.privateKey; var decryptedToken = { _id: tokenConfig.webserverId, authToken: tokenConfig.webserverToken }; var jwt = jsonwebtoken.sign(decryptedToken, privateKey); headers = { 'Authorization': 'Bearer ' + jwt }; admin._id = mongo.newObjectId('000000000000000000000000'); admin.name = 'systemAdmin'; admin.type = 'user'; admin.role = 'admin'; var apiConfig = config.api || {}; var host = apiConfig.internalHost || apiConfig.host; // from web server to api use internalHost name var useSSL = apiConfig.serverUseSSL !== undefined ? apiConfig.serverUseSSL : config.useSSL; baseUrl = (useSSL ? 'https://' : 'http://') + host; var port = config.api.port; if (port !== 80 && port !== 443) { baseUrl += ':' + port; } baseUrl += '/' + config.api.version; return config; }
[ "function", "init", "(", "config", ")", "{", "var", "tokenConfig", "=", "config", ".", "security", ".", "token", "||", "{", "}", ";", "var", "privateKey", "=", "tokenConfig", ".", "privateKey", ";", "var", "decryptedToken", "=", "{", "_id", ":", "tokenConfig", ".", "webserverId", ",", "authToken", ":", "tokenConfig", ".", "webserverToken", "}", ";", "var", "jwt", "=", "jsonwebtoken", ".", "sign", "(", "decryptedToken", ",", "privateKey", ")", ";", "headers", "=", "{", "'Authorization'", ":", "'Bearer '", "+", "jwt", "}", ";", "admin", ".", "_id", "=", "mongo", ".", "newObjectId", "(", "'000000000000000000000000'", ")", ";", "admin", ".", "name", "=", "'systemAdmin'", ";", "admin", ".", "type", "=", "'user'", ";", "admin", ".", "role", "=", "'admin'", ";", "var", "apiConfig", "=", "config", ".", "api", "||", "{", "}", ";", "var", "host", "=", "apiConfig", ".", "internalHost", "||", "apiConfig", ".", "host", ";", "// from web server to api use internalHost name", "var", "useSSL", "=", "apiConfig", ".", "serverUseSSL", "!==", "undefined", "?", "apiConfig", ".", "serverUseSSL", ":", "config", ".", "useSSL", ";", "baseUrl", "=", "(", "useSSL", "?", "'https://'", ":", "'http://'", ")", "+", "host", ";", "var", "port", "=", "config", ".", "api", ".", "port", ";", "if", "(", "port", "!==", "80", "&&", "port", "!==", "443", ")", "{", "baseUrl", "+=", "':'", "+", "port", ";", "}", "baseUrl", "+=", "'/'", "+", "config", ".", "api", ".", "version", ";", "return", "config", ";", "}" ]
Init called at startup and is used to @param config
[ "Init", "called", "at", "startup", "and", "is", "used", "to" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/services/adapters/apiclient/apiclient.adapter.js#L42-L72
52,620
gethuman/pancakes-recipe
services/adapters/apiclient/apiclient.adapter.js
send
function send(httpMethod, path, req) { req = req || {}; httpMethod = httpMethod.toUpperCase(); var deferred = Q.defer(); var url = baseUrl + path; var data = req.data || {}; // separate out data from request delete req.data; var isAdmin = req.caller && req.caller.role === 'admin'; delete req.caller; var id = req._id || data._id; // get id from request or data if (req._id) { delete req._id; } // delete id from request so no dupe var session = cls.getNamespace('appSession'); var caller = session && session.active && session.get('caller'); if (caller && !isAdmin) { _.extend(req, { // onBehalfOf used by API to know who is the caller onBehalfOfType: caller.type, onBehalfOfId: caller._id + '', onBehalfOfRole: caller.role, onBehalfOfName: caller.name }); } _.each(req, function (val, key) { if (!_.isString(val)) { req[key] = JSON.stringify(val); } }); // replace the ID portion of the URL url = id ? url.replace('{_id}', id + '') : url.replace('/{_id}', ''); var reqConfig = { headers: headers, url: url, method: httpMethod, qs: _.isEmpty(req) ? undefined : req, json: _.isEmpty(data) ? true : data }; // if baseUrl not there yet, wait for 100 seconds until it is (i.e. during system startup) if (!baseUrl) { setTimeout(function () { makeRequest(reqConfig, deferred); }, 100); } else { makeRequest(reqConfig, deferred); } return deferred.promise; }
javascript
function send(httpMethod, path, req) { req = req || {}; httpMethod = httpMethod.toUpperCase(); var deferred = Q.defer(); var url = baseUrl + path; var data = req.data || {}; // separate out data from request delete req.data; var isAdmin = req.caller && req.caller.role === 'admin'; delete req.caller; var id = req._id || data._id; // get id from request or data if (req._id) { delete req._id; } // delete id from request so no dupe var session = cls.getNamespace('appSession'); var caller = session && session.active && session.get('caller'); if (caller && !isAdmin) { _.extend(req, { // onBehalfOf used by API to know who is the caller onBehalfOfType: caller.type, onBehalfOfId: caller._id + '', onBehalfOfRole: caller.role, onBehalfOfName: caller.name }); } _.each(req, function (val, key) { if (!_.isString(val)) { req[key] = JSON.stringify(val); } }); // replace the ID portion of the URL url = id ? url.replace('{_id}', id + '') : url.replace('/{_id}', ''); var reqConfig = { headers: headers, url: url, method: httpMethod, qs: _.isEmpty(req) ? undefined : req, json: _.isEmpty(data) ? true : data }; // if baseUrl not there yet, wait for 100 seconds until it is (i.e. during system startup) if (!baseUrl) { setTimeout(function () { makeRequest(reqConfig, deferred); }, 100); } else { makeRequest(reqConfig, deferred); } return deferred.promise; }
[ "function", "send", "(", "httpMethod", ",", "path", ",", "req", ")", "{", "req", "=", "req", "||", "{", "}", ";", "httpMethod", "=", "httpMethod", ".", "toUpperCase", "(", ")", ";", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "url", "=", "baseUrl", "+", "path", ";", "var", "data", "=", "req", ".", "data", "||", "{", "}", ";", "// separate out data from request", "delete", "req", ".", "data", ";", "var", "isAdmin", "=", "req", ".", "caller", "&&", "req", ".", "caller", ".", "role", "===", "'admin'", ";", "delete", "req", ".", "caller", ";", "var", "id", "=", "req", ".", "_id", "||", "data", ".", "_id", ";", "// get id from request or data", "if", "(", "req", ".", "_id", ")", "{", "delete", "req", ".", "_id", ";", "}", "// delete id from request so no dupe", "var", "session", "=", "cls", ".", "getNamespace", "(", "'appSession'", ")", ";", "var", "caller", "=", "session", "&&", "session", ".", "active", "&&", "session", ".", "get", "(", "'caller'", ")", ";", "if", "(", "caller", "&&", "!", "isAdmin", ")", "{", "_", ".", "extend", "(", "req", ",", "{", "// onBehalfOf used by API to know who is the caller", "onBehalfOfType", ":", "caller", ".", "type", ",", "onBehalfOfId", ":", "caller", ".", "_id", "+", "''", ",", "onBehalfOfRole", ":", "caller", ".", "role", ",", "onBehalfOfName", ":", "caller", ".", "name", "}", ")", ";", "}", "_", ".", "each", "(", "req", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "val", ")", ")", "{", "req", "[", "key", "]", "=", "JSON", ".", "stringify", "(", "val", ")", ";", "}", "}", ")", ";", "// replace the ID portion of the URL", "url", "=", "id", "?", "url", ".", "replace", "(", "'{_id}'", ",", "id", "+", "''", ")", ":", "url", ".", "replace", "(", "'/{_id}'", ",", "''", ")", ";", "var", "reqConfig", "=", "{", "headers", ":", "headers", ",", "url", ":", "url", ",", "method", ":", "httpMethod", ",", "qs", ":", "_", ".", "isEmpty", "(", "req", ")", "?", "undefined", ":", "req", ",", "json", ":", "_", ".", "isEmpty", "(", "data", ")", "?", "true", ":", "data", "}", ";", "// if baseUrl not there yet, wait for 100 seconds until it is (i.e. during system startup)", "if", "(", "!", "baseUrl", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "makeRequest", "(", "reqConfig", ",", "deferred", ")", ";", "}", ",", "100", ")", ";", "}", "else", "{", "makeRequest", "(", "reqConfig", ",", "deferred", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
Send the request to the restful endpoint @param httpMethod @param path @param req
[ "Send", "the", "request", "to", "the", "restful", "endpoint" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/services/adapters/apiclient/apiclient.adapter.js#L86-L140
52,621
alexpods/ClazzJS
src/components/meta/Property/Getters.js
function(object, getters, property) { _.each(getters, function(getter, name) { object.__addGetter(property, name, getter); }); }
javascript
function(object, getters, property) { _.each(getters, function(getter, name) { object.__addGetter(property, name, getter); }); }
[ "function", "(", "object", ",", "getters", ",", "property", ")", "{", "_", ".", "each", "(", "getters", ",", "function", "(", "getter", ",", "name", ")", "{", "object", ".", "__addGetter", "(", "property", ",", "name", ",", "getter", ")", ";", "}", ")", ";", "}" ]
Add property getters to object @param {object} object Some object @param {object} getters Hash of property getters @param {string} property Property name @this {metaProcessor}
[ "Add", "property", "getters", "to", "object" ]
2f94496019669813c8246d48fcceb12a3e68a870
https://github.com/alexpods/ClazzJS/blob/2f94496019669813c8246d48fcceb12a3e68a870/src/components/meta/Property/Getters.js#L16-L21
52,622
wescravens/class-decorators
dist/index.js
_flatten
function _flatten(_ref) { var _ref2 = _toArray(_ref); var first = _ref2[0]; var rest = _ref2.slice(1); if (first === undefined) { return []; } else if (!Array.isArray(first)) { return [first].concat(_toConsumableArray(_flatten(rest))); } else { return [].concat(_toConsumableArray(_flatten(first)), _toConsumableArray(_flatten(rest))); } }
javascript
function _flatten(_ref) { var _ref2 = _toArray(_ref); var first = _ref2[0]; var rest = _ref2.slice(1); if (first === undefined) { return []; } else if (!Array.isArray(first)) { return [first].concat(_toConsumableArray(_flatten(rest))); } else { return [].concat(_toConsumableArray(_flatten(first)), _toConsumableArray(_flatten(rest))); } }
[ "function", "_flatten", "(", "_ref", ")", "{", "var", "_ref2", "=", "_toArray", "(", "_ref", ")", ";", "var", "first", "=", "_ref2", "[", "0", "]", ";", "var", "rest", "=", "_ref2", ".", "slice", "(", "1", ")", ";", "if", "(", "first", "===", "undefined", ")", "{", "return", "[", "]", ";", "}", "else", "if", "(", "!", "Array", ".", "isArray", "(", "first", ")", ")", "{", "return", "[", "first", "]", ".", "concat", "(", "_toConsumableArray", "(", "_flatten", "(", "rest", ")", ")", ")", ";", "}", "else", "{", "return", "[", "]", ".", "concat", "(", "_toConsumableArray", "(", "_flatten", "(", "first", ")", ")", ",", "_toConsumableArray", "(", "_flatten", "(", "rest", ")", ")", ")", ";", "}", "}" ]
Utility function for flattening nested arrays
[ "Utility", "function", "for", "flattening", "nested", "arrays" ]
72323df2857564f1997191364ea447adfe51007c
https://github.com/wescravens/class-decorators/blob/72323df2857564f1997191364ea447adfe51007c/dist/index.js#L149-L163
52,623
noblesamurai/noblerecord
src/nrutil.js
serialize
function serialize(val) { if (val == null) { return 'NULL' } else if (typeof val == 'string') { return "'" + val.replace(/(\\)/g, '\\$1').replace(/(')/g, '\\$1') + "'"; } else if (typeof val == 'number') { if (isNaN(val)) { return 'NULL'; } else { return val.toString(); } } else if ([true, false].indexOf(val) != -1) { return val.toString().toUpperCase(); } else if (val instanceof Date) { return "'" + makeDateStr(val) + "'"; } else { throw "Unable to serialize variable of type `" + typeof val + "`!"; } }
javascript
function serialize(val) { if (val == null) { return 'NULL' } else if (typeof val == 'string') { return "'" + val.replace(/(\\)/g, '\\$1').replace(/(')/g, '\\$1') + "'"; } else if (typeof val == 'number') { if (isNaN(val)) { return 'NULL'; } else { return val.toString(); } } else if ([true, false].indexOf(val) != -1) { return val.toString().toUpperCase(); } else if (val instanceof Date) { return "'" + makeDateStr(val) + "'"; } else { throw "Unable to serialize variable of type `" + typeof val + "`!"; } }
[ "function", "serialize", "(", "val", ")", "{", "if", "(", "val", "==", "null", ")", "{", "return", "'NULL'", "}", "else", "if", "(", "typeof", "val", "==", "'string'", ")", "{", "return", "\"'\"", "+", "val", ".", "replace", "(", "/", "(\\\\)", "/", "g", ",", "'\\\\$1'", ")", ".", "replace", "(", "/", "(')", "/", "g", ",", "'\\\\$1'", ")", "+", "\"'\"", ";", "}", "else", "if", "(", "typeof", "val", "==", "'number'", ")", "{", "if", "(", "isNaN", "(", "val", ")", ")", "{", "return", "'NULL'", ";", "}", "else", "{", "return", "val", ".", "toString", "(", ")", ";", "}", "}", "else", "if", "(", "[", "true", ",", "false", "]", ".", "indexOf", "(", "val", ")", "!=", "-", "1", ")", "{", "return", "val", ".", "toString", "(", ")", ".", "toUpperCase", "(", ")", ";", "}", "else", "if", "(", "val", "instanceof", "Date", ")", "{", "return", "\"'\"", "+", "makeDateStr", "(", "val", ")", "+", "\"'\"", ";", "}", "else", "{", "throw", "\"Unable to serialize variable of type `\"", "+", "typeof", "val", "+", "\"`!\"", ";", "}", "}" ]
Attempt to serialize a value as a string acceptable for an SQL statement.
[ "Attempt", "to", "serialize", "a", "value", "as", "a", "string", "acceptable", "for", "an", "SQL", "statement", "." ]
fc7d3aac186598c4c7023f5448979d4162ab5e38
https://github.com/noblesamurai/noblerecord/blob/fc7d3aac186598c4c7023f5448979d4162ab5e38/src/nrutil.js#L55-L78
52,624
noblesamurai/noblerecord
src/nrutil.js
parseSQLVal
function parseSQLVal(type, val) { if (val == 'NULL') { return null; } switch (type) { case 'datetime': case 'timestamp': if (val == 'CURRENT_TIMESTAMP') { return val; } else if (val == '0000-00-00 00:00:00') { // HACK(arlen): Not sure if this is correct, but constructing // a Date out of this yields "Invalid Date". return null; } else { return new Date(val); } case 'text': case 'string': return val; case 'integer': case 'primary_key': return parseInt(val); case 'float': return parseFloat(val); case 'boolean': return (val == "TRUE"); default: throw "Unknown friendly type `" + type + "`!"; } }
javascript
function parseSQLVal(type, val) { if (val == 'NULL') { return null; } switch (type) { case 'datetime': case 'timestamp': if (val == 'CURRENT_TIMESTAMP') { return val; } else if (val == '0000-00-00 00:00:00') { // HACK(arlen): Not sure if this is correct, but constructing // a Date out of this yields "Invalid Date". return null; } else { return new Date(val); } case 'text': case 'string': return val; case 'integer': case 'primary_key': return parseInt(val); case 'float': return parseFloat(val); case 'boolean': return (val == "TRUE"); default: throw "Unknown friendly type `" + type + "`!"; } }
[ "function", "parseSQLVal", "(", "type", ",", "val", ")", "{", "if", "(", "val", "==", "'NULL'", ")", "{", "return", "null", ";", "}", "switch", "(", "type", ")", "{", "case", "'datetime'", ":", "case", "'timestamp'", ":", "if", "(", "val", "==", "'CURRENT_TIMESTAMP'", ")", "{", "return", "val", ";", "}", "else", "if", "(", "val", "==", "'0000-00-00 00:00:00'", ")", "{", "// HACK(arlen): Not sure if this is correct, but constructing", "// a Date out of this yields \"Invalid Date\".", "return", "null", ";", "}", "else", "{", "return", "new", "Date", "(", "val", ")", ";", "}", "case", "'text'", ":", "case", "'string'", ":", "return", "val", ";", "case", "'integer'", ":", "case", "'primary_key'", ":", "return", "parseInt", "(", "val", ")", ";", "case", "'float'", ":", "return", "parseFloat", "(", "val", ")", ";", "case", "'boolean'", ":", "return", "(", "val", "==", "\"TRUE\"", ")", ";", "default", ":", "throw", "\"Unknown friendly type `\"", "+", "type", "+", "\"`!\"", ";", "}", "}" ]
Parses an SQL string into a JS object given the friendly type.
[ "Parses", "an", "SQL", "string", "into", "a", "JS", "object", "given", "the", "friendly", "type", "." ]
fc7d3aac186598c4c7023f5448979d4162ab5e38
https://github.com/noblesamurai/noblerecord/blob/fc7d3aac186598c4c7023f5448979d4162ab5e38/src/nrutil.js#L146-L176
52,625
micro-app/micro-storage
src/entry/micro-storage.js
microStorage
function microStorage ( namespace ) { list[namespace] = list[namespace] || {}; localStorage.setItem(packageName, JSON.stringify(list)); /** * Get or set value from storage * @param {String} name key * @param {AnyType} value value * @return {AnyType} value */ function storage ( name, value ) { if (arguments.length == 0) { return; } if (arguments.length == 1) { let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`)); return result ? result.$ : result; } localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value })); list[namespace][name] = ''; localStorage.setItem(packageName, JSON.stringify(list)); return value; }; /** * Remove value from storage * @param {String} name key */ storage.remove = function ( name ) { localStorage.removeItem(`${ namespace }.${ name }`); delete list[namespace][name]; localStorage.setItem(packageName, JSON.stringify(list)); }; /** * Return value list of storage * @return {Array} list list of storage */ storage.list = function () { return Object.keys(list[namespace]); }; /** * Clear all value from storage */ storage.clear = function () { this.list().forEach(( name ) => { this.remove(name); }); }; return storage; }
javascript
function microStorage ( namespace ) { list[namespace] = list[namespace] || {}; localStorage.setItem(packageName, JSON.stringify(list)); /** * Get or set value from storage * @param {String} name key * @param {AnyType} value value * @return {AnyType} value */ function storage ( name, value ) { if (arguments.length == 0) { return; } if (arguments.length == 1) { let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`)); return result ? result.$ : result; } localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value })); list[namespace][name] = ''; localStorage.setItem(packageName, JSON.stringify(list)); return value; }; /** * Remove value from storage * @param {String} name key */ storage.remove = function ( name ) { localStorage.removeItem(`${ namespace }.${ name }`); delete list[namespace][name]; localStorage.setItem(packageName, JSON.stringify(list)); }; /** * Return value list of storage * @return {Array} list list of storage */ storage.list = function () { return Object.keys(list[namespace]); }; /** * Clear all value from storage */ storage.clear = function () { this.list().forEach(( name ) => { this.remove(name); }); }; return storage; }
[ "function", "microStorage", "(", "namespace", ")", "{", "list", "[", "namespace", "]", "=", "list", "[", "namespace", "]", "||", "{", "}", ";", "localStorage", ".", "setItem", "(", "packageName", ",", "JSON", ".", "stringify", "(", "list", ")", ")", ";", "/**\n * Get or set value from storage\n * @param {String} name key\n * @param {AnyType} value value\n * @return {AnyType} value\n */", "function", "storage", "(", "name", ",", "value", ")", "{", "if", "(", "arguments", ".", "length", "==", "0", ")", "{", "return", ";", "}", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "let", "result", "=", "JSON", ".", "parse", "(", "localStorage", ".", "getItem", "(", "`", "${", "namespace", "}", "${", "name", "}", "`", ")", ")", ";", "return", "result", "?", "result", ".", "$", ":", "result", ";", "}", "localStorage", ".", "setItem", "(", "`", "${", "namespace", "}", "${", "name", "}", "`", ",", "JSON", ".", "stringify", "(", "{", "$", ":", "value", "}", ")", ")", ";", "list", "[", "namespace", "]", "[", "name", "]", "=", "''", ";", "localStorage", ".", "setItem", "(", "packageName", ",", "JSON", ".", "stringify", "(", "list", ")", ")", ";", "return", "value", ";", "}", ";", "/**\n * Remove value from storage\n * @param {String} name key\n */", "storage", ".", "remove", "=", "function", "(", "name", ")", "{", "localStorage", ".", "removeItem", "(", "`", "${", "namespace", "}", "${", "name", "}", "`", ")", ";", "delete", "list", "[", "namespace", "]", "[", "name", "]", ";", "localStorage", ".", "setItem", "(", "packageName", ",", "JSON", ".", "stringify", "(", "list", ")", ")", ";", "}", ";", "/**\n * Return value list of storage\n * @return {Array} list list of storage\n */", "storage", ".", "list", "=", "function", "(", ")", "{", "return", "Object", ".", "keys", "(", "list", "[", "namespace", "]", ")", ";", "}", ";", "/**\n * Clear all value from storage\n */", "storage", ".", "clear", "=", "function", "(", ")", "{", "this", ".", "list", "(", ")", ".", "forEach", "(", "(", "name", ")", "=>", "{", "this", ".", "remove", "(", "name", ")", ";", "}", ")", ";", "}", ";", "return", "storage", ";", "}" ]
A lite localStorage plugin with namespace @param {String} namespace namespace @return {Function} function
[ "A", "lite", "localStorage", "plugin", "with", "namespace" ]
775f73f4eb6651b2eba78d3408626dcb3a67e192
https://github.com/micro-app/micro-storage/blob/775f73f4eb6651b2eba78d3408626dcb3a67e192/src/entry/micro-storage.js#L17-L70
52,626
micro-app/micro-storage
src/entry/micro-storage.js
storage
function storage ( name, value ) { if (arguments.length == 0) { return; } if (arguments.length == 1) { let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`)); return result ? result.$ : result; } localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value })); list[namespace][name] = ''; localStorage.setItem(packageName, JSON.stringify(list)); return value; }
javascript
function storage ( name, value ) { if (arguments.length == 0) { return; } if (arguments.length == 1) { let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`)); return result ? result.$ : result; } localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value })); list[namespace][name] = ''; localStorage.setItem(packageName, JSON.stringify(list)); return value; }
[ "function", "storage", "(", "name", ",", "value", ")", "{", "if", "(", "arguments", ".", "length", "==", "0", ")", "{", "return", ";", "}", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "let", "result", "=", "JSON", ".", "parse", "(", "localStorage", ".", "getItem", "(", "`", "${", "namespace", "}", "${", "name", "}", "`", ")", ")", ";", "return", "result", "?", "result", ".", "$", ":", "result", ";", "}", "localStorage", ".", "setItem", "(", "`", "${", "namespace", "}", "${", "name", "}", "`", ",", "JSON", ".", "stringify", "(", "{", "$", ":", "value", "}", ")", ")", ";", "list", "[", "namespace", "]", "[", "name", "]", "=", "''", ";", "localStorage", ".", "setItem", "(", "packageName", ",", "JSON", ".", "stringify", "(", "list", ")", ")", ";", "return", "value", ";", "}" ]
Get or set value from storage @param {String} name key @param {AnyType} value value @return {AnyType} value
[ "Get", "or", "set", "value", "from", "storage" ]
775f73f4eb6651b2eba78d3408626dcb3a67e192
https://github.com/micro-app/micro-storage/blob/775f73f4eb6651b2eba78d3408626dcb3a67e192/src/entry/micro-storage.js#L28-L40
52,627
byron-dupreez/logging-utils
logging.js
isLoggingConfigured
function isLoggingConfigured(target) { return target && isBoolean(target.warnEnabled) && isBoolean(target.infoEnabled) && isBoolean(target.debugEnabled) && isBoolean(target.traceEnabled) && typeof target.error === 'function' && typeof target.warn === 'function' && typeof target.info === 'function' && typeof target.debug === 'function' && typeof target.trace === 'function'; }
javascript
function isLoggingConfigured(target) { return target && isBoolean(target.warnEnabled) && isBoolean(target.infoEnabled) && isBoolean(target.debugEnabled) && isBoolean(target.traceEnabled) && typeof target.error === 'function' && typeof target.warn === 'function' && typeof target.info === 'function' && typeof target.debug === 'function' && typeof target.trace === 'function'; }
[ "function", "isLoggingConfigured", "(", "target", ")", "{", "return", "target", "&&", "isBoolean", "(", "target", ".", "warnEnabled", ")", "&&", "isBoolean", "(", "target", ".", "infoEnabled", ")", "&&", "isBoolean", "(", "target", ".", "debugEnabled", ")", "&&", "isBoolean", "(", "target", ".", "traceEnabled", ")", "&&", "typeof", "target", ".", "error", "===", "'function'", "&&", "typeof", "target", ".", "warn", "===", "'function'", "&&", "typeof", "target", ".", "info", "===", "'function'", "&&", "typeof", "target", ".", "debug", "===", "'function'", "&&", "typeof", "target", ".", "trace", "===", "'function'", ";", "}" ]
Returns true, if the given target already has logging functionality configured on it; otherwise returns false. @param {Object} target the target object to check @return {*} true if configured; otherwise false
[ "Returns", "true", "if", "the", "given", "target", "already", "has", "logging", "functionality", "configured", "on", "it", ";", "otherwise", "returns", "false", "." ]
b5edac6efb288a2276dc88159a935d36816a859f
https://github.com/byron-dupreez/logging-utils/blob/b5edac6efb288a2276dc88159a935d36816a859f/logging.js#L112-L116
52,628
byron-dupreez/logging-utils
logging.js
isValidLogLevel
function isValidLogLevel(logLevel) { const level = cleanLogLevel(logLevel); switch (level) { case LogLevel.ERROR: case LogLevel.WARN: case LogLevel.INFO: case LogLevel.DEBUG: case LogLevel.TRACE: return true; default: return false; } }
javascript
function isValidLogLevel(logLevel) { const level = cleanLogLevel(logLevel); switch (level) { case LogLevel.ERROR: case LogLevel.WARN: case LogLevel.INFO: case LogLevel.DEBUG: case LogLevel.TRACE: return true; default: return false; } }
[ "function", "isValidLogLevel", "(", "logLevel", ")", "{", "const", "level", "=", "cleanLogLevel", "(", "logLevel", ")", ";", "switch", "(", "level", ")", "{", "case", "LogLevel", ".", "ERROR", ":", "case", "LogLevel", ".", "WARN", ":", "case", "LogLevel", ".", "INFO", ":", "case", "LogLevel", ".", "DEBUG", ":", "case", "LogLevel", ".", "TRACE", ":", "return", "true", ";", "default", ":", "return", "false", ";", "}", "}" ]
Returns true if the given log level is a valid logging level; otherwise returns false. @param {LogLevel|string|undefined} [logLevel] - the optional log level to validate @returns {boolean} true if a valid logging level; false otherwise
[ "Returns", "true", "if", "the", "given", "log", "level", "is", "a", "valid", "logging", "level", ";", "otherwise", "returns", "false", "." ]
b5edac6efb288a2276dc88159a935d36816a859f
https://github.com/byron-dupreez/logging-utils/blob/b5edac6efb288a2276dc88159a935d36816a859f/logging.js#L321-L333
52,629
jvandemo/contentful-agent
lib/agent.js
prepareResults
function prepareResults(contentTypes) { var results = _.reduce(contentTypes, function (result, contentType, key) { // If content type is string, treat is as content type id if(_.isString(contentType)){ var id = contentType; contentType = { id: id } } contentType.name = key; result.push(contentType); return result; }, []); return when.resolve(results); }
javascript
function prepareResults(contentTypes) { var results = _.reduce(contentTypes, function (result, contentType, key) { // If content type is string, treat is as content type id if(_.isString(contentType)){ var id = contentType; contentType = { id: id } } contentType.name = key; result.push(contentType); return result; }, []); return when.resolve(results); }
[ "function", "prepareResults", "(", "contentTypes", ")", "{", "var", "results", "=", "_", ".", "reduce", "(", "contentTypes", ",", "function", "(", "result", ",", "contentType", ",", "key", ")", "{", "// If content type is string, treat is as content type id", "if", "(", "_", ".", "isString", "(", "contentType", ")", ")", "{", "var", "id", "=", "contentType", ";", "contentType", "=", "{", "id", ":", "id", "}", "}", "contentType", ".", "name", "=", "key", ";", "result", ".", "push", "(", "contentType", ")", ";", "return", "result", ";", "}", ",", "[", "]", ")", ";", "return", "when", ".", "resolve", "(", "results", ")", ";", "}" ]
Convert object with content types to array with content types FROM: { 'team-members': { id: '', filters: {} } } TO: [ { id: '', filters: {}, name: 'team-members' } ] @param contentTypes @returns {*}
[ "Convert", "object", "with", "content", "types", "to", "array", "with", "content", "types" ]
f7abdd7f72ca6411abfdcc90e6c201f1c3e8b493
https://github.com/jvandemo/contentful-agent/blob/f7abdd7f72ca6411abfdcc90e6c201f1c3e8b493/lib/agent.js#L68-L83
52,630
jvandemo/contentful-agent
lib/agent.js
fetchEntries
function fetchEntries(contentTypes) { return when.map(contentTypes, function (contentType) { if (!contentType.id) { return when.reject('Content type `' + contentType.name + '` is missing an `id` value'); } var filters = _.merge({}, contentType.filters, {content_type: contentType.id}); return client.entries(filters).then(function (results) { response[contentType.name] = results; }); }); }
javascript
function fetchEntries(contentTypes) { return when.map(contentTypes, function (contentType) { if (!contentType.id) { return when.reject('Content type `' + contentType.name + '` is missing an `id` value'); } var filters = _.merge({}, contentType.filters, {content_type: contentType.id}); return client.entries(filters).then(function (results) { response[contentType.name] = results; }); }); }
[ "function", "fetchEntries", "(", "contentTypes", ")", "{", "return", "when", ".", "map", "(", "contentTypes", ",", "function", "(", "contentType", ")", "{", "if", "(", "!", "contentType", ".", "id", ")", "{", "return", "when", ".", "reject", "(", "'Content type `'", "+", "contentType", ".", "name", "+", "'` is missing an `id` value'", ")", ";", "}", "var", "filters", "=", "_", ".", "merge", "(", "{", "}", ",", "contentType", ".", "filters", ",", "{", "content_type", ":", "contentType", ".", "id", "}", ")", ";", "return", "client", ".", "entries", "(", "filters", ")", ".", "then", "(", "function", "(", "results", ")", "{", "response", "[", "contentType", ".", "name", "]", "=", "results", ";", "}", ")", ";", "}", ")", ";", "}" ]
Fetch entries from contentful @param contentTypes [ { id: '', filters: {}, name: 'team-members' } ]
[ "Fetch", "entries", "from", "contentful" ]
f7abdd7f72ca6411abfdcc90e6c201f1c3e8b493
https://github.com/jvandemo/contentful-agent/blob/f7abdd7f72ca6411abfdcc90e6c201f1c3e8b493/lib/agent.js#L90-L100
52,631
wbyoung/corazon
lib/class.js
function(properties, cls, superClass, options) { var opts = _.defaults({}, options, { wrap: true }); if (opts.wrap) { var prototype = cls.prototype; if (superClass) { // combine the cls prototype with the superClass prototype, but do so // using a new prototype chain to avoid copying (and invoking accessor // methods) either prototype. the combined prototype can be used to wrap // properties. prototype = Object.create(prototype); prototype.prototype = superClass.prototype; } properties = wrap.super.properties(properties, prototype); } _.extend(cls.prototype, properties); }
javascript
function(properties, cls, superClass, options) { var opts = _.defaults({}, options, { wrap: true }); if (opts.wrap) { var prototype = cls.prototype; if (superClass) { // combine the cls prototype with the superClass prototype, but do so // using a new prototype chain to avoid copying (and invoking accessor // methods) either prototype. the combined prototype can be used to wrap // properties. prototype = Object.create(prototype); prototype.prototype = superClass.prototype; } properties = wrap.super.properties(properties, prototype); } _.extend(cls.prototype, properties); }
[ "function", "(", "properties", ",", "cls", ",", "superClass", ",", "options", ")", "{", "var", "opts", "=", "_", ".", "defaults", "(", "{", "}", ",", "options", ",", "{", "wrap", ":", "true", "}", ")", ";", "if", "(", "opts", ".", "wrap", ")", "{", "var", "prototype", "=", "cls", ".", "prototype", ";", "if", "(", "superClass", ")", "{", "// combine the cls prototype with the superClass prototype, but do so", "// using a new prototype chain to avoid copying (and invoking accessor", "// methods) either prototype. the combined prototype can be used to wrap", "// properties.", "prototype", "=", "Object", ".", "create", "(", "prototype", ")", ";", "prototype", ".", "prototype", "=", "superClass", ".", "prototype", ";", "}", "properties", "=", "wrap", ".", "super", ".", "properties", "(", "properties", ",", "prototype", ")", ";", "}", "_", ".", "extend", "(", "cls", ".", "prototype", ",", "properties", ")", ";", "}" ]
Generic reopen to use for both instance and static methods. @name Class~reopen @param {Object} properties The properties to add. @param {ClassConstructor} cls The class to add properties to. @param {ClassConstructor} superClass The class's super class. @param {Object} [options] @param {Boolean} [options.wrap=true] Whether to wrap the properties.
[ "Generic", "reopen", "to", "use", "for", "both", "instance", "and", "static", "methods", "." ]
c3cc87f3de28f8e40ab091c8f215479c9e61f379
https://github.com/wbyoung/corazon/blob/c3cc87f3de28f8e40ab091c8f215479c9e61f379/lib/class.js#L163-L178
52,632
Everyplay/backbone-db-indexing-adapter
lib/indexed_collection_mixin.js
function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); return this._callAdapter('addToIndex', options, model); }
javascript
function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); return this._callAdapter('addToIndex', options, model); }
[ "function", "(", "model", ",", "options", ")", "{", "options", "=", "options", "?", "_", ".", "clone", "(", "options", ")", ":", "{", "}", ";", "if", "(", "!", "(", "model", "=", "this", ".", "_prepareModel", "(", "model", ",", "options", ")", ")", ")", "return", "false", ";", "if", "(", "!", "options", ".", "wait", ")", "this", ".", "add", "(", "model", ",", "options", ")", ";", "return", "this", ".", "_callAdapter", "(", "'addToIndex'", ",", "options", ",", "model", ")", ";", "}" ]
Adds a new model key to the index. @param {Model} model model whose key (id) is added to index @param {Object} options options @returns {Promise} promise
[ "Adds", "a", "new", "model", "key", "to", "the", "index", "." ]
9e6e51dd918f4c2e71ef1d478fa9bc7e4eae3112
https://github.com/Everyplay/backbone-db-indexing-adapter/blob/9e6e51dd918f4c2e71ef1d478fa9bc7e4eae3112/lib/indexed_collection_mixin.js#L14-L19
52,633
Everyplay/backbone-db-indexing-adapter
lib/indexed_collection_mixin.js
function(options) { options = options ? _.clone(options) : {}; options.indexKeys = this.indexKeys || options.indexKeys; options.unionKey = this.unionKey || options.unionKey; if (this.indexKey) options.indexKeys.push(this.indexKey); var args = [this, options]; return nodefn.apply(_.bind(this.indexDb.readFromIndexes, this.indexDb), args); }
javascript
function(options) { options = options ? _.clone(options) : {}; options.indexKeys = this.indexKeys || options.indexKeys; options.unionKey = this.unionKey || options.unionKey; if (this.indexKey) options.indexKeys.push(this.indexKey); var args = [this, options]; return nodefn.apply(_.bind(this.indexDb.readFromIndexes, this.indexDb), args); }
[ "function", "(", "options", ")", "{", "options", "=", "options", "?", "_", ".", "clone", "(", "options", ")", ":", "{", "}", ";", "options", ".", "indexKeys", "=", "this", ".", "indexKeys", "||", "options", ".", "indexKeys", ";", "options", ".", "unionKey", "=", "this", ".", "unionKey", "||", "options", ".", "unionKey", ";", "if", "(", "this", ".", "indexKey", ")", "options", ".", "indexKeys", ".", "push", "(", "this", ".", "indexKey", ")", ";", "var", "args", "=", "[", "this", ",", "options", "]", ";", "return", "nodefn", ".", "apply", "(", "_", ".", "bind", "(", "this", ".", "indexDb", ".", "readFromIndexes", ",", "this", ".", "indexDb", ")", ",", "args", ")", ";", "}" ]
Read all keys from multiple indexes. @param {Object} options options @returns {Promise} promise
[ "Read", "all", "keys", "from", "multiple", "indexes", "." ]
9e6e51dd918f4c2e71ef1d478fa9bc7e4eae3112
https://github.com/Everyplay/backbone-db-indexing-adapter/blob/9e6e51dd918f4c2e71ef1d478fa9bc7e4eae3112/lib/indexed_collection_mixin.js#L35-L42
52,634
Everyplay/backbone-db-indexing-adapter
lib/indexed_collection_mixin.js
function(models, options) { if(!models) return false; this.remove(models, options); var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); return this._callAdapter('removeFromIndex', options, models); }
javascript
function(models, options) { if(!models) return false; this.remove(models, options); var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); return this._callAdapter('removeFromIndex', options, models); }
[ "function", "(", "models", ",", "options", ")", "{", "if", "(", "!", "models", ")", "return", "false", ";", "this", ".", "remove", "(", "models", ",", "options", ")", ";", "var", "singular", "=", "!", "_", ".", "isArray", "(", "models", ")", ";", "models", "=", "singular", "?", "[", "models", "]", ":", "_", ".", "clone", "(", "models", ")", ";", "return", "this", ".", "_callAdapter", "(", "'removeFromIndex'", ",", "options", ",", "models", ")", ";", "}" ]
Removes a model's key from index @param {Array} models model(s) whose keys (ids) are removed from index @param {Object} options options @returns {Promise} promise
[ "Removes", "a", "model", "s", "key", "from", "index" ]
9e6e51dd918f4c2e71ef1d478fa9bc7e4eae3112
https://github.com/Everyplay/backbone-db-indexing-adapter/blob/9e6e51dd918f4c2e71ef1d478fa9bc7e4eae3112/lib/indexed_collection_mixin.js#L50-L56
52,635
Psychopoulet/node-promfs
lib/extends/_isDirectory.js
_isDirectory
function _isDirectory (directory, callback) { if ("undefined" === typeof directory) { throw new ReferenceError("missing \"directory\" argument"); } else if ("string" !== typeof directory) { throw new TypeError("\"directory\" argument is not a string"); } else if ("" === directory.trim()) { throw new Error("\"directory\" argument is empty"); } else if ("undefined" === typeof callback) { throw new ReferenceError("missing \"callback\" argument"); } else if ("function" !== typeof callback) { throw new TypeError("\"callback\" argument is not a function"); } else { lstat(directory, (err, stats) => { return callback(null, Boolean(!err && stats.isDirectory())); }); } }
javascript
function _isDirectory (directory, callback) { if ("undefined" === typeof directory) { throw new ReferenceError("missing \"directory\" argument"); } else if ("string" !== typeof directory) { throw new TypeError("\"directory\" argument is not a string"); } else if ("" === directory.trim()) { throw new Error("\"directory\" argument is empty"); } else if ("undefined" === typeof callback) { throw new ReferenceError("missing \"callback\" argument"); } else if ("function" !== typeof callback) { throw new TypeError("\"callback\" argument is not a function"); } else { lstat(directory, (err, stats) => { return callback(null, Boolean(!err && stats.isDirectory())); }); } }
[ "function", "_isDirectory", "(", "directory", ",", "callback", ")", "{", "if", "(", "\"undefined\"", "===", "typeof", "directory", ")", "{", "throw", "new", "ReferenceError", "(", "\"missing \\\"directory\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"string\"", "!==", "typeof", "directory", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"directory\\\" argument is not a string\"", ")", ";", "}", "else", "if", "(", "\"\"", "===", "directory", ".", "trim", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"\\\"directory\\\" argument is empty\"", ")", ";", "}", "else", "if", "(", "\"undefined\"", "===", "typeof", "callback", ")", "{", "throw", "new", "ReferenceError", "(", "\"missing \\\"callback\\\" argument\"", ")", ";", "}", "else", "if", "(", "\"function\"", "!==", "typeof", "callback", ")", "{", "throw", "new", "TypeError", "(", "\"\\\"callback\\\" argument is not a function\"", ")", ";", "}", "else", "{", "lstat", "(", "directory", ",", "(", "err", ",", "stats", ")", "=>", "{", "return", "callback", "(", "null", ",", "Boolean", "(", "!", "err", "&&", "stats", ".", "isDirectory", "(", ")", ")", ")", ";", "}", ")", ";", "}", "}" ]
methods Async isDirectory @param {string} directory : directory to check @param {function|null} callback : operation's result @returns {void}
[ "methods", "Async", "isDirectory" ]
016e272fc58c6ef6eae5ea551a0e8873f0ac20cc
https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/lib/extends/_isDirectory.js#L18-L43
52,636
semantic-math/math-traverse
lib/traverse.js
traverse
function traverse(node, {enter = () => {}, leave = () => {}}, path = []) { switch (node.type) { // regular non-leaf nodes case 'Apply': enter(node, path) node.args.forEach((arg, index) => traverse(arg, {enter, leave}, [...path, 'args', index])) leave(node, path) break // leaf nodes case 'Identifier': case 'Number': case 'Ellipsis': enter(node, path) leave(node, path) break // irregular non-leaf nodes case 'Parentheses': enter(node, path) traverse(node.body, {enter, leave}, [...path, 'body']) leave(node, path) break case 'List': case 'Sequence': enter(node, path) node.items.forEach((item, index) => traverse(item, {enter, leave}, [...path, 'items', index])) leave(node, path) break case 'System': enter(node, path) node.relations.forEach((rel, index) => traverse(rel, {enter, leave}, [...path, 'relations', index])) leave(node, path) break case 'Placeholder': // TODO(kevinb) handle children of the placeholder // e.g. we there might #a_0 could match x_0, y_0, z_0, etc. enter(node, path) leave(node, path) break default: throw new Error(`unrecognized node: ${node.type}`) } }
javascript
function traverse(node, {enter = () => {}, leave = () => {}}, path = []) { switch (node.type) { // regular non-leaf nodes case 'Apply': enter(node, path) node.args.forEach((arg, index) => traverse(arg, {enter, leave}, [...path, 'args', index])) leave(node, path) break // leaf nodes case 'Identifier': case 'Number': case 'Ellipsis': enter(node, path) leave(node, path) break // irregular non-leaf nodes case 'Parentheses': enter(node, path) traverse(node.body, {enter, leave}, [...path, 'body']) leave(node, path) break case 'List': case 'Sequence': enter(node, path) node.items.forEach((item, index) => traverse(item, {enter, leave}, [...path, 'items', index])) leave(node, path) break case 'System': enter(node, path) node.relations.forEach((rel, index) => traverse(rel, {enter, leave}, [...path, 'relations', index])) leave(node, path) break case 'Placeholder': // TODO(kevinb) handle children of the placeholder // e.g. we there might #a_0 could match x_0, y_0, z_0, etc. enter(node, path) leave(node, path) break default: throw new Error(`unrecognized node: ${node.type}`) } }
[ "function", "traverse", "(", "node", ",", "{", "enter", "=", "(", ")", "=>", "{", "}", ",", "leave", "=", "(", ")", "=>", "{", "}", "}", ",", "path", "=", "[", "]", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "// regular non-leaf nodes", "case", "'Apply'", ":", "enter", "(", "node", ",", "path", ")", "node", ".", "args", ".", "forEach", "(", "(", "arg", ",", "index", ")", "=>", "traverse", "(", "arg", ",", "{", "enter", ",", "leave", "}", ",", "[", "...", "path", ",", "'args'", ",", "index", "]", ")", ")", "leave", "(", "node", ",", "path", ")", "break", "// leaf nodes", "case", "'Identifier'", ":", "case", "'Number'", ":", "case", "'Ellipsis'", ":", "enter", "(", "node", ",", "path", ")", "leave", "(", "node", ",", "path", ")", "break", "// irregular non-leaf nodes", "case", "'Parentheses'", ":", "enter", "(", "node", ",", "path", ")", "traverse", "(", "node", ".", "body", ",", "{", "enter", ",", "leave", "}", ",", "[", "...", "path", ",", "'body'", "]", ")", "leave", "(", "node", ",", "path", ")", "break", "case", "'List'", ":", "case", "'Sequence'", ":", "enter", "(", "node", ",", "path", ")", "node", ".", "items", ".", "forEach", "(", "(", "item", ",", "index", ")", "=>", "traverse", "(", "item", ",", "{", "enter", ",", "leave", "}", ",", "[", "...", "path", ",", "'items'", ",", "index", "]", ")", ")", "leave", "(", "node", ",", "path", ")", "break", "case", "'System'", ":", "enter", "(", "node", ",", "path", ")", "node", ".", "relations", ".", "forEach", "(", "(", "rel", ",", "index", ")", "=>", "traverse", "(", "rel", ",", "{", "enter", ",", "leave", "}", ",", "[", "...", "path", ",", "'relations'", ",", "index", "]", ")", ")", "leave", "(", "node", ",", "path", ")", "break", "case", "'Placeholder'", ":", "// TODO(kevinb) handle children of the placeholder", "// e.g. we there might #a_0 could match x_0, y_0, z_0, etc.", "enter", "(", "node", ",", "path", ")", "leave", "(", "node", ",", "path", ")", "break", "default", ":", "throw", "new", "Error", "(", "`", "${", "node", ".", "type", "}", "`", ")", "}", "}" ]
traverse - walk all of the nodes in a tree.
[ "traverse", "-", "walk", "all", "of", "the", "nodes", "in", "a", "tree", "." ]
251430b4a984200fb1b3fd373fde2da50a78830c
https://github.com/semantic-math/math-traverse/blob/251430b4a984200fb1b3fd373fde2da50a78830c/lib/traverse.js#L5-L55
52,637
a-labo/aschema
shim/browser/aschema.js
validate
function validate(values) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var s = this; var _tv4$validateMultiple = tv4.validateMultiple(values, s), valid = _tv4$validateMultiple.valid, errors = _tv4$validateMultiple.errors; if (valid) { return null; } var assign = options.assign, _options$name = options.name, name = _options$name === void 0 ? 'SchemaError' : _options$name; var _s$schema = s.schema, schema = _s$schema === void 0 ? {} : _s$schema; var error = new Error("Validation failed with schema: ".concat(schema.title || schema.id || schema.description)); return Object.assign(error, { id: uuid.v4(), name: name, errors: errors, schema: schema, values: values, engine: 'tv4' }, assign); }
javascript
function validate(values) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var s = this; var _tv4$validateMultiple = tv4.validateMultiple(values, s), valid = _tv4$validateMultiple.valid, errors = _tv4$validateMultiple.errors; if (valid) { return null; } var assign = options.assign, _options$name = options.name, name = _options$name === void 0 ? 'SchemaError' : _options$name; var _s$schema = s.schema, schema = _s$schema === void 0 ? {} : _s$schema; var error = new Error("Validation failed with schema: ".concat(schema.title || schema.id || schema.description)); return Object.assign(error, { id: uuid.v4(), name: name, errors: errors, schema: schema, values: values, engine: 'tv4' }, assign); }
[ "function", "validate", "(", "values", ")", "{", "var", "options", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "}", ";", "var", "s", "=", "this", ";", "var", "_tv4$validateMultiple", "=", "tv4", ".", "validateMultiple", "(", "values", ",", "s", ")", ",", "valid", "=", "_tv4$validateMultiple", ".", "valid", ",", "errors", "=", "_tv4$validateMultiple", ".", "errors", ";", "if", "(", "valid", ")", "{", "return", "null", ";", "}", "var", "assign", "=", "options", ".", "assign", ",", "_options$name", "=", "options", ".", "name", ",", "name", "=", "_options$name", "===", "void", "0", "?", "'SchemaError'", ":", "_options$name", ";", "var", "_s$schema", "=", "s", ".", "schema", ",", "schema", "=", "_s$schema", "===", "void", "0", "?", "{", "}", ":", "_s$schema", ";", "var", "error", "=", "new", "Error", "(", "\"Validation failed with schema: \"", ".", "concat", "(", "schema", ".", "title", "||", "schema", ".", "id", "||", "schema", ".", "description", ")", ")", ";", "return", "Object", ".", "assign", "(", "error", ",", "{", "id", ":", "uuid", ".", "v4", "(", ")", ",", "name", ":", "name", ",", "errors", ":", "errors", ",", "schema", ":", "schema", ",", "values", ":", "values", ",", "engine", ":", "'tv4'", "}", ",", "assign", ")", ";", "}" ]
Validate values. @param {object} values - Values to validate. @param {object} [options] - Optional settings. @returns {object|null} - Null if success.
[ "Validate", "values", "." ]
b67da07ff618dd9a660646962e0e7ea04a763623
https://github.com/a-labo/aschema/blob/b67da07ff618dd9a660646962e0e7ea04a763623/shim/browser/aschema.js#L38-L64
52,638
a-labo/aschema
shim/browser/aschema.js
validateToThrow
function validateToThrow() { var s = this; var error = s.validate.apply(s, arguments); if (error) { throw error; } }
javascript
function validateToThrow() { var s = this; var error = s.validate.apply(s, arguments); if (error) { throw error; } }
[ "function", "validateToThrow", "(", ")", "{", "var", "s", "=", "this", ";", "var", "error", "=", "s", ".", "validate", ".", "apply", "(", "s", ",", "arguments", ")", ";", "if", "(", "error", ")", "{", "throw", "error", ";", "}", "}" ]
Throw an error if validate failed @throws Error
[ "Throw", "an", "error", "if", "validate", "failed" ]
b67da07ff618dd9a660646962e0e7ea04a763623
https://github.com/a-labo/aschema/blob/b67da07ff618dd9a660646962e0e7ea04a763623/shim/browser/aschema.js#L70-L77
52,639
a-labo/aschema
shim/browser/aschema.js
set
function set(values) { var s = this; if (arguments.length === 2) { values = {}; var key = arguments[0]; values[key] = arguments[1]; } Object.assign(s, values); return s; }
javascript
function set(values) { var s = this; if (arguments.length === 2) { values = {}; var key = arguments[0]; values[key] = arguments[1]; } Object.assign(s, values); return s; }
[ "function", "set", "(", "values", ")", "{", "var", "s", "=", "this", ";", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "values", "=", "{", "}", ";", "var", "key", "=", "arguments", "[", "0", "]", ";", "values", "[", "key", "]", "=", "arguments", "[", "1", "]", ";", "}", "Object", ".", "assign", "(", "s", ",", "values", ")", ";", "return", "s", ";", "}" ]
Set values. @param {object} values - Values to set @returns {ASchema} - Returns self.
[ "Set", "values", "." ]
b67da07ff618dd9a660646962e0e7ea04a763623
https://github.com/a-labo/aschema/blob/b67da07ff618dd9a660646962e0e7ea04a763623/shim/browser/aschema.js#L94-L105
52,640
a-labo/aschema
shim/browser/aschema.js
toJSON
function toJSON() { var s = this; var values = Object.assign({}, s.schema); Object.keys(values).forEach(function (key) { var isFunc = iftype.isFunction(values[key]); if (isFunc) { delete values[key]; } }); return values; }
javascript
function toJSON() { var s = this; var values = Object.assign({}, s.schema); Object.keys(values).forEach(function (key) { var isFunc = iftype.isFunction(values[key]); if (isFunc) { delete values[key]; } }); return values; }
[ "function", "toJSON", "(", ")", "{", "var", "s", "=", "this", ";", "var", "values", "=", "Object", ".", "assign", "(", "{", "}", ",", "s", ".", "schema", ")", ";", "Object", ".", "keys", "(", "values", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "isFunc", "=", "iftype", ".", "isFunction", "(", "values", "[", "key", "]", ")", ";", "if", "(", "isFunc", ")", "{", "delete", "values", "[", "key", "]", ";", "}", "}", ")", ";", "return", "values", ";", "}" ]
Convert to json. @returns {object} - JSON schema.
[ "Convert", "to", "json", "." ]
b67da07ff618dd9a660646962e0e7ea04a763623
https://github.com/a-labo/aschema/blob/b67da07ff618dd9a660646962e0e7ea04a763623/shim/browser/aschema.js#L111-L122
52,641
Lindurion/closure-pro-build
lib/closure-pro-build.js
expandFileGlobs
function expandFileGlobs(filesAndPatterns, rootDir, callbackFn) { fileMatcher.resolveAnyGlobPatternsAsync(filesAndPatterns, rootDir) .then(function(result) { callbackFn(null, result); }) .fail(callbackFn); }
javascript
function expandFileGlobs(filesAndPatterns, rootDir, callbackFn) { fileMatcher.resolveAnyGlobPatternsAsync(filesAndPatterns, rootDir) .then(function(result) { callbackFn(null, result); }) .fail(callbackFn); }
[ "function", "expandFileGlobs", "(", "filesAndPatterns", ",", "rootDir", ",", "callbackFn", ")", "{", "fileMatcher", ".", "resolveAnyGlobPatternsAsync", "(", "filesAndPatterns", ",", "rootDir", ")", ".", "then", "(", "function", "(", "result", ")", "{", "callbackFn", "(", "null", ",", "result", ")", ";", "}", ")", ".", "fail", "(", "callbackFn", ")", ";", "}" ]
As an exported convenience function, expands all glob patterns in the given list of filesAndPatterns into the list of matched files. @param {!Array.<string>} filesAndPatterns List of files and file patterns, e.g. ['my/single/file.js', 'dir/of/*.js']. @param {string} rootDir Root directory that filesAndPatterns are relative to. @param {function(Error, Array.<string>=)} callbackFn Called with the list of expanded files on success, or an Error on failure.
[ "As", "an", "exported", "convenience", "function", "expands", "all", "glob", "patterns", "in", "the", "given", "list", "of", "filesAndPatterns", "into", "the", "list", "of", "matched", "files", "." ]
c279d0fcc3a65969d2fe965f55e627b074792f1a
https://github.com/Lindurion/closure-pro-build/blob/c279d0fcc3a65969d2fe965f55e627b074792f1a/lib/closure-pro-build.js#L64-L68
52,642
eaze/potluck-opentok-adapter
vendor/opentok.js
function(selector, context) { var results = []; if (typeof(selector) === 'string') { var idSelector = detectIdSelectors.exec(selector); context = context || document; if (idSelector && idSelector[1]) { var element = context.getElementById(idSelector[1]); if (element) results.push(element); } else { results = context.querySelectorAll(selector); } } else if (selector && (selector.nodeType || window.XMLHttpRequest && selector instanceof XMLHttpRequest)) { // allow OTHelpers(DOMNode) and OTHelpers(xmlHttpRequest) results = [selector]; context = selector; } else if (OTHelpers.isArray(selector)) { results = selector.slice(); context = null; } return new ElementCollection(results, context); }
javascript
function(selector, context) { var results = []; if (typeof(selector) === 'string') { var idSelector = detectIdSelectors.exec(selector); context = context || document; if (idSelector && idSelector[1]) { var element = context.getElementById(idSelector[1]); if (element) results.push(element); } else { results = context.querySelectorAll(selector); } } else if (selector && (selector.nodeType || window.XMLHttpRequest && selector instanceof XMLHttpRequest)) { // allow OTHelpers(DOMNode) and OTHelpers(xmlHttpRequest) results = [selector]; context = selector; } else if (OTHelpers.isArray(selector)) { results = selector.slice(); context = null; } return new ElementCollection(results, context); }
[ "function", "(", "selector", ",", "context", ")", "{", "var", "results", "=", "[", "]", ";", "if", "(", "typeof", "(", "selector", ")", "===", "'string'", ")", "{", "var", "idSelector", "=", "detectIdSelectors", ".", "exec", "(", "selector", ")", ";", "context", "=", "context", "||", "document", ";", "if", "(", "idSelector", "&&", "idSelector", "[", "1", "]", ")", "{", "var", "element", "=", "context", ".", "getElementById", "(", "idSelector", "[", "1", "]", ")", ";", "if", "(", "element", ")", "results", ".", "push", "(", "element", ")", ";", "}", "else", "{", "results", "=", "context", ".", "querySelectorAll", "(", "selector", ")", ";", "}", "}", "else", "if", "(", "selector", "&&", "(", "selector", ".", "nodeType", "||", "window", ".", "XMLHttpRequest", "&&", "selector", "instanceof", "XMLHttpRequest", ")", ")", "{", "// allow OTHelpers(DOMNode) and OTHelpers(xmlHttpRequest)", "results", "=", "[", "selector", "]", ";", "context", "=", "selector", ";", "}", "else", "if", "(", "OTHelpers", ".", "isArray", "(", "selector", ")", ")", "{", "results", "=", "selector", ".", "slice", "(", ")", ";", "context", "=", "null", ";", "}", "return", "new", "ElementCollection", "(", "results", ",", "context", ")", ";", "}" ]
The top-level namespace, also performs basic DOMElement selecting. @example Get the DOM element with the id of 'domId' OTHelpers('#domId') @example Get all video elements OTHelpers('video') @example Get all elements with the class name of 'foo' OTHelpers('.foo') @example Get all elements with the class name of 'foo', and do something with the first. var collection = OTHelpers('.foo'); console.log(collection.first); The second argument is the context, that is document or parent Element, to select from. @example Get a video element within the element with the id of 'domId' OTHelpers('video', OTHelpers('#domId')) OTHelpers will accept any of the following and return a collection: OTHelpers() OTHelpers('css selector', optionalParentNode) OTHelpers(DomNode) OTHelpers([array of DomNode]) The collection is a ElementCollection object, see the ElementCollection docs for usage info.
[ "The", "top", "-", "level", "namespace", "also", "performs", "basic", "DOMElement", "selecting", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L83-L111
52,643
eaze/potluck-opentok-adapter
vendor/opentok.js
nodeListToArray
function nodeListToArray (nodes) { if ($.env.name !== 'IE' || $.env.version > 9) { return prototypeSlice.call(nodes); } // IE 9 and below call use Array.prototype.slice.call against // a NodeList, hence the following var array = []; for (var i=0, num=nodes.length; i<num; ++i) { array.push(nodes[i]); } return array; }
javascript
function nodeListToArray (nodes) { if ($.env.name !== 'IE' || $.env.version > 9) { return prototypeSlice.call(nodes); } // IE 9 and below call use Array.prototype.slice.call against // a NodeList, hence the following var array = []; for (var i=0, num=nodes.length; i<num; ++i) { array.push(nodes[i]); } return array; }
[ "function", "nodeListToArray", "(", "nodes", ")", "{", "if", "(", "$", ".", "env", ".", "name", "!==", "'IE'", "||", "$", ".", "env", ".", "version", ">", "9", ")", "{", "return", "prototypeSlice", ".", "call", "(", "nodes", ")", ";", "}", "// IE 9 and below call use Array.prototype.slice.call against", "// a NodeList, hence the following", "var", "array", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "num", "=", "nodes", ".", "length", ";", "i", "<", "num", ";", "++", "i", ")", "{", "array", ".", "push", "(", "nodes", "[", "i", "]", ")", ";", "}", "return", "array", ";", "}" ]
A helper for converting a NodeList to a JS Array
[ "A", "helper", "for", "converting", "a", "NodeList", "to", "a", "JS", "Array" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L117-L131
52,644
eaze/potluck-opentok-adapter
vendor/opentok.js
versionGEThan
function versionGEThan (otherVersion) { if (otherVersion === version) return true; if (typeof(otherVersion) === 'number' && typeof(version) === 'number') { return otherVersion > version; } // The versions have multiple components (i.e. 0.10.30) and // must be compared piecewise. // Note: I'm ignoring the case where one version has multiple // components and the other doesn't. var v1 = otherVersion.split('.'), v2 = version.split('.'), versionLength = (v1.length > v2.length ? v2 : v1).length; for (var i = 0; i < versionLength; ++i) { if (parseInt(v1[i], 10) > parseInt(v2[i], 10)) { return true; } } // Special case, v1 has extra components but the initial components // were identical, we assume this means newer but it might also mean // that someone changed versioning systems. if (i < v1.length) { return true; } return false; }
javascript
function versionGEThan (otherVersion) { if (otherVersion === version) return true; if (typeof(otherVersion) === 'number' && typeof(version) === 'number') { return otherVersion > version; } // The versions have multiple components (i.e. 0.10.30) and // must be compared piecewise. // Note: I'm ignoring the case where one version has multiple // components and the other doesn't. var v1 = otherVersion.split('.'), v2 = version.split('.'), versionLength = (v1.length > v2.length ? v2 : v1).length; for (var i = 0; i < versionLength; ++i) { if (parseInt(v1[i], 10) > parseInt(v2[i], 10)) { return true; } } // Special case, v1 has extra components but the initial components // were identical, we assume this means newer but it might also mean // that someone changed versioning systems. if (i < v1.length) { return true; } return false; }
[ "function", "versionGEThan", "(", "otherVersion", ")", "{", "if", "(", "otherVersion", "===", "version", ")", "return", "true", ";", "if", "(", "typeof", "(", "otherVersion", ")", "===", "'number'", "&&", "typeof", "(", "version", ")", "===", "'number'", ")", "{", "return", "otherVersion", ">", "version", ";", "}", "// The versions have multiple components (i.e. 0.10.30) and", "// must be compared piecewise.", "// Note: I'm ignoring the case where one version has multiple", "// components and the other doesn't.", "var", "v1", "=", "otherVersion", ".", "split", "(", "'.'", ")", ",", "v2", "=", "version", ".", "split", "(", "'.'", ")", ",", "versionLength", "=", "(", "v1", ".", "length", ">", "v2", ".", "length", "?", "v2", ":", "v1", ")", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "versionLength", ";", "++", "i", ")", "{", "if", "(", "parseInt", "(", "v1", "[", "i", "]", ",", "10", ")", ">", "parseInt", "(", "v2", "[", "i", "]", ",", "10", ")", ")", "{", "return", "true", ";", "}", "}", "// Special case, v1 has extra components but the initial components", "// were identical, we assume this means newer but it might also mean", "// that someone changed versioning systems.", "if", "(", "i", "<", "v1", ".", "length", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Returns true if otherVersion is greater than the current environment version.
[ "Returns", "true", "if", "otherVersion", "is", "greater", "than", "the", "current", "environment", "version", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L2727-L2756
52,645
eaze/potluck-opentok-adapter
vendor/opentok.js
executeListenersAsyncronously
function executeListenersAsyncronously(name, args, defaultAction) { var listeners = api.events[name]; if (!listeners || listeners.length === 0) return; var listenerAcks = listeners.length; $.forEach(listeners, function(listener) { // , index function filterHandlers(_listener) { return _listener.handler === listener.handler; } // We run this asynchronously so that it doesn't interfere with execution if an // error happens $.callAsync(function() { try { // have to check if the listener has not been removed if (api.events[name] && $.some(api.events[name], filterHandlers)) { (listener.closure || listener.handler).apply(listener.context || null, args); } } finally { listenerAcks--; if (listenerAcks === 0) { executeDefaultAction(defaultAction, args); } } }); }); }
javascript
function executeListenersAsyncronously(name, args, defaultAction) { var listeners = api.events[name]; if (!listeners || listeners.length === 0) return; var listenerAcks = listeners.length; $.forEach(listeners, function(listener) { // , index function filterHandlers(_listener) { return _listener.handler === listener.handler; } // We run this asynchronously so that it doesn't interfere with execution if an // error happens $.callAsync(function() { try { // have to check if the listener has not been removed if (api.events[name] && $.some(api.events[name], filterHandlers)) { (listener.closure || listener.handler).apply(listener.context || null, args); } } finally { listenerAcks--; if (listenerAcks === 0) { executeDefaultAction(defaultAction, args); } } }); }); }
[ "function", "executeListenersAsyncronously", "(", "name", ",", "args", ",", "defaultAction", ")", "{", "var", "listeners", "=", "api", ".", "events", "[", "name", "]", ";", "if", "(", "!", "listeners", "||", "listeners", ".", "length", "===", "0", ")", "return", ";", "var", "listenerAcks", "=", "listeners", ".", "length", ";", "$", ".", "forEach", "(", "listeners", ",", "function", "(", "listener", ")", "{", "// , index", "function", "filterHandlers", "(", "_listener", ")", "{", "return", "_listener", ".", "handler", "===", "listener", ".", "handler", ";", "}", "// We run this asynchronously so that it doesn't interfere with execution if an", "// error happens", "$", ".", "callAsync", "(", "function", "(", ")", "{", "try", "{", "// have to check if the listener has not been removed", "if", "(", "api", ".", "events", "[", "name", "]", "&&", "$", ".", "some", "(", "api", ".", "events", "[", "name", "]", ",", "filterHandlers", ")", ")", "{", "(", "listener", ".", "closure", "||", "listener", ".", "handler", ")", ".", "apply", "(", "listener", ".", "context", "||", "null", ",", "args", ")", ";", "}", "}", "finally", "{", "listenerAcks", "--", ";", "if", "(", "listenerAcks", "===", "0", ")", "{", "executeDefaultAction", "(", "defaultAction", ",", "args", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}" ]
Execute each handler in +listeners+ with +args+. Each handler will be executed async. On completion the defaultAction handler will be executed with the args. @param [Array] listeners An array of functions to execute. Each will be passed args. @param [Array] args An array of arguments to execute each function in +listeners+ with. @param [String] name The name of this event. @param [Function, Null, Undefined] defaultAction An optional function to execute after every other handler. This will execute even if +listeners+ is empty. +defaultAction+ will be passed args as a normal handler would. @return Undefined
[ "Execute", "each", "handler", "in", "+", "listeners", "+", "with", "+", "args", "+", ".", "Each", "handler", "will", "be", "executed", "async", ".", "On", "completion", "the", "defaultAction", "handler", "will", "be", "executed", "with", "the", "args", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L2985-L3014
52,646
eaze/potluck-opentok-adapter
vendor/opentok.js
executeListenersSyncronously
function executeListenersSyncronously(name, args) { // defaultAction is not used var listeners = api.events[name]; if (!listeners || listeners.length === 0) return; $.forEach(listeners, function(listener) { // index (listener.closure || listener.handler).apply(listener.context || null, args); }); }
javascript
function executeListenersSyncronously(name, args) { // defaultAction is not used var listeners = api.events[name]; if (!listeners || listeners.length === 0) return; $.forEach(listeners, function(listener) { // index (listener.closure || listener.handler).apply(listener.context || null, args); }); }
[ "function", "executeListenersSyncronously", "(", "name", ",", "args", ")", "{", "// defaultAction is not used", "var", "listeners", "=", "api", ".", "events", "[", "name", "]", ";", "if", "(", "!", "listeners", "||", "listeners", ".", "length", "===", "0", ")", "return", ";", "$", ".", "forEach", "(", "listeners", ",", "function", "(", "listener", ")", "{", "// index", "(", "listener", ".", "closure", "||", "listener", ".", "handler", ")", ".", "apply", "(", "listener", ".", "context", "||", "null", ",", "args", ")", ";", "}", ")", ";", "}" ]
This is identical to executeListenersAsyncronously except that handlers will be executed syncronously. On completion the defaultAction handler will be executed with the args. @param [Array] listeners An array of functions to execute. Each will be passed args. @param [Array] args An array of arguments to execute each function in +listeners+ with. @param [String] name The name of this event. @param [Function, Null, Undefined] defaultAction An optional function to execute after every other handler. This will execute even if +listeners+ is empty. +defaultAction+ will be passed args as a normal handler would. @return Undefined
[ "This", "is", "identical", "to", "executeListenersAsyncronously", "except", "that", "handlers", "will", "be", "executed", "syncronously", ".", "On", "completion", "the", "defaultAction", "handler", "will", "be", "executed", "with", "the", "args", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L3038-L3045
52,647
eaze/potluck-opentok-adapter
vendor/opentok.js
appendToLogs
function appendToLogs(level, args) { if (!args) return; var message = toDebugString(args); if (message.length <= 2) return; _logs.push( [level, formatDateStamp(), message] ); }
javascript
function appendToLogs(level, args) { if (!args) return; var message = toDebugString(args); if (message.length <= 2) return; _logs.push( [level, formatDateStamp(), message] ); }
[ "function", "appendToLogs", "(", "level", ",", "args", ")", "{", "if", "(", "!", "args", ")", "return", ";", "var", "message", "=", "toDebugString", "(", "args", ")", ";", "if", "(", "message", ".", "length", "<=", "2", ")", "return", ";", "_logs", ".", "push", "(", "[", "level", ",", "formatDateStamp", "(", ")", ",", "message", "]", ")", ";", "}" ]
Append +args+ to logs, along with the current log level and the a date stamp.
[ "Append", "+", "args", "+", "to", "logs", "along", "with", "the", "current", "log", "level", "and", "the", "a", "date", "stamp", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L3502-L3511
52,648
eaze/potluck-opentok-adapter
vendor/opentok.js
function (name, callback) { capabilities[name] = function() { var result = callback(); capabilities[name] = function() { return result; }; return result; }; }
javascript
function (name, callback) { capabilities[name] = function() { var result = callback(); capabilities[name] = function() { return result; }; return result; }; }
[ "function", "(", "name", ",", "callback", ")", "{", "capabilities", "[", "name", "]", "=", "function", "(", ")", "{", "var", "result", "=", "callback", "(", ")", ";", "capabilities", "[", "name", "]", "=", "function", "(", ")", "{", "return", "result", ";", "}", ";", "return", "result", ";", "}", ";", "}" ]
Wrap up a capability test in a function that memorises the result.
[ "Wrap", "up", "a", "capability", "test", "in", "a", "function", "that", "memorises", "the", "result", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L3949-L3958
52,649
eaze/potluck-opentok-adapter
vendor/opentok.js
shim
function shim () { if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, FNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; FNOP.prototype = this.prototype; fBound.prototype = new FNOP(); return fBound; }; } if(!Array.isArray) { Array.isArray = function (vArg) { return Object.prototype.toString.call(vArg) === '[object Array]'; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement, fromIndex) { var i, pivot = (fromIndex) ? fromIndex : 0, length; if (!this) { throw new TypeError(); } length = this.length; if (length === 0 || pivot >= length) { return -1; } if (pivot < 0) { pivot = length - Math.abs(pivot); } for (i = pivot; i < length; i++) { if (this[i] === searchElement) { return i; } } return -1; }; } if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisArg */) { 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = new Array(len); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { // NOTE: Absolute correctness would demand Object.defineProperty // be used. But this method is fairly new, and failure is // possible only if Object.prototype or Array.prototype // has a property |i| (very unlikely), so use a less-correct // but more portable alternative. if (i in t) res[i] = fun.call(thisArg, t[i], i, t); } return res; }; } }
javascript
function shim () { if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, FNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; FNOP.prototype = this.prototype; fBound.prototype = new FNOP(); return fBound; }; } if(!Array.isArray) { Array.isArray = function (vArg) { return Object.prototype.toString.call(vArg) === '[object Array]'; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement, fromIndex) { var i, pivot = (fromIndex) ? fromIndex : 0, length; if (!this) { throw new TypeError(); } length = this.length; if (length === 0 || pivot >= length) { return -1; } if (pivot < 0) { pivot = length - Math.abs(pivot); } for (i = pivot; i < length; i++) { if (this[i] === searchElement) { return i; } } return -1; }; } if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisArg */) { 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = new Array(len); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { // NOTE: Absolute correctness would demand Object.defineProperty // be used. But this method is fairly new, and failure is // possible only if Object.prototype or Array.prototype // has a property |i| (very unlikely), so use a less-correct // but more portable alternative. if (i in t) res[i] = fun.call(thisArg, t[i], i, t); } return res; }; } }
[ "function", "shim", "(", ")", "{", "if", "(", "!", "Function", ".", "prototype", ".", "bind", ")", "{", "Function", ".", "prototype", ".", "bind", "=", "function", "(", "oThis", ")", "{", "if", "(", "typeof", "this", "!==", "'function'", ")", "{", "// closest thing possible to the ECMAScript 5 internal IsCallable function", "throw", "new", "TypeError", "(", "'Function.prototype.bind - what is trying to be bound is not callable'", ")", ";", "}", "var", "aArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ",", "fToBind", "=", "this", ",", "FNOP", "=", "function", "(", ")", "{", "}", ",", "fBound", "=", "function", "(", ")", "{", "return", "fToBind", ".", "apply", "(", "this", "instanceof", "FNOP", "&&", "oThis", "?", "this", ":", "oThis", ",", "aArgs", ".", "concat", "(", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ")", ";", "}", ";", "FNOP", ".", "prototype", "=", "this", ".", "prototype", ";", "fBound", ".", "prototype", "=", "new", "FNOP", "(", ")", ";", "return", "fBound", ";", "}", ";", "}", "if", "(", "!", "Array", ".", "isArray", ")", "{", "Array", ".", "isArray", "=", "function", "(", "vArg", ")", "{", "return", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "vArg", ")", "===", "'[object Array]'", ";", "}", ";", "}", "if", "(", "!", "Array", ".", "prototype", ".", "indexOf", ")", "{", "Array", ".", "prototype", ".", "indexOf", "=", "function", "(", "searchElement", ",", "fromIndex", ")", "{", "var", "i", ",", "pivot", "=", "(", "fromIndex", ")", "?", "fromIndex", ":", "0", ",", "length", ";", "if", "(", "!", "this", ")", "{", "throw", "new", "TypeError", "(", ")", ";", "}", "length", "=", "this", ".", "length", ";", "if", "(", "length", "===", "0", "||", "pivot", ">=", "length", ")", "{", "return", "-", "1", ";", "}", "if", "(", "pivot", "<", "0", ")", "{", "pivot", "=", "length", "-", "Math", ".", "abs", "(", "pivot", ")", ";", "}", "for", "(", "i", "=", "pivot", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "this", "[", "i", "]", "===", "searchElement", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}", ";", "}", "if", "(", "!", "Array", ".", "prototype", ".", "map", ")", "{", "Array", ".", "prototype", ".", "map", "=", "function", "(", "fun", "/*, thisArg */", ")", "{", "'use strict'", ";", "if", "(", "this", "===", "void", "0", "||", "this", "===", "null", ")", "throw", "new", "TypeError", "(", ")", ";", "var", "t", "=", "Object", "(", "this", ")", ";", "var", "len", "=", "t", ".", "length", ">>>", "0", ";", "if", "(", "typeof", "fun", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", ")", ";", "}", "var", "res", "=", "new", "Array", "(", "len", ")", ";", "var", "thisArg", "=", "arguments", ".", "length", ">=", "2", "?", "arguments", "[", "1", "]", ":", "void", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "// NOTE: Absolute correctness would demand Object.defineProperty", "// be used. But this method is fairly new, and failure is", "// possible only if Object.prototype or Array.prototype", "// has a property |i| (very unlikely), so use a less-correct", "// but more portable alternative.", "if", "(", "i", "in", "t", ")", "res", "[", "i", "]", "=", "fun", ".", "call", "(", "thisArg", ",", "t", "[", "i", "]", ",", "i", ",", "t", ")", ";", "}", "return", "res", ";", "}", ";", "}", "}" ]
Shims for various missing things from JS Applied only after init is called to prevent unnecessary polution
[ "Shims", "for", "various", "missing", "things", "from", "JS", "Applied", "only", "after", "init", "is", "called", "to", "prevent", "unnecessary", "polution" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L6185-L6274
52,650
eaze/potluck-opentok-adapter
vendor/opentok.js
function (options, completion) { var Proto = function PluginProxy() {}, api = new Proto(), waitForReadySignal = pluginEventingBehaviour(api); refCountBehaviour(api); // Assign +plugin+ to this object and setup all the public // accessors that relate to the DOM Object. // var setPlugin = function setPlugin (plugin) { if (plugin) { api._ = plugin; api.parentElement = plugin.parentElement; api.$ = $(plugin); } else { api._ = null; api.parentElement = null; api.$ = $(); } }; api.uuid = generateCallbackID(); api.isValid = function() { return api._.valid; }; api.destroy = function() { api.removeAllRefs(); setPlugin(null); // Let listeners know that they should do any final book keeping // that relates to us. api.emit('destroy'); }; /// Initialise // The next statement creates the raw plugin object accessor on the Proxy. // This is null until we actually have created the Object. setPlugin(null); waitOnGlobalCallback(api.uuid, function(err) { if (err) { completion('The plugin with the mimeType of ' + options.mimeType + ' timed out while loading: ' + err); api.destroy(); return; } api._.setAttribute('id', 'tb_plugin_' + api._.uuid); api._.removeAttribute('tb_callback_id'); api.uuid = api._.uuid; api.id = api._.id; waitForReadySignal(function(err) { if (err) { completion('Error while starting up plugin ' + api.uuid + ': ' + err); api.destroy(); return; } completion(void 0, api); }); }); createObject(api.uuid, options, function(err, plugin) { setPlugin(plugin); }); return api; }
javascript
function (options, completion) { var Proto = function PluginProxy() {}, api = new Proto(), waitForReadySignal = pluginEventingBehaviour(api); refCountBehaviour(api); // Assign +plugin+ to this object and setup all the public // accessors that relate to the DOM Object. // var setPlugin = function setPlugin (plugin) { if (plugin) { api._ = plugin; api.parentElement = plugin.parentElement; api.$ = $(plugin); } else { api._ = null; api.parentElement = null; api.$ = $(); } }; api.uuid = generateCallbackID(); api.isValid = function() { return api._.valid; }; api.destroy = function() { api.removeAllRefs(); setPlugin(null); // Let listeners know that they should do any final book keeping // that relates to us. api.emit('destroy'); }; /// Initialise // The next statement creates the raw plugin object accessor on the Proxy. // This is null until we actually have created the Object. setPlugin(null); waitOnGlobalCallback(api.uuid, function(err) { if (err) { completion('The plugin with the mimeType of ' + options.mimeType + ' timed out while loading: ' + err); api.destroy(); return; } api._.setAttribute('id', 'tb_plugin_' + api._.uuid); api._.removeAttribute('tb_callback_id'); api.uuid = api._.uuid; api.id = api._.id; waitForReadySignal(function(err) { if (err) { completion('Error while starting up plugin ' + api.uuid + ': ' + err); api.destroy(); return; } completion(void 0, api); }); }); createObject(api.uuid, options, function(err, plugin) { setPlugin(plugin); }); return api; }
[ "function", "(", "options", ",", "completion", ")", "{", "var", "Proto", "=", "function", "PluginProxy", "(", ")", "{", "}", ",", "api", "=", "new", "Proto", "(", ")", ",", "waitForReadySignal", "=", "pluginEventingBehaviour", "(", "api", ")", ";", "refCountBehaviour", "(", "api", ")", ";", "// Assign +plugin+ to this object and setup all the public", "// accessors that relate to the DOM Object.", "//", "var", "setPlugin", "=", "function", "setPlugin", "(", "plugin", ")", "{", "if", "(", "plugin", ")", "{", "api", ".", "_", "=", "plugin", ";", "api", ".", "parentElement", "=", "plugin", ".", "parentElement", ";", "api", ".", "$", "=", "$", "(", "plugin", ")", ";", "}", "else", "{", "api", ".", "_", "=", "null", ";", "api", ".", "parentElement", "=", "null", ";", "api", ".", "$", "=", "$", "(", ")", ";", "}", "}", ";", "api", ".", "uuid", "=", "generateCallbackID", "(", ")", ";", "api", ".", "isValid", "=", "function", "(", ")", "{", "return", "api", ".", "_", ".", "valid", ";", "}", ";", "api", ".", "destroy", "=", "function", "(", ")", "{", "api", ".", "removeAllRefs", "(", ")", ";", "setPlugin", "(", "null", ")", ";", "// Let listeners know that they should do any final book keeping", "// that relates to us.", "api", ".", "emit", "(", "'destroy'", ")", ";", "}", ";", "/// Initialise", "// The next statement creates the raw plugin object accessor on the Proxy.", "// This is null until we actually have created the Object.", "setPlugin", "(", "null", ")", ";", "waitOnGlobalCallback", "(", "api", ".", "uuid", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "completion", "(", "'The plugin with the mimeType of '", "+", "options", ".", "mimeType", "+", "' timed out while loading: '", "+", "err", ")", ";", "api", ".", "destroy", "(", ")", ";", "return", ";", "}", "api", ".", "_", ".", "setAttribute", "(", "'id'", ",", "'tb_plugin_'", "+", "api", ".", "_", ".", "uuid", ")", ";", "api", ".", "_", ".", "removeAttribute", "(", "'tb_callback_id'", ")", ";", "api", ".", "uuid", "=", "api", ".", "_", ".", "uuid", ";", "api", ".", "id", "=", "api", ".", "_", ".", "id", ";", "waitForReadySignal", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "completion", "(", "'Error while starting up plugin '", "+", "api", ".", "uuid", "+", "': '", "+", "err", ")", ";", "api", ".", "destroy", "(", ")", ";", "return", ";", "}", "completion", "(", "void", "0", ",", "api", ")", ";", "}", ")", ";", "}", ")", ";", "createObject", "(", "api", ".", "uuid", ",", "options", ",", "function", "(", "err", ",", "plugin", ")", "{", "setPlugin", "(", "plugin", ")", ";", "}", ")", ";", "return", "api", ";", "}" ]
Reference counted wrapper for a plugin object
[ "Reference", "counted", "wrapper", "for", "a", "plugin", "object" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L6603-L6681
52,651
eaze/potluck-opentok-adapter
vendor/opentok.js
setPlugin
function setPlugin (plugin) { if (plugin) { api._ = plugin; api.parentElement = plugin.parentElement; api.$ = $(plugin); } else { api._ = null; api.parentElement = null; api.$ = $(); } }
javascript
function setPlugin (plugin) { if (plugin) { api._ = plugin; api.parentElement = plugin.parentElement; api.$ = $(plugin); } else { api._ = null; api.parentElement = null; api.$ = $(); } }
[ "function", "setPlugin", "(", "plugin", ")", "{", "if", "(", "plugin", ")", "{", "api", ".", "_", "=", "plugin", ";", "api", ".", "parentElement", "=", "plugin", ".", "parentElement", ";", "api", ".", "$", "=", "$", "(", "plugin", ")", ";", "}", "else", "{", "api", ".", "_", "=", "null", ";", "api", ".", "parentElement", "=", "null", ";", "api", ".", "$", "=", "$", "(", ")", ";", "}", "}" ]
Assign +plugin+ to this object and setup all the public accessors that relate to the DOM Object.
[ "Assign", "+", "plugin", "+", "to", "this", "object", "and", "setup", "all", "the", "public", "accessors", "that", "relate", "to", "the", "DOM", "Object", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L6613-L6624
52,652
eaze/potluck-opentok-adapter
vendor/opentok.js
makeMediaCapturerProxy
function makeMediaCapturerProxy (api) { api.selectSources = function() { return api._.selectSources.apply(api._, arguments); }; return api; }
javascript
function makeMediaCapturerProxy (api) { api.selectSources = function() { return api._.selectSources.apply(api._, arguments); }; return api; }
[ "function", "makeMediaCapturerProxy", "(", "api", ")", "{", "api", ".", "selectSources", "=", "function", "(", ")", "{", "return", "api", ".", "_", ".", "selectSources", ".", "apply", "(", "api", ".", "_", ",", "arguments", ")", ";", "}", ";", "return", "api", ";", "}" ]
Specialisation for the MediaCapturer API surface
[ "Specialisation", "for", "the", "MediaCapturer", "API", "surface" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L6687-L6694
52,653
eaze/potluck-opentok-adapter
vendor/opentok.js
makeMediaPeerProxy
function makeMediaPeerProxy (api) { api.setStream = function(stream, completion) { api._.setStream(stream); if (completion) { if (stream.hasVideo()) { // FIX ME renderingStarted currently doesn't first // api.once('renderingStarted', completion); var verifyStream = function() { if (!api._) { completion(new $.Error('The plugin went away before the stream could be bound.')); return; } if (api._.videoWidth > 0) { // This fires a little too soon. setTimeout(completion, 200); } else { setTimeout(verifyStream, 500); } }; setTimeout(verifyStream, 500); } else { // TODO Investigate whether there is a good way to detect // when the audio is ready. Does it even matter? // This fires a little too soon. setTimeout(completion, 200); } } return api; }; return api; }
javascript
function makeMediaPeerProxy (api) { api.setStream = function(stream, completion) { api._.setStream(stream); if (completion) { if (stream.hasVideo()) { // FIX ME renderingStarted currently doesn't first // api.once('renderingStarted', completion); var verifyStream = function() { if (!api._) { completion(new $.Error('The plugin went away before the stream could be bound.')); return; } if (api._.videoWidth > 0) { // This fires a little too soon. setTimeout(completion, 200); } else { setTimeout(verifyStream, 500); } }; setTimeout(verifyStream, 500); } else { // TODO Investigate whether there is a good way to detect // when the audio is ready. Does it even matter? // This fires a little too soon. setTimeout(completion, 200); } } return api; }; return api; }
[ "function", "makeMediaPeerProxy", "(", "api", ")", "{", "api", ".", "setStream", "=", "function", "(", "stream", ",", "completion", ")", "{", "api", ".", "_", ".", "setStream", "(", "stream", ")", ";", "if", "(", "completion", ")", "{", "if", "(", "stream", ".", "hasVideo", "(", ")", ")", "{", "// FIX ME renderingStarted currently doesn't first", "// api.once('renderingStarted', completion);", "var", "verifyStream", "=", "function", "(", ")", "{", "if", "(", "!", "api", ".", "_", ")", "{", "completion", "(", "new", "$", ".", "Error", "(", "'The plugin went away before the stream could be bound.'", ")", ")", ";", "return", ";", "}", "if", "(", "api", ".", "_", ".", "videoWidth", ">", "0", ")", "{", "// This fires a little too soon.", "setTimeout", "(", "completion", ",", "200", ")", ";", "}", "else", "{", "setTimeout", "(", "verifyStream", ",", "500", ")", ";", "}", "}", ";", "setTimeout", "(", "verifyStream", ",", "500", ")", ";", "}", "else", "{", "// TODO Investigate whether there is a good way to detect", "// when the audio is ready. Does it even matter?", "// This fires a little too soon.", "setTimeout", "(", "completion", ",", "200", ")", ";", "}", "}", "return", "api", ";", "}", ";", "return", "api", ";", "}" ]
Specialisation for the MediaPeer API surface
[ "Specialisation", "for", "the", "MediaPeer", "API", "surface" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L6698-L6736
52,654
eaze/potluck-opentok-adapter
vendor/opentok.js
versionGreaterThan
function versionGreaterThan (version1, version2) { if (version1 === version2) return false; if (version1 === -1) return version2; if (version2 === -1) return version1; if (version1.indexOf('.') === -1 && version2.indexOf('.') === -1) { return version1 > version2; } // The versions have multiple components (i.e. 0.10.30) and // must be compared piecewise. // Note: I'm ignoring the case where one version has multiple // components and the other doesn't. var v1 = version1.split('.'), v2 = version2.split('.'), versionLength = (v1.length > v2.length ? v2 : v1).length; for (var i = 0; i < versionLength; ++i) { if (parseInt(v1[i], 10) > parseInt(v2[i], 10)) { return true; } } // Special case, v1 has extra components but the initial components // were identical, we assume this means newer but it might also mean // that someone changed versioning systems. if (i < v1.length) { return true; } return false; }
javascript
function versionGreaterThan (version1, version2) { if (version1 === version2) return false; if (version1 === -1) return version2; if (version2 === -1) return version1; if (version1.indexOf('.') === -1 && version2.indexOf('.') === -1) { return version1 > version2; } // The versions have multiple components (i.e. 0.10.30) and // must be compared piecewise. // Note: I'm ignoring the case where one version has multiple // components and the other doesn't. var v1 = version1.split('.'), v2 = version2.split('.'), versionLength = (v1.length > v2.length ? v2 : v1).length; for (var i = 0; i < versionLength; ++i) { if (parseInt(v1[i], 10) > parseInt(v2[i], 10)) { return true; } } // Special case, v1 has extra components but the initial components // were identical, we assume this means newer but it might also mean // that someone changed versioning systems. if (i < v1.length) { return true; } return false; }
[ "function", "versionGreaterThan", "(", "version1", ",", "version2", ")", "{", "if", "(", "version1", "===", "version2", ")", "return", "false", ";", "if", "(", "version1", "===", "-", "1", ")", "return", "version2", ";", "if", "(", "version2", "===", "-", "1", ")", "return", "version1", ";", "if", "(", "version1", ".", "indexOf", "(", "'.'", ")", "===", "-", "1", "&&", "version2", ".", "indexOf", "(", "'.'", ")", "===", "-", "1", ")", "{", "return", "version1", ">", "version2", ";", "}", "// The versions have multiple components (i.e. 0.10.30) and", "// must be compared piecewise.", "// Note: I'm ignoring the case where one version has multiple", "// components and the other doesn't.", "var", "v1", "=", "version1", ".", "split", "(", "'.'", ")", ",", "v2", "=", "version2", ".", "split", "(", "'.'", ")", ",", "versionLength", "=", "(", "v1", ".", "length", ">", "v2", ".", "length", "?", "v2", ":", "v1", ")", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "versionLength", ";", "++", "i", ")", "{", "if", "(", "parseInt", "(", "v1", "[", "i", "]", ",", "10", ")", ">", "parseInt", "(", "v2", "[", "i", "]", ",", "10", ")", ")", "{", "return", "true", ";", "}", "}", "// Special case, v1 has extra components but the initial components", "// were identical, we assume this means newer but it might also mean", "// that someone changed versioning systems.", "if", "(", "i", "<", "v1", ".", "length", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
<- cached version, use getInstallerMimeType instead
[ "<", "-", "cached", "version", "use", "getInstallerMimeType", "instead" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L7535-L7567
52,655
eaze/potluck-opentok-adapter
vendor/opentok.js
_getUserMedia
function _getUserMedia(mediaConstraints, success, error) { PluginProxies.createMediaPeer(function(err, plugin) { if (err) { error.call(OTPlugin, err); return; } plugin._.getUserMedia(mediaConstraints.toHash(), function(streamJson) { success.call(OTPlugin, MediaStream.fromJson(streamJson, plugin)); }, error); }); }
javascript
function _getUserMedia(mediaConstraints, success, error) { PluginProxies.createMediaPeer(function(err, plugin) { if (err) { error.call(OTPlugin, err); return; } plugin._.getUserMedia(mediaConstraints.toHash(), function(streamJson) { success.call(OTPlugin, MediaStream.fromJson(streamJson, plugin)); }, error); }); }
[ "function", "_getUserMedia", "(", "mediaConstraints", ",", "success", ",", "error", ")", "{", "PluginProxies", ".", "createMediaPeer", "(", "function", "(", "err", ",", "plugin", ")", "{", "if", "(", "err", ")", "{", "error", ".", "call", "(", "OTPlugin", ",", "err", ")", ";", "return", ";", "}", "plugin", ".", "_", ".", "getUserMedia", "(", "mediaConstraints", ".", "toHash", "(", ")", ",", "function", "(", "streamJson", ")", "{", "success", ".", "call", "(", "OTPlugin", ",", "MediaStream", ".", "fromJson", "(", "streamJson", ",", "plugin", ")", ")", ";", "}", ",", "error", ")", ";", "}", ")", ";", "}" ]
Helper function for OTPlugin.getUserMedia
[ "Helper", "function", "for", "OTPlugin", ".", "getUserMedia" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L7908-L7919
52,656
eaze/potluck-opentok-adapter
vendor/opentok.js
measureUploadBandwidth
function measureUploadBandwidth(url, payload) { var xhr = new XMLHttpRequest(), resultPromise = new OT.$.RSVP.Promise(function(resolve, reject) { var startTs, lastTs, lastLoaded; xhr.upload.addEventListener('progress', function(evt) { if (!startTs) { startTs = Date.now(); } lastLoaded = evt.loaded; }); xhr.addEventListener('load', function() { lastTs = Date.now(); resolve(1000 * 8 * lastLoaded / (lastTs - startTs)); }); xhr.addEventListener('error', function(e) { reject(e); }); xhr.addEventListener('abort', function() { reject(); }); xhr.open('POST', url); xhr.send(payload); }); return { promise: resultPromise, abort: function() { xhr.abort(); } }; }
javascript
function measureUploadBandwidth(url, payload) { var xhr = new XMLHttpRequest(), resultPromise = new OT.$.RSVP.Promise(function(resolve, reject) { var startTs, lastTs, lastLoaded; xhr.upload.addEventListener('progress', function(evt) { if (!startTs) { startTs = Date.now(); } lastLoaded = evt.loaded; }); xhr.addEventListener('load', function() { lastTs = Date.now(); resolve(1000 * 8 * lastLoaded / (lastTs - startTs)); }); xhr.addEventListener('error', function(e) { reject(e); }); xhr.addEventListener('abort', function() { reject(); }); xhr.open('POST', url); xhr.send(payload); }); return { promise: resultPromise, abort: function() { xhr.abort(); } }; }
[ "function", "measureUploadBandwidth", "(", "url", ",", "payload", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ",", "resultPromise", "=", "new", "OT", ".", "$", ".", "RSVP", ".", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "startTs", ",", "lastTs", ",", "lastLoaded", ";", "xhr", ".", "upload", ".", "addEventListener", "(", "'progress'", ",", "function", "(", "evt", ")", "{", "if", "(", "!", "startTs", ")", "{", "startTs", "=", "Date", ".", "now", "(", ")", ";", "}", "lastLoaded", "=", "evt", ".", "loaded", ";", "}", ")", ";", "xhr", ".", "addEventListener", "(", "'load'", ",", "function", "(", ")", "{", "lastTs", "=", "Date", ".", "now", "(", ")", ";", "resolve", "(", "1000", "*", "8", "*", "lastLoaded", "/", "(", "lastTs", "-", "startTs", ")", ")", ";", "}", ")", ";", "xhr", ".", "addEventListener", "(", "'error'", ",", "function", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", ")", ";", "xhr", ".", "addEventListener", "(", "'abort'", ",", "function", "(", ")", "{", "reject", "(", ")", ";", "}", ")", ";", "xhr", ".", "open", "(", "'POST'", ",", "url", ")", ";", "xhr", ".", "send", "(", "payload", ")", ";", "}", ")", ";", "return", "{", "promise", ":", "resultPromise", ",", "abort", ":", "function", "(", ")", "{", "xhr", ".", "abort", "(", ")", ";", "}", "}", ";", "}" ]
Measures the bandwidth in bps. @param {string} url @param {ArrayBuffer} payload @returns {{promise: Promise, abort: function}}
[ "Measures", "the", "bandwidth", "in", "bps", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L11291-L11324
52,657
eaze/potluck-opentok-adapter
vendor/opentok.js
getMLineIndex
function getMLineIndex(sdpLines, mediaType) { var targetMLine = 'm=' + mediaType; // Find the index of the media line for +type+ return OT.$.findIndex(sdpLines, function(line) { if (line.indexOf(targetMLine) !== -1) { return true; } return false; }); }
javascript
function getMLineIndex(sdpLines, mediaType) { var targetMLine = 'm=' + mediaType; // Find the index of the media line for +type+ return OT.$.findIndex(sdpLines, function(line) { if (line.indexOf(targetMLine) !== -1) { return true; } return false; }); }
[ "function", "getMLineIndex", "(", "sdpLines", ",", "mediaType", ")", "{", "var", "targetMLine", "=", "'m='", "+", "mediaType", ";", "// Find the index of the media line for +type+", "return", "OT", ".", "$", ".", "findIndex", "(", "sdpLines", ",", "function", "(", "line", ")", "{", "if", "(", "line", ".", "indexOf", "(", "targetMLine", ")", "!==", "-", "1", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "}" ]
Search through sdpLines to find the Media Line of type +mediaType+.
[ "Search", "through", "sdpLines", "to", "find", "the", "Media", "Line", "of", "type", "+", "mediaType", "+", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L11391-L11402
52,658
eaze/potluck-opentok-adapter
vendor/opentok.js
getMLinePayloadTypes
function getMLinePayloadTypes (mediaLine, mediaType) { var mLineSelector = new RegExp('^m=' + mediaType + ' \\d+(/\\d+)? [a-zA-Z0-9/]+(( [a-zA-Z0-9/]+)+)$', 'i'); // Get all payload types that the line supports var payloadTypes = mediaLine.match(mLineSelector); if (!payloadTypes || payloadTypes.length < 2) { // Error, invalid M line? return []; } return OT.$.trim(payloadTypes[2]).split(' '); }
javascript
function getMLinePayloadTypes (mediaLine, mediaType) { var mLineSelector = new RegExp('^m=' + mediaType + ' \\d+(/\\d+)? [a-zA-Z0-9/]+(( [a-zA-Z0-9/]+)+)$', 'i'); // Get all payload types that the line supports var payloadTypes = mediaLine.match(mLineSelector); if (!payloadTypes || payloadTypes.length < 2) { // Error, invalid M line? return []; } return OT.$.trim(payloadTypes[2]).split(' '); }
[ "function", "getMLinePayloadTypes", "(", "mediaLine", ",", "mediaType", ")", "{", "var", "mLineSelector", "=", "new", "RegExp", "(", "'^m='", "+", "mediaType", "+", "' \\\\d+(/\\\\d+)? [a-zA-Z0-9/]+(( [a-zA-Z0-9/]+)+)$'", ",", "'i'", ")", ";", "// Get all payload types that the line supports", "var", "payloadTypes", "=", "mediaLine", ".", "match", "(", "mLineSelector", ")", ";", "if", "(", "!", "payloadTypes", "||", "payloadTypes", ".", "length", "<", "2", ")", "{", "// Error, invalid M line?", "return", "[", "]", ";", "}", "return", "OT", ".", "$", ".", "trim", "(", "payloadTypes", "[", "2", "]", ")", ".", "split", "(", "' '", ")", ";", "}" ]
Extract the payload types for a give Media Line.
[ "Extract", "the", "payload", "types", "for", "a", "give", "Media", "Line", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L11406-L11418
52,659
eaze/potluck-opentok-adapter
vendor/opentok.js
removeMediaEncoding
function removeMediaEncoding (sdp, mediaType, encodingName) { var sdpLines = sdp.split('\r\n'), mLineIndex = SDPHelpers.getMLineIndex(sdpLines, mediaType), mLine = mLineIndex > -1 ? sdpLines[mLineIndex] : void 0, typesToRemove = [], payloadTypes, match; if (mLineIndex === -1) { // Error, missing M line return sdpLines.join('\r\n'); } // Get all payload types that the line supports payloadTypes = SDPHelpers.getMLinePayloadTypes(mLine, mediaType); if (payloadTypes.length === 0) { // Error, invalid M line? return sdpLines.join('\r\n'); } // Find the location of all the rtpmap lines that relate to +encodingName+ // and any of the supported payload types var matcher = new RegExp('a=rtpmap:(' + payloadTypes.join('|') + ') ' + encodingName + '\\/\\d+', 'i'); sdpLines = OT.$.filter(sdpLines, function(line, index) { match = line.match(matcher); if (match === null) return true; typesToRemove.push(match[1]); if (index < mLineIndex) { // This removal changed the index of the mline, track it mLineIndex--; } // remove this one return false; }); if (typesToRemove.length > 0 && mLineIndex > -1) { // Remove all the payload types and we've removed from the media line sdpLines[mLineIndex] = SDPHelpers.removeTypesFromMLine(mLine, typesToRemove); } return sdpLines.join('\r\n'); }
javascript
function removeMediaEncoding (sdp, mediaType, encodingName) { var sdpLines = sdp.split('\r\n'), mLineIndex = SDPHelpers.getMLineIndex(sdpLines, mediaType), mLine = mLineIndex > -1 ? sdpLines[mLineIndex] : void 0, typesToRemove = [], payloadTypes, match; if (mLineIndex === -1) { // Error, missing M line return sdpLines.join('\r\n'); } // Get all payload types that the line supports payloadTypes = SDPHelpers.getMLinePayloadTypes(mLine, mediaType); if (payloadTypes.length === 0) { // Error, invalid M line? return sdpLines.join('\r\n'); } // Find the location of all the rtpmap lines that relate to +encodingName+ // and any of the supported payload types var matcher = new RegExp('a=rtpmap:(' + payloadTypes.join('|') + ') ' + encodingName + '\\/\\d+', 'i'); sdpLines = OT.$.filter(sdpLines, function(line, index) { match = line.match(matcher); if (match === null) return true; typesToRemove.push(match[1]); if (index < mLineIndex) { // This removal changed the index of the mline, track it mLineIndex--; } // remove this one return false; }); if (typesToRemove.length > 0 && mLineIndex > -1) { // Remove all the payload types and we've removed from the media line sdpLines[mLineIndex] = SDPHelpers.removeTypesFromMLine(mLine, typesToRemove); } return sdpLines.join('\r\n'); }
[ "function", "removeMediaEncoding", "(", "sdp", ",", "mediaType", ",", "encodingName", ")", "{", "var", "sdpLines", "=", "sdp", ".", "split", "(", "'\\r\\n'", ")", ",", "mLineIndex", "=", "SDPHelpers", ".", "getMLineIndex", "(", "sdpLines", ",", "mediaType", ")", ",", "mLine", "=", "mLineIndex", ">", "-", "1", "?", "sdpLines", "[", "mLineIndex", "]", ":", "void", "0", ",", "typesToRemove", "=", "[", "]", ",", "payloadTypes", ",", "match", ";", "if", "(", "mLineIndex", "===", "-", "1", ")", "{", "// Error, missing M line", "return", "sdpLines", ".", "join", "(", "'\\r\\n'", ")", ";", "}", "// Get all payload types that the line supports", "payloadTypes", "=", "SDPHelpers", ".", "getMLinePayloadTypes", "(", "mLine", ",", "mediaType", ")", ";", "if", "(", "payloadTypes", ".", "length", "===", "0", ")", "{", "// Error, invalid M line?", "return", "sdpLines", ".", "join", "(", "'\\r\\n'", ")", ";", "}", "// Find the location of all the rtpmap lines that relate to +encodingName+", "// and any of the supported payload types", "var", "matcher", "=", "new", "RegExp", "(", "'a=rtpmap:('", "+", "payloadTypes", ".", "join", "(", "'|'", ")", "+", "') '", "+", "encodingName", "+", "'\\\\/\\\\d+'", ",", "'i'", ")", ";", "sdpLines", "=", "OT", ".", "$", ".", "filter", "(", "sdpLines", ",", "function", "(", "line", ",", "index", ")", "{", "match", "=", "line", ".", "match", "(", "matcher", ")", ";", "if", "(", "match", "===", "null", ")", "return", "true", ";", "typesToRemove", ".", "push", "(", "match", "[", "1", "]", ")", ";", "if", "(", "index", "<", "mLineIndex", ")", "{", "// This removal changed the index of the mline, track it", "mLineIndex", "--", ";", "}", "// remove this one", "return", "false", ";", "}", ")", ";", "if", "(", "typesToRemove", ".", "length", ">", "0", "&&", "mLineIndex", ">", "-", "1", ")", "{", "// Remove all the payload types and we've removed from the media line", "sdpLines", "[", "mLineIndex", "]", "=", "SDPHelpers", ".", "removeTypesFromMLine", "(", "mLine", ",", "typesToRemove", ")", ";", "}", "return", "sdpLines", ".", "join", "(", "'\\r\\n'", ")", ";", "}" ]
Remove all references to a particular encodingName from a particular media type
[ "Remove", "all", "references", "to", "a", "particular", "encodingName", "from", "a", "particular", "media", "type" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L11429-L11475
52,660
eaze/potluck-opentok-adapter
vendor/opentok.js
DataChanneMessageEvent
function DataChanneMessageEvent (event) { this.data = event.data; this.source = event.source; this.lastEventId = event.lastEventId; this.origin = event.origin; this.timeStamp = event.timeStamp; this.type = event.type; this.ports = event.ports; this.path = event.path; }
javascript
function DataChanneMessageEvent (event) { this.data = event.data; this.source = event.source; this.lastEventId = event.lastEventId; this.origin = event.origin; this.timeStamp = event.timeStamp; this.type = event.type; this.ports = event.ports; this.path = event.path; }
[ "function", "DataChanneMessageEvent", "(", "event", ")", "{", "this", ".", "data", "=", "event", ".", "data", ";", "this", ".", "source", "=", "event", ".", "source", ";", "this", ".", "lastEventId", "=", "event", ".", "lastEventId", ";", "this", ".", "origin", "=", "event", ".", "origin", ";", "this", ".", "timeStamp", "=", "event", ".", "timeStamp", ";", "this", ".", "type", "=", "event", ".", "type", ";", "this", ".", "ports", "=", "event", ".", "ports", ";", "this", ".", "path", "=", "event", ".", "path", ";", "}" ]
Wraps up a native RTCDataChannelEvent object for the message event. This is so we never accidentally leak the native DataChannel. @constructor @private
[ "Wraps", "up", "a", "native", "RTCDataChannelEvent", "object", "for", "the", "message", "event", ".", "This", "is", "so", "we", "never", "accidentally", "leak", "the", "native", "DataChannel", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L12866-L12875
52,661
eaze/potluck-opentok-adapter
vendor/opentok.js
PeerConnectionChannels
function PeerConnectionChannels (pc) { /// Private Data var channels = [], api = {}; /// Private API var remove = function remove (channel) { OT.$.filter(channels, function(c) { return channel !== c; }); }; var add = function add (nativeChannel) { var channel = new DataChannel(nativeChannel); channels.push(channel); channel.on('close', function() { remove(channel); }); return channel; }; /// Public API api.add = function (label, options) { return add(pc.createDataChannel(label, options)); }; api.addMany = function (newChannels) { for (var label in newChannels) { if (newChannels.hasOwnProperty(label)) { api.add(label, newChannels[label]); } } }; api.get = function (label, options) { return OT.$.find(channels, function(channel) { return channel.equals(label, options); }); }; api.getOrAdd = function (label, options) { var channel = api.get(label, options); if (!channel) { channel = api.add(label, options); } return channel; }; api.destroy = function () { OT.$.forEach(channels, function(channel) { channel.close(); }); channels = []; }; /// Init pc.addEventListener('datachannel', function(event) { add(event.channel); }, false); return api; }
javascript
function PeerConnectionChannels (pc) { /// Private Data var channels = [], api = {}; /// Private API var remove = function remove (channel) { OT.$.filter(channels, function(c) { return channel !== c; }); }; var add = function add (nativeChannel) { var channel = new DataChannel(nativeChannel); channels.push(channel); channel.on('close', function() { remove(channel); }); return channel; }; /// Public API api.add = function (label, options) { return add(pc.createDataChannel(label, options)); }; api.addMany = function (newChannels) { for (var label in newChannels) { if (newChannels.hasOwnProperty(label)) { api.add(label, newChannels[label]); } } }; api.get = function (label, options) { return OT.$.find(channels, function(channel) { return channel.equals(label, options); }); }; api.getOrAdd = function (label, options) { var channel = api.get(label, options); if (!channel) { channel = api.add(label, options); } return channel; }; api.destroy = function () { OT.$.forEach(channels, function(channel) { channel.close(); }); channels = []; }; /// Init pc.addEventListener('datachannel', function(event) { add(event.channel); }, false); return api; }
[ "function", "PeerConnectionChannels", "(", "pc", ")", "{", "/// Private Data", "var", "channels", "=", "[", "]", ",", "api", "=", "{", "}", ";", "/// Private API", "var", "remove", "=", "function", "remove", "(", "channel", ")", "{", "OT", ".", "$", ".", "filter", "(", "channels", ",", "function", "(", "c", ")", "{", "return", "channel", "!==", "c", ";", "}", ")", ";", "}", ";", "var", "add", "=", "function", "add", "(", "nativeChannel", ")", "{", "var", "channel", "=", "new", "DataChannel", "(", "nativeChannel", ")", ";", "channels", ".", "push", "(", "channel", ")", ";", "channel", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "remove", "(", "channel", ")", ";", "}", ")", ";", "return", "channel", ";", "}", ";", "/// Public API", "api", ".", "add", "=", "function", "(", "label", ",", "options", ")", "{", "return", "add", "(", "pc", ".", "createDataChannel", "(", "label", ",", "options", ")", ")", ";", "}", ";", "api", ".", "addMany", "=", "function", "(", "newChannels", ")", "{", "for", "(", "var", "label", "in", "newChannels", ")", "{", "if", "(", "newChannels", ".", "hasOwnProperty", "(", "label", ")", ")", "{", "api", ".", "add", "(", "label", ",", "newChannels", "[", "label", "]", ")", ";", "}", "}", "}", ";", "api", ".", "get", "=", "function", "(", "label", ",", "options", ")", "{", "return", "OT", ".", "$", ".", "find", "(", "channels", ",", "function", "(", "channel", ")", "{", "return", "channel", ".", "equals", "(", "label", ",", "options", ")", ";", "}", ")", ";", "}", ";", "api", ".", "getOrAdd", "=", "function", "(", "label", ",", "options", ")", "{", "var", "channel", "=", "api", ".", "get", "(", "label", ",", "options", ")", ";", "if", "(", "!", "channel", ")", "{", "channel", "=", "api", ".", "add", "(", "label", ",", "options", ")", ";", "}", "return", "channel", ";", "}", ";", "api", ".", "destroy", "=", "function", "(", ")", "{", "OT", ".", "$", ".", "forEach", "(", "channels", ",", "function", "(", "channel", ")", "{", "channel", ".", "close", "(", ")", ";", "}", ")", ";", "channels", "=", "[", "]", ";", "}", ";", "/// Init", "pc", ".", "addEventListener", "(", "'datachannel'", ",", "function", "(", "event", ")", "{", "add", "(", "event", ".", "channel", ")", ";", "}", ",", "false", ")", ";", "return", "api", ";", "}" ]
Contains a collection of DataChannels for a particular RTCPeerConnection @param [RTCPeerConnection] pc A native peer connection object @constructor @private
[ "Contains", "a", "collection", "of", "DataChannels", "for", "a", "particular", "RTCPeerConnection" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L13023-L13094
52,662
eaze/potluck-opentok-adapter
vendor/opentok.js
function(messageDelegate) { return function(event) { if (event.candidate) { messageDelegate(OT.Raptor.Actions.CANDIDATE, { candidate: event.candidate.candidate, sdpMid: event.candidate.sdpMid || '', sdpMLineIndex: event.candidate.sdpMLineIndex || 0 }); } else { OT.debug('IceCandidateForwarder: No more ICE candidates.'); } }; }
javascript
function(messageDelegate) { return function(event) { if (event.candidate) { messageDelegate(OT.Raptor.Actions.CANDIDATE, { candidate: event.candidate.candidate, sdpMid: event.candidate.sdpMid || '', sdpMLineIndex: event.candidate.sdpMLineIndex || 0 }); } else { OT.debug('IceCandidateForwarder: No more ICE candidates.'); } }; }
[ "function", "(", "messageDelegate", ")", "{", "return", "function", "(", "event", ")", "{", "if", "(", "event", ".", "candidate", ")", "{", "messageDelegate", "(", "OT", ".", "Raptor", ".", "Actions", ".", "CANDIDATE", ",", "{", "candidate", ":", "event", ".", "candidate", ".", "candidate", ",", "sdpMid", ":", "event", ".", "candidate", ".", "sdpMid", "||", "''", ",", "sdpMLineIndex", ":", "event", ".", "candidate", ".", "sdpMLineIndex", "||", "0", "}", ")", ";", "}", "else", "{", "OT", ".", "debug", "(", "'IceCandidateForwarder: No more ICE candidates.'", ")", ";", "}", "}", ";", "}" ]
Helper function to forward Ice Candidates via +messageDelegate+
[ "Helper", "function", "to", "forward", "Ice", "Candidates", "via", "+", "messageDelegate", "+" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L13208-L13220
52,663
eaze/potluck-opentok-adapter
vendor/opentok.js
fixFitModeCover
function fixFitModeCover(element, containerWidth, containerHeight, intrinsicRatio, rotated) { var $video = OT.$('.OT_video-element', element); if ($video.length > 0) { var cssProps = {left: '', top: ''}; if (OTPlugin.isInstalled()) { cssProps.width = '100%'; cssProps.height = '100%'; } else { intrinsicRatio = intrinsicRatio || defaultAspectRatio; intrinsicRatio = rotated ? 1 / intrinsicRatio : intrinsicRatio; var containerRatio = containerWidth / containerHeight; var enforcedVideoWidth, enforcedVideoHeight; if (rotated) { // in case of rotation same code works for both kind of ration enforcedVideoHeight = containerWidth; enforcedVideoWidth = enforcedVideoHeight * intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.top = (enforcedVideoWidth + containerHeight) / 2 + 'px'; } else { if (intrinsicRatio < containerRatio) { // the container is wider than the video -> we will crop the height of the video enforcedVideoWidth = containerWidth; enforcedVideoHeight = enforcedVideoWidth / intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.top = (-enforcedVideoHeight + containerHeight) / 2 + 'px'; } else { enforcedVideoHeight = containerHeight; enforcedVideoWidth = enforcedVideoHeight * intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.left = (-enforcedVideoWidth + containerWidth) / 2 + 'px'; } } } $video.css(cssProps); } }
javascript
function fixFitModeCover(element, containerWidth, containerHeight, intrinsicRatio, rotated) { var $video = OT.$('.OT_video-element', element); if ($video.length > 0) { var cssProps = {left: '', top: ''}; if (OTPlugin.isInstalled()) { cssProps.width = '100%'; cssProps.height = '100%'; } else { intrinsicRatio = intrinsicRatio || defaultAspectRatio; intrinsicRatio = rotated ? 1 / intrinsicRatio : intrinsicRatio; var containerRatio = containerWidth / containerHeight; var enforcedVideoWidth, enforcedVideoHeight; if (rotated) { // in case of rotation same code works for both kind of ration enforcedVideoHeight = containerWidth; enforcedVideoWidth = enforcedVideoHeight * intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.top = (enforcedVideoWidth + containerHeight) / 2 + 'px'; } else { if (intrinsicRatio < containerRatio) { // the container is wider than the video -> we will crop the height of the video enforcedVideoWidth = containerWidth; enforcedVideoHeight = enforcedVideoWidth / intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.top = (-enforcedVideoHeight + containerHeight) / 2 + 'px'; } else { enforcedVideoHeight = containerHeight; enforcedVideoWidth = enforcedVideoHeight * intrinsicRatio; cssProps.width = enforcedVideoWidth + 'px'; cssProps.height = enforcedVideoHeight + 'px'; cssProps.left = (-enforcedVideoWidth + containerWidth) / 2 + 'px'; } } } $video.css(cssProps); } }
[ "function", "fixFitModeCover", "(", "element", ",", "containerWidth", ",", "containerHeight", ",", "intrinsicRatio", ",", "rotated", ")", "{", "var", "$video", "=", "OT", ".", "$", "(", "'.OT_video-element'", ",", "element", ")", ";", "if", "(", "$video", ".", "length", ">", "0", ")", "{", "var", "cssProps", "=", "{", "left", ":", "''", ",", "top", ":", "''", "}", ";", "if", "(", "OTPlugin", ".", "isInstalled", "(", ")", ")", "{", "cssProps", ".", "width", "=", "'100%'", ";", "cssProps", ".", "height", "=", "'100%'", ";", "}", "else", "{", "intrinsicRatio", "=", "intrinsicRatio", "||", "defaultAspectRatio", ";", "intrinsicRatio", "=", "rotated", "?", "1", "/", "intrinsicRatio", ":", "intrinsicRatio", ";", "var", "containerRatio", "=", "containerWidth", "/", "containerHeight", ";", "var", "enforcedVideoWidth", ",", "enforcedVideoHeight", ";", "if", "(", "rotated", ")", "{", "// in case of rotation same code works for both kind of ration", "enforcedVideoHeight", "=", "containerWidth", ";", "enforcedVideoWidth", "=", "enforcedVideoHeight", "*", "intrinsicRatio", ";", "cssProps", ".", "width", "=", "enforcedVideoWidth", "+", "'px'", ";", "cssProps", ".", "height", "=", "enforcedVideoHeight", "+", "'px'", ";", "cssProps", ".", "top", "=", "(", "enforcedVideoWidth", "+", "containerHeight", ")", "/", "2", "+", "'px'", ";", "}", "else", "{", "if", "(", "intrinsicRatio", "<", "containerRatio", ")", "{", "// the container is wider than the video -> we will crop the height of the video", "enforcedVideoWidth", "=", "containerWidth", ";", "enforcedVideoHeight", "=", "enforcedVideoWidth", "/", "intrinsicRatio", ";", "cssProps", ".", "width", "=", "enforcedVideoWidth", "+", "'px'", ";", "cssProps", ".", "height", "=", "enforcedVideoHeight", "+", "'px'", ";", "cssProps", ".", "top", "=", "(", "-", "enforcedVideoHeight", "+", "containerHeight", ")", "/", "2", "+", "'px'", ";", "}", "else", "{", "enforcedVideoHeight", "=", "containerHeight", ";", "enforcedVideoWidth", "=", "enforcedVideoHeight", "*", "intrinsicRatio", ";", "cssProps", ".", "width", "=", "enforcedVideoWidth", "+", "'px'", ";", "cssProps", ".", "height", "=", "enforcedVideoHeight", "+", "'px'", ";", "cssProps", ".", "left", "=", "(", "-", "enforcedVideoWidth", "+", "containerWidth", ")", "/", "2", "+", "'px'", ";", "}", "}", "}", "$video", ".", "css", "(", "cssProps", ")", ";", "}", "}" ]
Sets the video element size so by preserving the intrinsic aspect ratio of the element content but altering the width and height so that the video completely covers the container. @param {Element} element the container of the video element @param {number} containerWidth @param {number} containerHeight @param {number} intrinsicRatio the aspect ratio of the video media @param {boolean} rotated
[ "Sets", "the", "video", "element", "size", "so", "by", "preserving", "the", "intrinsic", "aspect", "ratio", "of", "the", "element", "content", "but", "altering", "the", "width", "and", "height", "so", "that", "the", "video", "completely", "covers", "the", "container", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L15203-L15253
52,664
eaze/potluck-opentok-adapter
vendor/opentok.js
function(config) { _cleanup(); if (!config) config = {}; _global = config.global || {}; _partners = config.partners || {}; if (!_loaded) _loaded = true; this.trigger('dynamicConfigChanged'); }
javascript
function(config) { _cleanup(); if (!config) config = {}; _global = config.global || {}; _partners = config.partners || {}; if (!_loaded) _loaded = true; this.trigger('dynamicConfigChanged'); }
[ "function", "(", "config", ")", "{", "_cleanup", "(", ")", ";", "if", "(", "!", "config", ")", "config", "=", "{", "}", ";", "_global", "=", "config", ".", "global", "||", "{", "}", ";", "_partners", "=", "config", ".", "partners", "||", "{", "}", ";", "if", "(", "!", "_loaded", ")", "_loaded", "=", "true", ";", "this", ".", "trigger", "(", "'dynamicConfigChanged'", ")", ";", "}" ]
This is public so that the dynamic config file can load itself. Using it for other purposes is discouraged, but not forbidden.
[ "This", "is", "public", "so", "that", "the", "dynamic", "config", "file", "can", "load", "itself", ".", "Using", "it", "for", "other", "purposes", "is", "discouraged", "but", "not", "forbidden", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L16681-L16691
52,665
eaze/potluck-opentok-adapter
vendor/opentok.js
function(key, value, oldValue) { if (oldValue) { self.trigger('styleValueChanged', key, value, oldValue); } else { self.trigger('styleValueChanged', key, value); } }
javascript
function(key, value, oldValue) { if (oldValue) { self.trigger('styleValueChanged', key, value, oldValue); } else { self.trigger('styleValueChanged', key, value); } }
[ "function", "(", "key", ",", "value", ",", "oldValue", ")", "{", "if", "(", "oldValue", ")", "{", "self", ".", "trigger", "(", "'styleValueChanged'", ",", "key", ",", "value", ",", "oldValue", ")", ";", "}", "else", "{", "self", ".", "trigger", "(", "'styleValueChanged'", ",", "key", ",", "value", ")", ";", "}", "}" ]
Broadcast style changes as the styleValueChanged event
[ "Broadcast", "style", "changes", "as", "the", "styleValueChanged", "event" ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L17068-L17074
52,666
eaze/potluck-opentok-adapter
vendor/opentok.js
handleInvalidStateChanges
function handleInvalidStateChanges(newState) { if (!isValidState(newState)) { signalChangeFailed('\'' + newState + '\' is not a valid state', newState); return false; } if (!isValidTransition(currentState, newState)) { signalChangeFailed('\'' + currentState + '\' cannot transition to \'' + newState + '\'', newState); return false; } return true; }
javascript
function handleInvalidStateChanges(newState) { if (!isValidState(newState)) { signalChangeFailed('\'' + newState + '\' is not a valid state', newState); return false; } if (!isValidTransition(currentState, newState)) { signalChangeFailed('\'' + currentState + '\' cannot transition to \'' + newState + '\'', newState); return false; } return true; }
[ "function", "handleInvalidStateChanges", "(", "newState", ")", "{", "if", "(", "!", "isValidState", "(", "newState", ")", ")", "{", "signalChangeFailed", "(", "'\\''", "+", "newState", "+", "'\\' is not a valid state'", ",", "newState", ")", ";", "return", "false", ";", "}", "if", "(", "!", "isValidTransition", "(", "currentState", ",", "newState", ")", ")", "{", "signalChangeFailed", "(", "'\\''", "+", "currentState", "+", "'\\' cannot transition to \\''", "+", "newState", "+", "'\\''", ",", "newState", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validates +newState+. If it's invalid it triggers stateChangeFailed and returns false.
[ "Validates", "+", "newState", "+", ".", "If", "it", "s", "invalid", "it", "triggers", "stateChangeFailed", "and", "returns", "false", "." ]
2b88a58ec0a8588955ee99004bc7d4bc361c5b12
https://github.com/eaze/potluck-opentok-adapter/blob/2b88a58ec0a8588955ee99004bc7d4bc361c5b12/vendor/opentok.js#L17477-L17492
52,667
zjgnlzq/serve-index-prefix
index.js
fileSort
function fileSort(a, b) { return Number(b.stat && b.stat.isDirectory()) - Number(a.stat && a.stat.isDirectory()) || String(a.name).toLocaleLowerCase().localeCompare(String(b.name).toLocaleLowerCase()); }
javascript
function fileSort(a, b) { return Number(b.stat && b.stat.isDirectory()) - Number(a.stat && a.stat.isDirectory()) || String(a.name).toLocaleLowerCase().localeCompare(String(b.name).toLocaleLowerCase()); }
[ "function", "fileSort", "(", "a", ",", "b", ")", "{", "return", "Number", "(", "b", ".", "stat", "&&", "b", ".", "stat", ".", "isDirectory", "(", ")", ")", "-", "Number", "(", "a", ".", "stat", "&&", "a", ".", "stat", ".", "isDirectory", "(", ")", ")", "||", "String", "(", "a", ".", "name", ")", ".", "toLocaleLowerCase", "(", ")", ".", "localeCompare", "(", "String", "(", "b", ".", "name", ")", ".", "toLocaleLowerCase", "(", ")", ")", ";", "}" ]
Sort function for with directories first.
[ "Sort", "function", "for", "with", "directories", "first", "." ]
0a37c2bc4df5e46e1b509a37697edbff1b3e519d
https://github.com/zjgnlzq/serve-index-prefix/blob/0a37c2bc4df5e46e1b509a37697edbff1b3e519d/index.js#L222-L225
52,668
zjgnlzq/serve-index-prefix
index.js
htmlPath
function htmlPath(dir) { var parts = dir.split('/'); var crumb = new Array(parts.length); for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part) { parts[i] = encodeURIComponent(part); crumb[i] = '<a href="' + escapeHtml(parts.slice(0, i + 1).join('/')) + '">' + escapeHtml(part) + '</a>'; } } return crumb.join(' / '); }
javascript
function htmlPath(dir) { var parts = dir.split('/'); var crumb = new Array(parts.length); for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part) { parts[i] = encodeURIComponent(part); crumb[i] = '<a href="' + escapeHtml(parts.slice(0, i + 1).join('/')) + '">' + escapeHtml(part) + '</a>'; } } return crumb.join(' / '); }
[ "function", "htmlPath", "(", "dir", ")", "{", "var", "parts", "=", "dir", ".", "split", "(", "'/'", ")", ";", "var", "crumb", "=", "new", "Array", "(", "parts", ".", "length", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "var", "part", "=", "parts", "[", "i", "]", ";", "if", "(", "part", ")", "{", "parts", "[", "i", "]", "=", "encodeURIComponent", "(", "part", ")", ";", "crumb", "[", "i", "]", "=", "'<a href=\"'", "+", "escapeHtml", "(", "parts", ".", "slice", "(", "0", ",", "i", "+", "1", ")", ".", "join", "(", "'/'", ")", ")", "+", "'\">'", "+", "escapeHtml", "(", "part", ")", "+", "'</a>'", ";", "}", "}", "return", "crumb", ".", "join", "(", "' / '", ")", ";", "}" ]
Map html `dir`, returning a linked path.
[ "Map", "html", "dir", "returning", "a", "linked", "path", "." ]
0a37c2bc4df5e46e1b509a37697edbff1b3e519d
https://github.com/zjgnlzq/serve-index-prefix/blob/0a37c2bc4df5e46e1b509a37697edbff1b3e519d/index.js#L231-L245
52,669
zjgnlzq/serve-index-prefix
index.js
iconLookup
function iconLookup(filename) { var ext = extname(filename); // try by extension if (icons[ext]) { return { className: 'icon-' + ext.substring(1), fileName: icons[ext] }; } var mimetype = mime.lookup(ext); // default if no mime type if (mimetype === false) { return { className: 'icon-default', fileName: icons.default }; } // try by mime type if (icons[mimetype]) { return { className: 'icon-' + mimetype.replace('/', '-'), fileName: icons[mimetype] }; } var suffix = mimetype.split('+')[1]; if (suffix && icons['+' + suffix]) { return { className: 'icon-' + suffix, fileName: icons['+' + suffix] }; } var type = mimetype.split('/')[0]; // try by type only if (icons[type]) { return { className: 'icon-' + type, fileName: icons[type] }; } return { className: 'icon-default', fileName: icons.default }; }
javascript
function iconLookup(filename) { var ext = extname(filename); // try by extension if (icons[ext]) { return { className: 'icon-' + ext.substring(1), fileName: icons[ext] }; } var mimetype = mime.lookup(ext); // default if no mime type if (mimetype === false) { return { className: 'icon-default', fileName: icons.default }; } // try by mime type if (icons[mimetype]) { return { className: 'icon-' + mimetype.replace('/', '-'), fileName: icons[mimetype] }; } var suffix = mimetype.split('+')[1]; if (suffix && icons['+' + suffix]) { return { className: 'icon-' + suffix, fileName: icons['+' + suffix] }; } var type = mimetype.split('/')[0]; // try by type only if (icons[type]) { return { className: 'icon-' + type, fileName: icons[type] }; } return { className: 'icon-default', fileName: icons.default }; }
[ "function", "iconLookup", "(", "filename", ")", "{", "var", "ext", "=", "extname", "(", "filename", ")", ";", "// try by extension", "if", "(", "icons", "[", "ext", "]", ")", "{", "return", "{", "className", ":", "'icon-'", "+", "ext", ".", "substring", "(", "1", ")", ",", "fileName", ":", "icons", "[", "ext", "]", "}", ";", "}", "var", "mimetype", "=", "mime", ".", "lookup", "(", "ext", ")", ";", "// default if no mime type", "if", "(", "mimetype", "===", "false", ")", "{", "return", "{", "className", ":", "'icon-default'", ",", "fileName", ":", "icons", ".", "default", "}", ";", "}", "// try by mime type", "if", "(", "icons", "[", "mimetype", "]", ")", "{", "return", "{", "className", ":", "'icon-'", "+", "mimetype", ".", "replace", "(", "'/'", ",", "'-'", ")", ",", "fileName", ":", "icons", "[", "mimetype", "]", "}", ";", "}", "var", "suffix", "=", "mimetype", ".", "split", "(", "'+'", ")", "[", "1", "]", ";", "if", "(", "suffix", "&&", "icons", "[", "'+'", "+", "suffix", "]", ")", "{", "return", "{", "className", ":", "'icon-'", "+", "suffix", ",", "fileName", ":", "icons", "[", "'+'", "+", "suffix", "]", "}", ";", "}", "var", "type", "=", "mimetype", ".", "split", "(", "'/'", ")", "[", "0", "]", ";", "// try by type only", "if", "(", "icons", "[", "type", "]", ")", "{", "return", "{", "className", ":", "'icon-'", "+", "type", ",", "fileName", ":", "icons", "[", "type", "]", "}", ";", "}", "return", "{", "className", ":", "'icon-default'", ",", "fileName", ":", "icons", ".", "default", "}", ";", "}" ]
Get the icon data for the file name.
[ "Get", "the", "icon", "data", "for", "the", "file", "name", "." ]
0a37c2bc4df5e46e1b509a37697edbff1b3e519d
https://github.com/zjgnlzq/serve-index-prefix/blob/0a37c2bc4df5e46e1b509a37697edbff1b3e519d/index.js#L251-L303
52,670
zjgnlzq/serve-index-prefix
index.js
iconStyle
function iconStyle (files, useIcons) { if (!useIcons) return ''; var className; var i; var iconName; var list = []; var rules = {}; var selector; var selectors = {}; var style = ''; for (i = 0; i < files.length; i++) { var file = files[i]; var isDir = '..' == file.name || (file.stat && file.stat.isDirectory()); var icon = isDir ? { className: 'icon-directory', fileName: icons.folder } : iconLookup(file.name); var iconName = icon.fileName; selector = '#files .' + icon.className + ' .name'; if (!rules[iconName]) { rules[iconName] = 'background-image: url(data:image/png;base64,' + load(iconName) + ');' selectors[iconName] = []; list.push(iconName); } if (selectors[iconName].indexOf(selector) === -1) { selectors[iconName].push(selector); } } for (i = 0; i < list.length; i++) { iconName = list[i]; style += selectors[iconName].join(',\n') + ' {\n ' + rules[iconName] + '\n}\n'; } return style; }
javascript
function iconStyle (files, useIcons) { if (!useIcons) return ''; var className; var i; var iconName; var list = []; var rules = {}; var selector; var selectors = {}; var style = ''; for (i = 0; i < files.length; i++) { var file = files[i]; var isDir = '..' == file.name || (file.stat && file.stat.isDirectory()); var icon = isDir ? { className: 'icon-directory', fileName: icons.folder } : iconLookup(file.name); var iconName = icon.fileName; selector = '#files .' + icon.className + ' .name'; if (!rules[iconName]) { rules[iconName] = 'background-image: url(data:image/png;base64,' + load(iconName) + ');' selectors[iconName] = []; list.push(iconName); } if (selectors[iconName].indexOf(selector) === -1) { selectors[iconName].push(selector); } } for (i = 0; i < list.length; i++) { iconName = list[i]; style += selectors[iconName].join(',\n') + ' {\n ' + rules[iconName] + '\n}\n'; } return style; }
[ "function", "iconStyle", "(", "files", ",", "useIcons", ")", "{", "if", "(", "!", "useIcons", ")", "return", "''", ";", "var", "className", ";", "var", "i", ";", "var", "iconName", ";", "var", "list", "=", "[", "]", ";", "var", "rules", "=", "{", "}", ";", "var", "selector", ";", "var", "selectors", "=", "{", "}", ";", "var", "style", "=", "''", ";", "for", "(", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "var", "file", "=", "files", "[", "i", "]", ";", "var", "isDir", "=", "'..'", "==", "file", ".", "name", "||", "(", "file", ".", "stat", "&&", "file", ".", "stat", ".", "isDirectory", "(", ")", ")", ";", "var", "icon", "=", "isDir", "?", "{", "className", ":", "'icon-directory'", ",", "fileName", ":", "icons", ".", "folder", "}", ":", "iconLookup", "(", "file", ".", "name", ")", ";", "var", "iconName", "=", "icon", ".", "fileName", ";", "selector", "=", "'#files .'", "+", "icon", ".", "className", "+", "' .name'", ";", "if", "(", "!", "rules", "[", "iconName", "]", ")", "{", "rules", "[", "iconName", "]", "=", "'background-image: url(data:image/png;base64,'", "+", "load", "(", "iconName", ")", "+", "');'", "selectors", "[", "iconName", "]", "=", "[", "]", ";", "list", ".", "push", "(", "iconName", ")", ";", "}", "if", "(", "selectors", "[", "iconName", "]", ".", "indexOf", "(", "selector", ")", "===", "-", "1", ")", "{", "selectors", "[", "iconName", "]", ".", "push", "(", "selector", ")", ";", "}", "}", "for", "(", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "iconName", "=", "list", "[", "i", "]", ";", "style", "+=", "selectors", "[", "iconName", "]", ".", "join", "(", "',\\n'", ")", "+", "' {\\n '", "+", "rules", "[", "iconName", "]", "+", "'\\n}\\n'", ";", "}", "return", "style", ";", "}" ]
Load icon images, return css string.
[ "Load", "icon", "images", "return", "css", "string", "." ]
0a37c2bc4df5e46e1b509a37697edbff1b3e519d
https://github.com/zjgnlzq/serve-index-prefix/blob/0a37c2bc4df5e46e1b509a37697edbff1b3e519d/index.js#L309-L348
52,671
zjgnlzq/serve-index-prefix
index.js
html
function html(files, dir, useIcons, view, req) { return '<ul id="files" class="view-' + escapeHtml(view) + '">' + (view == 'details' ? ( '<li class="header">' + '<span class="name">Name</span>' + '<span class="size">Size</span>' + '<span class="date">Modified</span>' + '</li>') : '') + files.map(function(file){ var isDir = '..' == file.name || (file.stat && file.stat.isDirectory()) , classes = [] , path = dir.split('/').map(function (c) { return encodeURIComponent(c); }); if (useIcons) { classes.push('icon'); if (isDir) { classes.push('icon-directory'); } else { var ext = extname(file.name); var icon = iconLookup(file.name); classes.push('icon'); classes.push('icon-' + ext.substring(1)); if (classes.indexOf(icon.className) === -1) { classes.push(icon.className); } } } path.push(encodeURIComponent(file.name)); var date = file.stat && file.name !== '..' ? file.stat.mtime.toDateString() + ' ' + file.stat.mtime.toLocaleTimeString() : ''; var size = file.stat && !isDir ? file.stat.size : ''; return '<li><a href="' + escapeHtml(normalizeSlashes(normalize(req.prefixPath + path.join('/')))) + '" class="' + escapeHtml(classes.join(' ')) + '"' + ' title="' + escapeHtml(file.name) + '">' + '<span class="name">' + escapeHtml(file.name) + '</span>' + '<span class="size">' + escapeHtml(size) + '</span>' + '<span class="date">' + escapeHtml(date) + '</span>' + '</a></li>'; }).join('\n') + '</ul>'; }
javascript
function html(files, dir, useIcons, view, req) { return '<ul id="files" class="view-' + escapeHtml(view) + '">' + (view == 'details' ? ( '<li class="header">' + '<span class="name">Name</span>' + '<span class="size">Size</span>' + '<span class="date">Modified</span>' + '</li>') : '') + files.map(function(file){ var isDir = '..' == file.name || (file.stat && file.stat.isDirectory()) , classes = [] , path = dir.split('/').map(function (c) { return encodeURIComponent(c); }); if (useIcons) { classes.push('icon'); if (isDir) { classes.push('icon-directory'); } else { var ext = extname(file.name); var icon = iconLookup(file.name); classes.push('icon'); classes.push('icon-' + ext.substring(1)); if (classes.indexOf(icon.className) === -1) { classes.push(icon.className); } } } path.push(encodeURIComponent(file.name)); var date = file.stat && file.name !== '..' ? file.stat.mtime.toDateString() + ' ' + file.stat.mtime.toLocaleTimeString() : ''; var size = file.stat && !isDir ? file.stat.size : ''; return '<li><a href="' + escapeHtml(normalizeSlashes(normalize(req.prefixPath + path.join('/')))) + '" class="' + escapeHtml(classes.join(' ')) + '"' + ' title="' + escapeHtml(file.name) + '">' + '<span class="name">' + escapeHtml(file.name) + '</span>' + '<span class="size">' + escapeHtml(size) + '</span>' + '<span class="date">' + escapeHtml(date) + '</span>' + '</a></li>'; }).join('\n') + '</ul>'; }
[ "function", "html", "(", "files", ",", "dir", ",", "useIcons", ",", "view", ",", "req", ")", "{", "return", "'<ul id=\"files\" class=\"view-'", "+", "escapeHtml", "(", "view", ")", "+", "'\">'", "+", "(", "view", "==", "'details'", "?", "(", "'<li class=\"header\">'", "+", "'<span class=\"name\">Name</span>'", "+", "'<span class=\"size\">Size</span>'", "+", "'<span class=\"date\">Modified</span>'", "+", "'</li>'", ")", ":", "''", ")", "+", "files", ".", "map", "(", "function", "(", "file", ")", "{", "var", "isDir", "=", "'..'", "==", "file", ".", "name", "||", "(", "file", ".", "stat", "&&", "file", ".", "stat", ".", "isDirectory", "(", ")", ")", ",", "classes", "=", "[", "]", ",", "path", "=", "dir", ".", "split", "(", "'/'", ")", ".", "map", "(", "function", "(", "c", ")", "{", "return", "encodeURIComponent", "(", "c", ")", ";", "}", ")", ";", "if", "(", "useIcons", ")", "{", "classes", ".", "push", "(", "'icon'", ")", ";", "if", "(", "isDir", ")", "{", "classes", ".", "push", "(", "'icon-directory'", ")", ";", "}", "else", "{", "var", "ext", "=", "extname", "(", "file", ".", "name", ")", ";", "var", "icon", "=", "iconLookup", "(", "file", ".", "name", ")", ";", "classes", ".", "push", "(", "'icon'", ")", ";", "classes", ".", "push", "(", "'icon-'", "+", "ext", ".", "substring", "(", "1", ")", ")", ";", "if", "(", "classes", ".", "indexOf", "(", "icon", ".", "className", ")", "===", "-", "1", ")", "{", "classes", ".", "push", "(", "icon", ".", "className", ")", ";", "}", "}", "}", "path", ".", "push", "(", "encodeURIComponent", "(", "file", ".", "name", ")", ")", ";", "var", "date", "=", "file", ".", "stat", "&&", "file", ".", "name", "!==", "'..'", "?", "file", ".", "stat", ".", "mtime", ".", "toDateString", "(", ")", "+", "' '", "+", "file", ".", "stat", ".", "mtime", ".", "toLocaleTimeString", "(", ")", ":", "''", ";", "var", "size", "=", "file", ".", "stat", "&&", "!", "isDir", "?", "file", ".", "stat", ".", "size", ":", "''", ";", "return", "'<li><a href=\"'", "+", "escapeHtml", "(", "normalizeSlashes", "(", "normalize", "(", "req", ".", "prefixPath", "+", "path", ".", "join", "(", "'/'", ")", ")", ")", ")", "+", "'\" class=\"'", "+", "escapeHtml", "(", "classes", ".", "join", "(", "' '", ")", ")", "+", "'\"'", "+", "' title=\"'", "+", "escapeHtml", "(", "file", ".", "name", ")", "+", "'\">'", "+", "'<span class=\"name\">'", "+", "escapeHtml", "(", "file", ".", "name", ")", "+", "'</span>'", "+", "'<span class=\"size\">'", "+", "escapeHtml", "(", "size", ")", "+", "'</span>'", "+", "'<span class=\"date\">'", "+", "escapeHtml", "(", "date", ")", "+", "'</span>'", "+", "'</a></li>'", ";", "}", ")", ".", "join", "(", "'\\n'", ")", "+", "'</ul>'", ";", "}" ]
Map html `files`, returning an html unordered list.
[ "Map", "html", "files", "returning", "an", "html", "unordered", "list", "." ]
0a37c2bc4df5e46e1b509a37697edbff1b3e519d
https://github.com/zjgnlzq/serve-index-prefix/blob/0a37c2bc4df5e46e1b509a37697edbff1b3e519d/index.js#L354-L404
52,672
zjgnlzq/serve-index-prefix
index.js
load
function load(icon) { if (cache[icon]) return cache[icon]; return cache[icon] = fs.readFileSync(__dirname + '/public/icons/' + icon, 'base64'); }
javascript
function load(icon) { if (cache[icon]) return cache[icon]; return cache[icon] = fs.readFileSync(__dirname + '/public/icons/' + icon, 'base64'); }
[ "function", "load", "(", "icon", ")", "{", "if", "(", "cache", "[", "icon", "]", ")", "return", "cache", "[", "icon", "]", ";", "return", "cache", "[", "icon", "]", "=", "fs", ".", "readFileSync", "(", "__dirname", "+", "'/public/icons/'", "+", "icon", ",", "'base64'", ")", ";", "}" ]
Load and cache the given `icon`. @param {String} icon @return {String} @api private
[ "Load", "and", "cache", "the", "given", "icon", "." ]
0a37c2bc4df5e46e1b509a37697edbff1b3e519d
https://github.com/zjgnlzq/serve-index-prefix/blob/0a37c2bc4df5e46e1b509a37697edbff1b3e519d/index.js#L414-L417
52,673
zjgnlzq/serve-index-prefix
index.js
stat
function stat(dir, files, cb) { var batch = new Batch(); batch.concurrency(10); files.forEach(function(file){ batch.push(function(done){ fs.stat(join(dir, file), function(err, stat){ if (err && err.code !== 'ENOENT') return done(err); // pass ENOENT as null stat, not error done(null, stat || null); }); }); }); batch.end(cb); }
javascript
function stat(dir, files, cb) { var batch = new Batch(); batch.concurrency(10); files.forEach(function(file){ batch.push(function(done){ fs.stat(join(dir, file), function(err, stat){ if (err && err.code !== 'ENOENT') return done(err); // pass ENOENT as null stat, not error done(null, stat || null); }); }); }); batch.end(cb); }
[ "function", "stat", "(", "dir", ",", "files", ",", "cb", ")", "{", "var", "batch", "=", "new", "Batch", "(", ")", ";", "batch", ".", "concurrency", "(", "10", ")", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "batch", ".", "push", "(", "function", "(", "done", ")", "{", "fs", ".", "stat", "(", "join", "(", "dir", ",", "file", ")", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "err", "&&", "err", ".", "code", "!==", "'ENOENT'", ")", "return", "done", "(", "err", ")", ";", "// pass ENOENT as null stat, not error", "done", "(", "null", ",", "stat", "||", "null", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "batch", ".", "end", "(", "cb", ")", ";", "}" ]
Stat all files and return array of stat in same order.
[ "Stat", "all", "files", "and", "return", "array", "of", "stat", "in", "same", "order", "." ]
0a37c2bc4df5e46e1b509a37697edbff1b3e519d
https://github.com/zjgnlzq/serve-index-prefix/blob/0a37c2bc4df5e46e1b509a37697edbff1b3e519d/index.js#L452-L469
52,674
skerit/alchemy
lib/core/middleware.js
getMiddlePaths
function getMiddlePaths(paths, ext, new_ext) { if (Array.isArray(paths)) { return paths.map(function eachEntry(entry) { return getMiddlePaths(entry, ext, new_ext); }); } if (ext && new_ext) { paths = paths.replace(ext, new_ext); } return paths; }
javascript
function getMiddlePaths(paths, ext, new_ext) { if (Array.isArray(paths)) { return paths.map(function eachEntry(entry) { return getMiddlePaths(entry, ext, new_ext); }); } if (ext && new_ext) { paths = paths.replace(ext, new_ext); } return paths; }
[ "function", "getMiddlePaths", "(", "paths", ",", "ext", ",", "new_ext", ")", "{", "if", "(", "Array", ".", "isArray", "(", "paths", ")", ")", "{", "return", "paths", ".", "map", "(", "function", "eachEntry", "(", "entry", ")", "{", "return", "getMiddlePaths", "(", "entry", ",", "ext", ",", "new_ext", ")", ";", "}", ")", ";", "}", "if", "(", "ext", "&&", "new_ext", ")", "{", "paths", "=", "paths", ".", "replace", "(", "ext", ",", "new_ext", ")", ";", "}", "return", "paths", ";", "}" ]
Get an array of paths, optionally replace text @author Jelle De Loecker <[email protected]> @since 0.2.3 @version 0.2.3
[ "Get", "an", "array", "of", "paths", "optionally", "replace", "text" ]
ede1dad07a5a737d5d1e10c2ff87fdfb057443f8
https://github.com/skerit/alchemy/blob/ede1dad07a5a737d5d1e10c2ff87fdfb057443f8/lib/core/middleware.js#L46-L59
52,675
SpaceRhino/localstorage-plus
src/store.js
function(name, autoFlushExpired) { var storeName; function __construct(name) { try { storeName = validateStoreName(name); if (autoFlushExpired === undefined || autoFlushExpired !== false) { flushExpired(); } } catch(error) { console.error(error); } } /** * Set a defined key with the given value * @param {string} key The name of the value * @param {mixed} data The data to store, can be any datatype * @param {int} [expiresAt] When should this value expire * @return {void} */ function set(key, data, expiresAt) { try { if (expiresAt !== undefined && typeof expiresAt === 'number') { STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString()); } STORE.setItem(storeName + key, decodeObjectString(data)); return true; } catch(error) { console.error(error); return false; } } /** * Get the value stored under the given key, or the whole store * @param {string} [key] Index defined in @set * @return {mixed} Stored value */ function get(key) { try { if (key !== undefined) { var result = encodeObjectString(STORE.getItem(storeName + key)); return result !== null ? result : false; } else { var resultAll = {}; Object.keys(STORE).map(function(key) { if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) { var varKey = key.replace(storeName, ''); resultAll[varKey] = get(varKey); } }); return resultAll; } } catch(error) { console.error(error) return false; } } /** * Check if the given key exists in the store * @param {string} key index of the value to test * @return {boolean} Key defined or not */ function isset(key) { return STORE.getItem(storeName + key) !== null ? true : false; } /** * Flush all values, that are stored in the store instance * @return {void} */ function flush() { util.flush(storeName); } /** * Remove an item, by the given key and its expire if set * @param {string} key Index of the value * @return {void} */ function remove(key) { util.remove(storeName + key); } /** * flush expired values defined in this store * @return {void} */ function flushExpired() { util.flushExpired(storeName); } /** * generate a store name * @param {string} storeName The name of the store instance * @return {string} The generated name * @throws {TypeError} */ function validateStoreName(storeName) { if (storeName === undefined) { throw new TypeError('Please provide a storename'); } if (typeof(storeName) !== 'string') { throw new TypeError('The storename has to be a string'); } var chargedStoreName = storeName = ROOT + storeName + '-'; return chargedStoreName; } /** * decode a value if its type is a object * @private * @param {mixed} data Value to decode * @return {mixed} The decoded value */ function decodeObjectString(data) { if (typeof data === 'object') { return JSON.stringify(data); } return data; } /** * encode a value if the value is a object * @param {mixed} data The value to encode * @return {mixed} The encoded value */ function encodeObjectString(data) { if (typeof data === 'string') { try { return JSON.parse(data); } catch(e) { return data; } } } __construct(name); // define public interface return { set : set, get : get, flush : flush, remove : remove, isset : isset } }
javascript
function(name, autoFlushExpired) { var storeName; function __construct(name) { try { storeName = validateStoreName(name); if (autoFlushExpired === undefined || autoFlushExpired !== false) { flushExpired(); } } catch(error) { console.error(error); } } /** * Set a defined key with the given value * @param {string} key The name of the value * @param {mixed} data The data to store, can be any datatype * @param {int} [expiresAt] When should this value expire * @return {void} */ function set(key, data, expiresAt) { try { if (expiresAt !== undefined && typeof expiresAt === 'number') { STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString()); } STORE.setItem(storeName + key, decodeObjectString(data)); return true; } catch(error) { console.error(error); return false; } } /** * Get the value stored under the given key, or the whole store * @param {string} [key] Index defined in @set * @return {mixed} Stored value */ function get(key) { try { if (key !== undefined) { var result = encodeObjectString(STORE.getItem(storeName + key)); return result !== null ? result : false; } else { var resultAll = {}; Object.keys(STORE).map(function(key) { if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) { var varKey = key.replace(storeName, ''); resultAll[varKey] = get(varKey); } }); return resultAll; } } catch(error) { console.error(error) return false; } } /** * Check if the given key exists in the store * @param {string} key index of the value to test * @return {boolean} Key defined or not */ function isset(key) { return STORE.getItem(storeName + key) !== null ? true : false; } /** * Flush all values, that are stored in the store instance * @return {void} */ function flush() { util.flush(storeName); } /** * Remove an item, by the given key and its expire if set * @param {string} key Index of the value * @return {void} */ function remove(key) { util.remove(storeName + key); } /** * flush expired values defined in this store * @return {void} */ function flushExpired() { util.flushExpired(storeName); } /** * generate a store name * @param {string} storeName The name of the store instance * @return {string} The generated name * @throws {TypeError} */ function validateStoreName(storeName) { if (storeName === undefined) { throw new TypeError('Please provide a storename'); } if (typeof(storeName) !== 'string') { throw new TypeError('The storename has to be a string'); } var chargedStoreName = storeName = ROOT + storeName + '-'; return chargedStoreName; } /** * decode a value if its type is a object * @private * @param {mixed} data Value to decode * @return {mixed} The decoded value */ function decodeObjectString(data) { if (typeof data === 'object') { return JSON.stringify(data); } return data; } /** * encode a value if the value is a object * @param {mixed} data The value to encode * @return {mixed} The encoded value */ function encodeObjectString(data) { if (typeof data === 'string') { try { return JSON.parse(data); } catch(e) { return data; } } } __construct(name); // define public interface return { set : set, get : get, flush : flush, remove : remove, isset : isset } }
[ "function", "(", "name", ",", "autoFlushExpired", ")", "{", "var", "storeName", ";", "function", "__construct", "(", "name", ")", "{", "try", "{", "storeName", "=", "validateStoreName", "(", "name", ")", ";", "if", "(", "autoFlushExpired", "===", "undefined", "||", "autoFlushExpired", "!==", "false", ")", "{", "flushExpired", "(", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "}", "}", "/**\r\n * Set a defined key with the given value\r\n * @param {string} key The name of the value\r\n * @param {mixed} data The data to store, can be any datatype\r\n * @param {int} [expiresAt] When should this value expire\r\n * @return {void}\r\n */", "function", "set", "(", "key", ",", "data", ",", "expiresAt", ")", "{", "try", "{", "if", "(", "expiresAt", "!==", "undefined", "&&", "typeof", "expiresAt", "===", "'number'", ")", "{", "STORE", ".", "setItem", "(", "storeName", "+", "key", "+", "EXPIRE_KEY", ",", "expiresAt", ".", "toString", "(", ")", ")", ";", "}", "STORE", ".", "setItem", "(", "storeName", "+", "key", ",", "decodeObjectString", "(", "data", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "return", "false", ";", "}", "}", "/**\r\n * Get the value stored under the given key, or the whole store\r\n * @param {string} [key] Index defined in @set\r\n * @return {mixed} Stored value\r\n */", "function", "get", "(", "key", ")", "{", "try", "{", "if", "(", "key", "!==", "undefined", ")", "{", "var", "result", "=", "encodeObjectString", "(", "STORE", ".", "getItem", "(", "storeName", "+", "key", ")", ")", ";", "return", "result", "!==", "null", "?", "result", ":", "false", ";", "}", "else", "{", "var", "resultAll", "=", "{", "}", ";", "Object", ".", "keys", "(", "STORE", ")", ".", "map", "(", "function", "(", "key", ")", "{", "if", "(", "key", ".", "indexOf", "(", "storeName", ")", "===", "0", "&&", "key", ".", "indexOf", "(", "EXPIRE_KEY", ")", "===", "-", "1", ")", "{", "var", "varKey", "=", "key", ".", "replace", "(", "storeName", ",", "''", ")", ";", "resultAll", "[", "varKey", "]", "=", "get", "(", "varKey", ")", ";", "}", "}", ")", ";", "return", "resultAll", ";", "}", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", "return", "false", ";", "}", "}", "/**\r\n * Check if the given key exists in the store\r\n * @param {string} key index of the value to test\r\n * @return {boolean} Key defined or not\r\n */", "function", "isset", "(", "key", ")", "{", "return", "STORE", ".", "getItem", "(", "storeName", "+", "key", ")", "!==", "null", "?", "true", ":", "false", ";", "}", "/**\r\n * Flush all values, that are stored in the store instance\r\n * @return {void}\r\n */", "function", "flush", "(", ")", "{", "util", ".", "flush", "(", "storeName", ")", ";", "}", "/**\r\n * Remove an item, by the given key and its expire if set\r\n * @param {string} key Index of the value\r\n * @return {void}\r\n */", "function", "remove", "(", "key", ")", "{", "util", ".", "remove", "(", "storeName", "+", "key", ")", ";", "}", "/**\r\n * flush expired values defined in this store\r\n * @return {void}\r\n */", "function", "flushExpired", "(", ")", "{", "util", ".", "flushExpired", "(", "storeName", ")", ";", "}", "/**\r\n * generate a store name\r\n * @param {string} storeName The name of the store instance\r\n * @return {string} The generated name\r\n * @throws {TypeError}\r\n */", "function", "validateStoreName", "(", "storeName", ")", "{", "if", "(", "storeName", "===", "undefined", ")", "{", "throw", "new", "TypeError", "(", "'Please provide a storename'", ")", ";", "}", "if", "(", "typeof", "(", "storeName", ")", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The storename has to be a string'", ")", ";", "}", "var", "chargedStoreName", "=", "storeName", "=", "ROOT", "+", "storeName", "+", "'-'", ";", "return", "chargedStoreName", ";", "}", "/**\r\n * decode a value if its type is a object\r\n * @private\r\n * @param {mixed} data Value to decode\r\n * @return {mixed} The decoded value\r\n */", "function", "decodeObjectString", "(", "data", ")", "{", "if", "(", "typeof", "data", "===", "'object'", ")", "{", "return", "JSON", ".", "stringify", "(", "data", ")", ";", "}", "return", "data", ";", "}", "/**\r\n * encode a value if the value is a object\r\n * @param {mixed} data The value to encode\r\n * @return {mixed} The encoded value\r\n */", "function", "encodeObjectString", "(", "data", ")", "{", "if", "(", "typeof", "data", "===", "'string'", ")", "{", "try", "{", "return", "JSON", ".", "parse", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "data", ";", "}", "}", "}", "__construct", "(", "name", ")", ";", "// define public interface\r", "return", "{", "set", ":", "set", ",", "get", ":", "get", ",", "flush", ":", "flush", ",", "remove", ":", "remove", ",", "isset", ":", "isset", "}", "}" ]
Define a new store @class @param {string} name The name of the store @param {boolean} [flushExpired] should the flush expired not run @return {Store} The store instance
[ "Define", "a", "new", "store" ]
7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a
https://github.com/SpaceRhino/localstorage-plus/blob/7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a/src/store.js#L48-L205
52,676
SpaceRhino/localstorage-plus
src/store.js
set
function set(key, data, expiresAt) { try { if (expiresAt !== undefined && typeof expiresAt === 'number') { STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString()); } STORE.setItem(storeName + key, decodeObjectString(data)); return true; } catch(error) { console.error(error); return false; } }
javascript
function set(key, data, expiresAt) { try { if (expiresAt !== undefined && typeof expiresAt === 'number') { STORE.setItem(storeName + key + EXPIRE_KEY, expiresAt.toString()); } STORE.setItem(storeName + key, decodeObjectString(data)); return true; } catch(error) { console.error(error); return false; } }
[ "function", "set", "(", "key", ",", "data", ",", "expiresAt", ")", "{", "try", "{", "if", "(", "expiresAt", "!==", "undefined", "&&", "typeof", "expiresAt", "===", "'number'", ")", "{", "STORE", ".", "setItem", "(", "storeName", "+", "key", "+", "EXPIRE_KEY", ",", "expiresAt", ".", "toString", "(", ")", ")", ";", "}", "STORE", ".", "setItem", "(", "storeName", "+", "key", ",", "decodeObjectString", "(", "data", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", ";", "return", "false", ";", "}", "}" ]
Set a defined key with the given value @param {string} key The name of the value @param {mixed} data The data to store, can be any datatype @param {int} [expiresAt] When should this value expire @return {void}
[ "Set", "a", "defined", "key", "with", "the", "given", "value" ]
7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a
https://github.com/SpaceRhino/localstorage-plus/blob/7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a/src/store.js#L70-L83
52,677
SpaceRhino/localstorage-plus
src/store.js
get
function get(key) { try { if (key !== undefined) { var result = encodeObjectString(STORE.getItem(storeName + key)); return result !== null ? result : false; } else { var resultAll = {}; Object.keys(STORE).map(function(key) { if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) { var varKey = key.replace(storeName, ''); resultAll[varKey] = get(varKey); } }); return resultAll; } } catch(error) { console.error(error) return false; } }
javascript
function get(key) { try { if (key !== undefined) { var result = encodeObjectString(STORE.getItem(storeName + key)); return result !== null ? result : false; } else { var resultAll = {}; Object.keys(STORE).map(function(key) { if (key.indexOf(storeName) === 0 && key.indexOf(EXPIRE_KEY) === -1) { var varKey = key.replace(storeName, ''); resultAll[varKey] = get(varKey); } }); return resultAll; } } catch(error) { console.error(error) return false; } }
[ "function", "get", "(", "key", ")", "{", "try", "{", "if", "(", "key", "!==", "undefined", ")", "{", "var", "result", "=", "encodeObjectString", "(", "STORE", ".", "getItem", "(", "storeName", "+", "key", ")", ")", ";", "return", "result", "!==", "null", "?", "result", ":", "false", ";", "}", "else", "{", "var", "resultAll", "=", "{", "}", ";", "Object", ".", "keys", "(", "STORE", ")", ".", "map", "(", "function", "(", "key", ")", "{", "if", "(", "key", ".", "indexOf", "(", "storeName", ")", "===", "0", "&&", "key", ".", "indexOf", "(", "EXPIRE_KEY", ")", "===", "-", "1", ")", "{", "var", "varKey", "=", "key", ".", "replace", "(", "storeName", ",", "''", ")", ";", "resultAll", "[", "varKey", "]", "=", "get", "(", "varKey", ")", ";", "}", "}", ")", ";", "return", "resultAll", ";", "}", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "error", ")", "return", "false", ";", "}", "}" ]
Get the value stored under the given key, or the whole store @param {string} [key] Index defined in @set @return {mixed} Stored value
[ "Get", "the", "value", "stored", "under", "the", "given", "key", "or", "the", "whole", "store" ]
7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a
https://github.com/SpaceRhino/localstorage-plus/blob/7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a/src/store.js#L90-L111
52,678
SpaceRhino/localstorage-plus
src/store.js
validateStoreName
function validateStoreName(storeName) { if (storeName === undefined) { throw new TypeError('Please provide a storename'); } if (typeof(storeName) !== 'string') { throw new TypeError('The storename has to be a string'); } var chargedStoreName = storeName = ROOT + storeName + '-'; return chargedStoreName; }
javascript
function validateStoreName(storeName) { if (storeName === undefined) { throw new TypeError('Please provide a storename'); } if (typeof(storeName) !== 'string') { throw new TypeError('The storename has to be a string'); } var chargedStoreName = storeName = ROOT + storeName + '-'; return chargedStoreName; }
[ "function", "validateStoreName", "(", "storeName", ")", "{", "if", "(", "storeName", "===", "undefined", ")", "{", "throw", "new", "TypeError", "(", "'Please provide a storename'", ")", ";", "}", "if", "(", "typeof", "(", "storeName", ")", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The storename has to be a string'", ")", ";", "}", "var", "chargedStoreName", "=", "storeName", "=", "ROOT", "+", "storeName", "+", "'-'", ";", "return", "chargedStoreName", ";", "}" ]
generate a store name @param {string} storeName The name of the store instance @return {string} The generated name @throws {TypeError}
[ "generate", "a", "store", "name" ]
7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a
https://github.com/SpaceRhino/localstorage-plus/blob/7d0fd7d533980f5de0f98de3c5bf4665f14b2e0a/src/store.js#L153-L164
52,679
7anshuai/html5-gen
index.js
invert
function invert(obj) { let result = {}; let keys = Object.keys(obj); for (let i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }
javascript
function invert(obj) { let result = {}; let keys = Object.keys(obj); for (let i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }
[ "function", "invert", "(", "obj", ")", "{", "let", "result", "=", "{", "}", ";", "let", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "for", "(", "let", "i", "=", "0", ",", "length", "=", "keys", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "result", "[", "obj", "[", "keys", "[", "i", "]", "]", "]", "=", "keys", "[", "i", "]", ";", "}", "return", "result", ";", "}" ]
Invert the keys and values of an object. The values must be serializable.
[ "Invert", "the", "keys", "and", "values", "of", "an", "object", ".", "The", "values", "must", "be", "serializable", "." ]
ed6286073e30be4bdf6a667f77defccbb240bc9a
https://github.com/7anshuai/html5-gen/blob/ed6286073e30be4bdf6a667f77defccbb240bc9a/index.js#L166-L173
52,680
alexpods/ClazzJS
src/components/clazz/Base.js
function(context, property, params) { context = context || this; var parent = context.__isClazz ? this.__parent : this.__parent.prototype; if (!property) { return parent; } if (!(property in parent)) { throw new Error('Parent does not have property "' + property + '"!'); } return _.isFunction(parent[property]) ? parent[property].apply(context, params || []) : parent[property]; }
javascript
function(context, property, params) { context = context || this; var parent = context.__isClazz ? this.__parent : this.__parent.prototype; if (!property) { return parent; } if (!(property in parent)) { throw new Error('Parent does not have property "' + property + '"!'); } return _.isFunction(parent[property]) ? parent[property].apply(context, params || []) : parent[property]; }
[ "function", "(", "context", ",", "property", ",", "params", ")", "{", "context", "=", "context", "||", "this", ";", "var", "parent", "=", "context", ".", "__isClazz", "?", "this", ".", "__parent", ":", "this", ".", "__parent", ".", "prototype", ";", "if", "(", "!", "property", ")", "{", "return", "parent", ";", "}", "if", "(", "!", "(", "property", "in", "parent", ")", ")", "{", "throw", "new", "Error", "(", "'Parent does not have property \"'", "+", "property", "+", "'\"!'", ")", ";", "}", "return", "_", ".", "isFunction", "(", "parent", "[", "property", "]", ")", "?", "parent", "[", "property", "]", ".", "apply", "(", "context", ",", "params", "||", "[", "]", ")", ":", "parent", "[", "property", "]", ";", "}" ]
Gets parent clazz, calls parent clazz method or gets parent clazz property @param {object} context Context for parent clazz calling @param {string} property Parent clazz method or property. If it does not specified - parent clazz is returning. @param {array} params Params for passing to parent clazz method call * @returns {*} Result of parent clazz method call or parent clazz property @throw {Error} if parent clazz does not have specified property
[ "Gets", "parent", "clazz", "calls", "parent", "clazz", "method", "or", "gets", "parent", "clazz", "property" ]
2f94496019669813c8246d48fcceb12a3e68a870
https://github.com/alexpods/ClazzJS/blob/2f94496019669813c8246d48fcceb12a3e68a870/src/components/clazz/Base.js#L32-L48
52,681
vkiding/jud-vue-render
src/render/browser/base/component/lazyload.js
loadIfNeeded
function loadIfNeeded (elementScope) { const notPreProcessed = elementScope.querySelectorAll('[img-src]') // image elements which have attribute 'i-lazy-src' were elements // that had been preprocessed by lib-img-core, but not loaded yet, and // must be loaded when 'appear' events were fired. It turns out the // 'appear' event was not fired correctly in the css-translate-transition // situation, so 'i-lazy-src' must be checked and lazyload must be // fired manually. const preProcessed = elementScope.querySelectorAll('[i-lazy-src]') if (notPreProcessed.length > 0 || preProcessed.length > 0) { fire() } }
javascript
function loadIfNeeded (elementScope) { const notPreProcessed = elementScope.querySelectorAll('[img-src]') // image elements which have attribute 'i-lazy-src' were elements // that had been preprocessed by lib-img-core, but not loaded yet, and // must be loaded when 'appear' events were fired. It turns out the // 'appear' event was not fired correctly in the css-translate-transition // situation, so 'i-lazy-src' must be checked and lazyload must be // fired manually. const preProcessed = elementScope.querySelectorAll('[i-lazy-src]') if (notPreProcessed.length > 0 || preProcessed.length > 0) { fire() } }
[ "function", "loadIfNeeded", "(", "elementScope", ")", "{", "const", "notPreProcessed", "=", "elementScope", ".", "querySelectorAll", "(", "'[img-src]'", ")", "// image elements which have attribute 'i-lazy-src' were elements", "// that had been preprocessed by lib-img-core, but not loaded yet, and", "// must be loaded when 'appear' events were fired. It turns out the", "// 'appear' event was not fired correctly in the css-translate-transition", "// situation, so 'i-lazy-src' must be checked and lazyload must be", "// fired manually.", "const", "preProcessed", "=", "elementScope", ".", "querySelectorAll", "(", "'[i-lazy-src]'", ")", "if", "(", "notPreProcessed", ".", "length", ">", "0", "||", "preProcessed", ".", "length", ">", "0", ")", "{", "fire", "(", ")", "}", "}" ]
for a scope of element, not for a image.
[ "for", "a", "scope", "of", "element", "not", "for", "a", "image", "." ]
07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47
https://github.com/vkiding/jud-vue-render/blob/07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47/src/render/browser/base/component/lazyload.js#L35-L47
52,682
filmic/Robol
lib/robol.js
function(configArray, validExt) { var success = true, fileMask, filePath, dirContent; configArray.forEach(function(cfg) { var files = []; // setup files' paths (join file's input directory path with name) // check for the wildcards cfg.input_files.forEach(function(f,i,array) { f = cfg.input_dir + "/" + f; fileMask = new RegExp(f.replace(/\*/g, '(.*)')); if (~f.indexOf('*')) { filePath = f.substr(0, f.lastIndexOf('/')+1); dirContent = fs.readdirSync(filePath); dirContent.forEach(function(ff) { var fp = filePath+ff; if (fileMask.test(fp)) { files.push(fp); } }); } else { files.push(f); } }); // Set the input files array after parsing the wildcards cfg.input_files = files.concat(); // check type of files (to reject unsupported scripts/styles) success = cfg.input_files.every(function(file) { if (validExt && validExt.indexOf(path.extname(file)) < 0) { callback(new Error('Cannot compile. Invalid type of file: ' + file)); return false; } else { return true; } }); }); return success; }
javascript
function(configArray, validExt) { var success = true, fileMask, filePath, dirContent; configArray.forEach(function(cfg) { var files = []; // setup files' paths (join file's input directory path with name) // check for the wildcards cfg.input_files.forEach(function(f,i,array) { f = cfg.input_dir + "/" + f; fileMask = new RegExp(f.replace(/\*/g, '(.*)')); if (~f.indexOf('*')) { filePath = f.substr(0, f.lastIndexOf('/')+1); dirContent = fs.readdirSync(filePath); dirContent.forEach(function(ff) { var fp = filePath+ff; if (fileMask.test(fp)) { files.push(fp); } }); } else { files.push(f); } }); // Set the input files array after parsing the wildcards cfg.input_files = files.concat(); // check type of files (to reject unsupported scripts/styles) success = cfg.input_files.every(function(file) { if (validExt && validExt.indexOf(path.extname(file)) < 0) { callback(new Error('Cannot compile. Invalid type of file: ' + file)); return false; } else { return true; } }); }); return success; }
[ "function", "(", "configArray", ",", "validExt", ")", "{", "var", "success", "=", "true", ",", "fileMask", ",", "filePath", ",", "dirContent", ";", "configArray", ".", "forEach", "(", "function", "(", "cfg", ")", "{", "var", "files", "=", "[", "]", ";", "// setup files' paths (join file's input directory path with name)", "// check for the wildcards", "cfg", ".", "input_files", ".", "forEach", "(", "function", "(", "f", ",", "i", ",", "array", ")", "{", "f", "=", "cfg", ".", "input_dir", "+", "\"/\"", "+", "f", ";", "fileMask", "=", "new", "RegExp", "(", "f", ".", "replace", "(", "/", "\\*", "/", "g", ",", "'(.*)'", ")", ")", ";", "if", "(", "~", "f", ".", "indexOf", "(", "'*'", ")", ")", "{", "filePath", "=", "f", ".", "substr", "(", "0", ",", "f", ".", "lastIndexOf", "(", "'/'", ")", "+", "1", ")", ";", "dirContent", "=", "fs", ".", "readdirSync", "(", "filePath", ")", ";", "dirContent", ".", "forEach", "(", "function", "(", "ff", ")", "{", "var", "fp", "=", "filePath", "+", "ff", ";", "if", "(", "fileMask", ".", "test", "(", "fp", ")", ")", "{", "files", ".", "push", "(", "fp", ")", ";", "}", "}", ")", ";", "}", "else", "{", "files", ".", "push", "(", "f", ")", ";", "}", "}", ")", ";", "// Set the input files array after parsing the wildcards", "cfg", ".", "input_files", "=", "files", ".", "concat", "(", ")", ";", "// check type of files (to reject unsupported scripts/styles)", "success", "=", "cfg", ".", "input_files", ".", "every", "(", "function", "(", "file", ")", "{", "if", "(", "validExt", "&&", "validExt", ".", "indexOf", "(", "path", ".", "extname", "(", "file", ")", ")", "<", "0", ")", "{", "callback", "(", "new", "Error", "(", "'Cannot compile. Invalid type of file: '", "+", "file", ")", ")", ";", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}", ")", ";", "}", ")", ";", "return", "success", ";", "}" ]
prepare and check input files
[ "prepare", "and", "check", "input", "files" ]
f0611bcabda7f8009a04063a0661b7daed603b5e
https://github.com/filmic/Robol/blob/f0611bcabda7f8009a04063a0661b7daed603b5e/lib/robol.js#L148-L192
52,683
filmic/Robol
lib/robol.js
function(prefix, obj) { return '\n'+prefix.cyan+'\n - '+ (Array.isArray(obj) ? obj.join('\n - ') : obj.toString()); }
javascript
function(prefix, obj) { return '\n'+prefix.cyan+'\n - '+ (Array.isArray(obj) ? obj.join('\n - ') : obj.toString()); }
[ "function", "(", "prefix", ",", "obj", ")", "{", "return", "'\\n'", "+", "prefix", ".", "cyan", "+", "'\\n - '", "+", "(", "Array", ".", "isArray", "(", "obj", ")", "?", "obj", ".", "join", "(", "'\\n - '", ")", ":", "obj", ".", "toString", "(", ")", ")", ";", "}" ]
Formats output for the log function @param {String} prefix Prefix @param {Array|String} obj Array of file names or String
[ "Formats", "output", "for", "the", "log", "function" ]
f0611bcabda7f8009a04063a0661b7daed603b5e
https://github.com/filmic/Robol/blob/f0611bcabda7f8009a04063a0661b7daed603b5e/lib/robol.js#L225-L228
52,684
filmic/Robol
lib/robol.js
function(cfg, callback) { var lessCompiledCode = ""; // Filter all Less files var lessFiles = filterInput(cfg.input_files, '.less'); // Filter all Css files var cssFiles = filterInput(cfg.input_files, '.css'); // Output file path var outputPath = path.join(cfg.output_dir, cfg.output_file); // Callback for Less compilation completed var onLessCompileComplete = function(result) { lessCompiledCode = result; }; // Callback for style concatenation task var concatWithCssCompiledCode = function(result) { return result + '\n' + lessCompiledCode; }; // Callback for lint task var onCSSLinted = function(blob) { if (blob.csslint && blob.csslint.length && blob.csslint[0].line !== undefined) { console.log('\nCSSLint reports issues in: '.red + blob.name); blob.csslint.forEach(function(i){ if (i) { console.log(' Line ' + i.line + ', Col ' + i.col + ': ' + i.message); } }); } }; // Build Styles if (cssFiles.length+lessFiles.length > 0) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Building styles:', cssFiles.concat(lessFiles))) .tasks({ readless: {task: ['read', lessFiles]}, combineless: {requires: 'readless', task: 'safeconcat'}, lesstocss: {requires: 'combineless', task: ['lesscompile', {callback: onLessCompileComplete}]}, readcss: {requires: 'lesstocss', task: ['read', cssFiles]}, lint: {requires: 'readcss', task: cfg.lint ? ['csslint', {config: cfg.lint_config, callback: onCSSLinted}] : 'noop'}, combinecss: {requires: 'lint', task: 'safeconcat'}, combineall: {requires: 'combinecss', task: ['concat', {callback: concatWithCssCompiledCode}]}, minify: {requires: 'combineall', task: cfg.minify ? ['stylesminify', {minify: cfg.minify, yuicompress: cfg.minify_config.yuicompress}] : 'noop'}, write: {requires: 'minify', task: ['write', outputPath]} }) .log(formatLog('Saved styles to: ', outputPath)) .run(callback); } else { callback(); } }
javascript
function(cfg, callback) { var lessCompiledCode = ""; // Filter all Less files var lessFiles = filterInput(cfg.input_files, '.less'); // Filter all Css files var cssFiles = filterInput(cfg.input_files, '.css'); // Output file path var outputPath = path.join(cfg.output_dir, cfg.output_file); // Callback for Less compilation completed var onLessCompileComplete = function(result) { lessCompiledCode = result; }; // Callback for style concatenation task var concatWithCssCompiledCode = function(result) { return result + '\n' + lessCompiledCode; }; // Callback for lint task var onCSSLinted = function(blob) { if (blob.csslint && blob.csslint.length && blob.csslint[0].line !== undefined) { console.log('\nCSSLint reports issues in: '.red + blob.name); blob.csslint.forEach(function(i){ if (i) { console.log(' Line ' + i.line + ', Col ' + i.col + ': ' + i.message); } }); } }; // Build Styles if (cssFiles.length+lessFiles.length > 0) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Building styles:', cssFiles.concat(lessFiles))) .tasks({ readless: {task: ['read', lessFiles]}, combineless: {requires: 'readless', task: 'safeconcat'}, lesstocss: {requires: 'combineless', task: ['lesscompile', {callback: onLessCompileComplete}]}, readcss: {requires: 'lesstocss', task: ['read', cssFiles]}, lint: {requires: 'readcss', task: cfg.lint ? ['csslint', {config: cfg.lint_config, callback: onCSSLinted}] : 'noop'}, combinecss: {requires: 'lint', task: 'safeconcat'}, combineall: {requires: 'combinecss', task: ['concat', {callback: concatWithCssCompiledCode}]}, minify: {requires: 'combineall', task: cfg.minify ? ['stylesminify', {minify: cfg.minify, yuicompress: cfg.minify_config.yuicompress}] : 'noop'}, write: {requires: 'minify', task: ['write', outputPath]} }) .log(formatLog('Saved styles to: ', outputPath)) .run(callback); } else { callback(); } }
[ "function", "(", "cfg", ",", "callback", ")", "{", "var", "lessCompiledCode", "=", "\"\"", ";", "// Filter all Less files", "var", "lessFiles", "=", "filterInput", "(", "cfg", ".", "input_files", ",", "'.less'", ")", ";", "// Filter all Css files", "var", "cssFiles", "=", "filterInput", "(", "cfg", ".", "input_files", ",", "'.css'", ")", ";", "// Output file path", "var", "outputPath", "=", "path", ".", "join", "(", "cfg", ".", "output_dir", ",", "cfg", ".", "output_file", ")", ";", "// Callback for Less compilation completed", "var", "onLessCompileComplete", "=", "function", "(", "result", ")", "{", "lessCompiledCode", "=", "result", ";", "}", ";", "// Callback for style concatenation task", "var", "concatWithCssCompiledCode", "=", "function", "(", "result", ")", "{", "return", "result", "+", "'\\n'", "+", "lessCompiledCode", ";", "}", ";", "// Callback for lint task", "var", "onCSSLinted", "=", "function", "(", "blob", ")", "{", "if", "(", "blob", ".", "csslint", "&&", "blob", ".", "csslint", ".", "length", "&&", "blob", ".", "csslint", "[", "0", "]", ".", "line", "!==", "undefined", ")", "{", "console", ".", "log", "(", "'\\nCSSLint reports issues in: '", ".", "red", "+", "blob", ".", "name", ")", ";", "blob", ".", "csslint", ".", "forEach", "(", "function", "(", "i", ")", "{", "if", "(", "i", ")", "{", "console", ".", "log", "(", "' Line '", "+", "i", ".", "line", "+", "', Col '", "+", "i", ".", "col", "+", "': '", "+", "i", ".", "message", ")", ";", "}", "}", ")", ";", "}", "}", ";", "// Build Styles", "if", "(", "cssFiles", ".", "length", "+", "lessFiles", ".", "length", ">", "0", ")", "{", "new", "gear", ".", "Queue", "(", "{", "registry", ":", "taskRegistry", "}", ")", "// register tasks", ".", "log", "(", "formatLog", "(", "'Building styles:'", ",", "cssFiles", ".", "concat", "(", "lessFiles", ")", ")", ")", ".", "tasks", "(", "{", "readless", ":", "{", "task", ":", "[", "'read'", ",", "lessFiles", "]", "}", ",", "combineless", ":", "{", "requires", ":", "'readless'", ",", "task", ":", "'safeconcat'", "}", ",", "lesstocss", ":", "{", "requires", ":", "'combineless'", ",", "task", ":", "[", "'lesscompile'", ",", "{", "callback", ":", "onLessCompileComplete", "}", "]", "}", ",", "readcss", ":", "{", "requires", ":", "'lesstocss'", ",", "task", ":", "[", "'read'", ",", "cssFiles", "]", "}", ",", "lint", ":", "{", "requires", ":", "'readcss'", ",", "task", ":", "cfg", ".", "lint", "?", "[", "'csslint'", ",", "{", "config", ":", "cfg", ".", "lint_config", ",", "callback", ":", "onCSSLinted", "}", "]", ":", "'noop'", "}", ",", "combinecss", ":", "{", "requires", ":", "'lint'", ",", "task", ":", "'safeconcat'", "}", ",", "combineall", ":", "{", "requires", ":", "'combinecss'", ",", "task", ":", "[", "'concat'", ",", "{", "callback", ":", "concatWithCssCompiledCode", "}", "]", "}", ",", "minify", ":", "{", "requires", ":", "'combineall'", ",", "task", ":", "cfg", ".", "minify", "?", "[", "'stylesminify'", ",", "{", "minify", ":", "cfg", ".", "minify", ",", "yuicompress", ":", "cfg", ".", "minify_config", ".", "yuicompress", "}", "]", ":", "'noop'", "}", ",", "write", ":", "{", "requires", ":", "'minify'", ",", "task", ":", "[", "'write'", ",", "outputPath", "]", "}", "}", ")", ".", "log", "(", "formatLog", "(", "'Saved styles to: '", ",", "outputPath", ")", ")", ".", "run", "(", "callback", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}" ]
Loads, compiles, concatenates and minifies style files @param {Object} cfg Build configuration @param {Function} callback Task complete callback
[ "Loads", "compiles", "concatenates", "and", "minifies", "style", "files" ]
f0611bcabda7f8009a04063a0661b7daed603b5e
https://github.com/filmic/Robol/blob/f0611bcabda7f8009a04063a0661b7daed603b5e/lib/robol.js#L303-L357
52,685
filmic/Robol
lib/robol.js
function(cfg, callback) { // Input dir var inputPath = cfg.input_dir; // Output dir var outputPath = cfg.output_dir; if (inputPath && outputPath) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Copying directory:', inputPath)) .copyDir({input: inputPath, output: outputPath}, callback) .log(formatLog('Copied directory to: ', outputPath)) .run(callback); } else { callback(); } }
javascript
function(cfg, callback) { // Input dir var inputPath = cfg.input_dir; // Output dir var outputPath = cfg.output_dir; if (inputPath && outputPath) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Copying directory:', inputPath)) .copyDir({input: inputPath, output: outputPath}, callback) .log(formatLog('Copied directory to: ', outputPath)) .run(callback); } else { callback(); } }
[ "function", "(", "cfg", ",", "callback", ")", "{", "// Input dir", "var", "inputPath", "=", "cfg", ".", "input_dir", ";", "// Output dir", "var", "outputPath", "=", "cfg", ".", "output_dir", ";", "if", "(", "inputPath", "&&", "outputPath", ")", "{", "new", "gear", ".", "Queue", "(", "{", "registry", ":", "taskRegistry", "}", ")", "// register tasks", ".", "log", "(", "formatLog", "(", "'Copying directory:'", ",", "inputPath", ")", ")", ".", "copyDir", "(", "{", "input", ":", "inputPath", ",", "output", ":", "outputPath", "}", ",", "callback", ")", ".", "log", "(", "formatLog", "(", "'Copied directory to: '", ",", "outputPath", ")", ")", ".", "run", "(", "callback", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}" ]
Copies single directory @param {Object} cfg Build configuration @param {Function} callback Task complete callback
[ "Copies", "single", "directory" ]
f0611bcabda7f8009a04063a0661b7daed603b5e
https://github.com/filmic/Robol/blob/f0611bcabda7f8009a04063a0661b7daed603b5e/lib/robol.js#L413-L429
52,686
filmic/Robol
lib/robol.js
function(cfg, callback) { // Input dir var inputPath = cfg.input_dir; if (inputPath) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Removing directory:', inputPath)) .removeDir({input: inputPath}, callback) .run(callback); } else { callback(); } }
javascript
function(cfg, callback) { // Input dir var inputPath = cfg.input_dir; if (inputPath) { new gear.Queue({registry: taskRegistry}) // register tasks .log(formatLog('Removing directory:', inputPath)) .removeDir({input: inputPath}, callback) .run(callback); } else { callback(); } }
[ "function", "(", "cfg", ",", "callback", ")", "{", "// Input dir", "var", "inputPath", "=", "cfg", ".", "input_dir", ";", "if", "(", "inputPath", ")", "{", "new", "gear", ".", "Queue", "(", "{", "registry", ":", "taskRegistry", "}", ")", "// register tasks", ".", "log", "(", "formatLog", "(", "'Removing directory:'", ",", "inputPath", ")", ")", ".", "removeDir", "(", "{", "input", ":", "inputPath", "}", ",", "callback", ")", ".", "run", "(", "callback", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}" ]
Removes single directory @param {Object} cfg Build configuration @param {Function} callback Task complete callback
[ "Removes", "single", "directory" ]
f0611bcabda7f8009a04063a0661b7daed603b5e
https://github.com/filmic/Robol/blob/f0611bcabda7f8009a04063a0661b7daed603b5e/lib/robol.js#L458-L470
52,687
filmic/Robol
lib/robol.js
function(cfg, callback) { var paths = cfg.input_files || cfg.input_file || cfg.input_dir; if (!Array.isArray(paths)) { paths = [paths]; } watchr.watch({ paths: paths, listener: function(eventName,filePath,fileCurrentStat,filePreviousStat){ console.log(formatLog('File changed:', filePath)); var singleFileCfg, outputDir, logTaskError = function(msg) { console.log('\n'+msg.red); }; // Detect what build configuration the file belongs to if (config.scripts.indexOf(cfg) !== -1) { // rebuild scripts buildScripts(cfg, function(err){ if (err) { logTaskError('Scripts not saved!'); } }); } else if (config.styles.indexOf(cfg) !== -1) { // rebuild styles buildStyles(cfg, function(err){ if (err) { logTaskError('Styles not saved!'); } }); } else if (config.copy_files.indexOf(cfg) !== -1) { // copy files singleFileCfg = {input_files: [filePath], output_dir: cfg.output_dir}; copyFiles(singleFileCfg, function(err){ if (err) { logTaskError('File not copied!'); } }); } else if (config.copy_file.indexOf(cfg) !== -1) { // copy/rename single file singleFileCfg = {input_file: filePath, output_file: cfg.output_file}; copyFile(singleFileCfg, function(err){ if (err) { logTaskError('File not copied!'); } }); } else if (config.copy_dir.indexOf(cfg) !== -1) { // copy single directory outputDir = path.dirname(filePath).replace(cfg.input_dir, cfg.output_dir); singleFileCfg = {input_files: [filePath], output_dir: outputDir}; copyFiles(singleFileCfg, function(err){ if (err) { logTaskError('Directory not copied!'); } }); } }, next: function(err,watcher){ if (err) { callback(err); } else { callback(); } } }); }
javascript
function(cfg, callback) { var paths = cfg.input_files || cfg.input_file || cfg.input_dir; if (!Array.isArray(paths)) { paths = [paths]; } watchr.watch({ paths: paths, listener: function(eventName,filePath,fileCurrentStat,filePreviousStat){ console.log(formatLog('File changed:', filePath)); var singleFileCfg, outputDir, logTaskError = function(msg) { console.log('\n'+msg.red); }; // Detect what build configuration the file belongs to if (config.scripts.indexOf(cfg) !== -1) { // rebuild scripts buildScripts(cfg, function(err){ if (err) { logTaskError('Scripts not saved!'); } }); } else if (config.styles.indexOf(cfg) !== -1) { // rebuild styles buildStyles(cfg, function(err){ if (err) { logTaskError('Styles not saved!'); } }); } else if (config.copy_files.indexOf(cfg) !== -1) { // copy files singleFileCfg = {input_files: [filePath], output_dir: cfg.output_dir}; copyFiles(singleFileCfg, function(err){ if (err) { logTaskError('File not copied!'); } }); } else if (config.copy_file.indexOf(cfg) !== -1) { // copy/rename single file singleFileCfg = {input_file: filePath, output_file: cfg.output_file}; copyFile(singleFileCfg, function(err){ if (err) { logTaskError('File not copied!'); } }); } else if (config.copy_dir.indexOf(cfg) !== -1) { // copy single directory outputDir = path.dirname(filePath).replace(cfg.input_dir, cfg.output_dir); singleFileCfg = {input_files: [filePath], output_dir: outputDir}; copyFiles(singleFileCfg, function(err){ if (err) { logTaskError('Directory not copied!'); } }); } }, next: function(err,watcher){ if (err) { callback(err); } else { callback(); } } }); }
[ "function", "(", "cfg", ",", "callback", ")", "{", "var", "paths", "=", "cfg", ".", "input_files", "||", "cfg", ".", "input_file", "||", "cfg", ".", "input_dir", ";", "if", "(", "!", "Array", ".", "isArray", "(", "paths", ")", ")", "{", "paths", "=", "[", "paths", "]", ";", "}", "watchr", ".", "watch", "(", "{", "paths", ":", "paths", ",", "listener", ":", "function", "(", "eventName", ",", "filePath", ",", "fileCurrentStat", ",", "filePreviousStat", ")", "{", "console", ".", "log", "(", "formatLog", "(", "'File changed:'", ",", "filePath", ")", ")", ";", "var", "singleFileCfg", ",", "outputDir", ",", "logTaskError", "=", "function", "(", "msg", ")", "{", "console", ".", "log", "(", "'\\n'", "+", "msg", ".", "red", ")", ";", "}", ";", "// Detect what build configuration the file belongs to", "if", "(", "config", ".", "scripts", ".", "indexOf", "(", "cfg", ")", "!==", "-", "1", ")", "{", "// rebuild scripts", "buildScripts", "(", "cfg", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logTaskError", "(", "'Scripts not saved!'", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "config", ".", "styles", ".", "indexOf", "(", "cfg", ")", "!==", "-", "1", ")", "{", "// rebuild styles", "buildStyles", "(", "cfg", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logTaskError", "(", "'Styles not saved!'", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "config", ".", "copy_files", ".", "indexOf", "(", "cfg", ")", "!==", "-", "1", ")", "{", "// copy files", "singleFileCfg", "=", "{", "input_files", ":", "[", "filePath", "]", ",", "output_dir", ":", "cfg", ".", "output_dir", "}", ";", "copyFiles", "(", "singleFileCfg", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logTaskError", "(", "'File not copied!'", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "config", ".", "copy_file", ".", "indexOf", "(", "cfg", ")", "!==", "-", "1", ")", "{", "// copy/rename single file", "singleFileCfg", "=", "{", "input_file", ":", "filePath", ",", "output_file", ":", "cfg", ".", "output_file", "}", ";", "copyFile", "(", "singleFileCfg", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logTaskError", "(", "'File not copied!'", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "config", ".", "copy_dir", ".", "indexOf", "(", "cfg", ")", "!==", "-", "1", ")", "{", "// copy single directory", "outputDir", "=", "path", ".", "dirname", "(", "filePath", ")", ".", "replace", "(", "cfg", ".", "input_dir", ",", "cfg", ".", "output_dir", ")", ";", "singleFileCfg", "=", "{", "input_files", ":", "[", "filePath", "]", ",", "output_dir", ":", "outputDir", "}", ";", "copyFiles", "(", "singleFileCfg", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "logTaskError", "(", "'Directory not copied!'", ")", ";", "}", "}", ")", ";", "}", "}", ",", "next", ":", "function", "(", "err", ",", "watcher", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Setup watching of changes in the input files @param {Object} cfg Build configuration @param {Function} callback Task complete callback
[ "Setup", "watching", "of", "changes", "in", "the", "input", "files" ]
f0611bcabda7f8009a04063a0661b7daed603b5e
https://github.com/filmic/Robol/blob/f0611bcabda7f8009a04063a0661b7daed603b5e/lib/robol.js#L479-L546
52,688
joscha/html-context
src/index.js
getWindowForElement
function getWindowForElement(element) { const e = element.documentElement || element; const doc = e.ownerDocument; return doc.defaultView; }
javascript
function getWindowForElement(element) { const e = element.documentElement || element; const doc = e.ownerDocument; return doc.defaultView; }
[ "function", "getWindowForElement", "(", "element", ")", "{", "const", "e", "=", "element", ".", "documentElement", "||", "element", ";", "const", "doc", "=", "e", ".", "ownerDocument", ";", "return", "doc", ".", "defaultView", ";", "}" ]
Gets the window object from a given element or document @private @param {!HTMLDocument|HTMLElement} element The element to get the window object for @return {Window|null} the window object for the given element
[ "Gets", "the", "window", "object", "from", "a", "given", "element", "or", "document" ]
e1d6dd64f10f33cf619c1dcd7363fcfcee6daa4d
https://github.com/joscha/html-context/blob/e1d6dd64f10f33cf619c1dcd7363fcfcee6daa4d/src/index.js#L13-L17
52,689
quantumpayments/media
lib/handlers/rate.js
handler
function handler(req, res) { var origin = req.headers.origin if (origin) { res.setHeader('Access-Control-Allow-Origin', origin) } var rating = {} rating.uri = req.body.uri rating.rating = req.body.rating rating.reviewer = req.session.userId debug(rating) if (!rating.reviewer) { res.send('must be authenticated') return } config = res.locals.config conn = res.locals.sequelize if (isNaN(rating.rating) || !rating.uri) { res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_input', { ui : config.ui }) return } else { qpm_media.addRating(rating, config, conn).then(function(ret) { res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_success', { ui : config.ui }) debug(ret) return }).catch(function(err){ res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_error', { ui : config.ui }) debug(ret) return }) } }
javascript
function handler(req, res) { var origin = req.headers.origin if (origin) { res.setHeader('Access-Control-Allow-Origin', origin) } var rating = {} rating.uri = req.body.uri rating.rating = req.body.rating rating.reviewer = req.session.userId debug(rating) if (!rating.reviewer) { res.send('must be authenticated') return } config = res.locals.config conn = res.locals.sequelize if (isNaN(rating.rating) || !rating.uri) { res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_input', { ui : config.ui }) return } else { qpm_media.addRating(rating, config, conn).then(function(ret) { res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_success', { ui : config.ui }) debug(ret) return }).catch(function(err){ res.status(200) res.header('Content-Type', 'text/html') res.render('pages/media/rate_error', { ui : config.ui }) debug(ret) return }) } }
[ "function", "handler", "(", "req", ",", "res", ")", "{", "var", "origin", "=", "req", ".", "headers", ".", "origin", "if", "(", "origin", ")", "{", "res", ".", "setHeader", "(", "'Access-Control-Allow-Origin'", ",", "origin", ")", "}", "var", "rating", "=", "{", "}", "rating", ".", "uri", "=", "req", ".", "body", ".", "uri", "rating", ".", "rating", "=", "req", ".", "body", ".", "rating", "rating", ".", "reviewer", "=", "req", ".", "session", ".", "userId", "debug", "(", "rating", ")", "if", "(", "!", "rating", ".", "reviewer", ")", "{", "res", ".", "send", "(", "'must be authenticated'", ")", "return", "}", "config", "=", "res", ".", "locals", ".", "config", "conn", "=", "res", ".", "locals", ".", "sequelize", "if", "(", "isNaN", "(", "rating", ".", "rating", ")", "||", "!", "rating", ".", "uri", ")", "{", "res", ".", "status", "(", "200", ")", "res", ".", "header", "(", "'Content-Type'", ",", "'text/html'", ")", "res", ".", "render", "(", "'pages/media/rate_input'", ",", "{", "ui", ":", "config", ".", "ui", "}", ")", "return", "}", "else", "{", "qpm_media", ".", "addRating", "(", "rating", ",", "config", ",", "conn", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "res", ".", "status", "(", "200", ")", "res", ".", "header", "(", "'Content-Type'", ",", "'text/html'", ")", "res", ".", "render", "(", "'pages/media/rate_success'", ",", "{", "ui", ":", "config", ".", "ui", "}", ")", "debug", "(", "ret", ")", "return", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "res", ".", "status", "(", "200", ")", "res", ".", "header", "(", "'Content-Type'", ",", "'text/html'", ")", "res", ".", "render", "(", "'pages/media/rate_error'", ",", "{", "ui", ":", "config", ".", "ui", "}", ")", "debug", "(", "ret", ")", "return", "}", ")", "}", "}" ]
Rating hander. @param {Object} req The request. @param {Object} res The response.
[ "Rating", "hander", "." ]
b53034e6dd2a94dca950e60a49e403aceaa1cdf1
https://github.com/quantumpayments/media/blob/b53034e6dd2a94dca950e60a49e403aceaa1cdf1/lib/handlers/rate.js#L13-L56
52,690
vmarkdown/vremark-parse
packages/vremark-toc/mdast-util-toc/lib/index.js
toc
function toc(node, options) { var settings = options || {}; var heading = settings.heading ? toExpression(settings.heading) : null; var result = search(node, heading, settings.maxDepth || 6); var map = result.map; result.map = map.length === 0 ? null : contents(map, settings.tight); /* No given heading */ if (!heading) { result.index = null; result.endIndex = null; } return result; }
javascript
function toc(node, options) { var settings = options || {}; var heading = settings.heading ? toExpression(settings.heading) : null; var result = search(node, heading, settings.maxDepth || 6); var map = result.map; result.map = map.length === 0 ? null : contents(map, settings.tight); /* No given heading */ if (!heading) { result.index = null; result.endIndex = null; } return result; }
[ "function", "toc", "(", "node", ",", "options", ")", "{", "var", "settings", "=", "options", "||", "{", "}", ";", "var", "heading", "=", "settings", ".", "heading", "?", "toExpression", "(", "settings", ".", "heading", ")", ":", "null", ";", "var", "result", "=", "search", "(", "node", ",", "heading", ",", "settings", ".", "maxDepth", "||", "6", ")", ";", "var", "map", "=", "result", ".", "map", ";", "result", ".", "map", "=", "map", ".", "length", "===", "0", "?", "null", ":", "contents", "(", "map", ",", "settings", ".", "tight", ")", ";", "/* No given heading */", "if", "(", "!", "heading", ")", "{", "result", ".", "index", "=", "null", ";", "result", ".", "endIndex", "=", "null", ";", "}", "return", "result", ";", "}" ]
Get a TOC representation of `node`. @param {Mdast} node - MDAST. @param {Object} options - Configuration. @return {Array} - TOC Markdown.
[ "Get", "a", "TOC", "representation", "of", "node", "." ]
d7b353dcb5d021eeceb40f3c505ece893202db7a
https://github.com/vmarkdown/vremark-parse/blob/d7b353dcb5d021eeceb40f3c505ece893202db7a/packages/vremark-toc/mdast-util-toc/lib/index.js#L24-L39
52,691
the-terribles/evergreen
lib/configurator.js
Configurator
function Configurator(){ // Store reference to the tree/template this.__tree = {}; // Cached instance of the fully rendered tree. this.__cachedResolvedTree = null; // Configuration for the GraphBuilder this.__config = { directives: { file: new (require('./directives/file.js')), http: new (require('./directives/http.js')), require: new (require('./directives/require.js')) }, resolvers: { absolute: { order: 1, resolve: Path.resolve(__dirname, './resolvers/absolute.js') }, relative: { order: 2, resolve: Path.resolve(__dirname, './resolvers/relative.js') }, environment: { order: 3, resolve: Path.resolve(__dirname, './resolvers/environment.js') } } }; }
javascript
function Configurator(){ // Store reference to the tree/template this.__tree = {}; // Cached instance of the fully rendered tree. this.__cachedResolvedTree = null; // Configuration for the GraphBuilder this.__config = { directives: { file: new (require('./directives/file.js')), http: new (require('./directives/http.js')), require: new (require('./directives/require.js')) }, resolvers: { absolute: { order: 1, resolve: Path.resolve(__dirname, './resolvers/absolute.js') }, relative: { order: 2, resolve: Path.resolve(__dirname, './resolvers/relative.js') }, environment: { order: 3, resolve: Path.resolve(__dirname, './resolvers/environment.js') } } }; }
[ "function", "Configurator", "(", ")", "{", "// Store reference to the tree/template", "this", ".", "__tree", "=", "{", "}", ";", "// Cached instance of the fully rendered tree.", "this", ".", "__cachedResolvedTree", "=", "null", ";", "// Configuration for the GraphBuilder", "this", ".", "__config", "=", "{", "directives", ":", "{", "file", ":", "new", "(", "require", "(", "'./directives/file.js'", ")", ")", ",", "http", ":", "new", "(", "require", "(", "'./directives/http.js'", ")", ")", ",", "require", ":", "new", "(", "require", "(", "'./directives/require.js'", ")", ")", "}", ",", "resolvers", ":", "{", "absolute", ":", "{", "order", ":", "1", ",", "resolve", ":", "Path", ".", "resolve", "(", "__dirname", ",", "'./resolvers/absolute.js'", ")", "}", ",", "relative", ":", "{", "order", ":", "2", ",", "resolve", ":", "Path", ".", "resolve", "(", "__dirname", ",", "'./resolvers/relative.js'", ")", "}", ",", "environment", ":", "{", "order", ":", "3", ",", "resolve", ":", "Path", ".", "resolve", "(", "__dirname", ",", "'./resolvers/environment.js'", ")", "}", "}", "}", ";", "}" ]
Main interface for interacting with Evergreen. @constructor
[ "Main", "interface", "for", "interacting", "with", "Evergreen", "." ]
c1adaea1ce825727c5c5ed75d858e2f0d22657e2
https://github.com/the-terribles/evergreen/blob/c1adaea1ce825727c5c5ed75d858e2f0d22657e2/lib/configurator.js#L16-L43
52,692
jmendiara/gitftw
src/commands.js
commit
function commit(options) { assert.ok(options.message, 'message is mandatory'); var args = [ 'commit', options.force ? '--amend' : null, options.noVerify ? '-n' : null, options.message ? '-m' : null, options.message ? options.message : null ]; return git(args) .catch(passWarning) .then(silent); }
javascript
function commit(options) { assert.ok(options.message, 'message is mandatory'); var args = [ 'commit', options.force ? '--amend' : null, options.noVerify ? '-n' : null, options.message ? '-m' : null, options.message ? options.message : null ]; return git(args) .catch(passWarning) .then(silent); }
[ "function", "commit", "(", "options", ")", "{", "assert", ".", "ok", "(", "options", ".", "message", ",", "'message is mandatory'", ")", ";", "var", "args", "=", "[", "'commit'", ",", "options", ".", "force", "?", "'--amend'", ":", "null", ",", "options", ".", "noVerify", "?", "'-n'", ":", "null", ",", "options", ".", "message", "?", "'-m'", ":", "null", ",", "options", ".", "message", "?", "options", ".", "message", ":", "null", "]", ";", "return", "git", "(", "args", ")", ".", "catch", "(", "passWarning", ")", ".", "then", "(", "silent", ")", ";", "}" ]
Commits the staging area Executes `git commit -m "First commit"` It does not fail when there is not anything to commit @example var git = require('gitftw'); git.commit({ message: 'First commit' }); @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|String} options.message The commit message @param {Resolvable|Boolean} [options.force] Replace the tip of the current branch by creating a new commit. The --amend flag @param {Resolvable|Boolean} [options.noVerify] This option bypasses the pre-commit and commit-msg hooks @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with undefined
[ "Commits", "the", "staging", "area", "Executes", "git", "commit", "-", "m", "First", "commit" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L88-L102
52,693
jmendiara/gitftw
src/commands.js
clone
function clone(options) { assert.ok(options.repository, 'repository is mandatory'); var branchOrTag = options.branch || options.tag; var args = [ 'clone', options.repository, options.directory, branchOrTag ? ('-b' + branchOrTag) : null, options.origin ? ('-o' + options.origin) : null, options.recursive ? '--recursive' : null, options.bare ? '--bare' : null, options.depth ? '--depth' : null, options.depth ? '' + options.depth : null ]; return git(args) .then(silent); }
javascript
function clone(options) { assert.ok(options.repository, 'repository is mandatory'); var branchOrTag = options.branch || options.tag; var args = [ 'clone', options.repository, options.directory, branchOrTag ? ('-b' + branchOrTag) : null, options.origin ? ('-o' + options.origin) : null, options.recursive ? '--recursive' : null, options.bare ? '--bare' : null, options.depth ? '--depth' : null, options.depth ? '' + options.depth : null ]; return git(args) .then(silent); }
[ "function", "clone", "(", "options", ")", "{", "assert", ".", "ok", "(", "options", ".", "repository", ",", "'repository is mandatory'", ")", ";", "var", "branchOrTag", "=", "options", ".", "branch", "||", "options", ".", "tag", ";", "var", "args", "=", "[", "'clone'", ",", "options", ".", "repository", ",", "options", ".", "directory", ",", "branchOrTag", "?", "(", "'-b'", "+", "branchOrTag", ")", ":", "null", ",", "options", ".", "origin", "?", "(", "'-o'", "+", "options", ".", "origin", ")", ":", "null", ",", "options", ".", "recursive", "?", "'--recursive'", ":", "null", ",", "options", ".", "bare", "?", "'--bare'", ":", "null", ",", "options", ".", "depth", "?", "'--depth'", ":", "null", ",", "options", ".", "depth", "?", "''", "+", "options", ".", "depth", ":", "null", "]", ";", "return", "git", "(", "args", ")", ".", "then", "(", "silent", ")", ";", "}" ]
Clones a git repo If both a branch and a tag are specified, the branch takes precedence @example var git = require('gitftw'); git.clone({ repository: '[email protected]:jmendiara/node-lru-cache.git', directory: './cache' //optional }); @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|String} options.repository The git repository endpoint @param {Resolvable|String} [options.directory] The directory where the repo will be cloned By default, git will clone it a new one specifed by the repo name @param {Resolvable|String} [options.branch] The remote repo branch to checkout after clone. @param {Resolvable|String} [options.tag] The remote repo tag to checkout after clone. @param {Resolvable|String} [options.origin] Instead of using the remote name origin to keep track of the upstream repository, use this parameter value @param {Resolvable|Boolean} [options.recursive] After the clone is created, initialize all @param {Resolvable|Boolean} [options.bare] Make a bare Git repository.: neither remote-tracking branches nor the related configuration variables are created. @param {Resolvable|Number} [options.depth] Create a shallow clone with a history truncated to the specified number of revisions. @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with undefined
[ "Clones", "a", "git", "repo" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L136-L154
52,694
jmendiara/gitftw
src/commands.js
add
function add(options) { assert.ok(options.files, 'files is mandatory'); return options.files .filter(function(file) { //Git exits OK with empty filenames. //Avoid an unnecessary call to git in these cases by removing the filename return !!file; }) .reduce(function(soFar, file) { var args = ['add', file]; return soFar .then(gitFn(args)) .then(silent); }, Promise.resolve()); }
javascript
function add(options) { assert.ok(options.files, 'files is mandatory'); return options.files .filter(function(file) { //Git exits OK with empty filenames. //Avoid an unnecessary call to git in these cases by removing the filename return !!file; }) .reduce(function(soFar, file) { var args = ['add', file]; return soFar .then(gitFn(args)) .then(silent); }, Promise.resolve()); }
[ "function", "add", "(", "options", ")", "{", "assert", ".", "ok", "(", "options", ".", "files", ",", "'files is mandatory'", ")", ";", "return", "options", ".", "files", ".", "filter", "(", "function", "(", "file", ")", "{", "//Git exits OK with empty filenames.", "//Avoid an unnecessary call to git in these cases by removing the filename", "return", "!", "!", "file", ";", "}", ")", ".", "reduce", "(", "function", "(", "soFar", ",", "file", ")", "{", "var", "args", "=", "[", "'add'", ",", "file", "]", ";", "return", "soFar", ".", "then", "(", "gitFn", "(", "args", ")", ")", ".", "then", "(", "silent", ")", ";", "}", ",", "Promise", ".", "resolve", "(", ")", ")", ";", "}" ]
Adds filenames to the stashing area Issues `git add README.md` @example var git = require('gitftw'); git.add({ files: ['README.md', 'index.js'] }); @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|Array<String>} options.files The files to be added, relative to the cwd @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with undefined
[ "Adds", "filenames", "to", "the", "stashing", "area", "Issues", "git", "add", "README", ".", "md" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L175-L190
52,695
jmendiara/gitftw
src/commands.js
push
function push(options) { var branchOrTag = options.branch || options.tag; var args = [ 'push', options.remote || 'origin', branchOrTag || 'HEAD', options.force ? '--force' : null ]; return git(args) .then(silent); }
javascript
function push(options) { var branchOrTag = options.branch || options.tag; var args = [ 'push', options.remote || 'origin', branchOrTag || 'HEAD', options.force ? '--force' : null ]; return git(args) .then(silent); }
[ "function", "push", "(", "options", ")", "{", "var", "branchOrTag", "=", "options", ".", "branch", "||", "options", ".", "tag", ";", "var", "args", "=", "[", "'push'", ",", "options", ".", "remote", "||", "'origin'", ",", "branchOrTag", "||", "'HEAD'", ",", "options", ".", "force", "?", "'--force'", ":", "null", "]", ";", "return", "git", "(", "args", ")", ".", "then", "(", "silent", ")", ";", "}" ]
Push the change sets to server Executes `git push origin master` Defaults to "origin", and don't follow configured refspecs for the upstream If both a branch and a tag are specified, the branch takes precedence @example var git = require('gitftw'); git.push(); //the current branch to `origin` @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|String} [options.remote="origin"] The remote ref to push to @param {Resolvable|String} [options.branch="HEAD"] The branch to push. HEAD will push the current branch @param {Resolvable|String} [options.tag] The tag to push @param {Resolvable|Boolean} [options.force] Force a remote update. Can cause the remote repository to lose commits; use it with care. --force flag @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with undefined
[ "Push", "the", "change", "sets", "to", "server", "Executes", "git", "push", "origin", "master" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L219-L231
52,696
jmendiara/gitftw
src/commands.js
pull
function pull(options) { options = options || {}; var branchOrTag = options.branch || options.tag; var args = [ 'pull', options.rebase ? '--rebase' : null, options.remote || 'origin', branchOrTag || git.getCurrentBranch ]; return git(args) .then(silent); }
javascript
function pull(options) { options = options || {}; var branchOrTag = options.branch || options.tag; var args = [ 'pull', options.rebase ? '--rebase' : null, options.remote || 'origin', branchOrTag || git.getCurrentBranch ]; return git(args) .then(silent); }
[ "function", "pull", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "branchOrTag", "=", "options", ".", "branch", "||", "options", ".", "tag", ";", "var", "args", "=", "[", "'pull'", ",", "options", ".", "rebase", "?", "'--rebase'", ":", "null", ",", "options", ".", "remote", "||", "'origin'", ",", "branchOrTag", "||", "git", ".", "getCurrentBranch", "]", ";", "return", "git", "(", "args", ")", ".", "then", "(", "silent", ")", ";", "}" ]
Pulls a remote branch into the current one Executes `git pull origin master` remote defaults to "origin", and don't follow configured refspecs for the upstream If both a branch and a tag are specified, the branch takes precedence When no branch and tag are specifies, this command will try to pull the actual local branch name from the remote @example var git = require('gitftw'); //While in master... git.getCurrentBranch().then(console.log) //Outputs: master //Pulls origin/master into the current branch (master) git.pull() @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|String} [options.remote="origin"] The remote @param {Resolvable|String} [options.branch=currentBranch] The remote branch to pull @param {Resolvable|String} [options.tag] The remote tag to pull @param {Resolvable|Boolean} [options.rebase] Make a rebase (--rebase tag) @param {callback} [cb] The execution callback result @return {Promise} Resolves with undefined
[ "Pulls", "a", "remote", "branch", "into", "the", "current", "one", "Executes", "git", "pull", "origin", "master" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L266-L280
52,697
jmendiara/gitftw
src/commands.js
checkout
function checkout(options) { var branchOrTag = options.branch || options.tag; assert.ok(branchOrTag, 'branch or tag is mandatory'); if ((options.create || options.oldCreate) && options.orphan) { throw new Error('create and orphan cannot be specified both together'); } if (options.create && options.oldCreate) { throw new Error('create and oldCreate cannot be specified both together'); } var args = [ 'checkout', options.create ? '-B' : options.oldCreate ? '-b' : null, options.orphan ? '--orphan' : null, branchOrTag, options.force ? '-f' : null ]; return git(args) .then(silent); }
javascript
function checkout(options) { var branchOrTag = options.branch || options.tag; assert.ok(branchOrTag, 'branch or tag is mandatory'); if ((options.create || options.oldCreate) && options.orphan) { throw new Error('create and orphan cannot be specified both together'); } if (options.create && options.oldCreate) { throw new Error('create and oldCreate cannot be specified both together'); } var args = [ 'checkout', options.create ? '-B' : options.oldCreate ? '-b' : null, options.orphan ? '--orphan' : null, branchOrTag, options.force ? '-f' : null ]; return git(args) .then(silent); }
[ "function", "checkout", "(", "options", ")", "{", "var", "branchOrTag", "=", "options", ".", "branch", "||", "options", ".", "tag", ";", "assert", ".", "ok", "(", "branchOrTag", ",", "'branch or tag is mandatory'", ")", ";", "if", "(", "(", "options", ".", "create", "||", "options", ".", "oldCreate", ")", "&&", "options", ".", "orphan", ")", "{", "throw", "new", "Error", "(", "'create and orphan cannot be specified both together'", ")", ";", "}", "if", "(", "options", ".", "create", "&&", "options", ".", "oldCreate", ")", "{", "throw", "new", "Error", "(", "'create and oldCreate cannot be specified both together'", ")", ";", "}", "var", "args", "=", "[", "'checkout'", ",", "options", ".", "create", "?", "'-B'", ":", "options", ".", "oldCreate", "?", "'-b'", ":", "null", ",", "options", ".", "orphan", "?", "'--orphan'", ":", "null", ",", "branchOrTag", ",", "options", ".", "force", "?", "'-f'", ":", "null", "]", ";", "return", "git", "(", "args", ")", ".", "then", "(", "silent", ")", ";", "}" ]
Checkout a local branch Executes `git checkout -B issues/12` If you specify create, it will try to create the branch, or will checkout it if it already exists If both a branch and a tag are specified, the branch takes precedence Cannot use create and orphan both together @example var git = require('gitftw'); git.checkout({ branch: 'master' }); @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|String} options.branch The branch to checkout @param {Resolvable|String} [options.tag] The tag to checkout @param {Resolvable|Boolean} [options.create] Try to create the branch (-B flag) @param {Resolvable|Boolean} [options.oldCreate] Try to create the branch (-b flag). Do not use along with 'create'. @param {Resolvable|Boolean} [options.orphan] Create an orphan branch (--orphan flag) @param {Resolvable|Boolean} [options.force] When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes. (-f flag) @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with undefined
[ "Checkout", "a", "local", "branch" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L317-L340
52,698
jmendiara/gitftw
src/commands.js
removeLocalBranch
function removeLocalBranch(options) { assert.ok(options.branch, 'branch is mandatory'); var args = [ 'branch', options.force ? '-D' : '-d', options.branch ]; return git(args) .then(silent); }
javascript
function removeLocalBranch(options) { assert.ok(options.branch, 'branch is mandatory'); var args = [ 'branch', options.force ? '-D' : '-d', options.branch ]; return git(args) .then(silent); }
[ "function", "removeLocalBranch", "(", "options", ")", "{", "assert", ".", "ok", "(", "options", ".", "branch", ",", "'branch is mandatory'", ")", ";", "var", "args", "=", "[", "'branch'", ",", "options", ".", "force", "?", "'-D'", ":", "'-d'", ",", "options", ".", "branch", "]", ";", "return", "git", "(", "args", ")", ".", "then", "(", "silent", ")", ";", "}" ]
Removes a local branch @example var git = require('gitftw'); //while in master... git.removeLocalBranch({ branch: 'master' }); @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|String} options.branch The branch name @param {Resolvable|Boolean} [options.force] force the delete (-D) @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with undefined
[ "Removes", "a", "local", "branch" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L466-L477
52,699
jmendiara/gitftw
src/commands.js
removeRemoteBranch
function removeRemoteBranch(options) { assert.ok(options.branch, 'branch is mandatory'); var args = [ 'push', options.remote || 'origin', ':' + options.branch ]; return git(args) .then(silent); }
javascript
function removeRemoteBranch(options) { assert.ok(options.branch, 'branch is mandatory'); var args = [ 'push', options.remote || 'origin', ':' + options.branch ]; return git(args) .then(silent); }
[ "function", "removeRemoteBranch", "(", "options", ")", "{", "assert", ".", "ok", "(", "options", ".", "branch", ",", "'branch is mandatory'", ")", ";", "var", "args", "=", "[", "'push'", ",", "options", ".", "remote", "||", "'origin'", ",", "':'", "+", "options", ".", "branch", "]", ";", "return", "git", "(", "args", ")", ".", "then", "(", "silent", ")", ";", "}" ]
Removes a remote branch @example var git = require('gitftw'); //while in master... git.removeRemoteBranch({ branch: 'master' }); @memberof git @type {command} @param {Object} options The options object. All its properties are {@link Resolvable} @param {Resolvable|String} options.branch The branch name @param {Resolvable|String} [options.remote="origin"] The remote ref where the branch will be removed @param {callback} [cb] The execution callback result @returns {Promise} Promise Resolves with undefined
[ "Removes", "a", "remote", "branch" ]
ba91b0d68b7791b5b557addc685737f6c912b4f3
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L499-L510