repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
winterstein/wwutils.js
src/wwutils.js
function(obj, propName, message) { assert(typeof(propName) === 'string'); if ( ! message) message = "Using this property indicates old/broken code."; // already blocked? bphush = true; try { let v = obj[propName]; } catch (err) { return obj; } bphush = false; if (obj[propName] !== undefined) { // already set to a value :( const ex = new Error("Having "+propName+" is blocked! "+message); if ( ! bphush) console.error(ex, this); // react can swallow stuff throw ex; } if ( ! Object.isExtensible(obj)) { // no need -- frozen or sealed return; } Object.defineProperty(obj, propName, { get: function () { const ex = new Error(propName+" is blocked! "+message); if ( ! bphush) console.error(ex, this); // react can swallow stuff throw ex; }, set: function () { const ex = new Error("Set "+propName+" is blocked! "+message); if ( ! bphush) console.error(ex, this); // react can swallow stuff throw ex; } }); return obj; }
javascript
function(obj, propName, message) { assert(typeof(propName) === 'string'); if ( ! message) message = "Using this property indicates old/broken code."; // already blocked? bphush = true; try { let v = obj[propName]; } catch (err) { return obj; } bphush = false; if (obj[propName] !== undefined) { // already set to a value :( const ex = new Error("Having "+propName+" is blocked! "+message); if ( ! bphush) console.error(ex, this); // react can swallow stuff throw ex; } if ( ! Object.isExtensible(obj)) { // no need -- frozen or sealed return; } Object.defineProperty(obj, propName, { get: function () { const ex = new Error(propName+" is blocked! "+message); if ( ! bphush) console.error(ex, this); // react can swallow stuff throw ex; }, set: function () { const ex = new Error("Set "+propName+" is blocked! "+message); if ( ! bphush) console.error(ex, this); // react can swallow stuff throw ex; } }); return obj; }
[ "function", "(", "obj", ",", "propName", ",", "message", ")", "{", "assert", "(", "typeof", "(", "propName", ")", "===", "'string'", ")", ";", "if", "(", "!", "message", ")", "message", "=", "\"Using this property indicates old/broken code.\"", ";", "bphush", "=", "true", ";", "try", "{", "let", "v", "=", "obj", "[", "propName", "]", ";", "}", "catch", "(", "err", ")", "{", "return", "obj", ";", "}", "bphush", "=", "false", ";", "if", "(", "obj", "[", "propName", "]", "!==", "undefined", ")", "{", "const", "ex", "=", "new", "Error", "(", "\"Having \"", "+", "propName", "+", "\" is blocked! \"", "+", "message", ")", ";", "if", "(", "!", "bphush", ")", "console", ".", "error", "(", "ex", ",", "this", ")", ";", "throw", "ex", ";", "}", "if", "(", "!", "Object", ".", "isExtensible", "(", "obj", ")", ")", "{", "return", ";", "}", "Object", ".", "defineProperty", "(", "obj", ",", "propName", ",", "{", "get", ":", "function", "(", ")", "{", "const", "ex", "=", "new", "Error", "(", "propName", "+", "\" is blocked! \"", "+", "message", ")", ";", "if", "(", "!", "bphush", ")", "console", ".", "error", "(", "ex", ",", "this", ")", ";", "throw", "ex", ";", "}", ",", "set", ":", "function", "(", ")", "{", "const", "ex", "=", "new", "Error", "(", "\"Set \"", "+", "propName", "+", "\" is blocked! \"", "+", "message", ")", ";", "if", "(", "!", "bphush", ")", "console", ".", "error", "(", "ex", ",", "this", ")", ";", "throw", "ex", ";", "}", "}", ")", ";", "return", "obj", ";", "}" ]
Rig obj so that any use of obj.propName will trigger an Error. @param {!String} propName @param {?String} message Optional helpful message, like "use foo() instead." @returns obj (allows for chaining)
[ "Rig", "obj", "so", "that", "any", "use", "of", "obj", ".", "propName", "will", "trigger", "an", "Error", "." ]
683743df0c896993b9ec455738154972ac54f0b6
https://github.com/winterstein/wwutils.js/blob/683743df0c896993b9ec455738154972ac54f0b6/src/wwutils.js#L414-L448
train
vesln/hydro
lib/cli/commands/help.js
coreFlags
function coreFlags() { console.log('Core flags:'); console.log(); flags.forEach(function(flag) { console.log(' ' + flag); }); }
javascript
function coreFlags() { console.log('Core flags:'); console.log(); flags.forEach(function(flag) { console.log(' ' + flag); }); }
[ "function", "coreFlags", "(", ")", "{", "console", ".", "log", "(", "'Core flags:'", ")", ";", "console", ".", "log", "(", ")", ";", "flags", ".", "forEach", "(", "function", "(", "flag", ")", "{", "console", ".", "log", "(", "' '", "+", "flag", ")", ";", "}", ")", ";", "}" ]
Print the code CLI flags. @api private
[ "Print", "the", "code", "CLI", "flags", "." ]
3f4d2e4926f913976187376e82f1496514c39890
https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/cli/commands/help.js#L50-L56
train
vesln/hydro
lib/cli/commands/help.js
pluginFlags
function pluginFlags(plugins) { var pflags = []; var len = 0; plugins.forEach(function(plugin) { Object.keys(plugin.flags || {}).forEach(function(flag) { pflags.push([flag, plugin.flags[flag]]); len = Math.max(flag.length, len); }); }); if (pflags.length) { console.log(); console.log('Plugin flags:'); console.log(); pflags.forEach(function(flag) { console.log(' %s %s', ljust(flag[0], len), flag[1]); }); } console.log(); }
javascript
function pluginFlags(plugins) { var pflags = []; var len = 0; plugins.forEach(function(plugin) { Object.keys(plugin.flags || {}).forEach(function(flag) { pflags.push([flag, plugin.flags[flag]]); len = Math.max(flag.length, len); }); }); if (pflags.length) { console.log(); console.log('Plugin flags:'); console.log(); pflags.forEach(function(flag) { console.log(' %s %s', ljust(flag[0], len), flag[1]); }); } console.log(); }
[ "function", "pluginFlags", "(", "plugins", ")", "{", "var", "pflags", "=", "[", "]", ";", "var", "len", "=", "0", ";", "plugins", ".", "forEach", "(", "function", "(", "plugin", ")", "{", "Object", ".", "keys", "(", "plugin", ".", "flags", "||", "{", "}", ")", ".", "forEach", "(", "function", "(", "flag", ")", "{", "pflags", ".", "push", "(", "[", "flag", ",", "plugin", ".", "flags", "[", "flag", "]", "]", ")", ";", "len", "=", "Math", ".", "max", "(", "flag", ".", "length", ",", "len", ")", ";", "}", ")", ";", "}", ")", ";", "if", "(", "pflags", ".", "length", ")", "{", "console", ".", "log", "(", ")", ";", "console", ".", "log", "(", "'Plugin flags:'", ")", ";", "console", ".", "log", "(", ")", ";", "pflags", ".", "forEach", "(", "function", "(", "flag", ")", "{", "console", ".", "log", "(", "' %s %s'", ",", "ljust", "(", "flag", "[", "0", "]", ",", "len", ")", ",", "flag", "[", "1", "]", ")", ";", "}", ")", ";", "}", "console", ".", "log", "(", ")", ";", "}" ]
Print CLI flags from plugins. @param {Array} plugins @api private
[ "Print", "CLI", "flags", "from", "plugins", "." ]
3f4d2e4926f913976187376e82f1496514c39890
https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/cli/commands/help.js#L65-L86
train
veo-labs/openveo-api
Gruntfile.js
loadConfig
function loadConfig(path) { var configuration = {}; var configurationFiles = fs.readdirSync(path); configurationFiles.forEach(function(configurationFile) { configuration[configurationFile.replace(/\.js$/, '')] = require(path + '/' + configurationFile); }); return configuration; }
javascript
function loadConfig(path) { var configuration = {}; var configurationFiles = fs.readdirSync(path); configurationFiles.forEach(function(configurationFile) { configuration[configurationFile.replace(/\.js$/, '')] = require(path + '/' + configurationFile); }); return configuration; }
[ "function", "loadConfig", "(", "path", ")", "{", "var", "configuration", "=", "{", "}", ";", "var", "configurationFiles", "=", "fs", ".", "readdirSync", "(", "path", ")", ";", "configurationFiles", ".", "forEach", "(", "function", "(", "configurationFile", ")", "{", "configuration", "[", "configurationFile", ".", "replace", "(", "/", "\\.js$", "/", ",", "''", ")", "]", "=", "require", "(", "path", "+", "'/'", "+", "configurationFile", ")", ";", "}", ")", ";", "return", "configuration", ";", "}" ]
Loads a bunch of grunt configuration files from the given directory. Loaded configurations can be referenced using the configuration file name. For example, if myConf.js returns an object with a property "test", it will be accessible using myConf.test. @param {String} path Path of the directory containing configuration files @return {Object} The list of configurations indexed by filename without the extension
[ "Loads", "a", "bunch", "of", "grunt", "configuration", "files", "from", "the", "given", "directory", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/Gruntfile.js#L21-L30
train
veo-labs/openveo-api
lib/socket/SocketServer.js
SocketServer
function SocketServer() { Object.defineProperties(this, { /** * The Socket.io server. * * @property io * @type Server */ io: {value: null, writable: true}, /** * The list of namespaces added to the server indexed by names. * * @property namespaces * @type Object */ namespaces: {value: {}} }); }
javascript
function SocketServer() { Object.defineProperties(this, { /** * The Socket.io server. * * @property io * @type Server */ io: {value: null, writable: true}, /** * The list of namespaces added to the server indexed by names. * * @property namespaces * @type Object */ namespaces: {value: {}} }); }
[ "function", "SocketServer", "(", ")", "{", "Object", ".", "defineProperties", "(", "this", ",", "{", "io", ":", "{", "value", ":", "null", ",", "writable", ":", "true", "}", ",", "namespaces", ":", "{", "value", ":", "{", "}", "}", "}", ")", ";", "}" ]
Defines a SocketServer around a socket.io server. Creating a server using socket.io can't be done without launching the server and start listening to messages. SocketServer helps creating a socket server and add namespaces to it without starting the server. var openVeoApi = require('@openveo/api'); var namespace1 = new openVeoApi.socket.SocketNamespace(); var namespace2 = new openVeoApi.socket.SocketNamespace(); var server = new openVeoApi.socket.SocketServer(); // Listen to a message on first namespace namespace1.on('namespace1.message', function() { console.log('namespace1.message received'); }); // Listen to a message on second namespace namespace2.on('namespace2.message', function() { console.log('namespace2.message received'); }); // Add namespace1 to the server server.addNamespace('/namespace1', namespace1); // Start server server.listen(80, function() { console.log('Socket server started'); namespace.emit('namespace1.message'); // Adding a namespace after the server is started will also work server.addNamespace('/namespace2', namespace2); namespace2.emit('namespace2.message'); }); @class SocketServer @constructor
[ "Defines", "a", "SocketServer", "around", "a", "socket", ".", "io", "server", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/socket/SocketServer.js#L48-L70
train
eface2face/meteor-html-tools
html-tools.js
function (scanner, matcher) { var start = scanner.pos; var result = matcher(scanner); scanner.pos = start; return result; }
javascript
function (scanner, matcher) { var start = scanner.pos; var result = matcher(scanner); scanner.pos = start; return result; }
[ "function", "(", "scanner", ",", "matcher", ")", "{", "var", "start", "=", "scanner", ".", "pos", ";", "var", "result", "=", "matcher", "(", "scanner", ")", ";", "scanner", ".", "pos", "=", "start", ";", "return", "result", ";", "}" ]
Run a provided "matcher" function but reset the current position afterwards. Fatal failure of the matcher is not suppressed.
[ "Run", "a", "provided", "matcher", "function", "but", "reset", "the", "current", "position", "afterwards", ".", "Fatal", "failure", "of", "the", "matcher", "is", "not", "suppressed", "." ]
93360c58596e7a9b88759d495cf8894d8c2c4f2d
https://github.com/eface2face/meteor-html-tools/blob/93360c58596e7a9b88759d495cf8894d8c2c4f2d/html-tools.js#L2400-L2405
train
eface2face/meteor-html-tools
html-tools.js
function (scanner, inAttribute) { // look for `&` followed by alphanumeric if (! peekMatcher(scanner, getPossibleNamedEntityStart)) return null; var matcher = getNamedEntityByFirstChar[scanner.rest().charAt(1)]; var entity = null; if (matcher) entity = peekMatcher(scanner, matcher); if (entity) { if (entity.slice(-1) !== ';') { // Certain character references with no semi are an error, like `&lt`. // In attribute values, however, this is not fatal if the next character // is alphanumeric. // // This rule affects href attributes, for example, deeming "/?foo=bar&ltc=abc" // to be ok but "/?foo=bar&lt=abc" to not be. if (inAttribute && ALPHANUMERIC.test(scanner.rest().charAt(entity.length))) return null; scanner.fatal("Character reference requires semicolon: " + entity); } else { scanner.pos += entity.length; return entity; } } else { // we couldn't match any real entity, so see if this is a bad entity // or something we can overlook. var badEntity = peekMatcher(scanner, getApparentNamedEntity); if (badEntity) scanner.fatal("Invalid character reference: " + badEntity); // `&aaaa` is ok with no semicolon return null; } }
javascript
function (scanner, inAttribute) { // look for `&` followed by alphanumeric if (! peekMatcher(scanner, getPossibleNamedEntityStart)) return null; var matcher = getNamedEntityByFirstChar[scanner.rest().charAt(1)]; var entity = null; if (matcher) entity = peekMatcher(scanner, matcher); if (entity) { if (entity.slice(-1) !== ';') { // Certain character references with no semi are an error, like `&lt`. // In attribute values, however, this is not fatal if the next character // is alphanumeric. // // This rule affects href attributes, for example, deeming "/?foo=bar&ltc=abc" // to be ok but "/?foo=bar&lt=abc" to not be. if (inAttribute && ALPHANUMERIC.test(scanner.rest().charAt(entity.length))) return null; scanner.fatal("Character reference requires semicolon: " + entity); } else { scanner.pos += entity.length; return entity; } } else { // we couldn't match any real entity, so see if this is a bad entity // or something we can overlook. var badEntity = peekMatcher(scanner, getApparentNamedEntity); if (badEntity) scanner.fatal("Invalid character reference: " + badEntity); // `&aaaa` is ok with no semicolon return null; } }
[ "function", "(", "scanner", ",", "inAttribute", ")", "{", "if", "(", "!", "peekMatcher", "(", "scanner", ",", "getPossibleNamedEntityStart", ")", ")", "return", "null", ";", "var", "matcher", "=", "getNamedEntityByFirstChar", "[", "scanner", ".", "rest", "(", ")", ".", "charAt", "(", "1", ")", "]", ";", "var", "entity", "=", "null", ";", "if", "(", "matcher", ")", "entity", "=", "peekMatcher", "(", "scanner", ",", "matcher", ")", ";", "if", "(", "entity", ")", "{", "if", "(", "entity", ".", "slice", "(", "-", "1", ")", "!==", "';'", ")", "{", "if", "(", "inAttribute", "&&", "ALPHANUMERIC", ".", "test", "(", "scanner", ".", "rest", "(", ")", ".", "charAt", "(", "entity", ".", "length", ")", ")", ")", "return", "null", ";", "scanner", ".", "fatal", "(", "\"Character reference requires semicolon: \"", "+", "entity", ")", ";", "}", "else", "{", "scanner", ".", "pos", "+=", "entity", ".", "length", ";", "return", "entity", ";", "}", "}", "else", "{", "var", "badEntity", "=", "peekMatcher", "(", "scanner", ",", "getApparentNamedEntity", ")", ";", "if", "(", "badEntity", ")", "scanner", ".", "fatal", "(", "\"Invalid character reference: \"", "+", "badEntity", ")", ";", "return", "null", ";", "}", "}" ]
Returns a string like "&" or a falsy value if no match. Fails fatally if something looks like a named entity but isn't.
[ "Returns", "a", "string", "like", "&amp", ";", "or", "a", "falsy", "value", "if", "no", "match", ".", "Fails", "fatally", "if", "something", "looks", "like", "a", "named", "entity", "but", "isn", "t", "." ]
93360c58596e7a9b88759d495cf8894d8c2c4f2d
https://github.com/eface2face/meteor-html-tools/blob/93360c58596e7a9b88759d495cf8894d8c2c4f2d/html-tools.js#L2409-L2443
train
andrewscwei/page-manager
src/PageManager.js
ready
function ready(callback) { let onLoaded = (event) => { if (document.addEventListener) { document.removeEventListener('DOMContentLoaded', onLoaded, false); window.removeEventListener('load', onLoaded, false); } else if (document.attachEvent) { document.detachEvent('onreadystatechange', onLoaded); window.detachEvent('onload', onLoaded); } setTimeout(callback, 1); }; if (document.readyState === 'complete') return setTimeout(callback, 1); if (document.addEventListener) { document.addEventListener('DOMContentLoaded', onLoaded, false); window.addEventListener('load', onLoaded, false); } else if (document.attachEvent) { document.attachEvent('onreadystatechange', onLoaded); window.attachEvent('onload', onLoaded); } }
javascript
function ready(callback) { let onLoaded = (event) => { if (document.addEventListener) { document.removeEventListener('DOMContentLoaded', onLoaded, false); window.removeEventListener('load', onLoaded, false); } else if (document.attachEvent) { document.detachEvent('onreadystatechange', onLoaded); window.detachEvent('onload', onLoaded); } setTimeout(callback, 1); }; if (document.readyState === 'complete') return setTimeout(callback, 1); if (document.addEventListener) { document.addEventListener('DOMContentLoaded', onLoaded, false); window.addEventListener('load', onLoaded, false); } else if (document.attachEvent) { document.attachEvent('onreadystatechange', onLoaded); window.attachEvent('onload', onLoaded); } }
[ "function", "ready", "(", "callback", ")", "{", "let", "onLoaded", "=", "(", "event", ")", "=>", "{", "if", "(", "document", ".", "addEventListener", ")", "{", "document", ".", "removeEventListener", "(", "'DOMContentLoaded'", ",", "onLoaded", ",", "false", ")", ";", "window", ".", "removeEventListener", "(", "'load'", ",", "onLoaded", ",", "false", ")", ";", "}", "else", "if", "(", "document", ".", "attachEvent", ")", "{", "document", ".", "detachEvent", "(", "'onreadystatechange'", ",", "onLoaded", ")", ";", "window", ".", "detachEvent", "(", "'onload'", ",", "onLoaded", ")", ";", "}", "setTimeout", "(", "callback", ",", "1", ")", ";", "}", ";", "if", "(", "document", ".", "readyState", "===", "'complete'", ")", "return", "setTimeout", "(", "callback", ",", "1", ")", ";", "if", "(", "document", ".", "addEventListener", ")", "{", "document", ".", "addEventListener", "(", "'DOMContentLoaded'", ",", "onLoaded", ",", "false", ")", ";", "window", ".", "addEventListener", "(", "'load'", ",", "onLoaded", ",", "false", ")", ";", "}", "else", "if", "(", "document", ".", "attachEvent", ")", "{", "document", ".", "attachEvent", "(", "'onreadystatechange'", ",", "onLoaded", ")", ";", "window", ".", "attachEvent", "(", "'onload'", ",", "onLoaded", ")", ";", "}", "}" ]
Helper function for invoking a callback when the DOM is ready. @param {Function} callback @private
[ "Helper", "function", "for", "invoking", "a", "callback", "when", "the", "DOM", "is", "ready", "." ]
c356ce9734e879dc0fe7b41c14cd4d4e345b06f6
https://github.com/andrewscwei/page-manager/blob/c356ce9734e879dc0fe7b41c14cd4d4e345b06f6/src/PageManager.js#L680-L704
train
netbek/chrys-cli
src/illustrator/swatches.js
addSwatchGroup
function addSwatchGroup(name) { var swatchGroup = doc.swatchGroups.add(); swatchGroup.name = name; return swatchGroup; }
javascript
function addSwatchGroup(name) { var swatchGroup = doc.swatchGroups.add(); swatchGroup.name = name; return swatchGroup; }
[ "function", "addSwatchGroup", "(", "name", ")", "{", "var", "swatchGroup", "=", "doc", ".", "swatchGroups", ".", "add", "(", ")", ";", "swatchGroup", ".", "name", "=", "name", ";", "return", "swatchGroup", ";", "}" ]
Adds swatch group. @param {String} name @returns {SwatchGroup}
[ "Adds", "swatch", "group", "." ]
e41e1c6261e964a97a5f773fbb5deefb602bc12f
https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L89-L94
train
netbek/chrys-cli
src/illustrator/swatches.js
addSwatch
function addSwatch(name, color) { var swatch = doc.swatches.add(); swatch.color = color; swatch.name = name; return swatch; }
javascript
function addSwatch(name, color) { var swatch = doc.swatches.add(); swatch.color = color; swatch.name = name; return swatch; }
[ "function", "addSwatch", "(", "name", ",", "color", ")", "{", "var", "swatch", "=", "doc", ".", "swatches", ".", "add", "(", ")", ";", "swatch", ".", "color", "=", "color", ";", "swatch", ".", "name", "=", "name", ";", "return", "swatch", ";", "}" ]
Adds swatch. @param {String} name @param {Color} color @returns {Swatch}
[ "Adds", "swatch", "." ]
e41e1c6261e964a97a5f773fbb5deefb602bc12f
https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L103-L109
train
netbek/chrys-cli
src/illustrator/swatches.js
removeAllSwatches
function removeAllSwatches() { for (var i = 0; i < doc.swatches.length; i++) { doc.swatches[i].remove(); } }
javascript
function removeAllSwatches() { for (var i = 0; i < doc.swatches.length; i++) { doc.swatches[i].remove(); } }
[ "function", "removeAllSwatches", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "doc", ".", "swatches", ".", "length", ";", "i", "++", ")", "{", "doc", ".", "swatches", "[", "i", "]", ".", "remove", "(", ")", ";", "}", "}" ]
Removes all swatches.
[ "Removes", "all", "swatches", "." ]
e41e1c6261e964a97a5f773fbb5deefb602bc12f
https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L114-L118
train
netbek/chrys-cli
src/illustrator/swatches.js
removeAllSwatchGroups
function removeAllSwatchGroups() { for (var i = 0; i < doc.swatchGroups.length; i++) { doc.swatchGroups[i].remove(); } }
javascript
function removeAllSwatchGroups() { for (var i = 0; i < doc.swatchGroups.length; i++) { doc.swatchGroups[i].remove(); } }
[ "function", "removeAllSwatchGroups", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "doc", ".", "swatchGroups", ".", "length", ";", "i", "++", ")", "{", "doc", ".", "swatchGroups", "[", "i", "]", ".", "remove", "(", ")", ";", "}", "}" ]
Removes all swatch groups.
[ "Removes", "all", "swatch", "groups", "." ]
e41e1c6261e964a97a5f773fbb5deefb602bc12f
https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L123-L127
train
netbek/chrys-cli
src/illustrator/swatches.js
drawSwatchRect
function drawSwatchRect(top, left, width, height, name, color) { var layer = doc.layers[0]; var rect = layer.pathItems.rectangle(top, left, width, height); rect.filled = true; rect.fillColor = color; rect.stroked = false; var textBounds = layer.pathItems.rectangle(top - height * config.swatchRect.textPosition, left + width * config.swatchRect.textPosition, width * (1 - config.swatchRect.textPosition * 2), height * (1 - config.swatchRect.textPosition * 2)); var text = layer.textFrames.areaText(textBounds); text.contents = name + '\n' + colorToString(color); charStyles['swatchRectTitle'].applyTo(text.textRange); return rect; }
javascript
function drawSwatchRect(top, left, width, height, name, color) { var layer = doc.layers[0]; var rect = layer.pathItems.rectangle(top, left, width, height); rect.filled = true; rect.fillColor = color; rect.stroked = false; var textBounds = layer.pathItems.rectangle(top - height * config.swatchRect.textPosition, left + width * config.swatchRect.textPosition, width * (1 - config.swatchRect.textPosition * 2), height * (1 - config.swatchRect.textPosition * 2)); var text = layer.textFrames.areaText(textBounds); text.contents = name + '\n' + colorToString(color); charStyles['swatchRectTitle'].applyTo(text.textRange); return rect; }
[ "function", "drawSwatchRect", "(", "top", ",", "left", ",", "width", ",", "height", ",", "name", ",", "color", ")", "{", "var", "layer", "=", "doc", ".", "layers", "[", "0", "]", ";", "var", "rect", "=", "layer", ".", "pathItems", ".", "rectangle", "(", "top", ",", "left", ",", "width", ",", "height", ")", ";", "rect", ".", "filled", "=", "true", ";", "rect", ".", "fillColor", "=", "color", ";", "rect", ".", "stroked", "=", "false", ";", "var", "textBounds", "=", "layer", ".", "pathItems", ".", "rectangle", "(", "top", "-", "height", "*", "config", ".", "swatchRect", ".", "textPosition", ",", "left", "+", "width", "*", "config", ".", "swatchRect", ".", "textPosition", ",", "width", "*", "(", "1", "-", "config", ".", "swatchRect", ".", "textPosition", "*", "2", ")", ",", "height", "*", "(", "1", "-", "config", ".", "swatchRect", ".", "textPosition", "*", "2", ")", ")", ";", "var", "text", "=", "layer", ".", "textFrames", ".", "areaText", "(", "textBounds", ")", ";", "text", ".", "contents", "=", "name", "+", "'\\n'", "+", "\\n", ";", "colorToString", "(", "color", ")", "charStyles", "[", "'swatchRectTitle'", "]", ".", "applyTo", "(", "text", ".", "textRange", ")", ";", "}" ]
Draws rectangle on artboard. @param {Number} top @param {Number} left @param {Number} width @param {Number} height @param {String} name @param {Color} color @returns {PathItem}
[ "Draws", "rectangle", "on", "artboard", "." ]
e41e1c6261e964a97a5f773fbb5deefb602bc12f
https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L140-L155
train
netbek/chrys-cli
src/illustrator/swatches.js
getColorGroups
function getColorGroups(colors) { var colorGroups = []; colors.forEach(function (color) { if (colorGroups.indexOf(color.group) < 0) { colorGroups.push(color.group); } }); return colorGroups; }
javascript
function getColorGroups(colors) { var colorGroups = []; colors.forEach(function (color) { if (colorGroups.indexOf(color.group) < 0) { colorGroups.push(color.group); } }); return colorGroups; }
[ "function", "getColorGroups", "(", "colors", ")", "{", "var", "colorGroups", "=", "[", "]", ";", "colors", ".", "forEach", "(", "function", "(", "color", ")", "{", "if", "(", "colorGroups", ".", "indexOf", "(", "color", ".", "group", ")", "<", "0", ")", "{", "colorGroups", ".", "push", "(", "color", ".", "group", ")", ";", "}", "}", ")", ";", "return", "colorGroups", ";", "}" ]
Returns an array of unique group names. @param {Array} colors @returns {Array)
[ "Returns", "an", "array", "of", "unique", "group", "names", "." ]
e41e1c6261e964a97a5f773fbb5deefb602bc12f
https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L163-L173
train
netbek/chrys-cli
src/illustrator/swatches.js
getMaxShades
function getMaxShades(colors) { var max = 0; var colorGroups = getColorGroups(colors); colorGroups.forEach(function (colorGroup, colorGroupIndex) { // Gets colors that belong to group. var groupColors = colors.filter(function (o) { return o.group === colorGroup; }); var len = groupColors.length; if (len > max) { max = len; } }); return max; }
javascript
function getMaxShades(colors) { var max = 0; var colorGroups = getColorGroups(colors); colorGroups.forEach(function (colorGroup, colorGroupIndex) { // Gets colors that belong to group. var groupColors = colors.filter(function (o) { return o.group === colorGroup; }); var len = groupColors.length; if (len > max) { max = len; } }); return max; }
[ "function", "getMaxShades", "(", "colors", ")", "{", "var", "max", "=", "0", ";", "var", "colorGroups", "=", "getColorGroups", "(", "colors", ")", ";", "colorGroups", ".", "forEach", "(", "function", "(", "colorGroup", ",", "colorGroupIndex", ")", "{", "var", "groupColors", "=", "colors", ".", "filter", "(", "function", "(", "o", ")", "{", "return", "o", ".", "group", "===", "colorGroup", ";", "}", ")", ";", "var", "len", "=", "groupColors", ".", "length", ";", "if", "(", "len", ">", "max", ")", "{", "max", "=", "len", ";", "}", "}", ")", ";", "return", "max", ";", "}" ]
Returns maximum number of shades. @param {Array} colors @returns {Number}
[ "Returns", "maximum", "number", "of", "shades", "." ]
e41e1c6261e964a97a5f773fbb5deefb602bc12f
https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L181-L199
train
Mammut-FE/nejm
src/base/platform/element.js
function(_tpl,_map){ _map = _map||_o; return _tpl.replace(_reg1,function($1,$2){ var _arr = $2.split('|'); return _map[_arr[0]]||_arr[1]||'0'; }); }
javascript
function(_tpl,_map){ _map = _map||_o; return _tpl.replace(_reg1,function($1,$2){ var _arr = $2.split('|'); return _map[_arr[0]]||_arr[1]||'0'; }); }
[ "function", "(", "_tpl", ",", "_map", ")", "{", "_map", "=", "_map", "||", "_o", ";", "return", "_tpl", ".", "replace", "(", "_reg1", ",", "function", "(", "$1", ",", "$2", ")", "{", "var", "_arr", "=", "$2", ".", "split", "(", "'|'", ")", ";", "return", "_map", "[", "_arr", "[", "0", "]", "]", "||", "_arr", "[", "1", "]", "||", "'0'", ";", "}", ")", ";", "}" ]
merge template and data
[ "merge", "template", "and", "data" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/base/platform/element.js#L280-L286
train
donejs/ir-reattach
src/render.js
read
async function read(reader, patcher) { let {done, value} = await reader.read(); if(done || isAttached()) { return false; } //!steal-remove-start log.mutations(value); //!steal-remove-end patcher.patch(value); return true; }
javascript
async function read(reader, patcher) { let {done, value} = await reader.read(); if(done || isAttached()) { return false; } //!steal-remove-start log.mutations(value); //!steal-remove-end patcher.patch(value); return true; }
[ "async", "function", "read", "(", "reader", ",", "patcher", ")", "{", "let", "{", "done", ",", "value", "}", "=", "await", "reader", ".", "read", "(", ")", ";", "if", "(", "done", "||", "isAttached", "(", ")", ")", "{", "return", "false", ";", "}", "log", ".", "mutations", "(", "value", ")", ";", "patcher", ".", "patch", "(", "value", ")", ";", "return", "true", ";", "}" ]
!steal-remove-end Read a value from the stream and pass it to the patcher
[ "!steal", "-", "remove", "-", "end", "Read", "a", "value", "from", "the", "stream", "and", "pass", "it", "to", "the", "patcher" ]
0440d4ed090982103d90347aa0b960f35a7e0628
https://github.com/donejs/ir-reattach/blob/0440d4ed090982103d90347aa0b960f35a7e0628/src/render.js#L10-L23
train
LeisureLink/magicbus
lib/amqp/exchange.js
getLibOptions
function getLibOptions(aliases, itemsToOmit) { let aliased = _.transform(options, function(result, value, key) { let alias = aliases[key]; result[alias || key] = value; }); return _.omit(aliased, itemsToOmit); }
javascript
function getLibOptions(aliases, itemsToOmit) { let aliased = _.transform(options, function(result, value, key) { let alias = aliases[key]; result[alias || key] = value; }); return _.omit(aliased, itemsToOmit); }
[ "function", "getLibOptions", "(", "aliases", ",", "itemsToOmit", ")", "{", "let", "aliased", "=", "_", ".", "transform", "(", "options", ",", "function", "(", "result", ",", "value", ",", "key", ")", "{", "let", "alias", "=", "aliases", "[", "key", "]", ";", "result", "[", "alias", "||", "key", "]", "=", "value", ";", "}", ")", ";", "return", "_", ".", "omit", "(", "aliased", ",", "itemsToOmit", ")", ";", "}" ]
Get options for amqp assertExchange call @private
[ "Get", "options", "for", "amqp", "assertExchange", "call" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/exchange.js#L44-L50
train
LeisureLink/magicbus
lib/amqp/exchange.js
define
function define() { let libOptions = getLibOptions({ alternate: 'alternateExchange' }, ['persistent', 'publishTimeout']); topLog.debug(`Declaring ${options.type} exchange \'${options.name}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(libOptions, ['name', 'type']))}`); return channel.assertExchange(options.name, options.type, libOptions); }
javascript
function define() { let libOptions = getLibOptions({ alternate: 'alternateExchange' }, ['persistent', 'publishTimeout']); topLog.debug(`Declaring ${options.type} exchange \'${options.name}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(libOptions, ['name', 'type']))}`); return channel.assertExchange(options.name, options.type, libOptions); }
[ "function", "define", "(", ")", "{", "let", "libOptions", "=", "getLibOptions", "(", "{", "alternate", ":", "'alternateExchange'", "}", ",", "[", "'persistent'", ",", "'publishTimeout'", "]", ")", ";", "topLog", ".", "debug", "(", "`", "${", "options", ".", "type", "}", "\\'", "${", "options", ".", "name", "}", "\\'", "\\'", "${", "connectionName", "}", "\\'", "${", "JSON", ".", "stringify", "(", "_", ".", "omit", "(", "libOptions", ",", "[", "'name'", ",", "'type'", "]", ")", ")", "}", "`", ")", ";", "return", "channel", ".", "assertExchange", "(", "options", ".", "name", ",", "options", ".", "type", ",", "libOptions", ")", ";", "}" ]
Define the exchange @public
[ "Define", "the", "exchange" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/exchange.js#L56-L62
train
chip-js/observations-js
src/computed-properties/when.js
WhenProperty
function WhenProperty(whenExpression, thenExpression) { if (!thenExpression) { thenExpression = whenExpression; whenExpression = 'true'; } this.whenExpression = whenExpression; this.thenExpression = thenExpression; }
javascript
function WhenProperty(whenExpression, thenExpression) { if (!thenExpression) { thenExpression = whenExpression; whenExpression = 'true'; } this.whenExpression = whenExpression; this.thenExpression = thenExpression; }
[ "function", "WhenProperty", "(", "whenExpression", ",", "thenExpression", ")", "{", "if", "(", "!", "thenExpression", ")", "{", "thenExpression", "=", "whenExpression", ";", "whenExpression", "=", "'true'", ";", "}", "this", ".", "whenExpression", "=", "whenExpression", ";", "this", ".", "thenExpression", "=", "thenExpression", ";", "}" ]
Calls the `thenExpression` and assigns the results to the object's property when the `whenExpression` changes value to anything other than a falsey value such as undefined. The return value of the `thenExpression` may be a Promise. @param {String} whenExpression The conditional expression use to determine when to call the `thenExpression` @param {String} thenExpression The expression which will be executed when the `when` value changes and the result (or the result of the returned promise) is set on the object.
[ "Calls", "the", "thenExpression", "and", "assigns", "the", "results", "to", "the", "object", "s", "property", "when", "the", "whenExpression", "changes", "value", "to", "anything", "other", "than", "a", "falsey", "value", "such", "as", "undefined", ".", "The", "return", "value", "of", "the", "thenExpression", "may", "be", "a", "Promise", "." ]
a48b32a648089bc86b502712d78cd0b3f8317d50
https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/computed-properties/when.js#L12-L20
train
feedhenry/fh-component-metrics
lib/clients/statsd.js
StatsdClient
function StatsdClient(opts) { BaseClient.apply(this, arguments); opts = opts || {}; this.host = opts.host || '127.0.0.1'; this.port = opts.port || 8125; this.keyBuilder = opts.keyBuilder || defaultMetricsKeyBuilder; this.socket = dgram.createSocket('udp4'); }
javascript
function StatsdClient(opts) { BaseClient.apply(this, arguments); opts = opts || {}; this.host = opts.host || '127.0.0.1'; this.port = opts.port || 8125; this.keyBuilder = opts.keyBuilder || defaultMetricsKeyBuilder; this.socket = dgram.createSocket('udp4'); }
[ "function", "StatsdClient", "(", "opts", ")", "{", "BaseClient", ".", "apply", "(", "this", ",", "arguments", ")", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "host", "=", "opts", ".", "host", "||", "'127.0.0.1'", ";", "this", ".", "port", "=", "opts", ".", "port", "||", "8125", ";", "this", ".", "keyBuilder", "=", "opts", ".", "keyBuilder", "||", "defaultMetricsKeyBuilder", ";", "this", ".", "socket", "=", "dgram", ".", "createSocket", "(", "'udp4'", ")", ";", "}" ]
A client that can send metrics data to a statsd backend @param {Object} opts options about the statsd backend @param {String} opts.host the host of the statsd server. Default is 127.0.0.1. @param {Number} opts.port the port of the statsd server. Default is 8125. @param {Function} opts.keyBuilder a function that will be used to format the meta data of a metric into a single key value. The signature of function is like this: function(key, tags, fieldName)
[ "A", "client", "that", "can", "send", "metrics", "data", "to", "a", "statsd", "backend" ]
c97a1a82ff0144f2a7c2abecbc22084fade1cbc8
https://github.com/feedhenry/fh-component-metrics/blob/c97a1a82ff0144f2a7c2abecbc22084fade1cbc8/lib/clients/statsd.js#L51-L58
train
cronvel/server-kit
lib/mimeType.js
mimeType
function mimeType( path ) { var extension = path.replace( /.*[./\\]/ , '' ).toLowerCase() ; if ( ! mimeType.extension[ extension ] ) { // default MIME type, when nothing is found return 'application/octet-stream' ; } return mimeType.extension[ extension ] ; }
javascript
function mimeType( path ) { var extension = path.replace( /.*[./\\]/ , '' ).toLowerCase() ; if ( ! mimeType.extension[ extension ] ) { // default MIME type, when nothing is found return 'application/octet-stream' ; } return mimeType.extension[ extension ] ; }
[ "function", "mimeType", "(", "path", ")", "{", "var", "extension", "=", "path", ".", "replace", "(", "/", ".*[./\\\\]", "/", ",", "''", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "mimeType", ".", "extension", "[", "extension", "]", ")", "{", "return", "'application/octet-stream'", ";", "}", "return", "mimeType", ".", "extension", "[", "extension", "]", ";", "}" ]
MIME types by extension, for most common files
[ "MIME", "types", "by", "extension", "for", "most", "common", "files" ]
8d2a45aeddf7933559331f75e6b6199a12912d7f
https://github.com/cronvel/server-kit/blob/8d2a45aeddf7933559331f75e6b6199a12912d7f/lib/mimeType.js#L33-L42
train
emeryrose/coalescent
lib/application.js
Application
function Application(options) { var self = this; if (!(self instanceof Application)) { return new Application(options); } stream.Duplex.call(self, { objectMode: true }); self.id = hat(); self.server = net.createServer(self._handleInbound.bind(self)); self.options = merge(Object.create(Application.DEFAULTS), options); self.connections = { inbound: [], outbound: [] }; // setup middlware stack with initial entry a simple passthrough self.stack = [function(socket) { return through(function(data) { this.queue(data); }); }]; Object.defineProperty(self, 'log', { value: this.options.logger || { info: NOOP, warn: NOOP, error: NOOP } }); // connect to seeds self._enterNetwork(); setInterval(self._enterNetwork.bind(self), self.options.retryInterval); }
javascript
function Application(options) { var self = this; if (!(self instanceof Application)) { return new Application(options); } stream.Duplex.call(self, { objectMode: true }); self.id = hat(); self.server = net.createServer(self._handleInbound.bind(self)); self.options = merge(Object.create(Application.DEFAULTS), options); self.connections = { inbound: [], outbound: [] }; // setup middlware stack with initial entry a simple passthrough self.stack = [function(socket) { return through(function(data) { this.queue(data); }); }]; Object.defineProperty(self, 'log', { value: this.options.logger || { info: NOOP, warn: NOOP, error: NOOP } }); // connect to seeds self._enterNetwork(); setInterval(self._enterNetwork.bind(self), self.options.retryInterval); }
[ "function", "Application", "(", "options", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "(", "self", "instanceof", "Application", ")", ")", "{", "return", "new", "Application", "(", "options", ")", ";", "}", "stream", ".", "Duplex", ".", "call", "(", "self", ",", "{", "objectMode", ":", "true", "}", ")", ";", "self", ".", "id", "=", "hat", "(", ")", ";", "self", ".", "server", "=", "net", ".", "createServer", "(", "self", ".", "_handleInbound", ".", "bind", "(", "self", ")", ")", ";", "self", ".", "options", "=", "merge", "(", "Object", ".", "create", "(", "Application", ".", "DEFAULTS", ")", ",", "options", ")", ";", "self", ".", "connections", "=", "{", "inbound", ":", "[", "]", ",", "outbound", ":", "[", "]", "}", ";", "self", ".", "stack", "=", "[", "function", "(", "socket", ")", "{", "return", "through", "(", "function", "(", "data", ")", "{", "this", ".", "queue", "(", "data", ")", ";", "}", ")", ";", "}", "]", ";", "Object", ".", "defineProperty", "(", "self", ",", "'log'", ",", "{", "value", ":", "this", ".", "options", ".", "logger", "||", "{", "info", ":", "NOOP", ",", "warn", ":", "NOOP", ",", "error", ":", "NOOP", "}", "}", ")", ";", "self", ".", "_enterNetwork", "(", ")", ";", "setInterval", "(", "self", ".", "_enterNetwork", ".", "bind", "(", "self", ")", ",", "self", ".", "options", ".", "retryInterval", ")", ";", "}" ]
P2P application framework @constructor @param {object} options
[ "P2P", "application", "framework" ]
5e722d4e1c16b9a9e959b281f6bb07713c60c46a
https://github.com/emeryrose/coalescent/blob/5e722d4e1c16b9a9e959b281f6bb07713c60c46a/lib/application.js#L32-L62
train
repetere/periodicjs.core.mailer
lib/sendEmail.js
sendEmail
function sendEmail(options = {}) { return new Promise((resolve, reject) => { try { const mailoptions = options; let mailTransportConfig = (this && this.config && this.config.transportConfig) ? this.config.transportConfig : options.transportConfig; let mailtransport = (this && this.transport) ? this.transport : options.transport; Promise.resolve(mailoptions) .then(mailoptions => { if (mailoptions.html || mailoptions.emailtemplatestring) { return mailoptions.html || mailoptions.emailtemplatestring; } else { return getEmailTemplateHTMLString(mailoptions); } }) .then(emailTemplateString => { mailoptions.emailtemplatestring = emailTemplateString; if (mailoptions.html) { return mailoptions.html; } else { if (mailoptions.emailtemplatefilepath && !mailoptions.emailtemplatedata.filename) { mailoptions.emailtemplatedata.filename = mailoptions.emailtemplatefilepath; } mailoptions.html = ejs.render(mailoptions.emailtemplatestring, mailoptions.emailtemplatedata); return mailoptions.html; } }) .then(mailhtml => { if (mailtransport && mailtransport.sendMail) { return mailtransport; } else { return getTransport({ transportObject: mailTransportConfig }) .then(transport => { mailtransport = transport; return Promise.resolve(transport); }) .catch(reject); } }) .then(mt => { mt.sendMail(mailoptions, (err, status) => { if (err) { reject(err); } else { resolve(status); } }); }) .catch(reject); } catch (e) { reject(e); } }); }
javascript
function sendEmail(options = {}) { return new Promise((resolve, reject) => { try { const mailoptions = options; let mailTransportConfig = (this && this.config && this.config.transportConfig) ? this.config.transportConfig : options.transportConfig; let mailtransport = (this && this.transport) ? this.transport : options.transport; Promise.resolve(mailoptions) .then(mailoptions => { if (mailoptions.html || mailoptions.emailtemplatestring) { return mailoptions.html || mailoptions.emailtemplatestring; } else { return getEmailTemplateHTMLString(mailoptions); } }) .then(emailTemplateString => { mailoptions.emailtemplatestring = emailTemplateString; if (mailoptions.html) { return mailoptions.html; } else { if (mailoptions.emailtemplatefilepath && !mailoptions.emailtemplatedata.filename) { mailoptions.emailtemplatedata.filename = mailoptions.emailtemplatefilepath; } mailoptions.html = ejs.render(mailoptions.emailtemplatestring, mailoptions.emailtemplatedata); return mailoptions.html; } }) .then(mailhtml => { if (mailtransport && mailtransport.sendMail) { return mailtransport; } else { return getTransport({ transportObject: mailTransportConfig }) .then(transport => { mailtransport = transport; return Promise.resolve(transport); }) .catch(reject); } }) .then(mt => { mt.sendMail(mailoptions, (err, status) => { if (err) { reject(err); } else { resolve(status); } }); }) .catch(reject); } catch (e) { reject(e); } }); }
[ "function", "sendEmail", "(", "options", "=", "{", "}", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "const", "mailoptions", "=", "options", ";", "let", "mailTransportConfig", "=", "(", "this", "&&", "this", ".", "config", "&&", "this", ".", "config", ".", "transportConfig", ")", "?", "this", ".", "config", ".", "transportConfig", ":", "options", ".", "transportConfig", ";", "let", "mailtransport", "=", "(", "this", "&&", "this", ".", "transport", ")", "?", "this", ".", "transport", ":", "options", ".", "transport", ";", "Promise", ".", "resolve", "(", "mailoptions", ")", ".", "then", "(", "mailoptions", "=>", "{", "if", "(", "mailoptions", ".", "html", "||", "mailoptions", ".", "emailtemplatestring", ")", "{", "return", "mailoptions", ".", "html", "||", "mailoptions", ".", "emailtemplatestring", ";", "}", "else", "{", "return", "getEmailTemplateHTMLString", "(", "mailoptions", ")", ";", "}", "}", ")", ".", "then", "(", "emailTemplateString", "=>", "{", "mailoptions", ".", "emailtemplatestring", "=", "emailTemplateString", ";", "if", "(", "mailoptions", ".", "html", ")", "{", "return", "mailoptions", ".", "html", ";", "}", "else", "{", "if", "(", "mailoptions", ".", "emailtemplatefilepath", "&&", "!", "mailoptions", ".", "emailtemplatedata", ".", "filename", ")", "{", "mailoptions", ".", "emailtemplatedata", ".", "filename", "=", "mailoptions", ".", "emailtemplatefilepath", ";", "}", "mailoptions", ".", "html", "=", "ejs", ".", "render", "(", "mailoptions", ".", "emailtemplatestring", ",", "mailoptions", ".", "emailtemplatedata", ")", ";", "return", "mailoptions", ".", "html", ";", "}", "}", ")", ".", "then", "(", "mailhtml", "=>", "{", "if", "(", "mailtransport", "&&", "mailtransport", ".", "sendMail", ")", "{", "return", "mailtransport", ";", "}", "else", "{", "return", "getTransport", "(", "{", "transportObject", ":", "mailTransportConfig", "}", ")", ".", "then", "(", "transport", "=>", "{", "mailtransport", "=", "transport", ";", "return", "Promise", ".", "resolve", "(", "transport", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", "}", ")", ".", "then", "(", "mt", "=>", "{", "mt", ".", "sendMail", "(", "mailoptions", ",", "(", "err", ",", "status", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "status", ")", ";", "}", "}", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", "catch", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", "}", ")", ";", "}" ]
sends email with nodemailer @static @param {any} [options={}] all of the options to a node mailer transport sendMail function @param {object|string} options.to @param {object|string} options.cc @param {object|string} options.bcc @param {object|string} options.replyto @param {object|string} options.subject @param {object|string} options.html @param {object|string} options.text @param {object|string} options.generateTextFromHTML @param {object|string} options.emailtemplatestring @param {object|string} options.emailtemplatedata @returns {promise} resolves the status of an email @memberof Mailer
[ "sends", "email", "with", "nodemailer" ]
f544584cb1520015adac0326f8b02c38fbbd3417
https://github.com/repetere/periodicjs.core.mailer/blob/f544584cb1520015adac0326f8b02c38fbbd3417/lib/sendEmail.js#L25-L81
train
nanlabs/econsole
sample.js
writeLogs
function writeLogs(customMethods) { // Error level logging with a message but no error console.error('Testing ERROR LEVEL without actual error') // Error level logging with an error but no message // This shows enhanced error parsing in logging console.error(new Error("some error")); // Error level logging with both message and error // This shows enhanced error parsing in logging console.error('Testing ERROR LEVEL with an error', new Error("some error")); // Warn level logging console.warn('Testing WARN LEVEL'); // Info level logging console.info('Testing INFO LEVEL'); // Log/Debug level logging console.log('Testing LOG LEVEL'); if(customMethods) { // Log/Debug level loggin using "debug" alias (not standard but clearer) console.debug('Testing DEBUG (AKA LOG) LEVEL'); // Verbose level logging (new level added to go beyond DEBUG) console.verbose('Testing TRACE LEVEL'); } }
javascript
function writeLogs(customMethods) { // Error level logging with a message but no error console.error('Testing ERROR LEVEL without actual error') // Error level logging with an error but no message // This shows enhanced error parsing in logging console.error(new Error("some error")); // Error level logging with both message and error // This shows enhanced error parsing in logging console.error('Testing ERROR LEVEL with an error', new Error("some error")); // Warn level logging console.warn('Testing WARN LEVEL'); // Info level logging console.info('Testing INFO LEVEL'); // Log/Debug level logging console.log('Testing LOG LEVEL'); if(customMethods) { // Log/Debug level loggin using "debug" alias (not standard but clearer) console.debug('Testing DEBUG (AKA LOG) LEVEL'); // Verbose level logging (new level added to go beyond DEBUG) console.verbose('Testing TRACE LEVEL'); } }
[ "function", "writeLogs", "(", "customMethods", ")", "{", "console", ".", "error", "(", "'Testing ERROR LEVEL without actual error'", ")", "console", ".", "error", "(", "new", "Error", "(", "\"some error\"", ")", ")", ";", "console", ".", "error", "(", "'Testing ERROR LEVEL with an error'", ",", "new", "Error", "(", "\"some error\"", ")", ")", ";", "console", ".", "warn", "(", "'Testing WARN LEVEL'", ")", ";", "console", ".", "info", "(", "'Testing INFO LEVEL'", ")", ";", "console", ".", "log", "(", "'Testing LOG LEVEL'", ")", ";", "if", "(", "customMethods", ")", "{", "console", ".", "debug", "(", "'Testing DEBUG (AKA LOG) LEVEL'", ")", ";", "console", ".", "verbose", "(", "'Testing TRACE LEVEL'", ")", ";", "}", "}" ]
Writes logs for the different levels @param customMethods if false, only standard node's console methods will be called. if true, besides standard methods, also the 2 new added methods are called
[ "Writes", "logs", "for", "the", "different", "levels" ]
2377a33e266b4e39a35cf981ece14b6b6a16af46
https://github.com/nanlabs/econsole/blob/2377a33e266b4e39a35cf981ece14b6b6a16af46/sample.js#L28-L57
train
hoast/hoast-changed
library/index.js
function(hoast, filePath, content) { return new Promise(function(resolve, reject) { hoast.helpers.createDirectory(path.dirname(filePath)) .then(function() { fs.writeFile(filePath, JSON.stringify(content), `utf8`, function(error) { if (error) { return reject(error); } resolve(); }); }) .catch(function(error) { reject(error); }); }); }
javascript
function(hoast, filePath, content) { return new Promise(function(resolve, reject) { hoast.helpers.createDirectory(path.dirname(filePath)) .then(function() { fs.writeFile(filePath, JSON.stringify(content), `utf8`, function(error) { if (error) { return reject(error); } resolve(); }); }) .catch(function(error) { reject(error); }); }); }
[ "function", "(", "hoast", ",", "filePath", ",", "content", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "hoast", ".", "helpers", ".", "createDirectory", "(", "path", ".", "dirname", "(", "filePath", ")", ")", ".", "then", "(", "function", "(", ")", "{", "fs", ".", "writeFile", "(", "filePath", ",", "JSON", ".", "stringify", "(", "content", ")", ",", "`", "`", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "return", "reject", "(", "error", ")", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Writes JS object to storage. @param {Object} hoast hoast instance. @param {String} filePath File path. @param {Object} content Object to write to storage.
[ "Writes", "JS", "object", "to", "storage", "." ]
51f6e699fd023720d724fd5139efc4a08a6af1fd
https://github.com/hoast/hoast-changed/blob/51f6e699fd023720d724fd5139efc4a08a6af1fd/library/index.js#L28-L43
train
hoast/hoast-changed
library/index.js
function(hoast, files) { debug(`Running module.`); // Loop through the files. const filtered = files.filter(function(file) { debug(`Filtering file '${file.path}'.`); // If it does not match if (this.expressions && hoast.helpers.matchExpressions(file.path, this.expressions, options.patternOptions.all)) { debug(`File path valid for skipping.`); return true; } // If it is in the list and not changed since the last time do not process. if (this.list[file.path] && this.list[file.path] >= file.stats.mtimeMs) { debug(`File not changed since last process.`); return false; } debug(`File changed or not processed before.`); // Update changed time and process. this.list[file.path] = file.stats.mtimeMs; return true; }, mod); debug(`Finished filtering files.`); // Return filtered files. return filtered; }
javascript
function(hoast, files) { debug(`Running module.`); // Loop through the files. const filtered = files.filter(function(file) { debug(`Filtering file '${file.path}'.`); // If it does not match if (this.expressions && hoast.helpers.matchExpressions(file.path, this.expressions, options.patternOptions.all)) { debug(`File path valid for skipping.`); return true; } // If it is in the list and not changed since the last time do not process. if (this.list[file.path] && this.list[file.path] >= file.stats.mtimeMs) { debug(`File not changed since last process.`); return false; } debug(`File changed or not processed before.`); // Update changed time and process. this.list[file.path] = file.stats.mtimeMs; return true; }, mod); debug(`Finished filtering files.`); // Return filtered files. return filtered; }
[ "function", "(", "hoast", ",", "files", ")", "{", "debug", "(", "`", "`", ")", ";", "const", "filtered", "=", "files", ".", "filter", "(", "function", "(", "file", ")", "{", "debug", "(", "`", "${", "file", ".", "path", "}", "`", ")", ";", "if", "(", "this", ".", "expressions", "&&", "hoast", ".", "helpers", ".", "matchExpressions", "(", "file", ".", "path", ",", "this", ".", "expressions", ",", "options", ".", "patternOptions", ".", "all", ")", ")", "{", "debug", "(", "`", "`", ")", ";", "return", "true", ";", "}", "if", "(", "this", ".", "list", "[", "file", ".", "path", "]", "&&", "this", ".", "list", "[", "file", ".", "path", "]", ">=", "file", ".", "stats", ".", "mtimeMs", ")", "{", "debug", "(", "`", "`", ")", ";", "return", "false", ";", "}", "debug", "(", "`", "`", ")", ";", "this", ".", "list", "[", "file", ".", "path", "]", "=", "file", ".", "stats", ".", "mtimeMs", ";", "return", "true", ";", "}", ",", "mod", ")", ";", "debug", "(", "`", "`", ")", ";", "return", "filtered", ";", "}" ]
Main module method.
[ "Main", "module", "method", "." ]
51f6e699fd023720d724fd5139efc4a08a6af1fd
https://github.com/hoast/hoast-changed/blob/51f6e699fd023720d724fd5139efc4a08a6af1fd/library/index.js#L58-L86
train
cronvel/logfella-common-transport
lib/Common.transport.js
CommonTransport
function CommonTransport( logger , config = {} ) { this.logger = null ; this.monitoring = false ; this.minLevel = 0 ; this.maxLevel = 7 ; this.messageFormatter = logger.messageFormatter.text ; this.timeFormatter = logger.timeFormatter.dateTime ; Object.defineProperty( this , 'logger' , { value: logger } ) ; if ( config.monitoring !== undefined ) { this.monitoring = !! config.monitoring ; } if ( config.minLevel !== undefined ) { if ( typeof config.minLevel === 'number' ) { this.minLevel = config.minLevel ; } else if ( typeof config.minLevel === 'string' ) { this.minLevel = this.logger.levelHash[ config.minLevel ] ; } } if ( config.maxLevel !== undefined ) { if ( typeof config.maxLevel === 'number' ) { this.maxLevel = config.maxLevel ; } else if ( typeof config.maxLevel === 'string' ) { this.maxLevel = this.logger.levelHash[ config.maxLevel ] ; } } if ( config.messageFormatter ) { if ( typeof config.messageFormatter === 'function' ) { this.messageFormatter = config.messageFormatter ; } else { this.messageFormatter = this.logger.messageFormatter[ config.messageFormatter ] ; } } if ( config.timeFormatter ) { if ( typeof config.timeFormatter === 'function' ) { this.timeFormatter = config.timeFormatter ; } else { this.timeFormatter = this.logger.timeFormatter[ config.timeFormatter ] ; } } }
javascript
function CommonTransport( logger , config = {} ) { this.logger = null ; this.monitoring = false ; this.minLevel = 0 ; this.maxLevel = 7 ; this.messageFormatter = logger.messageFormatter.text ; this.timeFormatter = logger.timeFormatter.dateTime ; Object.defineProperty( this , 'logger' , { value: logger } ) ; if ( config.monitoring !== undefined ) { this.monitoring = !! config.monitoring ; } if ( config.minLevel !== undefined ) { if ( typeof config.minLevel === 'number' ) { this.minLevel = config.minLevel ; } else if ( typeof config.minLevel === 'string' ) { this.minLevel = this.logger.levelHash[ config.minLevel ] ; } } if ( config.maxLevel !== undefined ) { if ( typeof config.maxLevel === 'number' ) { this.maxLevel = config.maxLevel ; } else if ( typeof config.maxLevel === 'string' ) { this.maxLevel = this.logger.levelHash[ config.maxLevel ] ; } } if ( config.messageFormatter ) { if ( typeof config.messageFormatter === 'function' ) { this.messageFormatter = config.messageFormatter ; } else { this.messageFormatter = this.logger.messageFormatter[ config.messageFormatter ] ; } } if ( config.timeFormatter ) { if ( typeof config.timeFormatter === 'function' ) { this.timeFormatter = config.timeFormatter ; } else { this.timeFormatter = this.logger.timeFormatter[ config.timeFormatter ] ; } } }
[ "function", "CommonTransport", "(", "logger", ",", "config", "=", "{", "}", ")", "{", "this", ".", "logger", "=", "null", ";", "this", ".", "monitoring", "=", "false", ";", "this", ".", "minLevel", "=", "0", ";", "this", ".", "maxLevel", "=", "7", ";", "this", ".", "messageFormatter", "=", "logger", ".", "messageFormatter", ".", "text", ";", "this", ".", "timeFormatter", "=", "logger", ".", "timeFormatter", ".", "dateTime", ";", "Object", ".", "defineProperty", "(", "this", ",", "'logger'", ",", "{", "value", ":", "logger", "}", ")", ";", "if", "(", "config", ".", "monitoring", "!==", "undefined", ")", "{", "this", ".", "monitoring", "=", "!", "!", "config", ".", "monitoring", ";", "}", "if", "(", "config", ".", "minLevel", "!==", "undefined", ")", "{", "if", "(", "typeof", "config", ".", "minLevel", "===", "'number'", ")", "{", "this", ".", "minLevel", "=", "config", ".", "minLevel", ";", "}", "else", "if", "(", "typeof", "config", ".", "minLevel", "===", "'string'", ")", "{", "this", ".", "minLevel", "=", "this", ".", "logger", ".", "levelHash", "[", "config", ".", "minLevel", "]", ";", "}", "}", "if", "(", "config", ".", "maxLevel", "!==", "undefined", ")", "{", "if", "(", "typeof", "config", ".", "maxLevel", "===", "'number'", ")", "{", "this", ".", "maxLevel", "=", "config", ".", "maxLevel", ";", "}", "else", "if", "(", "typeof", "config", ".", "maxLevel", "===", "'string'", ")", "{", "this", ".", "maxLevel", "=", "this", ".", "logger", ".", "levelHash", "[", "config", ".", "maxLevel", "]", ";", "}", "}", "if", "(", "config", ".", "messageFormatter", ")", "{", "if", "(", "typeof", "config", ".", "messageFormatter", "===", "'function'", ")", "{", "this", ".", "messageFormatter", "=", "config", ".", "messageFormatter", ";", "}", "else", "{", "this", ".", "messageFormatter", "=", "this", ".", "logger", ".", "messageFormatter", "[", "config", ".", "messageFormatter", "]", ";", "}", "}", "if", "(", "config", ".", "timeFormatter", ")", "{", "if", "(", "typeof", "config", ".", "timeFormatter", "===", "'function'", ")", "{", "this", ".", "timeFormatter", "=", "config", ".", "timeFormatter", ";", "}", "else", "{", "this", ".", "timeFormatter", "=", "this", ".", "logger", ".", "timeFormatter", "[", "config", ".", "timeFormatter", "]", ";", "}", "}", "}" ]
Empty constructor, it is just there to support instanceof operator
[ "Empty", "constructor", "it", "is", "just", "there", "to", "support", "instanceof", "operator" ]
194bba790fa864591394c8a1566bb0dff1670c33
https://github.com/cronvel/logfella-common-transport/blob/194bba790fa864591394c8a1566bb0dff1670c33/lib/Common.transport.js#L32-L63
train
hairyhenderson/node-fellowshipone
lib/household_communications.js
HouseholdCommunications
function HouseholdCommunications (f1, householdID) { if (!householdID) { throw new Error('HouseholdCommunications requires a household ID!') } Communications.call(this, f1, { path: '/Households/' + householdID + '/Communications' }) }
javascript
function HouseholdCommunications (f1, householdID) { if (!householdID) { throw new Error('HouseholdCommunications requires a household ID!') } Communications.call(this, f1, { path: '/Households/' + householdID + '/Communications' }) }
[ "function", "HouseholdCommunications", "(", "f1", ",", "householdID", ")", "{", "if", "(", "!", "householdID", ")", "{", "throw", "new", "Error", "(", "'HouseholdCommunications requires a household ID!'", ")", "}", "Communications", ".", "call", "(", "this", ",", "f1", ",", "{", "path", ":", "'/Households/'", "+", "householdID", "+", "'/Communications'", "}", ")", "}" ]
The Communications object, in a Household context. @param {Object} f1 - the F1 object @param {Number} householdID - the Household ID, for context
[ "The", "Communications", "object", "in", "a", "Household", "context", "." ]
5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b
https://github.com/hairyhenderson/node-fellowshipone/blob/5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b/lib/household_communications.js#L10-L17
train
LaxarJS/laxar-tooling
src/page_assembler.js
assemble
function assemble( page ) { if( typeof page !== 'object' ) { return Promise.reject( new Error( 'PageAssembler.assemble must be called with a page artifact (object)' ) ); } removeDisabledItems( page ); return loadPageRecursively( page, page.name, [] ); }
javascript
function assemble( page ) { if( typeof page !== 'object' ) { return Promise.reject( new Error( 'PageAssembler.assemble must be called with a page artifact (object)' ) ); } removeDisabledItems( page ); return loadPageRecursively( page, page.name, [] ); }
[ "function", "assemble", "(", "page", ")", "{", "if", "(", "typeof", "page", "!==", "'object'", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'PageAssembler.assemble must be called with a page artifact (object)'", ")", ")", ";", "}", "removeDisabledItems", "(", "page", ")", ";", "return", "loadPageRecursively", "(", "page", ",", "page", ".", "name", ",", "[", "]", ")", ";", "}" ]
Loads a page specification and resolves all extension and compositions. The result is a page were all referenced page fragments are merged in to one JavaScript object. Returns a promise that is either resolved with the constructed page or rejected with a JavaScript `Error` instance. @param {String} page the page to load. Usually a path relative to the base url, with the `.json` suffix omitted @return {Promise} the result promise
[ "Loads", "a", "page", "specification", "and", "resolves", "all", "extension", "and", "compositions", ".", "The", "result", "is", "a", "page", "were", "all", "referenced", "page", "fragments", "are", "merged", "in", "to", "one", "JavaScript", "object", ".", "Returns", "a", "promise", "that", "is", "either", "resolved", "with", "the", "constructed", "page", "or", "rejected", "with", "a", "JavaScript", "Error", "instance", "." ]
1c4a221994f342ec03a98b68533c4de77ccfeec6
https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/page_assembler.js#L56-L64
train
hoast/hoast-transform
library/index.js
function(extension) { // If transformer already cached return that. if (extension in transformers) { return transformers[extension]; } // Retrieve the transformer if available. const transformer = totransformer(extension); transformers[extension] = transformer ? jstransformer(transformer) : false; // Return transformer. return transformers[extension]; }
javascript
function(extension) { // If transformer already cached return that. if (extension in transformers) { return transformers[extension]; } // Retrieve the transformer if available. const transformer = totransformer(extension); transformers[extension] = transformer ? jstransformer(transformer) : false; // Return transformer. return transformers[extension]; }
[ "function", "(", "extension", ")", "{", "if", "(", "extension", "in", "transformers", ")", "{", "return", "transformers", "[", "extension", "]", ";", "}", "const", "transformer", "=", "totransformer", "(", "extension", ")", ";", "transformers", "[", "extension", "]", "=", "transformer", "?", "jstransformer", "(", "transformer", ")", ":", "false", ";", "return", "transformers", "[", "extension", "]", ";", "}" ]
Matches the extension to the transformer. @param {String} extension The file extension.
[ "Matches", "the", "extension", "to", "the", "transformer", "." ]
c6c03f1aa8a1557d985fef41d7d07fcbe932090b
https://github.com/hoast/hoast-transform/blob/c6c03f1aa8a1557d985fef41d7d07fcbe932090b/library/index.js#L14-L26
train
veo-labs/openveo-api
lib/storages/databases/Database.js
Database
function Database(configuration) { Database.super_.call(this, configuration); Object.defineProperties(this, { /** * Database host. * * @property host * @type String * @final */ host: {value: configuration.host}, /** * Database port. * * @property port * @type Number * @final */ port: {value: configuration.port}, /** * Database name. * * @property name * @type String * @final */ name: {value: configuration.database}, /** * Database user name. * * @property username * @type String * @final */ username: {value: configuration.username}, /** * Database user password. * * @property password * @type String * @final */ password: {value: configuration.password} }); }
javascript
function Database(configuration) { Database.super_.call(this, configuration); Object.defineProperties(this, { /** * Database host. * * @property host * @type String * @final */ host: {value: configuration.host}, /** * Database port. * * @property port * @type Number * @final */ port: {value: configuration.port}, /** * Database name. * * @property name * @type String * @final */ name: {value: configuration.database}, /** * Database user name. * * @property username * @type String * @final */ username: {value: configuration.username}, /** * Database user password. * * @property password * @type String * @final */ password: {value: configuration.password} }); }
[ "function", "Database", "(", "configuration", ")", "{", "Database", ".", "super_", ".", "call", "(", "this", ",", "configuration", ")", ";", "Object", ".", "defineProperties", "(", "this", ",", "{", "host", ":", "{", "value", ":", "configuration", ".", "host", "}", ",", "port", ":", "{", "value", ":", "configuration", ".", "port", "}", ",", "name", ":", "{", "value", ":", "configuration", ".", "database", "}", ",", "username", ":", "{", "value", ":", "configuration", ".", "username", "}", ",", "password", ":", "{", "value", ":", "configuration", ".", "password", "}", "}", ")", ";", "}" ]
Defines base database for all databases. This should not be used directly, use one of its subclasses instead. @class Database @extends Storage @constructor @param {Object} configuration A database configuration object depending on the database type @param {String} configuration.type The database type @param {String} configuration.host Database server host @param {Number} configuration.port Database server port @param {String} configuration.database The name of the database @param {String} configuration.username The name of the database user @param {String} configuration.password The password of the database user
[ "Defines", "base", "database", "for", "all", "databases", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/storages/databases/Database.js#L26-L77
train
AnyFetch/anyfetch-hydrater.js
lib/helpers/hydrater.js
function(err, changes) { if(cleaner.called) { return; } cleaner.called = true; if(err) { // Build a custom extra object, with hydration error details var extra = JSON.parse(JSON.stringify(task)); extra.changes = changes; extra.stdout = stdout; extra.stderr = stderr; logError(err, extra); child.reset(); } else { // Make the child available again child.available = true; } cb(err, changes); if(stdout !== "") { loggingTask.std = "out"; log.info(loggingTask, stdout); } if(stderr !== "") { loggingTask.std = "err"; log.info(loggingTask, stderr); } clearTimeout(timeout); }
javascript
function(err, changes) { if(cleaner.called) { return; } cleaner.called = true; if(err) { // Build a custom extra object, with hydration error details var extra = JSON.parse(JSON.stringify(task)); extra.changes = changes; extra.stdout = stdout; extra.stderr = stderr; logError(err, extra); child.reset(); } else { // Make the child available again child.available = true; } cb(err, changes); if(stdout !== "") { loggingTask.std = "out"; log.info(loggingTask, stdout); } if(stderr !== "") { loggingTask.std = "err"; log.info(loggingTask, stderr); } clearTimeout(timeout); }
[ "function", "(", "err", ",", "changes", ")", "{", "if", "(", "cleaner", ".", "called", ")", "{", "return", ";", "}", "cleaner", ".", "called", "=", "true", ";", "if", "(", "err", ")", "{", "var", "extra", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "task", ")", ")", ";", "extra", ".", "changes", "=", "changes", ";", "extra", ".", "stdout", "=", "stdout", ";", "extra", ".", "stderr", "=", "stderr", ";", "logError", "(", "err", ",", "extra", ")", ";", "child", ".", "reset", "(", ")", ";", "}", "else", "{", "child", ".", "available", "=", "true", ";", "}", "cb", "(", "err", ",", "changes", ")", ";", "if", "(", "stdout", "!==", "\"\"", ")", "{", "loggingTask", ".", "std", "=", "\"out\"", ";", "log", ".", "info", "(", "loggingTask", ",", "stdout", ")", ";", "}", "if", "(", "stderr", "!==", "\"\"", ")", "{", "loggingTask", ".", "std", "=", "\"err\"", ";", "log", ".", "info", "(", "loggingTask", ",", "stderr", ")", ";", "}", "clearTimeout", "(", "timeout", ")", ";", "}" ]
Function to call, either on domain error, on hydration error or successful hydration.
[ "Function", "to", "call", "either", "on", "domain", "error", "on", "hydration", "error", "or", "successful", "hydration", "." ]
1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae
https://github.com/AnyFetch/anyfetch-hydrater.js/blob/1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae/lib/helpers/hydrater.js#L50-L82
train
AnyFetch/anyfetch-hydrater.js
lib/helpers/hydrater.js
function(elem) { if(util.isArray(elem)) { return (elem.length === 0); } if(elem instanceof Object) { if(util.isDate(elem)) { return false; } return (Object.getOwnPropertyNames(elem).length === 0); } return false; }
javascript
function(elem) { if(util.isArray(elem)) { return (elem.length === 0); } if(elem instanceof Object) { if(util.isDate(elem)) { return false; } return (Object.getOwnPropertyNames(elem).length === 0); } return false; }
[ "function", "(", "elem", ")", "{", "if", "(", "util", ".", "isArray", "(", "elem", ")", ")", "{", "return", "(", "elem", ".", "length", "===", "0", ")", ";", "}", "if", "(", "elem", "instanceof", "Object", ")", "{", "if", "(", "util", ".", "isDate", "(", "elem", ")", ")", "{", "return", "false", ";", "}", "return", "(", "Object", ".", "getOwnPropertyNames", "(", "elem", ")", ".", "length", "===", "0", ")", ";", "}", "return", "false", ";", "}" ]
Removing empty changes to patch only effective changes
[ "Removing", "empty", "changes", "to", "patch", "only", "effective", "changes" ]
1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae
https://github.com/AnyFetch/anyfetch-hydrater.js/blob/1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae/lib/helpers/hydrater.js#L169-L180
train
ouroboroscoding/format-oc-javascript
format-oc.1.4.2.js
DateToStr
function DateToStr(date) { // Init the return variable var sRet = ''; // Add the year sRet += date.getFullYear() + '-'; // Add the month var iMonth = date.getMonth(); sRet += ((iMonth < 10) ? '0' + iMonth : iMonth.toString()) + '-' // Add the day var iDay = date.getDate(); sRet += ((iDay < 10) ? '0' + iDay : iDay.toString()) // Return the date return sRet; }
javascript
function DateToStr(date) { // Init the return variable var sRet = ''; // Add the year sRet += date.getFullYear() + '-'; // Add the month var iMonth = date.getMonth(); sRet += ((iMonth < 10) ? '0' + iMonth : iMonth.toString()) + '-' // Add the day var iDay = date.getDate(); sRet += ((iDay < 10) ? '0' + iDay : iDay.toString()) // Return the date return sRet; }
[ "function", "DateToStr", "(", "date", ")", "{", "var", "sRet", "=", "''", ";", "sRet", "+=", "date", ".", "getFullYear", "(", ")", "+", "'-'", ";", "var", "iMonth", "=", "date", ".", "getMonth", "(", ")", ";", "sRet", "+=", "(", "(", "iMonth", "<", "10", ")", "?", "'0'", "+", "iMonth", ":", "iMonth", ".", "toString", "(", ")", ")", "+", "'-'", "var", "iDay", "=", "date", ".", "getDate", "(", ")", ";", "sRet", "+=", "(", "(", "iDay", "<", "10", ")", "?", "'0'", "+", "iDay", ":", "iDay", ".", "toString", "(", ")", ")", "return", "sRet", ";", "}" ]
Date to String Turns a Date Object into a date string @name DateToStr @param Date date The value to turn into a string @return String
[ "Date", "to", "String" ]
bbcef0a11250053366df7596efc08ea4b45622e2
https://github.com/ouroboroscoding/format-oc-javascript/blob/bbcef0a11250053366df7596efc08ea4b45622e2/format-oc.1.4.2.js#L139-L157
train
ouroboroscoding/format-oc-javascript
format-oc.1.4.2.js
DateTimeToStr
function DateTimeToStr(datetime) { // Init the return variable with the date var sRet = DateToStr(datetime); // Add the time sRet += ' ' + datetime.toTimeString().substr(0,8); // Return the new date/time return sRet; }
javascript
function DateTimeToStr(datetime) { // Init the return variable with the date var sRet = DateToStr(datetime); // Add the time sRet += ' ' + datetime.toTimeString().substr(0,8); // Return the new date/time return sRet; }
[ "function", "DateTimeToStr", "(", "datetime", ")", "{", "var", "sRet", "=", "DateToStr", "(", "datetime", ")", ";", "sRet", "+=", "' '", "+", "datetime", ".", "toTimeString", "(", ")", ".", "substr", "(", "0", ",", "8", ")", ";", "return", "sRet", ";", "}" ]
DateTime to String Turns a Date Object into a date and time string @name DateTimeToStr @param Date datetime The value to turn into a string @return String
[ "DateTime", "to", "String" ]
bbcef0a11250053366df7596efc08ea4b45622e2
https://github.com/ouroboroscoding/format-oc-javascript/blob/bbcef0a11250053366df7596efc08ea4b45622e2/format-oc.1.4.2.js#L168-L178
train
vesln/hydro
lib/hydro.js
Hydro
function Hydro() { if (!(this instanceof Hydro)) { return new Hydro(); } this.loader = loader; this.plugins = []; this.emitter = new EventEmitter; this.runner = new Runner; this.frame = new Frame(this.runner.topLevel); this.interface = new Interface(this, this.frame); this.config = new Config; }
javascript
function Hydro() { if (!(this instanceof Hydro)) { return new Hydro(); } this.loader = loader; this.plugins = []; this.emitter = new EventEmitter; this.runner = new Runner; this.frame = new Frame(this.runner.topLevel); this.interface = new Interface(this, this.frame); this.config = new Config; }
[ "function", "Hydro", "(", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Hydro", ")", ")", "{", "return", "new", "Hydro", "(", ")", ";", "}", "this", ".", "loader", "=", "loader", ";", "this", ".", "plugins", "=", "[", "]", ";", "this", ".", "emitter", "=", "new", "EventEmitter", ";", "this", ".", "runner", "=", "new", "Runner", ";", "this", ".", "frame", "=", "new", "Frame", "(", "this", ".", "runner", ".", "topLevel", ")", ";", "this", ".", "interface", "=", "new", "Interface", "(", "this", ",", "this", ".", "frame", ")", ";", "this", ".", "config", "=", "new", "Config", ";", "}" ]
Hydro - the main class that external parties interact with. TODO(vesln): use `delegates`? @constructor
[ "Hydro", "-", "the", "main", "class", "that", "external", "parties", "interact", "with", "." ]
3f4d2e4926f913976187376e82f1496514c39890
https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/hydro.js#L28-L40
train
DavidSouther/JEFRi
modeler/angular/app/scripts/lib/codemirror/mode/tiddlywiki/tiddlywiki.js
twTokenStrike
function twTokenStrike(stream, state) { var maybeEnd = false, ch, nr; while (ch = stream.next()) { if (ch == "-" && maybeEnd) { state.tokenize = jsTokenBase; break; } maybeEnd = (ch == "-"); } return ret("text", "strikethrough"); }
javascript
function twTokenStrike(stream, state) { var maybeEnd = false, ch, nr; while (ch = stream.next()) { if (ch == "-" && maybeEnd) { state.tokenize = jsTokenBase; break; } maybeEnd = (ch == "-"); } return ret("text", "strikethrough"); }
[ "function", "twTokenStrike", "(", "stream", ",", "state", ")", "{", "var", "maybeEnd", "=", "false", ",", "ch", ",", "nr", ";", "while", "(", "ch", "=", "stream", ".", "next", "(", ")", ")", "{", "if", "(", "ch", "==", "\"-\"", "&&", "maybeEnd", ")", "{", "state", ".", "tokenize", "=", "jsTokenBase", ";", "break", ";", "}", "maybeEnd", "=", "(", "ch", "==", "\"-\"", ")", ";", "}", "return", "ret", "(", "\"text\"", ",", "\"strikethrough\"", ")", ";", "}" ]
tw strike through text looks ugly change CSS if needed
[ "tw", "strike", "through", "text", "looks", "ugly", "change", "CSS", "if", "needed" ]
161f24e242e05b9b2114cc1123a257141a60eaf2
https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/codemirror/mode/tiddlywiki/tiddlywiki.js#L316-L328
train
veo-labs/openveo-api
lib/providers/Provider.js
Provider
function Provider(storage) { Object.defineProperties(this, { /** * The provider storage. * * @property storage * @type Storage * @final */ storage: {value: storage} }); if (!(this.storage instanceof Storage)) throw new TypeError('storage must be of type Storage'); }
javascript
function Provider(storage) { Object.defineProperties(this, { /** * The provider storage. * * @property storage * @type Storage * @final */ storage: {value: storage} }); if (!(this.storage instanceof Storage)) throw new TypeError('storage must be of type Storage'); }
[ "function", "Provider", "(", "storage", ")", "{", "Object", ".", "defineProperties", "(", "this", ",", "{", "storage", ":", "{", "value", ":", "storage", "}", "}", ")", ";", "if", "(", "!", "(", "this", ".", "storage", "instanceof", "Storage", ")", ")", "throw", "new", "TypeError", "(", "'storage must be of type Storage'", ")", ";", "}" ]
Defines the base provider for all providers. A provider manages resources from its associated storage. @class Provider @constructor @param {Storage} storage The storage to use to store provider resources @throws {TypeError} If storage is not valid
[ "Defines", "the", "base", "provider", "for", "all", "providers", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/providers/Provider.js#L19-L35
train
LeisureLink/magicbus
lib/config/subscriber-configuration.js
function() { return { useConsumer: useConsumer, useEventDispatcher: useEventDispatcher, useEnvelope: useEnvelope, usePipeline: usePipeline, useRouteName: useRouteName, useRoutePattern: useRoutePattern }; }
javascript
function() { return { useConsumer: useConsumer, useEventDispatcher: useEventDispatcher, useEnvelope: useEnvelope, usePipeline: usePipeline, useRouteName: useRouteName, useRoutePattern: useRoutePattern }; }
[ "function", "(", ")", "{", "return", "{", "useConsumer", ":", "useConsumer", ",", "useEventDispatcher", ":", "useEventDispatcher", ",", "useEnvelope", ":", "useEnvelope", ",", "usePipeline", ":", "usePipeline", ",", "useRouteName", ":", "useRouteName", ",", "useRoutePattern", ":", "useRoutePattern", "}", ";", "}" ]
Gets the target for a configurator function to run on @public @param {Function} configFunc - the configuration function for the instance
[ "Gets", "the", "target", "for", "a", "configurator", "function", "to", "run", "on" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/subscriber-configuration.js#L91-L100
train
Runnable/monitor-dog
lib/timer.js
Timer
function Timer (callback, start) { this.callback = callback; this.startDate = null; if (!exists(start) || start !== false) { this.start(); } }
javascript
function Timer (callback, start) { this.callback = callback; this.startDate = null; if (!exists(start) || start !== false) { this.start(); } }
[ "function", "Timer", "(", "callback", ",", "start", ")", "{", "this", ".", "callback", "=", "callback", ";", "this", ".", "startDate", "=", "null", ";", "if", "(", "!", "exists", "(", "start", ")", "||", "start", "!==", "false", ")", "{", "this", ".", "start", "(", ")", ";", "}", "}" ]
Timer class for performing time calculations through the monitor module. @class @param {function} callback Callback to execute when the timer is stopped. @param {boolean} start Whether or not to start the timer upon construction, default: `true`.
[ "Timer", "class", "for", "performing", "time", "calculations", "through", "the", "monitor", "module", "." ]
040b259dfc8c6b5d934dc235f76028e5ab9094cc
https://github.com/Runnable/monitor-dog/blob/040b259dfc8c6b5d934dc235f76028e5ab9094cc/lib/timer.js#L20-L26
train
Mammut-FE/nejm
src/base/util.js
function(_list,_low,_high){ if (_low>_high) return -1; var _middle = Math.ceil((_low+_high)/2), _result = _docheck(_list[_middle],_middle,_list); if (_result==0) return _middle; if (_result<0) return _doSearch(_list,_low,_middle-1); return _doSearch(_list,_middle+1,_high); }
javascript
function(_list,_low,_high){ if (_low>_high) return -1; var _middle = Math.ceil((_low+_high)/2), _result = _docheck(_list[_middle],_middle,_list); if (_result==0) return _middle; if (_result<0) return _doSearch(_list,_low,_middle-1); return _doSearch(_list,_middle+1,_high); }
[ "function", "(", "_list", ",", "_low", ",", "_high", ")", "{", "if", "(", "_low", ">", "_high", ")", "return", "-", "1", ";", "var", "_middle", "=", "Math", ".", "ceil", "(", "(", "_low", "+", "_high", ")", "/", "2", ")", ",", "_result", "=", "_docheck", "(", "_list", "[", "_middle", "]", ",", "_middle", ",", "_list", ")", ";", "if", "(", "_result", "==", "0", ")", "return", "_middle", ";", "if", "(", "_result", "<", "0", ")", "return", "_doSearch", "(", "_list", ",", "_low", ",", "_middle", "-", "1", ")", ";", "return", "_doSearch", "(", "_list", ",", "_middle", "+", "1", ",", "_high", ")", ";", "}" ]
do binary search
[ "do", "binary", "search" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/base/util.js#L299-L308
train
urturn/urturn-expression-api
lib/expression-api/Image.js
function(url, img) { var svgImage = document.createElementNS(SVG_NS_URL, 'image'); svgImage.setAttributeNS(XLINK_NS_URL, 'xlink:href', url); svgImage.setAttribute('x', 0); svgImage.setAttribute('y', 0); svgImage.setAttribute('width', img.width); svgImage.setAttribute('height', img.height); return svgImage; }
javascript
function(url, img) { var svgImage = document.createElementNS(SVG_NS_URL, 'image'); svgImage.setAttributeNS(XLINK_NS_URL, 'xlink:href', url); svgImage.setAttribute('x', 0); svgImage.setAttribute('y', 0); svgImage.setAttribute('width', img.width); svgImage.setAttribute('height', img.height); return svgImage; }
[ "function", "(", "url", ",", "img", ")", "{", "var", "svgImage", "=", "document", ".", "createElementNS", "(", "SVG_NS_URL", ",", "'image'", ")", ";", "svgImage", ".", "setAttributeNS", "(", "XLINK_NS_URL", ",", "'xlink:href'", ",", "url", ")", ";", "svgImage", ".", "setAttribute", "(", "'x'", ",", "0", ")", ";", "svgImage", ".", "setAttribute", "(", "'y'", ",", "0", ")", ";", "svgImage", ".", "setAttribute", "(", "'width'", ",", "img", ".", "width", ")", ";", "svgImage", ".", "setAttribute", "(", "'height'", ",", "img", ".", "height", ")", ";", "return", "svgImage", ";", "}" ]
Build an svg image tag.
[ "Build", "an", "svg", "image", "tag", "." ]
009a272ee670dbbe5eefb5c070ed827dd778bb07
https://github.com/urturn/urturn-expression-api/blob/009a272ee670dbbe5eefb5c070ed827dd778bb07/lib/expression-api/Image.js#L199-L207
train
Mammut-FE/nejm
src/util/highlight/touch.js
function(_id,_clazz,_event){ _cache[_id] = _v._$page(_event); _e._$addClassName(_id,_clazz); }
javascript
function(_id,_clazz,_event){ _cache[_id] = _v._$page(_event); _e._$addClassName(_id,_clazz); }
[ "function", "(", "_id", ",", "_clazz", ",", "_event", ")", "{", "_cache", "[", "_id", "]", "=", "_v", ".", "_$page", "(", "_event", ")", ";", "_e", ".", "_$addClassName", "(", "_id", ",", "_clazz", ")", ";", "}" ]
touch start event
[ "touch", "start", "event" ]
dfc09ac66a8d67620a7aea65e34d8a179976b3fb
https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/highlight/touch.js#L54-L57
train
aldojs/http
lib/server.js
_wrap
function _wrap (handler, emitter) { return async (req, res) => { try { let response = await handler(req) await response.send(res) } catch (err) { // normalize if (! (err instanceof Error)) { err = new Error(`Non-error thrown: "${typeof err}"`) } // support ENOENT if (err.code === 'ENOENT') { err.expose = true err.status = 404 } // send res.statusCode = err.status || err.statusCode || 500 res.end() // delegate emitter.emit('error', err) } } }
javascript
function _wrap (handler, emitter) { return async (req, res) => { try { let response = await handler(req) await response.send(res) } catch (err) { // normalize if (! (err instanceof Error)) { err = new Error(`Non-error thrown: "${typeof err}"`) } // support ENOENT if (err.code === 'ENOENT') { err.expose = true err.status = 404 } // send res.statusCode = err.status || err.statusCode || 500 res.end() // delegate emitter.emit('error', err) } } }
[ "function", "_wrap", "(", "handler", ",", "emitter", ")", "{", "return", "async", "(", "req", ",", "res", ")", "=>", "{", "try", "{", "let", "response", "=", "await", "handler", "(", "req", ")", "await", "response", ".", "send", "(", "res", ")", "}", "catch", "(", "err", ")", "{", "if", "(", "!", "(", "err", "instanceof", "Error", ")", ")", "{", "err", "=", "new", "Error", "(", "`", "${", "typeof", "err", "}", "`", ")", "}", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "{", "err", ".", "expose", "=", "true", "err", ".", "status", "=", "404", "}", "res", ".", "statusCode", "=", "err", ".", "status", "||", "err", ".", "statusCode", "||", "500", "res", ".", "end", "(", ")", "emitter", ".", "emit", "(", "'error'", ",", "err", ")", "}", "}", "}" ]
Wrap the request handler @param {Function} handler The request handler @param {EventEmitter} emitter @private
[ "Wrap", "the", "request", "handler" ]
e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7
https://github.com/aldojs/http/blob/e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7/lib/server.js#L138-L164
train
aldojs/http
lib/server.js
_onError
function _onError (err) { if (err.status === 404 || err.statusCode === 404 || err.expose) return let msg = err.stack || err.toString() console.error(`\n${msg.replace(/^/gm, ' ')}\n`) }
javascript
function _onError (err) { if (err.status === 404 || err.statusCode === 404 || err.expose) return let msg = err.stack || err.toString() console.error(`\n${msg.replace(/^/gm, ' ')}\n`) }
[ "function", "_onError", "(", "err", ")", "{", "if", "(", "err", ".", "status", "===", "404", "||", "err", ".", "statusCode", "===", "404", "||", "err", ".", "expose", ")", "return", "let", "msg", "=", "err", ".", "stack", "||", "err", ".", "toString", "(", ")", "console", ".", "error", "(", "`", "\\n", "${", "msg", ".", "replace", "(", "/", "^", "/", "gm", ",", "' '", ")", "}", "\\n", "`", ")", "}" ]
The default `error` handler @param {Error} err The error object @private
[ "The", "default", "error", "handler" ]
e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7
https://github.com/aldojs/http/blob/e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7/lib/server.js#L172-L178
train
eface2face/meteor-spacebars-compiler
spacebars-compiler.js
function (ttag, scanner) { if (ttag.type === 'INCLUSION' || ttag.type === 'BLOCKOPEN') { var args = ttag.args; if (ttag.path[0] === 'each' && args[1] && args[1][0] === 'PATH' && args[1][1][0] === 'in') { // For slightly better error messages, we detect the each-in case // here in order not to complain if the user writes `{{#each 3 in x}}` // that "3 is not a function" } else { if (args.length > 1 && args[0].length === 2 && args[0][0] !== 'PATH') { // we have a positional argument that is not a PATH followed by // other arguments scanner.fatal("First argument must be a function, to be called on " + "the rest of the arguments; found " + args[0][0]); } } } var position = ttag.position || TEMPLATE_TAG_POSITION.ELEMENT; if (position === TEMPLATE_TAG_POSITION.IN_ATTRIBUTE) { if (ttag.type === 'DOUBLE' || ttag.type === 'ESCAPE') { return; } else if (ttag.type === 'BLOCKOPEN') { var path = ttag.path; var path0 = path[0]; if (! (path.length === 1 && (path0 === 'if' || path0 === 'unless' || path0 === 'with' || path0 === 'each'))) { scanner.fatal("Custom block helpers are not allowed in an HTML attribute, only built-in ones like #each and #if"); } } else { scanner.fatal(ttag.type + " template tag is not allowed in an HTML attribute"); } } else if (position === TEMPLATE_TAG_POSITION.IN_START_TAG) { if (! (ttag.type === 'DOUBLE')) { scanner.fatal("Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type " + ttag.type + " is not allowed here."); } if (scanner.peek() === '=') { scanner.fatal("Template tags are not allowed in attribute names, only in attribute values or in the form of a single {{helper}} that evaluates to a dictionary of name=value pairs."); } } }
javascript
function (ttag, scanner) { if (ttag.type === 'INCLUSION' || ttag.type === 'BLOCKOPEN') { var args = ttag.args; if (ttag.path[0] === 'each' && args[1] && args[1][0] === 'PATH' && args[1][1][0] === 'in') { // For slightly better error messages, we detect the each-in case // here in order not to complain if the user writes `{{#each 3 in x}}` // that "3 is not a function" } else { if (args.length > 1 && args[0].length === 2 && args[0][0] !== 'PATH') { // we have a positional argument that is not a PATH followed by // other arguments scanner.fatal("First argument must be a function, to be called on " + "the rest of the arguments; found " + args[0][0]); } } } var position = ttag.position || TEMPLATE_TAG_POSITION.ELEMENT; if (position === TEMPLATE_TAG_POSITION.IN_ATTRIBUTE) { if (ttag.type === 'DOUBLE' || ttag.type === 'ESCAPE') { return; } else if (ttag.type === 'BLOCKOPEN') { var path = ttag.path; var path0 = path[0]; if (! (path.length === 1 && (path0 === 'if' || path0 === 'unless' || path0 === 'with' || path0 === 'each'))) { scanner.fatal("Custom block helpers are not allowed in an HTML attribute, only built-in ones like #each and #if"); } } else { scanner.fatal(ttag.type + " template tag is not allowed in an HTML attribute"); } } else if (position === TEMPLATE_TAG_POSITION.IN_START_TAG) { if (! (ttag.type === 'DOUBLE')) { scanner.fatal("Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type " + ttag.type + " is not allowed here."); } if (scanner.peek() === '=') { scanner.fatal("Template tags are not allowed in attribute names, only in attribute values or in the form of a single {{helper}} that evaluates to a dictionary of name=value pairs."); } } }
[ "function", "(", "ttag", ",", "scanner", ")", "{", "if", "(", "ttag", ".", "type", "===", "'INCLUSION'", "||", "ttag", ".", "type", "===", "'BLOCKOPEN'", ")", "{", "var", "args", "=", "ttag", ".", "args", ";", "if", "(", "ttag", ".", "path", "[", "0", "]", "===", "'each'", "&&", "args", "[", "1", "]", "&&", "args", "[", "1", "]", "[", "0", "]", "===", "'PATH'", "&&", "args", "[", "1", "]", "[", "1", "]", "[", "0", "]", "===", "'in'", ")", "{", "}", "else", "{", "if", "(", "args", ".", "length", ">", "1", "&&", "args", "[", "0", "]", ".", "length", "===", "2", "&&", "args", "[", "0", "]", "[", "0", "]", "!==", "'PATH'", ")", "{", "scanner", ".", "fatal", "(", "\"First argument must be a function, to be called on \"", "+", "\"the rest of the arguments; found \"", "+", "args", "[", "0", "]", "[", "0", "]", ")", ";", "}", "}", "}", "var", "position", "=", "ttag", ".", "position", "||", "TEMPLATE_TAG_POSITION", ".", "ELEMENT", ";", "if", "(", "position", "===", "TEMPLATE_TAG_POSITION", ".", "IN_ATTRIBUTE", ")", "{", "if", "(", "ttag", ".", "type", "===", "'DOUBLE'", "||", "ttag", ".", "type", "===", "'ESCAPE'", ")", "{", "return", ";", "}", "else", "if", "(", "ttag", ".", "type", "===", "'BLOCKOPEN'", ")", "{", "var", "path", "=", "ttag", ".", "path", ";", "var", "path0", "=", "path", "[", "0", "]", ";", "if", "(", "!", "(", "path", ".", "length", "===", "1", "&&", "(", "path0", "===", "'if'", "||", "path0", "===", "'unless'", "||", "path0", "===", "'with'", "||", "path0", "===", "'each'", ")", ")", ")", "{", "scanner", ".", "fatal", "(", "\"Custom block helpers are not allowed in an HTML attribute, only built-in ones like #each and #if\"", ")", ";", "}", "}", "else", "{", "scanner", ".", "fatal", "(", "ttag", ".", "type", "+", "\" template tag is not allowed in an HTML attribute\"", ")", ";", "}", "}", "else", "if", "(", "position", "===", "TEMPLATE_TAG_POSITION", ".", "IN_START_TAG", ")", "{", "if", "(", "!", "(", "ttag", ".", "type", "===", "'DOUBLE'", ")", ")", "{", "scanner", ".", "fatal", "(", "\"Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type \"", "+", "ttag", ".", "type", "+", "\" is not allowed here.\"", ")", ";", "}", "if", "(", "scanner", ".", "peek", "(", ")", "===", "'='", ")", "{", "scanner", ".", "fatal", "(", "\"Template tags are not allowed in attribute names, only in attribute values or in the form of a single {{helper}} that evaluates to a dictionary of name=value pairs.\"", ")", ";", "}", "}", "}" ]
Validate that `templateTag` is correctly formed and legal for its HTML position. Use `scanner` to report errors. On success, does nothing.
[ "Validate", "that", "templateTag", "is", "correctly", "formed", "and", "legal", "for", "its", "HTML", "position", ".", "Use", "scanner", "to", "report", "errors", ".", "On", "success", "does", "nothing", "." ]
ad197c715cdcafebaa2fca31a6c17173d29746d7
https://github.com/eface2face/meteor-spacebars-compiler/blob/ad197c715cdcafebaa2fca31a6c17173d29746d7/spacebars-compiler.js#L472-L516
train
eface2face/meteor-spacebars-compiler
spacebars-compiler.js
function (path, args, mustacheType) { var self = this; var nameCode = self.codeGenPath(path); var argCode = self.codeGenMustacheArgs(args); var mustache = (mustacheType || 'mustache'); return 'Spacebars.' + mustache + '(' + nameCode + (argCode ? ', ' + argCode.join(', ') : '') + ')'; }
javascript
function (path, args, mustacheType) { var self = this; var nameCode = self.codeGenPath(path); var argCode = self.codeGenMustacheArgs(args); var mustache = (mustacheType || 'mustache'); return 'Spacebars.' + mustache + '(' + nameCode + (argCode ? ', ' + argCode.join(', ') : '') + ')'; }
[ "function", "(", "path", ",", "args", ",", "mustacheType", ")", "{", "var", "self", "=", "this", ";", "var", "nameCode", "=", "self", ".", "codeGenPath", "(", "path", ")", ";", "var", "argCode", "=", "self", ".", "codeGenMustacheArgs", "(", "args", ")", ";", "var", "mustache", "=", "(", "mustacheType", "||", "'mustache'", ")", ";", "return", "'Spacebars.'", "+", "mustache", "+", "'('", "+", "nameCode", "+", "(", "argCode", "?", "', '", "+", "argCode", ".", "join", "(", "', '", ")", ":", "''", ")", "+", "')'", ";", "}" ]
Generates a call to `Spacebars.fooMustache` on evaluated arguments. The resulting code has no function literals and must be wrapped in one for fine-grained reactivity.
[ "Generates", "a", "call", "to", "Spacebars", ".", "fooMustache", "on", "evaluated", "arguments", ".", "The", "resulting", "code", "has", "no", "function", "literals", "and", "must", "be", "wrapped", "in", "one", "for", "fine", "-", "grained", "reactivity", "." ]
ad197c715cdcafebaa2fca31a6c17173d29746d7
https://github.com/eface2face/meteor-spacebars-compiler/blob/ad197c715cdcafebaa2fca31a6c17173d29746d7/spacebars-compiler.js#L1049-L1058
train
mozilla-jetpack/jetpack-validation
index.js
validate
function validate (rootPath) { var manifest; var webextensionManifest; var errors = {}; try { manifest = JSON.parse(fs.readFileSync(join(rootPath, "package.json"))); } catch (e) { errors.parsing = utils.getErrorMessage("COULD_NOT_PARSE") + "\n" + e.message; return errors; } if (!validateID(manifest)) { errors.id = utils.getErrorMessage("INVALID_ID"); } if (!validateMain(rootPath)) { errors.main = utils.getErrorMessage("MAIN_DNE"); } if (!validateTitle(manifest)) { errors.title = utils.getErrorMessage("INVALID_TITLE"); } if (!validateName(manifest)) { errors.name = utils.getErrorMessage("INVALID_NAME"); } if (!validateVersion(manifest)) { errors.version = utils.getErrorMessage("INVALID_VERSION"); } // If both a package.json and a manifest.json files exists in the addon // root dir, raise an helpful error message that suggest to use web-ext instead. if (fs.existsSync(join(rootPath, "manifest.json"))) { errors.webextensionManifestFound = utils.getErrorMessage("WEBEXT_ERROR"); } return errors; }
javascript
function validate (rootPath) { var manifest; var webextensionManifest; var errors = {}; try { manifest = JSON.parse(fs.readFileSync(join(rootPath, "package.json"))); } catch (e) { errors.parsing = utils.getErrorMessage("COULD_NOT_PARSE") + "\n" + e.message; return errors; } if (!validateID(manifest)) { errors.id = utils.getErrorMessage("INVALID_ID"); } if (!validateMain(rootPath)) { errors.main = utils.getErrorMessage("MAIN_DNE"); } if (!validateTitle(manifest)) { errors.title = utils.getErrorMessage("INVALID_TITLE"); } if (!validateName(manifest)) { errors.name = utils.getErrorMessage("INVALID_NAME"); } if (!validateVersion(manifest)) { errors.version = utils.getErrorMessage("INVALID_VERSION"); } // If both a package.json and a manifest.json files exists in the addon // root dir, raise an helpful error message that suggest to use web-ext instead. if (fs.existsSync(join(rootPath, "manifest.json"))) { errors.webextensionManifestFound = utils.getErrorMessage("WEBEXT_ERROR"); } return errors; }
[ "function", "validate", "(", "rootPath", ")", "{", "var", "manifest", ";", "var", "webextensionManifest", ";", "var", "errors", "=", "{", "}", ";", "try", "{", "manifest", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "join", "(", "rootPath", ",", "\"package.json\"", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "errors", ".", "parsing", "=", "utils", ".", "getErrorMessage", "(", "\"COULD_NOT_PARSE\"", ")", "+", "\"\\n\"", "+", "\\n", ";", "e", ".", "message", "}", "return", "errors", ";", "if", "(", "!", "validateID", "(", "manifest", ")", ")", "{", "errors", ".", "id", "=", "utils", ".", "getErrorMessage", "(", "\"INVALID_ID\"", ")", ";", "}", "if", "(", "!", "validateMain", "(", "rootPath", ")", ")", "{", "errors", ".", "main", "=", "utils", ".", "getErrorMessage", "(", "\"MAIN_DNE\"", ")", ";", "}", "if", "(", "!", "validateTitle", "(", "manifest", ")", ")", "{", "errors", ".", "title", "=", "utils", ".", "getErrorMessage", "(", "\"INVALID_TITLE\"", ")", ";", "}", "if", "(", "!", "validateName", "(", "manifest", ")", ")", "{", "errors", ".", "name", "=", "utils", ".", "getErrorMessage", "(", "\"INVALID_NAME\"", ")", ";", "}", "if", "(", "!", "validateVersion", "(", "manifest", ")", ")", "{", "errors", ".", "version", "=", "utils", ".", "getErrorMessage", "(", "\"INVALID_VERSION\"", ")", ";", "}", "if", "(", "fs", ".", "existsSync", "(", "join", "(", "rootPath", ",", "\"manifest.json\"", ")", ")", ")", "{", "errors", ".", "webextensionManifestFound", "=", "utils", ".", "getErrorMessage", "(", "\"WEBEXT_ERROR\"", ")", ";", "}", "}" ]
Takes a root directory for an addon, where the package.json lives, and build options and validates the information available in the addon. @param {Object} rootPath @return {Object}
[ "Takes", "a", "root", "directory", "for", "an", "addon", "where", "the", "package", ".", "json", "lives", "and", "build", "options", "and", "validates", "the", "information", "available", "in", "the", "addon", "." ]
d6b104ed98e295b527d3cc743a1dbde98bed7baa
https://github.com/mozilla-jetpack/jetpack-validation/blob/d6b104ed98e295b527d3cc743a1dbde98bed7baa/index.js#L16-L56
train
eface2face/meteor-htmljs
html.js
function (tagName) { // HTMLTag is the per-tagName constructor of a HTML.Tag subclass var HTMLTag = function (/*arguments*/) { // Work with or without `new`. If not called with `new`, // perform instantiation by recursively calling this constructor. // We can't pass varargs, so pass no args. var instance = (this instanceof HTML.Tag) ? this : new HTMLTag; var i = 0; var attrs = arguments.length && arguments[0]; if (attrs && (typeof attrs === 'object')) { // Treat vanilla JS object as an attributes dictionary. if (! HTML.isConstructedObject(attrs)) { instance.attrs = attrs; i++; } else if (attrs instanceof HTML.Attrs) { var array = attrs.value; if (array.length === 1) { instance.attrs = array[0]; } else if (array.length > 1) { instance.attrs = array; } i++; } } // If no children, don't create an array at all, use the prototype's // (frozen, empty) array. This way we don't create an empty array // every time someone creates a tag without `new` and this constructor // calls itself with no arguments (above). if (i < arguments.length) instance.children = SLICE.call(arguments, i); return instance; }; HTMLTag.prototype = new HTML.Tag; HTMLTag.prototype.constructor = HTMLTag; HTMLTag.prototype.tagName = tagName; return HTMLTag; }
javascript
function (tagName) { // HTMLTag is the per-tagName constructor of a HTML.Tag subclass var HTMLTag = function (/*arguments*/) { // Work with or without `new`. If not called with `new`, // perform instantiation by recursively calling this constructor. // We can't pass varargs, so pass no args. var instance = (this instanceof HTML.Tag) ? this : new HTMLTag; var i = 0; var attrs = arguments.length && arguments[0]; if (attrs && (typeof attrs === 'object')) { // Treat vanilla JS object as an attributes dictionary. if (! HTML.isConstructedObject(attrs)) { instance.attrs = attrs; i++; } else if (attrs instanceof HTML.Attrs) { var array = attrs.value; if (array.length === 1) { instance.attrs = array[0]; } else if (array.length > 1) { instance.attrs = array; } i++; } } // If no children, don't create an array at all, use the prototype's // (frozen, empty) array. This way we don't create an empty array // every time someone creates a tag without `new` and this constructor // calls itself with no arguments (above). if (i < arguments.length) instance.children = SLICE.call(arguments, i); return instance; }; HTMLTag.prototype = new HTML.Tag; HTMLTag.prototype.constructor = HTMLTag; HTMLTag.prototype.tagName = tagName; return HTMLTag; }
[ "function", "(", "tagName", ")", "{", "var", "HTMLTag", "=", "function", "(", ")", "{", "var", "instance", "=", "(", "this", "instanceof", "HTML", ".", "Tag", ")", "?", "this", ":", "new", "HTMLTag", ";", "var", "i", "=", "0", ";", "var", "attrs", "=", "arguments", ".", "length", "&&", "arguments", "[", "0", "]", ";", "if", "(", "attrs", "&&", "(", "typeof", "attrs", "===", "'object'", ")", ")", "{", "if", "(", "!", "HTML", ".", "isConstructedObject", "(", "attrs", ")", ")", "{", "instance", ".", "attrs", "=", "attrs", ";", "i", "++", ";", "}", "else", "if", "(", "attrs", "instanceof", "HTML", ".", "Attrs", ")", "{", "var", "array", "=", "attrs", ".", "value", ";", "if", "(", "array", ".", "length", "===", "1", ")", "{", "instance", ".", "attrs", "=", "array", "[", "0", "]", ";", "}", "else", "if", "(", "array", ".", "length", ">", "1", ")", "{", "instance", ".", "attrs", "=", "array", ";", "}", "i", "++", ";", "}", "}", "if", "(", "i", "<", "arguments", ".", "length", ")", "instance", ".", "children", "=", "SLICE", ".", "call", "(", "arguments", ",", "i", ")", ";", "return", "instance", ";", "}", ";", "HTMLTag", ".", "prototype", "=", "new", "HTML", ".", "Tag", ";", "HTMLTag", ".", "prototype", ".", "constructor", "=", "HTMLTag", ";", "HTMLTag", ".", "prototype", ".", "tagName", "=", "tagName", ";", "return", "HTMLTag", ";", "}" ]
Given "p" create the function `HTML.P`.
[ "Given", "p", "create", "the", "function", "HTML", ".", "P", "." ]
6f7c221af9a2153648c37d26721f90d1dad4561d
https://github.com/eface2face/meteor-htmljs/blob/6f7c221af9a2153648c37d26721f90d1dad4561d/html.js#L349-L390
train
veo-labs/openveo-api
lib/errors/NotFoundError.js
NotFoundError
function NotFoundError(id) { Error.captureStackTrace(this, this.constructor); Object.defineProperties(this, { /** * The resource id which hasn't been found. * * @property id * @type Mixed * @final */ id: {value: id}, /** * Error message. * * @property message * @type String * @final */ message: {value: 'Could not found resource "' + id + '"', writable: true}, /** * The error name. * * @property name * @type String * @final */ name: {value: 'NotFoundError', writable: true} }); }
javascript
function NotFoundError(id) { Error.captureStackTrace(this, this.constructor); Object.defineProperties(this, { /** * The resource id which hasn't been found. * * @property id * @type Mixed * @final */ id: {value: id}, /** * Error message. * * @property message * @type String * @final */ message: {value: 'Could not found resource "' + id + '"', writable: true}, /** * The error name. * * @property name * @type String * @final */ name: {value: 'NotFoundError', writable: true} }); }
[ "function", "NotFoundError", "(", "id", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "Object", ".", "defineProperties", "(", "this", ",", "{", "id", ":", "{", "value", ":", "id", "}", ",", "message", ":", "{", "value", ":", "'Could not found resource \"'", "+", "id", "+", "'\"'", ",", "writable", ":", "true", "}", ",", "name", ":", "{", "value", ":", "'NotFoundError'", ",", "writable", ":", "true", "}", "}", ")", ";", "}" ]
Defines a NotFoundError to be thrown when a resource is not found. var openVeoApi = require('@openveo/api'); throw new openVeoApi.errors.NotFoundError(42); @class NotFoundError @extends Error @constructor @param {String|Number} id The resource id which hasn't been found
[ "Defines", "a", "NotFoundError", "to", "be", "thrown", "when", "a", "resource", "is", "not", "found", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/errors/NotFoundError.js#L20-L54
train
veo-labs/openveo-api
lib/fileSystem.js
mkdirRecursive
function mkdirRecursive(directoryPath, callback) { directoryPath = path.resolve(directoryPath); // Try to create directory fs.mkdir(directoryPath, function(error) { if (error && error.code === 'EEXIST') { // Can't create directory it already exists // It may have been created by another loop callback(); } else if (error && error.code === 'ENOENT') { // Can't create directory, parent directory does not exist // Create parent directory mkdirRecursive(path.dirname(directoryPath), function(error) { if (!error) { // Now that parent directory is created, create requested directory fs.mkdir(directoryPath, function(error) { if (error && error.code === 'EEXIST') { // Can't create directory it already exists // It may have been created by another loop callback(); } else callback(error); }); } else callback(error); }); } else callback(error); }); }
javascript
function mkdirRecursive(directoryPath, callback) { directoryPath = path.resolve(directoryPath); // Try to create directory fs.mkdir(directoryPath, function(error) { if (error && error.code === 'EEXIST') { // Can't create directory it already exists // It may have been created by another loop callback(); } else if (error && error.code === 'ENOENT') { // Can't create directory, parent directory does not exist // Create parent directory mkdirRecursive(path.dirname(directoryPath), function(error) { if (!error) { // Now that parent directory is created, create requested directory fs.mkdir(directoryPath, function(error) { if (error && error.code === 'EEXIST') { // Can't create directory it already exists // It may have been created by another loop callback(); } else callback(error); }); } else callback(error); }); } else callback(error); }); }
[ "function", "mkdirRecursive", "(", "directoryPath", ",", "callback", ")", "{", "directoryPath", "=", "path", ".", "resolve", "(", "directoryPath", ")", ";", "fs", ".", "mkdir", "(", "directoryPath", ",", "function", "(", "error", ")", "{", "if", "(", "error", "&&", "error", ".", "code", "===", "'EEXIST'", ")", "{", "callback", "(", ")", ";", "}", "else", "if", "(", "error", "&&", "error", ".", "code", "===", "'ENOENT'", ")", "{", "mkdirRecursive", "(", "path", ".", "dirname", "(", "directoryPath", ")", ",", "function", "(", "error", ")", "{", "if", "(", "!", "error", ")", "{", "fs", ".", "mkdir", "(", "directoryPath", ",", "function", "(", "error", ")", "{", "if", "(", "error", "&&", "error", ".", "code", "===", "'EEXIST'", ")", "{", "callback", "(", ")", ";", "}", "else", "callback", "(", "error", ")", ";", "}", ")", ";", "}", "else", "callback", "(", "error", ")", ";", "}", ")", ";", "}", "else", "callback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Creates a directory recursively and asynchronously. If parent directories do not exist, they will be automatically created. @method mkdirRecursive @private @static @async @param {String} directoryPath The directory system path to create @param {Function} callback The function to call when done - **Error** The error if an error occurred, null otherwise
[ "Creates", "a", "directory", "recursively", "and", "asynchronously", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/fileSystem.js#L32-L70
train
veo-labs/openveo-api
lib/fileSystem.js
rmdirRecursive
function rmdirRecursive(directoryPath, callback) { // Open directory fs.readdir(directoryPath, function(error, resources) { // Failed reading directory if (error) return callback(error); var pendingResourceNumber = resources.length; // No more pending resources, done for this directory if (!pendingResourceNumber) { // Remove directory fs.rmdir(directoryPath, callback); } // Iterate through the list of resources in the directory resources.forEach(function(resource) { var resourcePath = path.join(directoryPath, resource); // Get resource stats fs.stat(resourcePath, function(error, stats) { if (error) return callback(error); // Resource correspond to a directory if (stats.isDirectory()) { resources = rmdirRecursive(path.join(directoryPath, resource), function(error) { if (error) return callback(error); pendingResourceNumber--; if (!pendingResourceNumber) fs.rmdir(directoryPath, callback); }); } else { // Resource does not correspond to a directory // Mark resource as treated // Remove file fs.unlink(resourcePath, function(error) { if (error) return callback(error); else { pendingResourceNumber--; if (!pendingResourceNumber) fs.rmdir(directoryPath, callback); } }); } }); }); }); }
javascript
function rmdirRecursive(directoryPath, callback) { // Open directory fs.readdir(directoryPath, function(error, resources) { // Failed reading directory if (error) return callback(error); var pendingResourceNumber = resources.length; // No more pending resources, done for this directory if (!pendingResourceNumber) { // Remove directory fs.rmdir(directoryPath, callback); } // Iterate through the list of resources in the directory resources.forEach(function(resource) { var resourcePath = path.join(directoryPath, resource); // Get resource stats fs.stat(resourcePath, function(error, stats) { if (error) return callback(error); // Resource correspond to a directory if (stats.isDirectory()) { resources = rmdirRecursive(path.join(directoryPath, resource), function(error) { if (error) return callback(error); pendingResourceNumber--; if (!pendingResourceNumber) fs.rmdir(directoryPath, callback); }); } else { // Resource does not correspond to a directory // Mark resource as treated // Remove file fs.unlink(resourcePath, function(error) { if (error) return callback(error); else { pendingResourceNumber--; if (!pendingResourceNumber) fs.rmdir(directoryPath, callback); } }); } }); }); }); }
[ "function", "rmdirRecursive", "(", "directoryPath", ",", "callback", ")", "{", "fs", ".", "readdir", "(", "directoryPath", ",", "function", "(", "error", ",", "resources", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "var", "pendingResourceNumber", "=", "resources", ".", "length", ";", "if", "(", "!", "pendingResourceNumber", ")", "{", "fs", ".", "rmdir", "(", "directoryPath", ",", "callback", ")", ";", "}", "resources", ".", "forEach", "(", "function", "(", "resource", ")", "{", "var", "resourcePath", "=", "path", ".", "join", "(", "directoryPath", ",", "resource", ")", ";", "fs", ".", "stat", "(", "resourcePath", ",", "function", "(", "error", ",", "stats", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "resources", "=", "rmdirRecursive", "(", "path", ".", "join", "(", "directoryPath", ",", "resource", ")", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "pendingResourceNumber", "--", ";", "if", "(", "!", "pendingResourceNumber", ")", "fs", ".", "rmdir", "(", "directoryPath", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "{", "fs", ".", "unlink", "(", "resourcePath", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "else", "{", "pendingResourceNumber", "--", ";", "if", "(", "!", "pendingResourceNumber", ")", "fs", ".", "rmdir", "(", "directoryPath", ",", "callback", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Removes a directory and all its content recursively and asynchronously. It is assumed that the directory exists. @method rmdirRecursive @private @static @async @param {String} directoryPath Path of the directory to remove @param {Function} callback The function to call when done - **Error** The error if an error occurred, null otherwise
[ "Removes", "a", "directory", "and", "all", "its", "content", "recursively", "and", "asynchronously", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/fileSystem.js#L85-L154
train
veo-labs/openveo-api
lib/fileSystem.js
copyFile
function copyFile(sourceFilePath, destinationFilePath, callback) { var onError = function(error) { callback(error); }; var safecopy = function(sourceFilePath, destinationFilePath, callback) { if (sourceFilePath && destinationFilePath && callback) { try { var is = fs.createReadStream(sourceFilePath); var os = fs.createWriteStream(destinationFilePath); is.on('error', onError); os.on('error', onError); is.on('end', function() { os.end(); }); os.on('finish', function() { callback(); }); is.pipe(os); } catch (e) { callback(new Error(e.message)); } } else callback(new Error('File path not defined')); }; var pathDir = path.dirname(destinationFilePath); this.mkdir(pathDir, function(error) { if (error) callback(error); else safecopy(sourceFilePath, destinationFilePath, callback); } ); }
javascript
function copyFile(sourceFilePath, destinationFilePath, callback) { var onError = function(error) { callback(error); }; var safecopy = function(sourceFilePath, destinationFilePath, callback) { if (sourceFilePath && destinationFilePath && callback) { try { var is = fs.createReadStream(sourceFilePath); var os = fs.createWriteStream(destinationFilePath); is.on('error', onError); os.on('error', onError); is.on('end', function() { os.end(); }); os.on('finish', function() { callback(); }); is.pipe(os); } catch (e) { callback(new Error(e.message)); } } else callback(new Error('File path not defined')); }; var pathDir = path.dirname(destinationFilePath); this.mkdir(pathDir, function(error) { if (error) callback(error); else safecopy(sourceFilePath, destinationFilePath, callback); } ); }
[ "function", "copyFile", "(", "sourceFilePath", ",", "destinationFilePath", ",", "callback", ")", "{", "var", "onError", "=", "function", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "}", ";", "var", "safecopy", "=", "function", "(", "sourceFilePath", ",", "destinationFilePath", ",", "callback", ")", "{", "if", "(", "sourceFilePath", "&&", "destinationFilePath", "&&", "callback", ")", "{", "try", "{", "var", "is", "=", "fs", ".", "createReadStream", "(", "sourceFilePath", ")", ";", "var", "os", "=", "fs", ".", "createWriteStream", "(", "destinationFilePath", ")", ";", "is", ".", "on", "(", "'error'", ",", "onError", ")", ";", "os", ".", "on", "(", "'error'", ",", "onError", ")", ";", "is", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "os", ".", "end", "(", ")", ";", "}", ")", ";", "os", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "callback", "(", ")", ";", "}", ")", ";", "is", ".", "pipe", "(", "os", ")", ";", "}", "catch", "(", "e", ")", "{", "callback", "(", "new", "Error", "(", "e", ".", "message", ")", ")", ";", "}", "}", "else", "callback", "(", "new", "Error", "(", "'File path not defined'", ")", ")", ";", "}", ";", "var", "pathDir", "=", "path", ".", "dirname", "(", "destinationFilePath", ")", ";", "this", ".", "mkdir", "(", "pathDir", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "callback", "(", "error", ")", ";", "else", "safecopy", "(", "sourceFilePath", ",", "destinationFilePath", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Copies a file. If directory does not exist it will be automatically created. @method copyFile @private @static @async @param {String} sourceFilePath Path of the file @param {String} destinationFilePath Final path of the file @param {Function} callback The function to call when done - **Error** The error if an error occurred, null otherwise
[ "Copies", "a", "file", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/fileSystem.js#L245-L282
train
ofidj/fidj
.todo/miapp.tools.resize.js
removeResizeListener
function removeResizeListener(resizeListener) { removeIdFromList(rootListener, resizeListener.id); if (a4p.isDefined(listenersIndex[resizeListener.id])) { delete listenersIndex[resizeListener.id]; } if (a4p.isDefined(listenersIndex[resizeListener.name]) && (listenersIndex[resizeListener.name].id == resizeListener.id)) { delete listenersIndex[resizeListener.name]; } }
javascript
function removeResizeListener(resizeListener) { removeIdFromList(rootListener, resizeListener.id); if (a4p.isDefined(listenersIndex[resizeListener.id])) { delete listenersIndex[resizeListener.id]; } if (a4p.isDefined(listenersIndex[resizeListener.name]) && (listenersIndex[resizeListener.name].id == resizeListener.id)) { delete listenersIndex[resizeListener.name]; } }
[ "function", "removeResizeListener", "(", "resizeListener", ")", "{", "removeIdFromList", "(", "rootListener", ",", "resizeListener", ".", "id", ")", ";", "if", "(", "a4p", ".", "isDefined", "(", "listenersIndex", "[", "resizeListener", ".", "id", "]", ")", ")", "{", "delete", "listenersIndex", "[", "resizeListener", ".", "id", "]", ";", "}", "if", "(", "a4p", ".", "isDefined", "(", "listenersIndex", "[", "resizeListener", ".", "name", "]", ")", "&&", "(", "listenersIndex", "[", "resizeListener", ".", "name", "]", ".", "id", "==", "resizeListener", ".", "id", ")", ")", "{", "delete", "listenersIndex", "[", "resizeListener", ".", "name", "]", ";", "}", "}" ]
Remove a listener @param resizeListener
[ "Remove", "a", "listener" ]
e57ebece54ee68211d43802a8e0feeef098d3e36
https://github.com/ofidj/fidj/blob/e57ebece54ee68211d43802a8e0feeef098d3e36/.todo/miapp.tools.resize.js#L282-L290
train
ofidj/fidj
.todo/miapp.tools.aes.js
keyExpansion
function keyExpansion(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [�5.2] var Nb = 4; // Number of columns (32-bit words) comprising the State. For this standard, Nb = 4. var Nk = key.length / 4; // Number of 32-bit words comprising the Cipher Key. Nk = 4/6/8 for 128/192/256-bit keys var Nr = Nk + 6; // Number of rounds. Nr = 10/12/14 for 128/192/256-bit keys var trace; var w = new Array(Nb * (Nr + 1)); var temp = new Array(4); for (var i = 0; i < Nk; i++) { var r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]; w[i] = r; /* trace = new Array(4); for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]); console.log('w['+i+']='+fidj.Hex.encode(trace.join(''))); */ } for (var i = Nk; i < (Nb * (Nr + 1)); i++) { w[i] = new Array(4); for (var t = 0; t < 4; t++) temp[t] = w[i - 1][t]; if (i % Nk == 0) { temp = subWord(rotWord(temp)); for (var t = 0; t < 4; t++) temp[t] ^= rCon[i / Nk][t]; } else if (Nk > 6 && i % Nk == 4) { temp = subWord(temp); } for (var t = 0; t < 4; t++) w[i][t] = w[i - Nk][t] ^ temp[t]; /* trace = new Array(4); for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]); console.log('w['+i+']='+fidj.Hex.encode(trace.join(''))); */ } return w; }
javascript
function keyExpansion(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [�5.2] var Nb = 4; // Number of columns (32-bit words) comprising the State. For this standard, Nb = 4. var Nk = key.length / 4; // Number of 32-bit words comprising the Cipher Key. Nk = 4/6/8 for 128/192/256-bit keys var Nr = Nk + 6; // Number of rounds. Nr = 10/12/14 for 128/192/256-bit keys var trace; var w = new Array(Nb * (Nr + 1)); var temp = new Array(4); for (var i = 0; i < Nk; i++) { var r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]; w[i] = r; /* trace = new Array(4); for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]); console.log('w['+i+']='+fidj.Hex.encode(trace.join(''))); */ } for (var i = Nk; i < (Nb * (Nr + 1)); i++) { w[i] = new Array(4); for (var t = 0; t < 4; t++) temp[t] = w[i - 1][t]; if (i % Nk == 0) { temp = subWord(rotWord(temp)); for (var t = 0; t < 4; t++) temp[t] ^= rCon[i / Nk][t]; } else if (Nk > 6 && i % Nk == 4) { temp = subWord(temp); } for (var t = 0; t < 4; t++) w[i][t] = w[i - Nk][t] ^ temp[t]; /* trace = new Array(4); for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]); console.log('w['+i+']='+fidj.Hex.encode(trace.join(''))); */ } return w; }
[ "function", "keyExpansion", "(", "key", ")", "{", "var", "Nb", "=", "4", ";", "var", "Nk", "=", "key", ".", "length", "/", "4", ";", "var", "Nr", "=", "Nk", "+", "6", ";", "var", "trace", ";", "var", "w", "=", "new", "Array", "(", "Nb", "*", "(", "Nr", "+", "1", ")", ")", ";", "var", "temp", "=", "new", "Array", "(", "4", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "Nk", ";", "i", "++", ")", "{", "var", "r", "=", "[", "key", "[", "4", "*", "i", "]", ",", "key", "[", "4", "*", "i", "+", "1", "]", ",", "key", "[", "4", "*", "i", "+", "2", "]", ",", "key", "[", "4", "*", "i", "+", "3", "]", "]", ";", "w", "[", "i", "]", "=", "r", ";", "}", "for", "(", "var", "i", "=", "Nk", ";", "i", "<", "(", "Nb", "*", "(", "Nr", "+", "1", ")", ")", ";", "i", "++", ")", "{", "w", "[", "i", "]", "=", "new", "Array", "(", "4", ")", ";", "for", "(", "var", "t", "=", "0", ";", "t", "<", "4", ";", "t", "++", ")", "temp", "[", "t", "]", "=", "w", "[", "i", "-", "1", "]", "[", "t", "]", ";", "if", "(", "i", "%", "Nk", "==", "0", ")", "{", "temp", "=", "subWord", "(", "rotWord", "(", "temp", ")", ")", ";", "for", "(", "var", "t", "=", "0", ";", "t", "<", "4", ";", "t", "++", ")", "temp", "[", "t", "]", "^=", "rCon", "[", "i", "/", "Nk", "]", "[", "t", "]", ";", "}", "else", "if", "(", "Nk", ">", "6", "&&", "i", "%", "Nk", "==", "4", ")", "{", "temp", "=", "subWord", "(", "temp", ")", ";", "}", "for", "(", "var", "t", "=", "0", ";", "t", "<", "4", ";", "t", "++", ")", "w", "[", "i", "]", "[", "t", "]", "=", "w", "[", "i", "-", "Nk", "]", "[", "t", "]", "^", "temp", "[", "t", "]", ";", "}", "return", "w", ";", "}" ]
Perform Key Expansion to generate a Key Schedule @param {Number[]} key Key as 16/24/32-byte array @returns {Number[][]} Expanded key schedule as 2D byte-array (Nr+1 x Nb bytes)
[ "Perform", "Key", "Expansion", "to", "generate", "a", "Key", "Schedule" ]
e57ebece54ee68211d43802a8e0feeef098d3e36
https://github.com/ofidj/fidj/blob/e57ebece54ee68211d43802a8e0feeef098d3e36/.todo/miapp.tools.aes.js#L430-L467
train
jldec/pub-util
pub-util.js
slugify
function slugify(s, opts) { opts = opts || {}; s = str(s); if (!opts.mixedCase) { s = s.toLowerCase(); } return s .replace(/&/g, '-and-') .replace(/\+/g, '-plus-') .replace((opts.allow ? new RegExp('[^-.a-zA-Z0-9' + _.escapeRegExp(opts.allow) + ']+', 'g') : /[^-.a-zA-Z0-9]+/g), '-') .replace(/--+/g, '-') .replace(/^-(.)/, '$1') .replace(/(.)-$/, '$1'); }
javascript
function slugify(s, opts) { opts = opts || {}; s = str(s); if (!opts.mixedCase) { s = s.toLowerCase(); } return s .replace(/&/g, '-and-') .replace(/\+/g, '-plus-') .replace((opts.allow ? new RegExp('[^-.a-zA-Z0-9' + _.escapeRegExp(opts.allow) + ']+', 'g') : /[^-.a-zA-Z0-9]+/g), '-') .replace(/--+/g, '-') .replace(/^-(.)/, '$1') .replace(/(.)-$/, '$1'); }
[ "function", "slugify", "(", "s", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "s", "=", "str", "(", "s", ")", ";", "if", "(", "!", "opts", ".", "mixedCase", ")", "{", "s", "=", "s", ".", "toLowerCase", "(", ")", ";", "}", "return", "s", ".", "replace", "(", "/", "&", "/", "g", ",", "'-and-'", ")", ".", "replace", "(", "/", "\\+", "/", "g", ",", "'-plus-'", ")", ".", "replace", "(", "(", "opts", ".", "allow", "?", "new", "RegExp", "(", "'[^-.a-zA-Z0-9'", "+", "_", ".", "escapeRegExp", "(", "opts", ".", "allow", ")", "+", "']+'", ",", "'g'", ")", ":", "/", "[^-.a-zA-Z0-9]+", "/", "g", ")", ",", "'-'", ")", ".", "replace", "(", "/", "--+", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "^-(.)", "/", ",", "'$1'", ")", ".", "replace", "(", "/", "(.)-$", "/", ",", "'$1'", ")", ";", "}" ]
convert names to slugified url strings containing only - . a-z 0-9 opts.noprefix => remove leading numbers opts.mixedCase => don't lowercase opts.allow => string of additional characters to allow
[ "convert", "names", "to", "slugified", "url", "strings", "containing", "only", "-", ".", "a", "-", "z", "0", "-", "9", "opts", ".", "noprefix", "=", ">", "remove", "leading", "numbers", "opts", ".", "mixedCase", "=", ">", "don", "t", "lowercase", "opts", ".", "allow", "=", ">", "string", "of", "additional", "characters", "to", "allow" ]
18a95ec03e81a70cf34fce4a4467a5a6052d4fce
https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L123-L136
train
jldec/pub-util
pub-util.js
unPrefix
function unPrefix(s, prefix) { s = str(s); if (!prefix) return s; if (s.slice(0, prefix.length) === prefix) return s.slice(prefix.length); return s; }
javascript
function unPrefix(s, prefix) { s = str(s); if (!prefix) return s; if (s.slice(0, prefix.length) === prefix) return s.slice(prefix.length); return s; }
[ "function", "unPrefix", "(", "s", ",", "prefix", ")", "{", "s", "=", "str", "(", "s", ")", ";", "if", "(", "!", "prefix", ")", "return", "s", ";", "if", "(", "s", ".", "slice", "(", "0", ",", "prefix", ".", "length", ")", "===", "prefix", ")", "return", "s", ".", "slice", "(", "prefix", ".", "length", ")", ";", "return", "s", ";", "}" ]
return string minus prefix, if the prefix matches
[ "return", "string", "minus", "prefix", "if", "the", "prefix", "matches" ]
18a95ec03e81a70cf34fce4a4467a5a6052d4fce
https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L168-L173
train
jldec/pub-util
pub-util.js
cap1
function cap1(s) { s = str(s); return s.slice(0,1).toUpperCase() + s.slice(1); }
javascript
function cap1(s) { s = str(s); return s.slice(0,1).toUpperCase() + s.slice(1); }
[ "function", "cap1", "(", "s", ")", "{", "s", "=", "str", "(", "s", ")", ";", "return", "s", ".", "slice", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "s", ".", "slice", "(", "1", ")", ";", "}" ]
return string with first letter capitalized
[ "return", "string", "with", "first", "letter", "capitalized" ]
18a95ec03e81a70cf34fce4a4467a5a6052d4fce
https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L182-L185
train
jldec/pub-util
pub-util.js
csv
function csv(arg) { return ( _.isArray(arg) ? arg : _.isObject(arg) ? _.values(arg) : [arg]).join(', '); }
javascript
function csv(arg) { return ( _.isArray(arg) ? arg : _.isObject(arg) ? _.values(arg) : [arg]).join(', '); }
[ "function", "csv", "(", "arg", ")", "{", "return", "(", "_", ".", "isArray", "(", "arg", ")", "?", "arg", ":", "_", ".", "isObject", "(", "arg", ")", "?", "_", ".", "values", "(", "arg", ")", ":", "[", "arg", "]", ")", ".", "join", "(", "', '", ")", ";", "}" ]
turns a vector into a single string of comma-separated values
[ "turns", "a", "vector", "into", "a", "single", "string", "of", "comma", "-", "separated", "values" ]
18a95ec03e81a70cf34fce4a4467a5a6052d4fce
https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L251-L255
train
andrewscwei/gulp-prismic-mpa-builder
plugins/metadata.js
matchedMetadata
function matchedMetadata(file, metadata) { for (let name in metadata) { const data = metadata[name]; if (!data.pattern) return undefined; if (minimatch(file, data.pattern)) return data.metadata; } return undefined; }
javascript
function matchedMetadata(file, metadata) { for (let name in metadata) { const data = metadata[name]; if (!data.pattern) return undefined; if (minimatch(file, data.pattern)) return data.metadata; } return undefined; }
[ "function", "matchedMetadata", "(", "file", ",", "metadata", ")", "{", "for", "(", "let", "name", "in", "metadata", ")", "{", "const", "data", "=", "metadata", "[", "name", "]", ";", "if", "(", "!", "data", ".", "pattern", ")", "return", "undefined", ";", "if", "(", "minimatch", "(", "file", ",", "data", ".", "pattern", ")", ")", "return", "data", ".", "metadata", ";", "}", "return", "undefined", ";", "}" ]
Checks if the given file matches the pattern in the metadata object and returns the metadata if there is a match. @param {string} file - File path. @param {Object} metadata - Object containing all metadata of all file patterns. @return {Object} Matching metadata.
[ "Checks", "if", "the", "given", "file", "matches", "the", "pattern", "in", "the", "metadata", "object", "and", "returns", "the", "metadata", "if", "there", "is", "a", "match", "." ]
c7fb9180de2aeca2657f0318c0befbd166a9bff5
https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/plugins/metadata.js#L39-L46
train
Runnable/api-client
lib/remove-url-path.js
removeUrlPath
function removeUrlPath (uri) { var parsed = url.parse(uri); if (parsed.host) { delete parsed.pathname; } return url.format(parsed); }
javascript
function removeUrlPath (uri) { var parsed = url.parse(uri); if (parsed.host) { delete parsed.pathname; } return url.format(parsed); }
[ "function", "removeUrlPath", "(", "uri", ")", "{", "var", "parsed", "=", "url", ".", "parse", "(", "uri", ")", ";", "if", "(", "parsed", ".", "host", ")", "{", "delete", "parsed", ".", "pathname", ";", "}", "return", "url", ".", "format", "(", "parsed", ")", ";", "}" ]
remove path from url @param {string} uri full url @return {string} uriWithoutPath
[ "remove", "path", "from", "url" ]
e6089c4ed0b8c6ed383a82cbd50514e1e720f154
https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/remove-url-path.js#L10-L16
train
mozilla/marketplace-gulp
plugins/imgurls-parse.js
transform
function transform(file) { // Parses CSS file and turns it into a \n-separated img URLs. var data = file.contents.toString('utf-8'); var matches = []; var match; while ((match = url_pattern.exec(data)) !== null) { var url = match[1]; // Ensure it is an absolute URL (no relative URLs). var has_origin = url.search(/(https?):|\/\//) === 0 || url[0] === '/'; if (!has_origin) { var absolute_path = path.join(MKT_CONFIG.CSS_DEST_PATH, url); url = '/' + path.relative('src', absolute_path); } if (img_urls.indexOf(url) === -1) { matches.push(url); img_urls.push(url); } } return matches.join('\n'); }
javascript
function transform(file) { // Parses CSS file and turns it into a \n-separated img URLs. var data = file.contents.toString('utf-8'); var matches = []; var match; while ((match = url_pattern.exec(data)) !== null) { var url = match[1]; // Ensure it is an absolute URL (no relative URLs). var has_origin = url.search(/(https?):|\/\//) === 0 || url[0] === '/'; if (!has_origin) { var absolute_path = path.join(MKT_CONFIG.CSS_DEST_PATH, url); url = '/' + path.relative('src', absolute_path); } if (img_urls.indexOf(url) === -1) { matches.push(url); img_urls.push(url); } } return matches.join('\n'); }
[ "function", "transform", "(", "file", ")", "{", "var", "data", "=", "file", ".", "contents", ".", "toString", "(", "'utf-8'", ")", ";", "var", "matches", "=", "[", "]", ";", "var", "match", ";", "while", "(", "(", "match", "=", "url_pattern", ".", "exec", "(", "data", ")", ")", "!==", "null", ")", "{", "var", "url", "=", "match", "[", "1", "]", ";", "var", "has_origin", "=", "url", ".", "search", "(", "/", "(https?):|\\/\\/", "/", ")", "===", "0", "||", "url", "[", "0", "]", "===", "'/'", ";", "if", "(", "!", "has_origin", ")", "{", "var", "absolute_path", "=", "path", ".", "join", "(", "MKT_CONFIG", ".", "CSS_DEST_PATH", ",", "url", ")", ";", "url", "=", "'/'", "+", "path", ".", "relative", "(", "'src'", ",", "absolute_path", ")", ";", "}", "if", "(", "img_urls", ".", "indexOf", "(", "url", ")", "===", "-", "1", ")", "{", "matches", ".", "push", "(", "url", ")", ";", "img_urls", ".", "push", "(", "url", ")", ";", "}", "}", "return", "matches", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Keep track of duplicates.
[ "Keep", "track", "of", "duplicates", "." ]
6c0e405275342edf70bdf265670d64053d1d9a43
https://github.com/mozilla/marketplace-gulp/blob/6c0e405275342edf70bdf265670d64053d1d9a43/plugins/imgurls-parse.js#L12-L35
train
andrewscwei/gulp-prismic-mpa-builder
tasks/views.js
build
function build(config, locale, done) { const shouldWatch = (util.env[`watch`] || util.env[`w`]) && (config.watch !== false); if (locale && config.i18n && (config.i18n.locales instanceof Array) && (locale === config.i18n.locales[0])) locale = undefined; config = normalizeConfig(config, locale); metalsmith(config.base || __dirname) .clean(false) .source(config.src) .ignore(config.ignore) .destination(config.dest) .metadata(config.metadata.global) .use(collections(config.collections)) .use(related(config.related)) .use((config.tags) ? tags(config.tags) : noop()) .use(pagination(config.pagination)) .use(metadata(config.metadata.collections)) .use(markdown(config.markdown)) .use(config.multilingual ? multilingual(locale) : noop()) .use(permalinks(config.permalinks)) .use(pathfinder(locale, config.i18n && config.i18n.locales)) .use(layouts(config.layouts)) .use(inPlace(config.inPlace)) .use((config.prism !== false) ? prism(config.prism, locale) : noop()) .use((config.mathjax !== false) ? mathjax(config.mathjax, locale) : noop()) .use(permalinks(config.permalinks)) .use(reporter(locale)) .build(function(err) { if (err && shouldWatch) util.log(util.colors.blue(`[metalsmith]`), util.colors.red(err)); done(!shouldWatch && err); }); }
javascript
function build(config, locale, done) { const shouldWatch = (util.env[`watch`] || util.env[`w`]) && (config.watch !== false); if (locale && config.i18n && (config.i18n.locales instanceof Array) && (locale === config.i18n.locales[0])) locale = undefined; config = normalizeConfig(config, locale); metalsmith(config.base || __dirname) .clean(false) .source(config.src) .ignore(config.ignore) .destination(config.dest) .metadata(config.metadata.global) .use(collections(config.collections)) .use(related(config.related)) .use((config.tags) ? tags(config.tags) : noop()) .use(pagination(config.pagination)) .use(metadata(config.metadata.collections)) .use(markdown(config.markdown)) .use(config.multilingual ? multilingual(locale) : noop()) .use(permalinks(config.permalinks)) .use(pathfinder(locale, config.i18n && config.i18n.locales)) .use(layouts(config.layouts)) .use(inPlace(config.inPlace)) .use((config.prism !== false) ? prism(config.prism, locale) : noop()) .use((config.mathjax !== false) ? mathjax(config.mathjax, locale) : noop()) .use(permalinks(config.permalinks)) .use(reporter(locale)) .build(function(err) { if (err && shouldWatch) util.log(util.colors.blue(`[metalsmith]`), util.colors.red(err)); done(!shouldWatch && err); }); }
[ "function", "build", "(", "config", ",", "locale", ",", "done", ")", "{", "const", "shouldWatch", "=", "(", "util", ".", "env", "[", "`", "`", "]", "||", "util", ".", "env", "[", "`", "`", "]", ")", "&&", "(", "config", ".", "watch", "!==", "false", ")", ";", "if", "(", "locale", "&&", "config", ".", "i18n", "&&", "(", "config", ".", "i18n", ".", "locales", "instanceof", "Array", ")", "&&", "(", "locale", "===", "config", ".", "i18n", ".", "locales", "[", "0", "]", ")", ")", "locale", "=", "undefined", ";", "config", "=", "normalizeConfig", "(", "config", ",", "locale", ")", ";", "metalsmith", "(", "config", ".", "base", "||", "__dirname", ")", ".", "clean", "(", "false", ")", ".", "source", "(", "config", ".", "src", ")", ".", "ignore", "(", "config", ".", "ignore", ")", ".", "destination", "(", "config", ".", "dest", ")", ".", "metadata", "(", "config", ".", "metadata", ".", "global", ")", ".", "use", "(", "collections", "(", "config", ".", "collections", ")", ")", ".", "use", "(", "related", "(", "config", ".", "related", ")", ")", ".", "use", "(", "(", "config", ".", "tags", ")", "?", "tags", "(", "config", ".", "tags", ")", ":", "noop", "(", ")", ")", ".", "use", "(", "pagination", "(", "config", ".", "pagination", ")", ")", ".", "use", "(", "metadata", "(", "config", ".", "metadata", ".", "collections", ")", ")", ".", "use", "(", "markdown", "(", "config", ".", "markdown", ")", ")", ".", "use", "(", "config", ".", "multilingual", "?", "multilingual", "(", "locale", ")", ":", "noop", "(", ")", ")", ".", "use", "(", "permalinks", "(", "config", ".", "permalinks", ")", ")", ".", "use", "(", "pathfinder", "(", "locale", ",", "config", ".", "i18n", "&&", "config", ".", "i18n", ".", "locales", ")", ")", ".", "use", "(", "layouts", "(", "config", ".", "layouts", ")", ")", ".", "use", "(", "inPlace", "(", "config", ".", "inPlace", ")", ")", ".", "use", "(", "(", "config", ".", "prism", "!==", "false", ")", "?", "prism", "(", "config", ".", "prism", ",", "locale", ")", ":", "noop", "(", ")", ")", ".", "use", "(", "(", "config", ".", "mathjax", "!==", "false", ")", "?", "mathjax", "(", "config", ".", "mathjax", ",", "locale", ")", ":", "noop", "(", ")", ")", ".", "use", "(", "permalinks", "(", "config", ".", "permalinks", ")", ")", ".", "use", "(", "reporter", "(", "locale", ")", ")", ".", "build", "(", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "shouldWatch", ")", "util", ".", "log", "(", "util", ".", "colors", ".", "blue", "(", "`", "`", ")", ",", "util", ".", "colors", ".", "red", "(", "err", ")", ")", ";", "done", "(", "!", "shouldWatch", "&&", "err", ")", ";", "}", ")", ";", "}" ]
Runs Metalsmith build on specified locale. @param {Object} config @param {string} locale @param {Function} done
[ "Runs", "Metalsmith", "build", "on", "specified", "locale", "." ]
c7fb9180de2aeca2657f0318c0befbd166a9bff5
https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/tasks/views.js#L175-L208
train
andrewscwei/gulp-prismic-mpa-builder
tasks/views.js
getDefaults
function getDefaults(context, options) { const defaults = _.cloneDeep(DEFAULT_CONFIG); const taskName = context && context.seq[0]; if (options.src) { if (taskName) defaults.watch = { files: [$.glob(`**/*`, { base: $.glob(options.src, { base: options.base }), exts: FILE_EXTENSIONS })], tasks: [taskName] }; defaults.jade.basedir = $.glob(options.src, { base: options.base }); defaults.pug.basedir = $.glob(options.src, { base: options.base }); defaults.inPlace.engineOptions.basedir = $.glob(options.src, { base: options.base }); } return defaults; }
javascript
function getDefaults(context, options) { const defaults = _.cloneDeep(DEFAULT_CONFIG); const taskName = context && context.seq[0]; if (options.src) { if (taskName) defaults.watch = { files: [$.glob(`**/*`, { base: $.glob(options.src, { base: options.base }), exts: FILE_EXTENSIONS })], tasks: [taskName] }; defaults.jade.basedir = $.glob(options.src, { base: options.base }); defaults.pug.basedir = $.glob(options.src, { base: options.base }); defaults.inPlace.engineOptions.basedir = $.glob(options.src, { base: options.base }); } return defaults; }
[ "function", "getDefaults", "(", "context", ",", "options", ")", "{", "const", "defaults", "=", "_", ".", "cloneDeep", "(", "DEFAULT_CONFIG", ")", ";", "const", "taskName", "=", "context", "&&", "context", ".", "seq", "[", "0", "]", ";", "if", "(", "options", ".", "src", ")", "{", "if", "(", "taskName", ")", "defaults", ".", "watch", "=", "{", "files", ":", "[", "$", ".", "glob", "(", "`", "`", ",", "{", "base", ":", "$", ".", "glob", "(", "options", ".", "src", ",", "{", "base", ":", "options", ".", "base", "}", ")", ",", "exts", ":", "FILE_EXTENSIONS", "}", ")", "]", ",", "tasks", ":", "[", "taskName", "]", "}", ";", "defaults", ".", "jade", ".", "basedir", "=", "$", ".", "glob", "(", "options", ".", "src", ",", "{", "base", ":", "options", ".", "base", "}", ")", ";", "defaults", ".", "pug", ".", "basedir", "=", "$", ".", "glob", "(", "options", ".", "src", ",", "{", "base", ":", "options", ".", "base", "}", ")", ";", "defaults", ".", "inPlace", ".", "engineOptions", ".", "basedir", "=", "$", ".", "glob", "(", "options", ".", "src", ",", "{", "base", ":", "options", ".", "base", "}", ")", ";", "}", "return", "defaults", ";", "}" ]
Gets preprocessed default config. @param {Object} context @param {Object} options @return {Object}
[ "Gets", "preprocessed", "default", "config", "." ]
c7fb9180de2aeca2657f0318c0befbd166a9bff5
https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/tasks/views.js#L218-L235
train
andrewscwei/gulp-prismic-mpa-builder
tasks/views.js
getConfig
function getConfig(context, options, extendsDefaults) { const defaults = getDefaults(context, options); const config = $.config(options, defaults, (typeof extendsDefaults !== `boolean`) || extendsDefaults); config.metadata = { global: config.metadata, collections: { 'error-pages': { pattern: `**/{500,404}.*`, metadata: { permalink: false } } }}; return config; }
javascript
function getConfig(context, options, extendsDefaults) { const defaults = getDefaults(context, options); const config = $.config(options, defaults, (typeof extendsDefaults !== `boolean`) || extendsDefaults); config.metadata = { global: config.metadata, collections: { 'error-pages': { pattern: `**/{500,404}.*`, metadata: { permalink: false } } }}; return config; }
[ "function", "getConfig", "(", "context", ",", "options", ",", "extendsDefaults", ")", "{", "const", "defaults", "=", "getDefaults", "(", "context", ",", "options", ")", ";", "const", "config", "=", "$", ".", "config", "(", "options", ",", "defaults", ",", "(", "typeof", "extendsDefaults", "!==", "`", "`", ")", "||", "extendsDefaults", ")", ";", "config", ".", "metadata", "=", "{", "global", ":", "config", ".", "metadata", ",", "collections", ":", "{", "'error-pages'", ":", "{", "pattern", ":", "`", "`", ",", "metadata", ":", "{", "permalink", ":", "false", "}", "}", "}", "}", ";", "return", "config", ";", "}" ]
Gets postprocessed config. @param {Object} context @param {Object} options @param {boolean} extendsDefaults @return {Object}
[ "Gets", "postprocessed", "config", "." ]
c7fb9180de2aeca2657f0318c0befbd166a9bff5
https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/tasks/views.js#L351-L363
train
taskcluster/pulse-publisher
src/exchanges.js
function(entries, exchangePrefix, connectionFunc, options) { events.EventEmitter.call(this); assert(options.validator, 'options.validator must be provided'); this._conn = null; this.__reconnectTimer = null; this._connectionFunc = connectionFunc; this._channel = null; this._connecting = null; this._entries = entries; this._exchangePrefix = exchangePrefix; this._options = options; this._errCount = 0; this._lastErr = Date.now(); this._lastTime = 0; this._sleeping = null; this._sleepingTimeout = null; if (options.drain || options.component) { console.log('taskcluster-lib-stats is now deprecated!\n' + 'Use the `monitor` option rather than `drain`.\n' + '`monitor` should be an instance of taskcluster-lib-monitor.\n' + '`component` is no longer needed. Prefix your `monitor` before use.'); } var monitor = null; if (options.monitor) { monitor = options.monitor; } entries.forEach((entry) => { this[entry.name] = (...args) => { // Construct message and routing key from arguments var message = entry.messageBuilder.apply(undefined, args); common.validateMessage(this._options.rootUrl, this._options.serviceName, this._options.version, options.validator, entry, message); var routingKey = common.routingKeyToString(entry, entry.routingKeyBuilder.apply(undefined, args)); var CCs = entry.CCBuilder.apply(undefined, args); assert(CCs instanceof Array, 'CCBuilder must return an array'); // Serialize message to buffer var payload = new Buffer(JSON.stringify(message), 'utf8'); // Find exchange name var exchange = exchangePrefix + entry.exchange; // Log that we're publishing a message debug('Publishing message on exchange: %s', exchange); // Return promise return this._connect().then(channel => { return new Promise((accept, reject) => { // Start timer var start = null; if (monitor) { start = process.hrtime(); } // Set a timeout let done = false; this._sleep12Seconds().then(() => { if (!done) { let err = new Error('publish message timed out after 12s'); this._handleError(err); reject(err); } }); // Publish message channel.publish(exchange, routingKey, payload, { persistent: true, contentType: 'application/json', contentEncoding: 'utf-8', CC: CCs, }, (err, val) => { // NOTE: many channel errors will not invoke this callback at all, // hence the 12-second timeout done = true; if (monitor) { var d = process.hrtime(start); monitor.measure(exchange, d[0] * 1000 + d[1] / 1000000); monitor.count(exchange); } // Handle errors if (err) { err.methodName = entry.name; err.exchange = exchange; err.routingKey = routingKey; err.payload = payload; err.ccRoutingKeys = CCs; debug('Failed to publish message: %j and routingKey: %s, ' + 'with error: %s, %j', message, routingKey, err, err); if (monitor) { monitor.reportError(err); } return reject(err); } accept(val); }); }); }); }; }); }
javascript
function(entries, exchangePrefix, connectionFunc, options) { events.EventEmitter.call(this); assert(options.validator, 'options.validator must be provided'); this._conn = null; this.__reconnectTimer = null; this._connectionFunc = connectionFunc; this._channel = null; this._connecting = null; this._entries = entries; this._exchangePrefix = exchangePrefix; this._options = options; this._errCount = 0; this._lastErr = Date.now(); this._lastTime = 0; this._sleeping = null; this._sleepingTimeout = null; if (options.drain || options.component) { console.log('taskcluster-lib-stats is now deprecated!\n' + 'Use the `monitor` option rather than `drain`.\n' + '`monitor` should be an instance of taskcluster-lib-monitor.\n' + '`component` is no longer needed. Prefix your `monitor` before use.'); } var monitor = null; if (options.monitor) { monitor = options.monitor; } entries.forEach((entry) => { this[entry.name] = (...args) => { // Construct message and routing key from arguments var message = entry.messageBuilder.apply(undefined, args); common.validateMessage(this._options.rootUrl, this._options.serviceName, this._options.version, options.validator, entry, message); var routingKey = common.routingKeyToString(entry, entry.routingKeyBuilder.apply(undefined, args)); var CCs = entry.CCBuilder.apply(undefined, args); assert(CCs instanceof Array, 'CCBuilder must return an array'); // Serialize message to buffer var payload = new Buffer(JSON.stringify(message), 'utf8'); // Find exchange name var exchange = exchangePrefix + entry.exchange; // Log that we're publishing a message debug('Publishing message on exchange: %s', exchange); // Return promise return this._connect().then(channel => { return new Promise((accept, reject) => { // Start timer var start = null; if (monitor) { start = process.hrtime(); } // Set a timeout let done = false; this._sleep12Seconds().then(() => { if (!done) { let err = new Error('publish message timed out after 12s'); this._handleError(err); reject(err); } }); // Publish message channel.publish(exchange, routingKey, payload, { persistent: true, contentType: 'application/json', contentEncoding: 'utf-8', CC: CCs, }, (err, val) => { // NOTE: many channel errors will not invoke this callback at all, // hence the 12-second timeout done = true; if (monitor) { var d = process.hrtime(start); monitor.measure(exchange, d[0] * 1000 + d[1] / 1000000); monitor.count(exchange); } // Handle errors if (err) { err.methodName = entry.name; err.exchange = exchange; err.routingKey = routingKey; err.payload = payload; err.ccRoutingKeys = CCs; debug('Failed to publish message: %j and routingKey: %s, ' + 'with error: %s, %j', message, routingKey, err, err); if (monitor) { monitor.reportError(err); } return reject(err); } accept(val); }); }); }); }; }); }
[ "function", "(", "entries", ",", "exchangePrefix", ",", "connectionFunc", ",", "options", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "assert", "(", "options", ".", "validator", ",", "'options.validator must be provided'", ")", ";", "this", ".", "_conn", "=", "null", ";", "this", ".", "__reconnectTimer", "=", "null", ";", "this", ".", "_connectionFunc", "=", "connectionFunc", ";", "this", ".", "_channel", "=", "null", ";", "this", ".", "_connecting", "=", "null", ";", "this", ".", "_entries", "=", "entries", ";", "this", ".", "_exchangePrefix", "=", "exchangePrefix", ";", "this", ".", "_options", "=", "options", ";", "this", ".", "_errCount", "=", "0", ";", "this", ".", "_lastErr", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "_lastTime", "=", "0", ";", "this", ".", "_sleeping", "=", "null", ";", "this", ".", "_sleepingTimeout", "=", "null", ";", "if", "(", "options", ".", "drain", "||", "options", ".", "component", ")", "{", "console", ".", "log", "(", "'taskcluster-lib-stats is now deprecated!\\n'", "+", "\\n", "+", "'Use the `monitor` option rather than `drain`.\\n'", "+", "\\n", ")", ";", "}", "'`monitor` should be an instance of taskcluster-lib-monitor.\\n'", "\\n", "'`component` is no longer needed. Prefix your `monitor` before use.'", "}" ]
Class for publishing to a set of declared exchanges
[ "Class", "for", "publishing", "to", "a", "set", "of", "declared", "exchanges" ]
a2f9afb48bf7b425a460d389e81999b8c9a5c038
https://github.com/taskcluster/pulse-publisher/blob/a2f9afb48bf7b425a460d389e81999b8c9a5c038/src/exchanges.js#L25-L129
train
taskcluster/pulse-publisher
src/exchanges.js
function(options) { this._entries = []; this._options = { durableExchanges: true, }; assert(options.serviceName, 'serviceName must be provided'); assert(options.projectName, 'projectName must be provided'); assert(options.version, 'version must be provided'); assert(options.title, 'title must be provided'); assert(options.description, 'description must be provided'); assert(!options.exchangePrefix, 'exchangePrefix is not allowed'); assert(!options.schemaPrefix, 'schemaPrefix is not allowed'); this.configure(options); }
javascript
function(options) { this._entries = []; this._options = { durableExchanges: true, }; assert(options.serviceName, 'serviceName must be provided'); assert(options.projectName, 'projectName must be provided'); assert(options.version, 'version must be provided'); assert(options.title, 'title must be provided'); assert(options.description, 'description must be provided'); assert(!options.exchangePrefix, 'exchangePrefix is not allowed'); assert(!options.schemaPrefix, 'schemaPrefix is not allowed'); this.configure(options); }
[ "function", "(", "options", ")", "{", "this", ".", "_entries", "=", "[", "]", ";", "this", ".", "_options", "=", "{", "durableExchanges", ":", "true", ",", "}", ";", "assert", "(", "options", ".", "serviceName", ",", "'serviceName must be provided'", ")", ";", "assert", "(", "options", ".", "projectName", ",", "'projectName must be provided'", ")", ";", "assert", "(", "options", ".", "version", ",", "'version must be provided'", ")", ";", "assert", "(", "options", ".", "title", ",", "'title must be provided'", ")", ";", "assert", "(", "options", ".", "description", ",", "'description must be provided'", ")", ";", "assert", "(", "!", "options", ".", "exchangePrefix", ",", "'exchangePrefix is not allowed'", ")", ";", "assert", "(", "!", "options", ".", "schemaPrefix", ",", "'schemaPrefix is not allowed'", ")", ";", "this", ".", "configure", "(", "options", ")", ";", "}" ]
Create a collection of exchange declarations options: { serviceName: 'foo', version: 'v1', title: "Title of documentation page", description: "Description in markdown", durableExchanges: true || false // If exchanges are durable (default true) }
[ "Create", "a", "collection", "of", "exchange", "declarations" ]
a2f9afb48bf7b425a460d389e81999b8c9a5c038
https://github.com/taskcluster/pulse-publisher/blob/a2f9afb48bf7b425a460d389e81999b8c9a5c038/src/exchanges.js#L310-L323
train
LeisureLink/magicbus
lib/config/index.js
LoggerConfiguration
function LoggerConfiguration(logger) { /** * Override default logger instance with the provided logger * @public * @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function */ function useLogger(loggerOrFactoryFunction) { cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction'); if (typeof(loggerOrFactoryFunction) === 'function') { logger = loggerOrFactoryFunction(); } else { logger = loggerOrFactoryFunction; } }; /** * Gets the default or overridden logger * @public */ function getParams() { return { logger }; } return { /** * Gets the target for a configurator function to run on * @public */ getTarget: function() { return { useLogger: useLogger }; }, getParams: getParams }; }
javascript
function LoggerConfiguration(logger) { /** * Override default logger instance with the provided logger * @public * @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function */ function useLogger(loggerOrFactoryFunction) { cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction'); if (typeof(loggerOrFactoryFunction) === 'function') { logger = loggerOrFactoryFunction(); } else { logger = loggerOrFactoryFunction; } }; /** * Gets the default or overridden logger * @public */ function getParams() { return { logger }; } return { /** * Gets the target for a configurator function to run on * @public */ getTarget: function() { return { useLogger: useLogger }; }, getParams: getParams }; }
[ "function", "LoggerConfiguration", "(", "logger", ")", "{", "function", "useLogger", "(", "loggerOrFactoryFunction", ")", "{", "cutil", ".", "assertObjectOrFunction", "(", "loggerOrFactoryFunction", ",", "'loggerOrFactoryFunction'", ")", ";", "if", "(", "typeof", "(", "loggerOrFactoryFunction", ")", "===", "'function'", ")", "{", "logger", "=", "loggerOrFactoryFunction", "(", ")", ";", "}", "else", "{", "logger", "=", "loggerOrFactoryFunction", ";", "}", "}", ";", "function", "getParams", "(", ")", "{", "return", "{", "logger", "}", ";", "}", "return", "{", "getTarget", ":", "function", "(", ")", "{", "return", "{", "useLogger", ":", "useLogger", "}", ";", "}", ",", "getParams", ":", "getParams", "}", ";", "}" ]
Provides logger configurability @private @param {Object} logger - the default logger
[ "Provides", "logger", "configurability" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L28-L63
train
LeisureLink/magicbus
lib/config/index.js
useLogger
function useLogger(loggerOrFactoryFunction) { cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction'); if (typeof(loggerOrFactoryFunction) === 'function') { logger = loggerOrFactoryFunction(); } else { logger = loggerOrFactoryFunction; } }
javascript
function useLogger(loggerOrFactoryFunction) { cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction'); if (typeof(loggerOrFactoryFunction) === 'function') { logger = loggerOrFactoryFunction(); } else { logger = loggerOrFactoryFunction; } }
[ "function", "useLogger", "(", "loggerOrFactoryFunction", ")", "{", "cutil", ".", "assertObjectOrFunction", "(", "loggerOrFactoryFunction", ",", "'loggerOrFactoryFunction'", ")", ";", "if", "(", "typeof", "(", "loggerOrFactoryFunction", ")", "===", "'function'", ")", "{", "logger", "=", "loggerOrFactoryFunction", "(", ")", ";", "}", "else", "{", "logger", "=", "loggerOrFactoryFunction", ";", "}", "}" ]
Override default logger instance with the provided logger @public @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function
[ "Override", "default", "logger", "instance", "with", "the", "provided", "logger" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L34-L43
train
LeisureLink/magicbus
lib/config/index.js
getParams
function getParams(configFunc, configurator) { assert.optionalFunc(configurator, 'configurator'); let config = configFunc(); let loggerConfig = LoggerConfiguration(logger); if (configurator) { let configTarget = _.assign({}, config.getTarget(), loggerConfig.getTarget()); configurator(configTarget); } return _.assign({}, config.getParams(), loggerConfig.getParams()); }
javascript
function getParams(configFunc, configurator) { assert.optionalFunc(configurator, 'configurator'); let config = configFunc(); let loggerConfig = LoggerConfiguration(logger); if (configurator) { let configTarget = _.assign({}, config.getTarget(), loggerConfig.getTarget()); configurator(configTarget); } return _.assign({}, config.getParams(), loggerConfig.getParams()); }
[ "function", "getParams", "(", "configFunc", ",", "configurator", ")", "{", "assert", ".", "optionalFunc", "(", "configurator", ",", "'configurator'", ")", ";", "let", "config", "=", "configFunc", "(", ")", ";", "let", "loggerConfig", "=", "LoggerConfiguration", "(", "logger", ")", ";", "if", "(", "configurator", ")", "{", "let", "configTarget", "=", "_", ".", "assign", "(", "{", "}", ",", "config", ".", "getTarget", "(", ")", ",", "loggerConfig", ".", "getTarget", "(", ")", ")", ";", "configurator", "(", "configTarget", ")", ";", "}", "return", "_", ".", "assign", "(", "{", "}", ",", "config", ".", "getParams", "(", ")", ",", "loggerConfig", ".", "getParams", "(", ")", ")", ";", "}" ]
Gets the parameters for the construction of the instance @private @param {Function} configFunc - the configuration function for the instance @param {Function} configFunc - the configuration function for the instance
[ "Gets", "the", "parameters", "for", "the", "construction", "of", "the", "instance" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L93-L102
train
LeisureLink/magicbus
lib/config/index.js
createTopology
function createTopology(connectionInfo, logger) { let options = connectionInfo; if (typeof(connectionInfo) === 'string') { let parsed = url.parse(connectionInfo); options = { server: parsed.hostname, port: parsed.port || '5672', protocol: parsed.protocol || 'amqp://', user: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[0]) : 'guest', pass: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[1]) : 'guest', vhost: parsed.path && parsed.path.substring(1) }; } let connection = Connection(options, logger.withNamespace('connection')); let topology = Topology(connection, logger.withNamespace('topology')); return topology; }
javascript
function createTopology(connectionInfo, logger) { let options = connectionInfo; if (typeof(connectionInfo) === 'string') { let parsed = url.parse(connectionInfo); options = { server: parsed.hostname, port: parsed.port || '5672', protocol: parsed.protocol || 'amqp://', user: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[0]) : 'guest', pass: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[1]) : 'guest', vhost: parsed.path && parsed.path.substring(1) }; } let connection = Connection(options, logger.withNamespace('connection')); let topology = Topology(connection, logger.withNamespace('topology')); return topology; }
[ "function", "createTopology", "(", "connectionInfo", ",", "logger", ")", "{", "let", "options", "=", "connectionInfo", ";", "if", "(", "typeof", "(", "connectionInfo", ")", "===", "'string'", ")", "{", "let", "parsed", "=", "url", ".", "parse", "(", "connectionInfo", ")", ";", "options", "=", "{", "server", ":", "parsed", ".", "hostname", ",", "port", ":", "parsed", ".", "port", "||", "'5672'", ",", "protocol", ":", "parsed", ".", "protocol", "||", "'amqp://'", ",", "user", ":", "parsed", ".", "auth", "&&", "parsed", ".", "auth", ".", "indexOf", "(", "':'", ")", "!==", "-", "1", "?", "unescape", "(", "parsed", ".", "auth", ".", "split", "(", "':'", ")", "[", "0", "]", ")", ":", "'guest'", ",", "pass", ":", "parsed", ".", "auth", "&&", "parsed", ".", "auth", ".", "indexOf", "(", "':'", ")", "!==", "-", "1", "?", "unescape", "(", "parsed", ".", "auth", ".", "split", "(", "':'", ")", "[", "1", "]", ")", ":", "'guest'", ",", "vhost", ":", "parsed", ".", "path", "&&", "parsed", ".", "path", ".", "substring", "(", "1", ")", "}", ";", "}", "let", "connection", "=", "Connection", "(", "options", ",", "logger", ".", "withNamespace", "(", "'connection'", ")", ")", ";", "let", "topology", "=", "Topology", "(", "connection", ",", "logger", ".", "withNamespace", "(", "'topology'", ")", ")", ";", "return", "topology", ";", "}" ]
Create a Topology instance, for use in broker or binder @public @param {Object|String} connectionInfo - connection info to be passed to amqplib's connect method (required) @param {String} connectionInfo.name - connection name (for logging purposes) @param {String} connectionInfo.server - list of servers to connect to, separated by ',' @param {String} connectionInfo.port - list of ports to connect to, separated by ','. Must have the same number of entries as connectionInfo.server @param {Number} connectionInfo.heartbeat - heartbeat timer - defaults to 30 seconds @param {String} connectionInfo.protocol - connection protocol - defaults to amqp:// or amqps:// @param {String} connectionInfo.user - user name - defaults to guest @param {String} connectionInfo.pass - password - defaults to guest @param {String} connectionInfo.vhost - vhost to connect to - defaults to '/' @param {String} connectionInfo.timeout - connection timeout @param {String} connectionInfo.certPath - certificate file path (for SSL) @param {String} connectionInfo.keyPath - key file path (for SSL) @param {String} connectionInfo.caPath - certificate file path(s), separated by ',' (for SSL) @param {String} connectionInfo.passphrase - certificate passphrase (for SSL) @param {String} connectionInfo.pfxPath - pfx file path (for SSL) @param {Object} logger - the logger to use when creating the connection & topology /* eslint-disable complexity
[ "Create", "a", "Topology", "instance", "for", "use", "in", "broker", "or", "binder" ]
0370c38ebb8c7917cfd3894263d734aefc2d3d29
https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L141-L157
train
andrewscwei/gulp-prismic-mpa-builder
index.js
generatePrismicDocuments
function generatePrismicDocuments(config) { return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken }) .then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`))))) .then(res => { util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`); if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`)); const documents = prismic.reduce(res.results, false, config); // Populate config metadata with retrieved documents. if (!config.metadata) config.metadata = { $data: {} }; _.merge(config.metadata.$data, documents); for (let docType in documents) { const c = _.get(config, `collections.${docType}`); if (c && c.permalink) { const subdir = `.prismic/${docType}`; const dir = path.join(path.join(config.base || ``, config.src || ``), subdir); c.pattern = path.join(subdir, `**/*`); documents[docType].forEach(doc => { const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`; const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`])); fs.mkdirsSync(dir); fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`); }); } } return; }); }
javascript
function generatePrismicDocuments(config) { return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken }) .then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`))))) .then(res => { util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`); if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`)); const documents = prismic.reduce(res.results, false, config); // Populate config metadata with retrieved documents. if (!config.metadata) config.metadata = { $data: {} }; _.merge(config.metadata.$data, documents); for (let docType in documents) { const c = _.get(config, `collections.${docType}`); if (c && c.permalink) { const subdir = `.prismic/${docType}`; const dir = path.join(path.join(config.base || ``, config.src || ``), subdir); c.pattern = path.join(subdir, `**/*`); documents[docType].forEach(doc => { const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`; const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`])); fs.mkdirsSync(dir); fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`); }); } } return; }); }
[ "function", "generatePrismicDocuments", "(", "config", ")", "{", "return", "prismic", ".", "getAPI", "(", "config", ".", "apiEndpoint", ",", "{", "accessToken", ":", "config", ".", "accessToken", "}", ")", ".", "then", "(", "api", "=>", "(", "prismic", ".", "getEverything", "(", "api", ",", "null", ",", "`", "`", ",", "_", ".", "flatMap", "(", "config", ".", "collections", ",", "(", "val", ",", "key", ")", "=>", "(", "`", "${", "key", "}", "${", "val", ".", "sortBy", "}", "${", "val", ".", "reverse", "?", "`", "`", ":", "`", "`", "}", "`", ")", ")", ")", ")", ")", ".", "then", "(", "res", "=>", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "blue", "(", "`", "`", ")", ",", "`", "${", "res", ".", "results", ".", "length", "}", "`", ")", ";", "if", "(", "res", ".", "results", ".", "length", ")", "res", ".", "results", ".", "forEach", "(", "doc", "=>", "util", ".", "log", "(", "util", ".", "colors", ".", "blue", "(", "`", "`", ")", ",", "`", "${", "doc", ".", "type", "}", "${", "doc", ".", "slug", "}", "`", ")", ")", ";", "const", "documents", "=", "prismic", ".", "reduce", "(", "res", ".", "results", ",", "false", ",", "config", ")", ";", "if", "(", "!", "config", ".", "metadata", ")", "config", ".", "metadata", "=", "{", "$data", ":", "{", "}", "}", ";", "_", ".", "merge", "(", "config", ".", "metadata", ".", "$data", ",", "documents", ")", ";", "for", "(", "let", "docType", "in", "documents", ")", "{", "const", "c", "=", "_", ".", "get", "(", "config", ",", "`", "${", "docType", "}", "`", ")", ";", "if", "(", "c", "&&", "c", ".", "permalink", ")", "{", "const", "subdir", "=", "`", "${", "docType", "}", "`", ";", "const", "dir", "=", "path", ".", "join", "(", "path", ".", "join", "(", "config", ".", "base", "||", "`", "`", ",", "config", ".", "src", "||", "`", "`", ")", ",", "subdir", ")", ";", "c", ".", "pattern", "=", "path", ".", "join", "(", "subdir", ",", "`", "`", ")", ";", "documents", "[", "docType", "]", ".", "forEach", "(", "doc", "=>", "{", "const", "filename", "=", "`", "${", "doc", ".", "uid", "||", "_", ".", "kebabCase", "(", "doc", ".", "slug", ")", "}", "`", ";", "const", "frontMatter", "=", "yaml", ".", "stringify", "(", "_", ".", "omit", "(", "doc", ",", "[", "`", "`", ",", "`", "`", "]", ")", ")", ";", "fs", ".", "mkdirsSync", "(", "dir", ")", ";", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "dir", ",", "filename", ")", ",", "`", "\\n", "${", "frontMatter", "}", "\\n", "`", ")", ";", "}", ")", ";", "}", "}", "return", ";", "}", ")", ";", "}" ]
Generates HTML files with YAML front matters from Prismic documents. @param {Object} config - Config object. @return {Promise} - Promise with no fulfillment value.
[ "Generates", "HTML", "files", "with", "YAML", "front", "matters", "from", "Prismic", "documents", "." ]
c7fb9180de2aeca2657f0318c0befbd166a9bff5
https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/index.js#L276-L307
train
veo-labs/openveo-api
lib/imageProcessor.js
function(linesImagesPaths, linePath, lineWidth, lineHeight, horizontally, lineQuality) { return function(callback) { self.aggregate( linesImagesPaths, linePath, lineWidth, lineHeight, horizontally, lineQuality, temporaryDirectoryPath, callback ); }; }
javascript
function(linesImagesPaths, linePath, lineWidth, lineHeight, horizontally, lineQuality) { return function(callback) { self.aggregate( linesImagesPaths, linePath, lineWidth, lineHeight, horizontally, lineQuality, temporaryDirectoryPath, callback ); }; }
[ "function", "(", "linesImagesPaths", ",", "linePath", ",", "lineWidth", ",", "lineHeight", ",", "horizontally", ",", "lineQuality", ")", "{", "return", "function", "(", "callback", ")", "{", "self", ".", "aggregate", "(", "linesImagesPaths", ",", "linePath", ",", "lineWidth", ",", "lineHeight", ",", "horizontally", ",", "lineQuality", ",", "temporaryDirectoryPath", ",", "callback", ")", ";", "}", ";", "}" ]
Creates sprite lines by aggregating images. @param {Array} linesImagesPaths The list of images paths to aggregate @param {String} linePath The path of the image to generate @param {Number} lineWidth The line width (in px) @param {Number} lineHeight The line height (in px) @param {Boolean} horizontally true to create an horizontal line, false to create a vertical line @param {Number} lineQuality The line quality from 0 to 100 (default to 90 with 100 the best) @return {Function} The async function of the operation
[ "Creates", "sprite", "lines", "by", "aggregating", "images", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L258-L271
train
veo-labs/openveo-api
lib/imageProcessor.js
function(callback) { if (imagesPaths.length >= numberOfColumns * numberOfRows) return callback(); var transparentImagePath = path.join(temporaryDirectoryPath, 'transparent.png'); gm(width, height, '#00000000').write(transparentImagePath, function(error) { // Add as many as needed transparent images to the list of images var totalMissingImages = numberOfColumns * numberOfRows - imagesPaths.length; for (var i = 0; i < totalMissingImages; i++) imagesPaths.push(transparentImagePath); callback(error); }); }
javascript
function(callback) { if (imagesPaths.length >= numberOfColumns * numberOfRows) return callback(); var transparentImagePath = path.join(temporaryDirectoryPath, 'transparent.png'); gm(width, height, '#00000000').write(transparentImagePath, function(error) { // Add as many as needed transparent images to the list of images var totalMissingImages = numberOfColumns * numberOfRows - imagesPaths.length; for (var i = 0; i < totalMissingImages; i++) imagesPaths.push(transparentImagePath); callback(error); }); }
[ "function", "(", "callback", ")", "{", "if", "(", "imagesPaths", ".", "length", ">=", "numberOfColumns", "*", "numberOfRows", ")", "return", "callback", "(", ")", ";", "var", "transparentImagePath", "=", "path", ".", "join", "(", "temporaryDirectoryPath", ",", "'transparent.png'", ")", ";", "gm", "(", "width", ",", "height", ",", "'#00000000'", ")", ".", "write", "(", "transparentImagePath", ",", "function", "(", "error", ")", "{", "var", "totalMissingImages", "=", "numberOfColumns", "*", "numberOfRows", "-", "imagesPaths", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "totalMissingImages", ";", "i", "++", ")", "imagesPaths", ".", "push", "(", "transparentImagePath", ")", ";", "callback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Complete the grid defined by numberOfColumns and numberOfRows using transparent images if needed
[ "Complete", "the", "grid", "defined", "by", "numberOfColumns", "and", "numberOfRows", "using", "transparent", "images", "if", "needed" ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L290-L304
train
veo-labs/openveo-api
lib/imageProcessor.js
function(callback) { var asyncFunctions = []; for (var i = 0; i < numberOfRows; i++) { var rowsImagesPaths = imagesPaths.slice(i * numberOfColumns, i * numberOfColumns + numberOfColumns); var lineWidth = width; var lineHeight = height; var linePath = path.join(temporaryDirectoryPath, 'line-' + i); linesPaths.push(linePath); asyncFunctions.push(createLine(rowsImagesPaths, linePath, lineWidth, lineHeight, true, 100)); } async.parallel(asyncFunctions, function(error, results) { if (error) return callback(error); results.forEach(function(line) { line.forEach(function(image) { if (image.image === path.join(temporaryDirectoryPath, 'transparent.png')) return; var spritePathChunks = path.parse(image.sprite).name.match(/-([0-9]+)$/); var lineIndex = (spritePathChunks && parseInt(spritePathChunks[1])) || 0; image.y = image.y + (lineIndex * height); image.sprite = destinationPath; images.push(image); }); }); callback(); }); }
javascript
function(callback) { var asyncFunctions = []; for (var i = 0; i < numberOfRows; i++) { var rowsImagesPaths = imagesPaths.slice(i * numberOfColumns, i * numberOfColumns + numberOfColumns); var lineWidth = width; var lineHeight = height; var linePath = path.join(temporaryDirectoryPath, 'line-' + i); linesPaths.push(linePath); asyncFunctions.push(createLine(rowsImagesPaths, linePath, lineWidth, lineHeight, true, 100)); } async.parallel(asyncFunctions, function(error, results) { if (error) return callback(error); results.forEach(function(line) { line.forEach(function(image) { if (image.image === path.join(temporaryDirectoryPath, 'transparent.png')) return; var spritePathChunks = path.parse(image.sprite).name.match(/-([0-9]+)$/); var lineIndex = (spritePathChunks && parseInt(spritePathChunks[1])) || 0; image.y = image.y + (lineIndex * height); image.sprite = destinationPath; images.push(image); }); }); callback(); }); }
[ "function", "(", "callback", ")", "{", "var", "asyncFunctions", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numberOfRows", ";", "i", "++", ")", "{", "var", "rowsImagesPaths", "=", "imagesPaths", ".", "slice", "(", "i", "*", "numberOfColumns", ",", "i", "*", "numberOfColumns", "+", "numberOfColumns", ")", ";", "var", "lineWidth", "=", "width", ";", "var", "lineHeight", "=", "height", ";", "var", "linePath", "=", "path", ".", "join", "(", "temporaryDirectoryPath", ",", "'line-'", "+", "i", ")", ";", "linesPaths", ".", "push", "(", "linePath", ")", ";", "asyncFunctions", ".", "push", "(", "createLine", "(", "rowsImagesPaths", ",", "linePath", ",", "lineWidth", ",", "lineHeight", ",", "true", ",", "100", ")", ")", ";", "}", "async", ".", "parallel", "(", "asyncFunctions", ",", "function", "(", "error", ",", "results", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", ";", "results", ".", "forEach", "(", "function", "(", "line", ")", "{", "line", ".", "forEach", "(", "function", "(", "image", ")", "{", "if", "(", "image", ".", "image", "===", "path", ".", "join", "(", "temporaryDirectoryPath", ",", "'transparent.png'", ")", ")", "return", ";", "var", "spritePathChunks", "=", "path", ".", "parse", "(", "image", ".", "sprite", ")", ".", "name", ".", "match", "(", "/", "-([0-9]+)$", "/", ")", ";", "var", "lineIndex", "=", "(", "spritePathChunks", "&&", "parseInt", "(", "spritePathChunks", "[", "1", "]", ")", ")", "||", "0", ";", "image", ".", "y", "=", "image", ".", "y", "+", "(", "lineIndex", "*", "height", ")", ";", "image", ".", "sprite", "=", "destinationPath", ";", "images", ".", "push", "(", "image", ")", ";", "}", ")", ";", "}", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Create sprite horizontal lines
[ "Create", "sprite", "horizontal", "lines" ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L307-L338
train
veo-labs/openveo-api
lib/imageProcessor.js
function(callback) { createLine(linesPaths, destinationPath, width * numberOfColumns, height, false, quality)(callback); }
javascript
function(callback) { createLine(linesPaths, destinationPath, width * numberOfColumns, height, false, quality)(callback); }
[ "function", "(", "callback", ")", "{", "createLine", "(", "linesPaths", ",", "destinationPath", ",", "width", "*", "numberOfColumns", ",", "height", ",", "false", ",", "quality", ")", "(", "callback", ")", ";", "}" ]
Aggregate lines vertically
[ "Aggregate", "lines", "vertically" ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L341-L343
train
veo-labs/openveo-api
lib/imageProcessor.js
function(spriteImagesPaths, spriteDestinationPath) { return function(callback) { self.generateSprite( spriteImagesPaths, spriteDestinationPath, width, height, totalColumns, maxRows, quality, temporaryDirectoryPath, callback ); }; }
javascript
function(spriteImagesPaths, spriteDestinationPath) { return function(callback) { self.generateSprite( spriteImagesPaths, spriteDestinationPath, width, height, totalColumns, maxRows, quality, temporaryDirectoryPath, callback ); }; }
[ "function", "(", "spriteImagesPaths", ",", "spriteDestinationPath", ")", "{", "return", "function", "(", "callback", ")", "{", "self", ".", "generateSprite", "(", "spriteImagesPaths", ",", "spriteDestinationPath", ",", "width", ",", "height", ",", "totalColumns", ",", "maxRows", ",", "quality", ",", "temporaryDirectoryPath", ",", "callback", ")", ";", "}", ";", "}" ]
Creates a sprite. @param {Array} spriteImagesPaths The list of images to include in the sprite @param {String} spriteDestinationPath The sprite path @return {Function} The async function of the operation
[ "Creates", "a", "sprite", "." ]
493a811e9a5ba4d3e14910facaa7452caba1ab38
https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L400-L414
train
j-/ok
ok.js
function () { var properties = this.properties; _.forEach(properties, function (prop, name) { prop = this.getProperty(name); this.stopListening(prop, EVENT_CHANGE); }, this); }
javascript
function () { var properties = this.properties; _.forEach(properties, function (prop, name) { prop = this.getProperty(name); this.stopListening(prop, EVENT_CHANGE); }, this); }
[ "function", "(", ")", "{", "var", "properties", "=", "this", ".", "properties", ";", "_", ".", "forEach", "(", "properties", ",", "function", "(", "prop", ",", "name", ")", "{", "prop", "=", "this", ".", "getProperty", "(", "name", ")", ";", "this", ".", "stopListening", "(", "prop", ",", "EVENT_CHANGE", ")", ";", "}", ",", "this", ")", ";", "}" ]
Remove all events listeners @deprecated Use {@link #stopListening} (with no arguments) instead
[ "Remove", "all", "events", "listeners" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L796-L802
train
j-/ok
ok.js
function (properties) { properties = properties || {}; _.forEach(properties, function (property, name) { this.initProperty(name, property); }, this); }
javascript
function (properties) { properties = properties || {}; _.forEach(properties, function (property, name) { this.initProperty(name, property); }, this); }
[ "function", "(", "properties", ")", "{", "properties", "=", "properties", "||", "{", "}", ";", "_", ".", "forEach", "(", "properties", ",", "function", "(", "property", ",", "name", ")", "{", "this", ".", "initProperty", "(", "name", ",", "property", ")", ";", "}", ",", "this", ")", ";", "}" ]
Declare the values of a hash of properties @param {Object} properties Hash of properties and values
[ "Declare", "the", "values", "of", "a", "hash", "of", "properties" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L820-L825
train
j-/ok
ok.js
function (name, value) { var prop = this.getProperty(name); var Constructor; if (!prop) { Constructor = this.getConstructor(name, value); prop = new Constructor(); prop = this.setProperty(name, prop); } if (typeof value !== 'undefined') { prop.set(value); } return prop; }
javascript
function (name, value) { var prop = this.getProperty(name); var Constructor; if (!prop) { Constructor = this.getConstructor(name, value); prop = new Constructor(); prop = this.setProperty(name, prop); } if (typeof value !== 'undefined') { prop.set(value); } return prop; }
[ "function", "(", "name", ",", "value", ")", "{", "var", "prop", "=", "this", ".", "getProperty", "(", "name", ")", ";", "var", "Constructor", ";", "if", "(", "!", "prop", ")", "{", "Constructor", "=", "this", ".", "getConstructor", "(", "name", ",", "value", ")", ";", "prop", "=", "new", "Constructor", "(", ")", ";", "prop", "=", "this", ".", "setProperty", "(", "name", ",", "prop", ")", ";", "}", "if", "(", "typeof", "value", "!==", "'undefined'", ")", "{", "prop", ".", "set", "(", "value", ")", ";", "}", "return", "prop", ";", "}" ]
Declare the value of a single property @param {string} name Property name @param {*} value Property value @return {module:ok.Property} New property instance
[ "Declare", "the", "value", "of", "a", "single", "property" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L832-L844
train
j-/ok
ok.js
function (name) { var args = arguments; var len = args.length; if (len === 0) { return this.getMap(); } else if (len === 1) { return this.getValue(name); } else { return this.getValues.apply(this, args); } }
javascript
function (name) { var args = arguments; var len = args.length; if (len === 0) { return this.getMap(); } else if (len === 1) { return this.getValue(name); } else { return this.getValues.apply(this, args); } }
[ "function", "(", "name", ")", "{", "var", "args", "=", "arguments", ";", "var", "len", "=", "args", ".", "length", ";", "if", "(", "len", "===", "0", ")", "{", "return", "this", ".", "getMap", "(", ")", ";", "}", "else", "if", "(", "len", "===", "1", ")", "{", "return", "this", ".", "getValue", "(", "name", ")", ";", "}", "else", "{", "return", "this", ".", "getValues", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "}" ]
Get the values of one or more properties @param {...string=} name Optional property names. If omitted, a map of all properties will be returned. If one property name is given then the value of that property will be returned. Otherwise, if more than one property name is given, the values of those properties will be returned as an array. @return {Object|Array|*} Result of the get operation depending on the number of property names given.
[ "Get", "the", "values", "of", "one", "or", "more", "properties" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L875-L887
train
j-/ok
ok.js
function () { var map = this.properties; var pairs = _.map(map, function (prop, name) { return [name, prop.get()]; }); var result = _.object(pairs); return result; }
javascript
function () { var map = this.properties; var pairs = _.map(map, function (prop, name) { return [name, prop.get()]; }); var result = _.object(pairs); return result; }
[ "function", "(", ")", "{", "var", "map", "=", "this", ".", "properties", ";", "var", "pairs", "=", "_", ".", "map", "(", "map", ",", "function", "(", "prop", ",", "name", ")", "{", "return", "[", "name", ",", "prop", ".", "get", "(", ")", "]", ";", "}", ")", ";", "var", "result", "=", "_", ".", "object", "(", "pairs", ")", ";", "return", "result", ";", "}" ]
Get the values of all properties @return {Object} Map of all properties. Each property has had its `get` function invoked.
[ "Get", "the", "values", "of", "all", "properties" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L893-L900
train
j-/ok
ok.js
function () { var result = []; var args = arguments; var l = args.length; var name, value; for (var i = 0; i < l; i++) { name = args[i]; value = this.getValue(name); result.push(value); } return result; }
javascript
function () { var result = []; var args = arguments; var l = args.length; var name, value; for (var i = 0; i < l; i++) { name = args[i]; value = this.getValue(name); result.push(value); } return result; }
[ "function", "(", ")", "{", "var", "result", "=", "[", "]", ";", "var", "args", "=", "arguments", ";", "var", "l", "=", "args", ".", "length", ";", "var", "name", ",", "value", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "name", "=", "args", "[", "i", "]", ";", "value", "=", "this", ".", "getValue", "(", "name", ")", ";", "result", ".", "push", "(", "value", ")", ";", "}", "return", "result", ";", "}" ]
Get the value of multiple properties @param {...string} names Property names @return {Array} Array of values from each property's `get` function
[ "Get", "the", "value", "of", "multiple", "properties" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L915-L926
train
j-/ok
ok.js
function (name, newValue) { if (arguments.length > 1) { this.setValue(name, newValue); } else { var attrs = name; this.setMap(attrs); } }
javascript
function (name, newValue) { if (arguments.length > 1) { this.setValue(name, newValue); } else { var attrs = name; this.setMap(attrs); } }
[ "function", "(", "name", ",", "newValue", ")", "{", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "this", ".", "setValue", "(", "name", ",", "newValue", ")", ";", "}", "else", "{", "var", "attrs", "=", "name", ";", "this", ".", "setMap", "(", "attrs", ")", ";", "}", "}" ]
Set the value of one or more properties @method module:ok.Map#set @param {Object} attrs Hash of property names and values to set Set the value of a single property @param {string} name Property name @param {*} newValue Property value
[ "Set", "the", "value", "of", "one", "or", "more", "properties" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L953-L961
train
j-/ok
ok.js
function (attrs) { attrs = attrs || {}; _.forEach(attrs, function (val, name) { this.setValue(name, val); }, this); }
javascript
function (attrs) { attrs = attrs || {}; _.forEach(attrs, function (val, name) { this.setValue(name, val); }, this); }
[ "function", "(", "attrs", ")", "{", "attrs", "=", "attrs", "||", "{", "}", ";", "_", ".", "forEach", "(", "attrs", ",", "function", "(", "val", ",", "name", ")", "{", "this", ".", "setValue", "(", "name", ",", "val", ")", ";", "}", ",", "this", ")", ";", "}" ]
Set values of properties using an object @param {Object} attrs Hash of property names and values to set
[ "Set", "values", "of", "properties", "using", "an", "object" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L966-L971
train
j-/ok
ok.js
function (name, newValue) { var property = this.getProperty(name); if (!property) { this.initProperty(name, newValue); } else { property.set(newValue); } }
javascript
function (name, newValue) { var property = this.getProperty(name); if (!property) { this.initProperty(name, newValue); } else { property.set(newValue); } }
[ "function", "(", "name", ",", "newValue", ")", "{", "var", "property", "=", "this", ".", "getProperty", "(", "name", ")", ";", "if", "(", "!", "property", ")", "{", "this", ".", "initProperty", "(", "name", ",", "newValue", ")", ";", "}", "else", "{", "property", ".", "set", "(", "newValue", ")", ";", "}", "}" ]
Set the value of a single property @param {string} name Property name @param {*} newValue Property value
[ "Set", "the", "value", "of", "a", "single", "property" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L977-L985
train
j-/ok
ok.js
function (name, prop) { this.unsetProperty(name); this.properties[name] = prop; this.listenTo(prop, EVENT_CHANGE, this.change); return prop; }
javascript
function (name, prop) { this.unsetProperty(name); this.properties[name] = prop; this.listenTo(prop, EVENT_CHANGE, this.change); return prop; }
[ "function", "(", "name", ",", "prop", ")", "{", "this", ".", "unsetProperty", "(", "name", ")", ";", "this", ".", "properties", "[", "name", "]", "=", "prop", ";", "this", ".", "listenTo", "(", "prop", ",", "EVENT_CHANGE", ",", "this", ".", "change", ")", ";", "return", "prop", ";", "}" ]
Set a single property to a new value @param {string} name Property name @param {module:ok.Property} prop Property object @return {module:ok.Property} The new property
[ "Set", "a", "single", "property", "to", "a", "new", "value" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L992-L997
train
j-/ok
ok.js
function (name) { var prop = this.properties[name]; if (prop) { this.stopListening(prop, EVENT_CHANGE, this.change); delete this.properties[name]; return prop; } return null; }
javascript
function (name) { var prop = this.properties[name]; if (prop) { this.stopListening(prop, EVENT_CHANGE, this.change); delete this.properties[name]; return prop; } return null; }
[ "function", "(", "name", ")", "{", "var", "prop", "=", "this", ".", "properties", "[", "name", "]", ";", "if", "(", "prop", ")", "{", "this", ".", "stopListening", "(", "prop", ",", "EVENT_CHANGE", ",", "this", ".", "change", ")", ";", "delete", "this", ".", "properties", "[", "name", "]", ";", "return", "prop", ";", "}", "return", "null", ";", "}" ]
Remove a single property from the map @param {String} name Property name @return {?module:ok.Property} Removed property or `null`
[ "Remove", "a", "single", "property", "from", "the", "map" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1003-L1011
train
j-/ok
ok.js
function (/* items... */) { var items = slice(arguments); var item; for (var i = 0, l = items.length; i < l; i++) { item = items[i]; $Array.push.call(this, item); this.trigger(EVENT_ADD, item, this.length); } return this.length; }
javascript
function (/* items... */) { var items = slice(arguments); var item; for (var i = 0, l = items.length; i < l; i++) { item = items[i]; $Array.push.call(this, item); this.trigger(EVENT_ADD, item, this.length); } return this.length; }
[ "function", "(", ")", "{", "var", "items", "=", "slice", "(", "arguments", ")", ";", "var", "item", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "items", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "item", "=", "items", "[", "i", "]", ";", "$Array", ".", "push", ".", "call", "(", "this", ",", "item", ")", ";", "this", ".", "trigger", "(", "EVENT_ADD", ",", "item", ",", "this", ".", "length", ")", ";", "}", "return", "this", ".", "length", ";", "}" ]
Push new items to the top of the stack @param {...*} New items to push @return {int} New length after items have been pushed @fires add
[ "Push", "new", "items", "to", "the", "top", "of", "the", "stack" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1046-L1055
train
j-/ok
ok.js
function (start, length) { var removed, item; if (arguments.length < 1) { start = 0; } if (arguments.length < 2) { length = this.length - start; } removed = []; while (start < this.length && length-- > 0) { item = this[start]; $Array.splice.call(this, start, 1); this.trigger(EVENT_REMOVE, item); removed.push(item); } return removed; }
javascript
function (start, length) { var removed, item; if (arguments.length < 1) { start = 0; } if (arguments.length < 2) { length = this.length - start; } removed = []; while (start < this.length && length-- > 0) { item = this[start]; $Array.splice.call(this, start, 1); this.trigger(EVENT_REMOVE, item); removed.push(item); } return removed; }
[ "function", "(", "start", ",", "length", ")", "{", "var", "removed", ",", "item", ";", "if", "(", "arguments", ".", "length", "<", "1", ")", "{", "start", "=", "0", ";", "}", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "length", "=", "this", ".", "length", "-", "start", ";", "}", "removed", "=", "[", "]", ";", "while", "(", "start", "<", "this", ".", "length", "&&", "length", "--", ">", "0", ")", "{", "item", "=", "this", "[", "start", "]", ";", "$Array", ".", "splice", ".", "call", "(", "this", ",", "start", ",", "1", ")", ";", "this", ".", "trigger", "(", "EVENT_REMOVE", ",", "item", ")", ";", "removed", ".", "push", "(", "item", ")", ";", "}", "return", "removed", ";", "}" ]
Remove items from the array @param {int=} start Start index. If omitted, will start at 0. @param {int=} length Number of items to remove. If omitted, will remove all items until the end of the array. @return {Array} Collection of removed items @fires remove
[ "Remove", "items", "from", "the", "array" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1122-L1138
train
j-/ok
ok.js
function (start/*, items... */) { var items = slice(arguments, 1); var item, index; for (var i = 0, l = items.length; i < l; i++) { item = items[i]; index = start + i; $Array.splice.call(this, index, 0, item); this.trigger(EVENT_ADD, item, index); } return this.length; }
javascript
function (start/*, items... */) { var items = slice(arguments, 1); var item, index; for (var i = 0, l = items.length; i < l; i++) { item = items[i]; index = start + i; $Array.splice.call(this, index, 0, item); this.trigger(EVENT_ADD, item, index); } return this.length; }
[ "function", "(", "start", ")", "{", "var", "items", "=", "slice", "(", "arguments", ",", "1", ")", ";", "var", "item", ",", "index", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "items", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "item", "=", "items", "[", "i", "]", ";", "index", "=", "start", "+", "i", ";", "$Array", ".", "splice", ".", "call", "(", "this", ",", "index", ",", "0", ",", "item", ")", ";", "this", ".", "trigger", "(", "EVENT_ADD", ",", "item", ",", "index", ")", ";", "}", "return", "this", ".", "length", ";", "}" ]
Insert items into the array @param {int} start Starting index @param {...*} items New items to insert @return {int} New length after items have been added @fires add
[ "Insert", "items", "into", "the", "array" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1155-L1165
train
j-/ok
ok.js
function (items) { var args = slice(items); args.unshift(0); this.empty(); this.insert.apply(this, args); return this.length; }
javascript
function (items) { var args = slice(items); args.unshift(0); this.empty(); this.insert.apply(this, args); return this.length; }
[ "function", "(", "items", ")", "{", "var", "args", "=", "slice", "(", "items", ")", ";", "args", ".", "unshift", "(", "0", ")", ";", "this", ".", "empty", "(", ")", ";", "this", ".", "insert", ".", "apply", "(", "this", ",", "args", ")", ";", "return", "this", ".", "length", ";", "}" ]
Set the contents of this array. Empties it first. @param {Array} items New contents of array @return {int} New length after items have been added @fires remove @fires add
[ "Set", "the", "contents", "of", "this", "array", ".", "Empties", "it", "first", "." ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1173-L1179
train
j-/ok
ok.js
function (index) { if (arguments.length < 1) { return this; } if (index < 0) { index = this.length + index; } if (hasProperty(this, index)) { return this[index]; } return null; }
javascript
function (index) { if (arguments.length < 1) { return this; } if (index < 0) { index = this.length + index; } if (hasProperty(this, index)) { return this[index]; } return null; }
[ "function", "(", "index", ")", "{", "if", "(", "arguments", ".", "length", "<", "1", ")", "{", "return", "this", ";", "}", "if", "(", "index", "<", "0", ")", "{", "index", "=", "this", ".", "length", "+", "index", ";", "}", "if", "(", "hasProperty", "(", "this", ",", "index", ")", ")", "{", "return", "this", "[", "index", "]", ";", "}", "return", "null", ";", "}" ]
Get the item at a given index. Can be negative. If no index is given, a reference to the array will be returned. @param {int=} Index of item to get @return {?ok.Items|*} Item at given index or whole array
[ "Get", "the", "item", "at", "a", "given", "index", ".", "Can", "be", "negative", ".", "If", "no", "index", "is", "given", "a", "reference", "to", "the", "array", "will", "be", "returned", "." ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1186-L1197
train
j-/ok
ok.js
Collection
function Collection (items) { this.items = new ok.Items(); this.start(); if (items) { this.add(items); } this.init(); }
javascript
function Collection (items) { this.items = new ok.Items(); this.start(); if (items) { this.add(items); } this.init(); }
[ "function", "Collection", "(", "items", ")", "{", "this", ".", "items", "=", "new", "ok", ".", "Items", "(", ")", ";", "this", ".", "start", "(", ")", ";", "if", "(", "items", ")", "{", "this", ".", "add", "(", "items", ")", ";", "}", "this", ".", "init", "(", ")", ";", "}" ]
Initialize with items
[ "Initialize", "with", "items" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1280-L1287
train
j-/ok
ok.js
function () { this.stop(); this.listenTo(this.items, EVENT_ADD, this.triggerAdd); this.listenTo(this.items, EVENT_REMOVE, this.triggerRemove); this.listenTo(this.items, EVENT_SORT, this.triggerSort); this.listenTo(this.items, EVENT_ADD, this.updateLength); this.listenTo(this.items, EVENT_REMOVE, this.updateLength); this.listenTo(this.items, EVENT_ADD, this.watchItem); this.listenTo(this.items, EVENT_REMOVE, this.unwatchItem); }
javascript
function () { this.stop(); this.listenTo(this.items, EVENT_ADD, this.triggerAdd); this.listenTo(this.items, EVENT_REMOVE, this.triggerRemove); this.listenTo(this.items, EVENT_SORT, this.triggerSort); this.listenTo(this.items, EVENT_ADD, this.updateLength); this.listenTo(this.items, EVENT_REMOVE, this.updateLength); this.listenTo(this.items, EVENT_ADD, this.watchItem); this.listenTo(this.items, EVENT_REMOVE, this.unwatchItem); }
[ "function", "(", ")", "{", "this", ".", "stop", "(", ")", ";", "this", ".", "listenTo", "(", "this", ".", "items", ",", "EVENT_ADD", ",", "this", ".", "triggerAdd", ")", ";", "this", ".", "listenTo", "(", "this", ".", "items", ",", "EVENT_REMOVE", ",", "this", ".", "triggerRemove", ")", ";", "this", ".", "listenTo", "(", "this", ".", "items", ",", "EVENT_SORT", ",", "this", ".", "triggerSort", ")", ";", "this", ".", "listenTo", "(", "this", ".", "items", ",", "EVENT_ADD", ",", "this", ".", "updateLength", ")", ";", "this", ".", "listenTo", "(", "this", ".", "items", ",", "EVENT_REMOVE", ",", "this", ".", "updateLength", ")", ";", "this", ".", "listenTo", "(", "this", ".", "items", ",", "EVENT_ADD", ",", "this", ".", "watchItem", ")", ";", "this", ".", "listenTo", "(", "this", ".", "items", ",", "EVENT_REMOVE", ",", "this", ".", "unwatchItem", ")", ";", "}" ]
Begin listening to changes on the internal items storage array
[ "Begin", "listening", "to", "changes", "on", "the", "internal", "items", "storage", "array" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1291-L1300
train
j-/ok
ok.js
function () { var items = _.flatten(arguments); for (var i = 0, l = items.length; i < l; i++) { this.addItem(items[i], this.items.length); } }
javascript
function () { var items = _.flatten(arguments); for (var i = 0, l = items.length; i < l; i++) { this.addItem(items[i], this.items.length); } }
[ "function", "(", ")", "{", "var", "items", "=", "_", ".", "flatten", "(", "arguments", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "items", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "this", ".", "addItem", "(", "items", "[", "i", "]", ",", "this", ".", "items", ".", "length", ")", ";", "}", "}" ]
Add one or more items @param {*|Array.<*>} items A single item or array of items which will be added to this collection @fires add
[ "Add", "one", "or", "more", "items" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1357-L1362
train
j-/ok
ok.js
function (item/*, index*/) { var old = item; var Constructor; if (!(item instanceof ok.Base)) { Constructor = this.getConstructor(item); item = new Constructor(item); } var identified = this.identify(item); if (identified) { identified.set(old); } else { var index = this.findInsertIndex(item); this.items.insert(index + 1, item); } }
javascript
function (item/*, index*/) { var old = item; var Constructor; if (!(item instanceof ok.Base)) { Constructor = this.getConstructor(item); item = new Constructor(item); } var identified = this.identify(item); if (identified) { identified.set(old); } else { var index = this.findInsertIndex(item); this.items.insert(index + 1, item); } }
[ "function", "(", "item", ")", "{", "var", "old", "=", "item", ";", "var", "Constructor", ";", "if", "(", "!", "(", "item", "instanceof", "ok", ".", "Base", ")", ")", "{", "Constructor", "=", "this", ".", "getConstructor", "(", "item", ")", ";", "item", "=", "new", "Constructor", "(", "item", ")", ";", "}", "var", "identified", "=", "this", ".", "identify", "(", "item", ")", ";", "if", "(", "identified", ")", "{", "identified", ".", "set", "(", "old", ")", ";", "}", "else", "{", "var", "index", "=", "this", ".", "findInsertIndex", "(", "item", ")", ";", "this", ".", "items", ".", "insert", "(", "index", "+", "1", ",", "item", ")", ";", "}", "}" ]
Add a single item to this collection @param {*} item Item to add to collection @param {int} index Position to add the item @fires add
[ "Add", "a", "single", "item", "to", "this", "collection" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1369-L1384
train
j-/ok
ok.js
function (item) { var index = -1; this.items.forEach(function (comparedTo, newIndex) { if (this.comparator(comparedTo, item) <= 0) { index = newIndex; return false; } }, this); return index; }
javascript
function (item) { var index = -1; this.items.forEach(function (comparedTo, newIndex) { if (this.comparator(comparedTo, item) <= 0) { index = newIndex; return false; } }, this); return index; }
[ "function", "(", "item", ")", "{", "var", "index", "=", "-", "1", ";", "this", ".", "items", ".", "forEach", "(", "function", "(", "comparedTo", ",", "newIndex", ")", "{", "if", "(", "this", ".", "comparator", "(", "comparedTo", ",", "item", ")", "<=", "0", ")", "{", "index", "=", "newIndex", ";", "return", "false", ";", "}", "}", ",", "this", ")", ";", "return", "index", ";", "}" ]
Determine where a newly inserted item would fit in this collection. Find the index of the item to insert after, or -1 to insert at the first index. @param {*} item Item to be added to collection @return {int} Index of the item to insert after @todo Rephrase
[ "Determine", "where", "a", "newly", "inserted", "item", "would", "fit", "in", "this", "collection", ".", "Find", "the", "index", "of", "the", "item", "to", "insert", "after", "or", "-", "1", "to", "insert", "at", "the", "first", "index", "." ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1407-L1416
train
j-/ok
ok.js
function (item) { var items = this.items; var removed = 0; for (var i = 0, l = items.length; i < l; i++) { if (items[i] === item) { items.splice(i, 1); i--; removed++; } } return removed; }
javascript
function (item) { var items = this.items; var removed = 0; for (var i = 0, l = items.length; i < l; i++) { if (items[i] === item) { items.splice(i, 1); i--; removed++; } } return removed; }
[ "function", "(", "item", ")", "{", "var", "items", "=", "this", ".", "items", ";", "var", "removed", "=", "0", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "items", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "items", "[", "i", "]", "===", "item", ")", "{", "items", ".", "splice", "(", "i", ",", "1", ")", ";", "i", "--", ";", "removed", "++", ";", "}", "}", "return", "removed", ";", "}" ]
Remove a specific item from the collection @param {*} item Item to remove @return {int} Number of items which have been removed @fires remove
[ "Remove", "a", "specific", "item", "from", "the", "collection" ]
f1e4d9af3565574c5fdeccf4313972f2428cf3f8
https://github.com/j-/ok/blob/f1e4d9af3565574c5fdeccf4313972f2428cf3f8/ok.js#L1431-L1442
train