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
pex-gl/pex-color
index.js
setLab
function setLab(color, l, a, b) { var white = [ 95.047, 100.000, 108.883 ]; //for X, Y, Z var y = (l + 16) / 116; var x = a / 500 + y; var z = y - b / 200; x = fromLabValueToXYZValue(x, white[0]); y = fromLabValueToXYZValue(y, white[1]); z = fromLabValueToXYZValue(z, white[2]); return setXYZ(color, x, y, z); }
javascript
function setLab(color, l, a, b) { var white = [ 95.047, 100.000, 108.883 ]; //for X, Y, Z var y = (l + 16) / 116; var x = a / 500 + y; var z = y - b / 200; x = fromLabValueToXYZValue(x, white[0]); y = fromLabValueToXYZValue(y, white[1]); z = fromLabValueToXYZValue(z, white[2]); return setXYZ(color, x, y, z); }
[ "function", "setLab", "(", "color", ",", "l", ",", "a", ",", "b", ")", "{", "var", "white", "=", "[", "95.047", ",", "100.000", ",", "108.883", "]", ";", "var", "y", "=", "(", "l", "+", "16", ")", "/", "116", ";", "var", "x", "=", "a", "/", "500", "+", "y", ";", "var", "z", "=", "y", "-", "b", "/", "200", ";", "x", "=", "fromLabValueToXYZValue", "(", "x", ",", "white", "[", "0", "]", ")", ";", "y", "=", "fromLabValueToXYZValue", "(", "y", ",", "white", "[", "1", "]", ")", ";", "z", "=", "fromLabValueToXYZValue", "(", "z", ",", "white", "[", "2", "]", ")", ";", "return", "setXYZ", "(", "color", ",", "x", ",", "y", ",", "z", ")", ";", "}" ]
Updates a color based on l, a, b, component values @param {Array} color - RGBA color array [r,g,b,a] to update @param {Number} l - l component (0..100) @param {Number} a - a component (-128..127) @param {Number} b - b component (-128..127) @return {Array} - updated RGBA color array [r,g,b,a] (0..1)
[ "Updates", "a", "color", "based", "on", "l", "a", "b", "component", "values" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L445-L457
train
pex-gl/pex-color
index.js
getLab
function getLab(color) { var xyz = getXYZ(color); var white = [ 95.047, 100.000, 108.883 ]; //for X, Y, Z var x = fromXYZValueToLabValue(xyz[0], white[0]); var y = fromXYZValueToLabValue(xyz[1], white[1]); var z = fromXYZValueToLabValue(xyz[2], white[2]); return [ 116 * y - 16, 500 * (x - y), 200 * (y - z) ] }
javascript
function getLab(color) { var xyz = getXYZ(color); var white = [ 95.047, 100.000, 108.883 ]; //for X, Y, Z var x = fromXYZValueToLabValue(xyz[0], white[0]); var y = fromXYZValueToLabValue(xyz[1], white[1]); var z = fromXYZValueToLabValue(xyz[2], white[2]); return [ 116 * y - 16, 500 * (x - y), 200 * (y - z) ] }
[ "function", "getLab", "(", "color", ")", "{", "var", "xyz", "=", "getXYZ", "(", "color", ")", ";", "var", "white", "=", "[", "95.047", ",", "100.000", ",", "108.883", "]", ";", "var", "x", "=", "fromXYZValueToLabValue", "(", "xyz", "[", "0", "]", ",", "white", "[", "0", "]", ")", ";", "var", "y", "=", "fromXYZValueToLabValue", "(", "xyz", "[", "1", "]", ",", "white", "[", "1", "]", ")", ";", "var", "z", "=", "fromXYZValueToLabValue", "(", "xyz", "[", "2", "]", ",", "white", "[", "2", "]", ")", ";", "return", "[", "116", "*", "y", "-", "16", ",", "500", "*", "(", "x", "-", "y", ")", ",", "200", "*", "(", "y", "-", "z", ")", "]", "}" ]
Returns LAB color components @param {Array} color - RGBA color array [r,g,b,a] @return {Array} - LAB values array [l,a,b] (l:0..100, a:-128..127, b:-128..127)
[ "Returns", "LAB", "color", "components" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L464-L478
train
Evo-Forge/Crux
lib/components/sql/model.js
DatabaseDbModel
function DatabaseDbModel(name, tableName) { this.__name = name; this.hasRelationships = false; this.hasValidations = false; this.hasMethods = false; this.hasStatics = false; this.hasFields = false; this.fields = {}; this.__hasMany = {}; this.__hasOne = {}; this.__belongsTo = {}; this.__errors = {}; this.__jsonFields = []; this.hasJsonFields = false; this.methods = {}; this.statics = {}; this.validations = {}; this.options = { timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', deletedAt: false }; if (typeof tableName === 'string') { this.options['tableName'] = tableName; } else { this.options['tableName'] = tableName; } this.instanceMethods(); }
javascript
function DatabaseDbModel(name, tableName) { this.__name = name; this.hasRelationships = false; this.hasValidations = false; this.hasMethods = false; this.hasStatics = false; this.hasFields = false; this.fields = {}; this.__hasMany = {}; this.__hasOne = {}; this.__belongsTo = {}; this.__errors = {}; this.__jsonFields = []; this.hasJsonFields = false; this.methods = {}; this.statics = {}; this.validations = {}; this.options = { timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', deletedAt: false }; if (typeof tableName === 'string') { this.options['tableName'] = tableName; } else { this.options['tableName'] = tableName; } this.instanceMethods(); }
[ "function", "DatabaseDbModel", "(", "name", ",", "tableName", ")", "{", "this", ".", "__name", "=", "name", ";", "this", ".", "hasRelationships", "=", "false", ";", "this", ".", "hasValidations", "=", "false", ";", "this", ".", "hasMethods", "=", "false", ";", "this", ".", "hasStatics", "=", "false", ";", "this", ".", "hasFields", "=", "false", ";", "this", ".", "fields", "=", "{", "}", ";", "this", ".", "__hasMany", "=", "{", "}", ";", "this", ".", "__hasOne", "=", "{", "}", ";", "this", ".", "__belongsTo", "=", "{", "}", ";", "this", ".", "__errors", "=", "{", "}", ";", "this", ".", "__jsonFields", "=", "[", "]", ";", "this", ".", "hasJsonFields", "=", "false", ";", "this", ".", "methods", "=", "{", "}", ";", "this", ".", "statics", "=", "{", "}", ";", "this", ".", "validations", "=", "{", "}", ";", "this", ".", "options", "=", "{", "timestamps", ":", "true", ",", "createdAt", ":", "'created_at'", ",", "updatedAt", ":", "'updated_at'", ",", "deletedAt", ":", "false", "}", ";", "if", "(", "typeof", "tableName", "===", "'string'", ")", "{", "this", ".", "options", "[", "'tableName'", "]", "=", "tableName", ";", "}", "else", "{", "this", ".", "options", "[", "'tableName'", "]", "=", "tableName", ";", "}", "this", ".", "instanceMethods", "(", ")", ";", "}" ]
This is the base model used by every crux model definition to register themselves in the crux sql component @memberof crux.Database.Sql @class Model @param {String} name - the model definition's name @param {String} tableName - the model's table name @example // current model file: models/user.js module.exports = function(user, Seq, Db) { // At this point, the table name is "user" but we can change that user.tableName('users'); // The model's name is by default its file name. We can also change that user.name('Users'); user .field('id', Seq.PRIMARY) // primary int(11) auto_incremented .field('name', Seq.STRING) .field('age', Seq.INTEGER, { allowNull: true, defaultValue: null }); // We can also manually decare indexes. user.index('name'); // Having previously declared the model application, we can create a relationship to it user .hasMany('application', { as: 'application', foreignKey: 'application_id' }); // We can also attach a method to our model INSTANCES. user .method('hello', function() { console.log("Hello from %s", this.get('id'); }) // We can also attach a method to the MODEL object (as a static function). // At this point, we need to use the Db (crux.Database.Sql) component to get the model name. .static('read', function ReadUser(id) { return crux.promise(function(resolve, reject) { Db.getModel('user').find(id).then(function(user) { if(!user) return reject(new Error('USER_NOT_FOUND')); // We can also attach custom data to the model instance user.data('someKey', 'someValue'); // And we can later on access it var a = user.data('someKey'); // => "someValue" resolve(user); }).error(reject); }); }); };
[ "This", "is", "the", "base", "model", "used", "by", "every", "crux", "model", "definition", "to", "register", "themselves", "in", "the", "crux", "sql", "component" ]
f5264fbc2eb053e3170cf2b7b38d46d08f779feb
https://github.com/Evo-Forge/Crux/blob/f5264fbc2eb053e3170cf2b7b38d46d08f779feb/lib/components/sql/model.js#L54-L83
train
JS-MF/jsmf-core
src/Enum.js
Enum
function Enum(name, values) { /** The generic Enum instance * @constructor */ function EnumInstance(x) {return _.includes(EnumInstance, x)} Object.defineProperties(EnumInstance, { __jsmf__: {value: {uuid: generateId(), conformsTo: Enum}} , __name: {value: name} , getName: {value: getName} , conformsTo: {value: () => conformsTo(EnumInstance)} }) if (_.isArray(values)) { _.forEach(values, (v, k) => EnumInstance[v] = k) } else { _.forEach(values, (v, k) => EnumInstance[k] = v) } return EnumInstance }
javascript
function Enum(name, values) { /** The generic Enum instance * @constructor */ function EnumInstance(x) {return _.includes(EnumInstance, x)} Object.defineProperties(EnumInstance, { __jsmf__: {value: {uuid: generateId(), conformsTo: Enum}} , __name: {value: name} , getName: {value: getName} , conformsTo: {value: () => conformsTo(EnumInstance)} }) if (_.isArray(values)) { _.forEach(values, (v, k) => EnumInstance[v] = k) } else { _.forEach(values, (v, k) => EnumInstance[k] = v) } return EnumInstance }
[ "function", "Enum", "(", "name", ",", "values", ")", "{", "function", "EnumInstance", "(", "x", ")", "{", "return", "_", ".", "includes", "(", "EnumInstance", ",", "x", ")", "}", "Object", ".", "defineProperties", "(", "EnumInstance", ",", "{", "__jsmf__", ":", "{", "value", ":", "{", "uuid", ":", "generateId", "(", ")", ",", "conformsTo", ":", "Enum", "}", "}", ",", "__name", ":", "{", "value", ":", "name", "}", ",", "getName", ":", "{", "value", ":", "getName", "}", ",", "conformsTo", ":", "{", "value", ":", "(", ")", "=>", "conformsTo", "(", "EnumInstance", ")", "}", "}", ")", "if", "(", "_", ".", "isArray", "(", "values", ")", ")", "{", "_", ".", "forEach", "(", "values", ",", "(", "v", ",", "k", ")", "=>", "EnumInstance", "[", "v", "]", "=", "k", ")", "}", "else", "{", "_", ".", "forEach", "(", "values", ",", "(", "v", ",", "k", ")", "=>", "EnumInstance", "[", "k", "]", "=", "v", ")", "}", "return", "EnumInstance", "}" ]
Define an Enum @constructor @param {string} name - The name of the created Enum @param values - Either an Array of string or an Object. If an Array is provided, the indexes are used as Enum values.
[ "Define", "an", "Enum" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Enum.js#L40-L57
train
catalyst/catalyst-toggle-switch
tasks/build.js
createElementModule
function createElementModule() { return gulp .src(`./${config.src.path}/${config.src.entrypoint}`) .pipe( modifyFile(content => { return content.replace( new RegExp(`../node_modules/${config.element.scope}/`, 'g'), '../' ); }) ) .pipe( rename({ basename: config.element.tag }) ) .pipe(gulp.dest(`./${config.temp.path}`)); }
javascript
function createElementModule() { return gulp .src(`./${config.src.path}/${config.src.entrypoint}`) .pipe( modifyFile(content => { return content.replace( new RegExp(`../node_modules/${config.element.scope}/`, 'g'), '../' ); }) ) .pipe( rename({ basename: config.element.tag }) ) .pipe(gulp.dest(`./${config.temp.path}`)); }
[ "function", "createElementModule", "(", ")", "{", "return", "gulp", ".", "src", "(", "`", "${", "config", ".", "src", ".", "path", "}", "${", "config", ".", "src", ".", "entrypoint", "}", "`", ")", ".", "pipe", "(", "modifyFile", "(", "content", "=>", "{", "return", "content", ".", "replace", "(", "new", "RegExp", "(", "`", "${", "config", ".", "element", ".", "scope", "}", "`", ",", "'g'", ")", ",", "'../'", ")", ";", "}", ")", ")", ".", "pipe", "(", "rename", "(", "{", "basename", ":", "config", ".", "element", ".", "tag", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "`", "${", "config", ".", "temp", ".", "path", "}", "`", ")", ")", ";", "}" ]
Create the element module file. @returns {NodeJS.ReadWriteStream}
[ "Create", "the", "element", "module", "file", "." ]
c3ec57cd132b1ab6f070ed6f0fd9728906a62b02
https://github.com/catalyst/catalyst-toggle-switch/blob/c3ec57cd132b1ab6f070ed6f0fd9728906a62b02/tasks/build.js#L28-L45
train
catalyst/catalyst-toggle-switch
tasks/build.js
injectTemplate
function injectTemplate(forModule) { return ( gulp .src( forModule ? `./${config.temp.path}/${config.element.tag}.js` : `./${config.temp.path}/${config.element.tag}.script.js` ) // Inject the template html. .pipe( inject(gulp.src(`./${config.temp.path}/${config.src.template.html}`), { starttag: '[[inject:template]]', endtag: '[[endinject]]', removeTags: true, transform: util.transforms.getFileContents }) ) // Inject the style css. .pipe( inject(gulp.src(`./${config.temp.path}/${config.src.template.css}`), { starttag: '[[inject:style]]', endtag: '[[endinject]]', removeTags: true, transform: util.transforms.getFileContents }) ) .pipe(gulp.dest(`./${config.temp.path}`)) ); }
javascript
function injectTemplate(forModule) { return ( gulp .src( forModule ? `./${config.temp.path}/${config.element.tag}.js` : `./${config.temp.path}/${config.element.tag}.script.js` ) // Inject the template html. .pipe( inject(gulp.src(`./${config.temp.path}/${config.src.template.html}`), { starttag: '[[inject:template]]', endtag: '[[endinject]]', removeTags: true, transform: util.transforms.getFileContents }) ) // Inject the style css. .pipe( inject(gulp.src(`./${config.temp.path}/${config.src.template.css}`), { starttag: '[[inject:style]]', endtag: '[[endinject]]', removeTags: true, transform: util.transforms.getFileContents }) ) .pipe(gulp.dest(`./${config.temp.path}`)) ); }
[ "function", "injectTemplate", "(", "forModule", ")", "{", "return", "(", "gulp", ".", "src", "(", "forModule", "?", "`", "${", "config", ".", "temp", ".", "path", "}", "${", "config", ".", "element", ".", "tag", "}", "`", ":", "`", "${", "config", ".", "temp", ".", "path", "}", "${", "config", ".", "element", ".", "tag", "}", "`", ")", ".", "pipe", "(", "inject", "(", "gulp", ".", "src", "(", "`", "${", "config", ".", "temp", ".", "path", "}", "${", "config", ".", "src", ".", "template", ".", "html", "}", "`", ")", ",", "{", "starttag", ":", "'[[inject:template]]'", ",", "endtag", ":", "'[[endinject]]'", ",", "removeTags", ":", "true", ",", "transform", ":", "util", ".", "transforms", ".", "getFileContents", "}", ")", ")", ".", "pipe", "(", "inject", "(", "gulp", ".", "src", "(", "`", "${", "config", ".", "temp", ".", "path", "}", "${", "config", ".", "src", ".", "template", ".", "css", "}", "`", ")", ",", "{", "starttag", ":", "'[[inject:style]]'", ",", "endtag", ":", "'[[endinject]]'", ",", "removeTags", ":", "true", ",", "transform", ":", "util", ".", "transforms", ".", "getFileContents", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "`", "${", "config", ".", "temp", ".", "path", "}", "`", ")", ")", ")", ";", "}" ]
Inject the template into the element. @param {boolean} forModule States whether or not the injection is for the module. If not, it is assumed to be for the script. @returns {NodeJS.ReadWriteStream}
[ "Inject", "the", "template", "into", "the", "element", "." ]
c3ec57cd132b1ab6f070ed6f0fd9728906a62b02
https://github.com/catalyst/catalyst-toggle-switch/blob/c3ec57cd132b1ab6f070ed6f0fd9728906a62b02/tasks/build.js#L233-L263
train
jsCow/jscow
dist/jscow.js
function(index, value) { if (index && value) { if (this.cache[index] === undefined) { this.cache[index] = false; } this.cache[index] = value; }else{ if (!index) { return this.cache; } else if (this.cache[index]) { return this.cache[index]; } } return this; }
javascript
function(index, value) { if (index && value) { if (this.cache[index] === undefined) { this.cache[index] = false; } this.cache[index] = value; }else{ if (!index) { return this.cache; } else if (this.cache[index]) { return this.cache[index]; } } return this; }
[ "function", "(", "index", ",", "value", ")", "{", "if", "(", "index", "&&", "value", ")", "{", "if", "(", "this", ".", "cache", "[", "index", "]", "===", "undefined", ")", "{", "this", ".", "cache", "[", "index", "]", "=", "false", ";", "}", "this", ".", "cache", "[", "index", "]", "=", "value", ";", "}", "else", "{", "if", "(", "!", "index", ")", "{", "return", "this", ".", "cache", ";", "}", "else", "if", "(", "this", ".", "cache", "[", "index", "]", ")", "{", "return", "this", ".", "cache", "[", "index", "]", ";", "}", "}", "return", "this", ";", "}" ]
Get an cached object from the cache property or set a value to the cache property @method cache @param {String} index Index or name of the set value. @param {Object} value Value, which is to be stored. @return {Object} Returns the value for the defined index. @chainable
[ "Get", "an", "cached", "object", "from", "the", "cache", "property", "or", "set", "a", "value", "to", "the", "cache", "property" ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L147-L166
train
jsCow/jscow
dist/jscow.js
function(component) { var cid, foundCmp; if (typeof component === 'object') { cid = component.id(); } foundCmp = false; $.each(jsCow.componentsObjectList, function(i, c) { if (c.id() === component) { foundCmp = c; } }); return foundCmp; }
javascript
function(component) { var cid, foundCmp; if (typeof component === 'object') { cid = component.id(); } foundCmp = false; $.each(jsCow.componentsObjectList, function(i, c) { if (c.id() === component) { foundCmp = c; } }); return foundCmp; }
[ "function", "(", "component", ")", "{", "var", "cid", ",", "foundCmp", ";", "if", "(", "typeof", "component", "===", "'object'", ")", "{", "cid", "=", "component", ".", "id", "(", ")", ";", "}", "foundCmp", "=", "false", ";", "$", ".", "each", "(", "jsCow", ".", "componentsObjectList", ",", "function", "(", "i", ",", "c", ")", "{", "if", "(", "c", ".", "id", "(", ")", "===", "component", ")", "{", "foundCmp", "=", "c", ";", "}", "}", ")", ";", "return", "foundCmp", ";", "}" ]
Find an registered component instance within the jsCow framework instance @method find @param {String} component Id of the component instance or instance object. @return {Object} Return the found component instance.
[ "Find", "an", "registered", "component", "instance", "within", "the", "jsCow", "framework", "instance" ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L236-L253
train
jsCow/jscow
dist/jscow.js
function(childs) { var list = []; if ( childs instanceof Array ) { list = childs; } else { list.push(childs); } $.each(list, (function(self) { return function(i, child) { if (typeof child === 'object' && !child.__cfg__.__execInit__) { var content = self.view().content(); if ( content ) { content.append( child.placeholder() ); } else { content = self.placeholder(); } child.parent(self); child.target(content); self.__children__.push(child); } }; })(this)); return this; }
javascript
function(childs) { var list = []; if ( childs instanceof Array ) { list = childs; } else { list.push(childs); } $.each(list, (function(self) { return function(i, child) { if (typeof child === 'object' && !child.__cfg__.__execInit__) { var content = self.view().content(); if ( content ) { content.append( child.placeholder() ); } else { content = self.placeholder(); } child.parent(self); child.target(content); self.__children__.push(child); } }; })(this)); return this; }
[ "function", "(", "childs", ")", "{", "var", "list", "=", "[", "]", ";", "if", "(", "childs", "instanceof", "Array", ")", "{", "list", "=", "childs", ";", "}", "else", "{", "list", ".", "push", "(", "childs", ")", ";", "}", "$", ".", "each", "(", "list", ",", "(", "function", "(", "self", ")", "{", "return", "function", "(", "i", ",", "child", ")", "{", "if", "(", "typeof", "child", "===", "'object'", "&&", "!", "child", ".", "__cfg__", ".", "__execInit__", ")", "{", "var", "content", "=", "self", ".", "view", "(", ")", ".", "content", "(", ")", ";", "if", "(", "content", ")", "{", "content", ".", "append", "(", "child", ".", "placeholder", "(", ")", ")", ";", "}", "else", "{", "content", "=", "self", ".", "placeholder", "(", ")", ";", "}", "child", ".", "parent", "(", "self", ")", ";", "child", ".", "target", "(", "content", ")", ";", "self", ".", "__children__", ".", "push", "(", "child", ")", ";", "}", "}", ";", "}", ")", "(", "this", ")", ")", ";", "return", "this", ";", "}" ]
Add a new component as a children into the current component. This method should be used before the application will be run. @method add @param {Object} child Defines the reference to the insert component @return {Object} child Defines the reference to the component itself @chainable
[ "Add", "a", "new", "component", "as", "a", "children", "into", "the", "current", "component", ".", "This", "method", "should", "be", "used", "before", "the", "application", "will", "be", "run", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L413-L447
train
jsCow/jscow
dist/jscow.js
function(child) { window.setTimeout((function(self, child) { return function() { if (!child.config.__execInit__ && typeof child === 'object') { self.add(child); child.__init(); } }; }(this, child)), 0); return this; }
javascript
function(child) { window.setTimeout((function(self, child) { return function() { if (!child.config.__execInit__ && typeof child === 'object') { self.add(child); child.__init(); } }; }(this, child)), 0); return this; }
[ "function", "(", "child", ")", "{", "window", ".", "setTimeout", "(", "(", "function", "(", "self", ",", "child", ")", "{", "return", "function", "(", ")", "{", "if", "(", "!", "child", ".", "config", ".", "__execInit__", "&&", "typeof", "child", "===", "'object'", ")", "{", "self", ".", "add", "(", "child", ")", ";", "child", ".", "__init", "(", ")", ";", "}", "}", ";", "}", "(", "this", ",", "child", ")", ")", ",", "0", ")", ";", "return", "this", ";", "}" ]
Fügt eine neue Kind-Komponente der aktuellen Komponente hinzu. Die hinzuzufügende Komponente muss bereits als Instanz vorliegen. @method append @param {Object} child Referenz auf die Instanz der hinzuzufügenden Komponente. @return {Object} child Referenz auf die aktuelle Komponente selbst. @chainable
[ "F&uuml", ";", "gt", "eine", "neue", "Kind", "-", "Komponente", "der", "aktuellen", "Komponente", "hinzu", ".", "Die", "hinzuzuf&uuml", ";", "gende", "Komponente", "muss", "bereits", "als", "Instanz", "vorliegen", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L552-L563
train
jsCow/jscow
dist/jscow.js
function(cmp) { // Remove the component reference from parent children list if (typeof cmp !== 'undefined' && typeof cmp === 'object') { $(this.children()).each((function(self, cmp) { return function(i,c) { if (c.id() === cmp.id()) { self.__children__.splice(i,1); } }; })(this, cmp)); } else { // Call to remove the component reference from parent children list if (typeof this.parent() !== 'undefined' && this.parent()) { this.parent().del(this); } // Remove the component domelemeents and delete the component instance from global jscow instance list $(jsCow.componentsObjectList).each((function(self) { return function(i, c) { if (c !== 'undefined' && c.id() === self.id()) { c.view().removeAll(); jsCow.componentsObjectList.splice(i,1); } }; })(this)); // Delete children components of the component to be delete var list = this.__children__; if (list.length > 0) { $(list).each(function(i,c) { c.del(); }); } } return this; }
javascript
function(cmp) { // Remove the component reference from parent children list if (typeof cmp !== 'undefined' && typeof cmp === 'object') { $(this.children()).each((function(self, cmp) { return function(i,c) { if (c.id() === cmp.id()) { self.__children__.splice(i,1); } }; })(this, cmp)); } else { // Call to remove the component reference from parent children list if (typeof this.parent() !== 'undefined' && this.parent()) { this.parent().del(this); } // Remove the component domelemeents and delete the component instance from global jscow instance list $(jsCow.componentsObjectList).each((function(self) { return function(i, c) { if (c !== 'undefined' && c.id() === self.id()) { c.view().removeAll(); jsCow.componentsObjectList.splice(i,1); } }; })(this)); // Delete children components of the component to be delete var list = this.__children__; if (list.length > 0) { $(list).each(function(i,c) { c.del(); }); } } return this; }
[ "function", "(", "cmp", ")", "{", "if", "(", "typeof", "cmp", "!==", "'undefined'", "&&", "typeof", "cmp", "===", "'object'", ")", "{", "$", "(", "this", ".", "children", "(", ")", ")", ".", "each", "(", "(", "function", "(", "self", ",", "cmp", ")", "{", "return", "function", "(", "i", ",", "c", ")", "{", "if", "(", "c", ".", "id", "(", ")", "===", "cmp", ".", "id", "(", ")", ")", "{", "self", ".", "__children__", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", ";", "}", ")", "(", "this", ",", "cmp", ")", ")", ";", "}", "else", "{", "if", "(", "typeof", "this", ".", "parent", "(", ")", "!==", "'undefined'", "&&", "this", ".", "parent", "(", ")", ")", "{", "this", ".", "parent", "(", ")", ".", "del", "(", "this", ")", ";", "}", "$", "(", "jsCow", ".", "componentsObjectList", ")", ".", "each", "(", "(", "function", "(", "self", ")", "{", "return", "function", "(", "i", ",", "c", ")", "{", "if", "(", "c", "!==", "'undefined'", "&&", "c", ".", "id", "(", ")", "===", "self", ".", "id", "(", ")", ")", "{", "c", ".", "view", "(", ")", ".", "removeAll", "(", ")", ";", "jsCow", ".", "componentsObjectList", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", ";", "}", ")", "(", "this", ")", ")", ";", "var", "list", "=", "this", ".", "__children__", ";", "if", "(", "list", ".", "length", ">", "0", ")", "{", "$", "(", "list", ")", ".", "each", "(", "function", "(", "i", ",", "c", ")", "{", "c", ".", "del", "(", ")", ";", "}", ")", ";", "}", "}", "return", "this", ";", "}" ]
Delete a component and remove all related dom elements. @method del @param {Object} [optional] cmp Instance of the component to be deleted @return {Object} Reference to the current component instance object @chainable
[ "Delete", "a", "component", "and", "remove", "all", "related", "dom", "elements", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L639-L682
train
jsCow/jscow
dist/jscow.js
function(method, root) { var methodList; if (root === true) { $.extend(true, this, method); } else { var _this = this; if (!this.extension) { var ext = function() {}; methodList = {}; $.each(method, function(i, m) { methodList[i] = (function( _super, m, i ) { m._super = typeof _super[i] === 'function' ? _super[i] : function(){}; return function() { m.apply( _super, arguments); }; })( _this, m, i ); }); $.extend(true, ext.prototype, methodList); this.extension = new ext(); } else { methodList = {}; $.each(method, function(i, m) { methodList[i] = (function( _super, m, i ) { m._super = typeof _super[i] === 'function' ? _super[i] : function(){}; return function() { m.apply( _super, arguments); }; })( _this, m, i ); }); $.extend(true, this.extension, methodList); } } return this; }
javascript
function(method, root) { var methodList; if (root === true) { $.extend(true, this, method); } else { var _this = this; if (!this.extension) { var ext = function() {}; methodList = {}; $.each(method, function(i, m) { methodList[i] = (function( _super, m, i ) { m._super = typeof _super[i] === 'function' ? _super[i] : function(){}; return function() { m.apply( _super, arguments); }; })( _this, m, i ); }); $.extend(true, ext.prototype, methodList); this.extension = new ext(); } else { methodList = {}; $.each(method, function(i, m) { methodList[i] = (function( _super, m, i ) { m._super = typeof _super[i] === 'function' ? _super[i] : function(){}; return function() { m.apply( _super, arguments); }; })( _this, m, i ); }); $.extend(true, this.extension, methodList); } } return this; }
[ "function", "(", "method", ",", "root", ")", "{", "var", "methodList", ";", "if", "(", "root", "===", "true", ")", "{", "$", ".", "extend", "(", "true", ",", "this", ",", "method", ")", ";", "}", "else", "{", "var", "_this", "=", "this", ";", "if", "(", "!", "this", ".", "extension", ")", "{", "var", "ext", "=", "function", "(", ")", "{", "}", ";", "methodList", "=", "{", "}", ";", "$", ".", "each", "(", "method", ",", "function", "(", "i", ",", "m", ")", "{", "methodList", "[", "i", "]", "=", "(", "function", "(", "_super", ",", "m", ",", "i", ")", "{", "m", ".", "_super", "=", "typeof", "_super", "[", "i", "]", "===", "'function'", "?", "_super", "[", "i", "]", ":", "function", "(", ")", "{", "}", ";", "return", "function", "(", ")", "{", "m", ".", "apply", "(", "_super", ",", "arguments", ")", ";", "}", ";", "}", ")", "(", "_this", ",", "m", ",", "i", ")", ";", "}", ")", ";", "$", ".", "extend", "(", "true", ",", "ext", ".", "prototype", ",", "methodList", ")", ";", "this", ".", "extension", "=", "new", "ext", "(", ")", ";", "}", "else", "{", "methodList", "=", "{", "}", ";", "$", ".", "each", "(", "method", ",", "function", "(", "i", ",", "m", ")", "{", "methodList", "[", "i", "]", "=", "(", "function", "(", "_super", ",", "m", ",", "i", ")", "{", "m", ".", "_super", "=", "typeof", "_super", "[", "i", "]", "===", "'function'", "?", "_super", "[", "i", "]", ":", "function", "(", ")", "{", "}", ";", "return", "function", "(", ")", "{", "m", ".", "apply", "(", "_super", ",", "arguments", ")", ";", "}", ";", "}", ")", "(", "_this", ",", "m", ",", "i", ")", ";", "}", ")", ";", "$", ".", "extend", "(", "true", ",", "this", ".", "extension", ",", "methodList", ")", ";", "}", "}", "return", "this", ";", "}" ]
Erweitert die aktuelle Komponente und reichert sie mit den definierten neuen Methoden an. @method extend @param {Object} method Objekt mit allen hinzuzufügenden Methoden. @param {Boolean} root Wird root als "true" definiert, werden alle Methoden als Extension angelegt, ohne bestehende Standard-Methoden zu überschreiben. Muss eine neue Methode den gleichen Namen einer Standard-Methode haben, kann Dies über eine solche Extension genutzt werden. Innerhalb einer solchen Extension-Methode steht "this" im Scope der Haupt-Klasse der aktuellen Komponente. @return {Object} Referenz der aktuellen Komponente. @chainable
[ "Erweitert", "die", "aktuelle", "Komponente", "und", "reichert", "sie", "mit", "den", "definierten", "neuen", "Methoden", "an", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L747-L799
train
jsCow/jscow
dist/jscow.js
function(config) { var cfg = config; var self = this; var viewList = this.list(); $(viewList).each(function(i, view) { if (!view.isInit) { if (view.dom !== 'undefined' && view.dom.main !== 'undefined') { if (i === 0 && self.cmp().placeholder()) { self.cmp().placeholder().replaceWith( view.dom.main ); } if (i > 0) { viewList[ i - 1 ].dom.main.after( view.dom.main ); } } view.isInit = true; } }).promise().done(function() { self.cmp().trigger('view.ready'); }); }
javascript
function(config) { var cfg = config; var self = this; var viewList = this.list(); $(viewList).each(function(i, view) { if (!view.isInit) { if (view.dom !== 'undefined' && view.dom.main !== 'undefined') { if (i === 0 && self.cmp().placeholder()) { self.cmp().placeholder().replaceWith( view.dom.main ); } if (i > 0) { viewList[ i - 1 ].dom.main.after( view.dom.main ); } } view.isInit = true; } }).promise().done(function() { self.cmp().trigger('view.ready'); }); }
[ "function", "(", "config", ")", "{", "var", "cfg", "=", "config", ";", "var", "self", "=", "this", ";", "var", "viewList", "=", "this", ".", "list", "(", ")", ";", "$", "(", "viewList", ")", ".", "each", "(", "function", "(", "i", ",", "view", ")", "{", "if", "(", "!", "view", ".", "isInit", ")", "{", "if", "(", "view", ".", "dom", "!==", "'undefined'", "&&", "view", ".", "dom", ".", "main", "!==", "'undefined'", ")", "{", "if", "(", "i", "===", "0", "&&", "self", ".", "cmp", "(", ")", ".", "placeholder", "(", ")", ")", "{", "self", ".", "cmp", "(", ")", ".", "placeholder", "(", ")", ".", "replaceWith", "(", "view", ".", "dom", ".", "main", ")", ";", "}", "if", "(", "i", ">", "0", ")", "{", "viewList", "[", "i", "-", "1", "]", ".", "dom", ".", "main", ".", "after", "(", "view", ".", "dom", ".", "main", ")", ";", "}", "}", "view", ".", "isInit", "=", "true", ";", "}", "}", ")", ".", "promise", "(", ")", ".", "done", "(", "function", "(", ")", "{", "self", ".", "cmp", "(", ")", ".", "trigger", "(", "'view.ready'", ")", ";", "}", ")", ";", "}" ]
Init method of all views of the current component instance @method init @param {Object} config Object with all default view configurations.
[ "Init", "method", "of", "all", "views", "of", "the", "current", "component", "instance" ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L1538-L1568
train
jsCow/jscow
dist/jscow.js
function() { var self = this; var viewList = this.list(); $.each(viewList, function(i, view) { self.cmp().trigger("view.update"); }); return this; }
javascript
function() { var self = this; var viewList = this.list(); $.each(viewList, function(i, view) { self.cmp().trigger("view.update"); }); return this; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "viewList", "=", "this", ".", "list", "(", ")", ";", "$", ".", "each", "(", "viewList", ",", "function", "(", "i", ",", "view", ")", "{", "self", ".", "cmp", "(", ")", ".", "trigger", "(", "\"view.update\"", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Add a view to the current component. @method update @return {Object} Returns the view manager of the current component. @chainable
[ "Add", "a", "view", "to", "the", "current", "component", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L1853-L1865
train
jsCow/jscow
dist/jscow.js
function(target) { var self = this; var viewList = this.list(); $.each(viewList, function(i, view) { view.main().appendTo(target); self.cmp().target(target); }); return this; }
javascript
function(target) { var self = this; var viewList = this.list(); $.each(viewList, function(i, view) { view.main().appendTo(target); self.cmp().target(target); }); return this; }
[ "function", "(", "target", ")", "{", "var", "self", "=", "this", ";", "var", "viewList", "=", "this", ".", "list", "(", ")", ";", "$", ".", "each", "(", "viewList", ",", "function", "(", "i", ",", "view", ")", "{", "view", ".", "main", "(", ")", ".", "appendTo", "(", "target", ")", ";", "self", ".", "cmp", "(", ")", ".", "target", "(", "target", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Move the current main DOM element into a other element. @method appendTo @param {DOM Element} target jQuery DOM element. @return {Object} Returns the view manager. @chainable
[ "Move", "the", "current", "main", "DOM", "element", "into", "a", "other", "element", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L1965-L1976
train
jsCow/jscow
dist/jscow.js
function (event, d, l) { var config = this.cmp().config(); var data = d; var local = l; if (typeof d === 'undefined' || !d) { data = config; }else if (typeof d === 'object') { data = d; }else{ data = {}; } if (data) { var self = this; if (typeof local === 'undefined' || !local) { local = this.cmp(); } else { local = false; } if (jsCow.events[event] !== undefined) { $.each(jsCow.events[event], (function(self, event, data, local) { return function (i, e) { if (typeof local === "object" && local.id() === e.sender.id() && e.local) { setTimeout( function() { if (jsCow.debug.events) { console.log("local :: trigger event ", "'"+e.event+"'", "from", "'"+self.cmp().id()+"' for '"+e.that.id()+"'."); } e.handler.apply(e.that, [{ data: data, sender: self.cmp(), date: new Date() }]); }, 0 ); } else if (self.isNot(local) === e.local) { setTimeout( function() { if (jsCow.debug.events) { console.log("global :: trigger even", "'"+e.event+"'", "from", "'"+self.cmp().id()+"' for '"+e.that.id()+"'."); } e.handler.apply(e.that, [{ data: data, sender: self.cmp(), date: new Date() }]); }, 0 ); } }; })(self, event, data, local)); } } return this; }
javascript
function (event, d, l) { var config = this.cmp().config(); var data = d; var local = l; if (typeof d === 'undefined' || !d) { data = config; }else if (typeof d === 'object') { data = d; }else{ data = {}; } if (data) { var self = this; if (typeof local === 'undefined' || !local) { local = this.cmp(); } else { local = false; } if (jsCow.events[event] !== undefined) { $.each(jsCow.events[event], (function(self, event, data, local) { return function (i, e) { if (typeof local === "object" && local.id() === e.sender.id() && e.local) { setTimeout( function() { if (jsCow.debug.events) { console.log("local :: trigger event ", "'"+e.event+"'", "from", "'"+self.cmp().id()+"' for '"+e.that.id()+"'."); } e.handler.apply(e.that, [{ data: data, sender: self.cmp(), date: new Date() }]); }, 0 ); } else if (self.isNot(local) === e.local) { setTimeout( function() { if (jsCow.debug.events) { console.log("global :: trigger even", "'"+e.event+"'", "from", "'"+self.cmp().id()+"' for '"+e.that.id()+"'."); } e.handler.apply(e.that, [{ data: data, sender: self.cmp(), date: new Date() }]); }, 0 ); } }; })(self, event, data, local)); } } return this; }
[ "function", "(", "event", ",", "d", ",", "l", ")", "{", "var", "config", "=", "this", ".", "cmp", "(", ")", ".", "config", "(", ")", ";", "var", "data", "=", "d", ";", "var", "local", "=", "l", ";", "if", "(", "typeof", "d", "===", "'undefined'", "||", "!", "d", ")", "{", "data", "=", "config", ";", "}", "else", "if", "(", "typeof", "d", "===", "'object'", ")", "{", "data", "=", "d", ";", "}", "else", "{", "data", "=", "{", "}", ";", "}", "if", "(", "data", ")", "{", "var", "self", "=", "this", ";", "if", "(", "typeof", "local", "===", "'undefined'", "||", "!", "local", ")", "{", "local", "=", "this", ".", "cmp", "(", ")", ";", "}", "else", "{", "local", "=", "false", ";", "}", "if", "(", "jsCow", ".", "events", "[", "event", "]", "!==", "undefined", ")", "{", "$", ".", "each", "(", "jsCow", ".", "events", "[", "event", "]", ",", "(", "function", "(", "self", ",", "event", ",", "data", ",", "local", ")", "{", "return", "function", "(", "i", ",", "e", ")", "{", "if", "(", "typeof", "local", "===", "\"object\"", "&&", "local", ".", "id", "(", ")", "===", "e", ".", "sender", ".", "id", "(", ")", "&&", "e", ".", "local", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "jsCow", ".", "debug", ".", "events", ")", "{", "console", ".", "log", "(", "\"local :: trigger event \"", ",", "\"'\"", "+", "e", ".", "event", "+", "\"'\"", ",", "\"from\"", ",", "\"'\"", "+", "self", ".", "cmp", "(", ")", ".", "id", "(", ")", "+", "\"' for '\"", "+", "e", ".", "that", ".", "id", "(", ")", "+", "\"'.\"", ")", ";", "}", "e", ".", "handler", ".", "apply", "(", "e", ".", "that", ",", "[", "{", "data", ":", "data", ",", "sender", ":", "self", ".", "cmp", "(", ")", ",", "date", ":", "new", "Date", "(", ")", "}", "]", ")", ";", "}", ",", "0", ")", ";", "}", "else", "if", "(", "self", ".", "isNot", "(", "local", ")", "===", "e", ".", "local", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "jsCow", ".", "debug", ".", "events", ")", "{", "console", ".", "log", "(", "\"global :: trigger even\"", ",", "\"'\"", "+", "e", ".", "event", "+", "\"'\"", ",", "\"from\"", ",", "\"'\"", "+", "self", ".", "cmp", "(", ")", ".", "id", "(", ")", "+", "\"' for '\"", "+", "e", ".", "that", ".", "id", "(", ")", "+", "\"'.\"", ")", ";", "}", "e", ".", "handler", ".", "apply", "(", "e", ".", "that", ",", "[", "{", "data", ":", "data", ",", "sender", ":", "self", ".", "cmp", "(", ")", ",", "date", ":", "new", "Date", "(", ")", "}", "]", ")", ";", "}", ",", "0", ")", ";", "}", "}", ";", "}", ")", "(", "self", ",", "event", ",", "data", ",", "local", ")", ")", ";", "}", "}", "return", "this", ";", "}" ]
Trigger an attached event. @method trigger @param {String} event Defines the name of the attached event @param {Object} d Defines the event data by trigger the attached event. @param {Boolean} l Defines the type (local or global) of the event. @return {Object} Returns the reference to the current event handler. @chainable
[ "Trigger", "an", "attached", "event", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L2558-L2630
train
jsCow/jscow
dist/jscow.js
function (event, data, local) { // trigger event in current component var bubble = this.bubbleTrigger(event, data, local); if (bubble) { // Next Event bubbling - up this.bubbleOut(event, data, local); // Next Event bubbling - down this.bubbleIn(event, data, local); } }
javascript
function (event, data, local) { // trigger event in current component var bubble = this.bubbleTrigger(event, data, local); if (bubble) { // Next Event bubbling - up this.bubbleOut(event, data, local); // Next Event bubbling - down this.bubbleIn(event, data, local); } }
[ "function", "(", "event", ",", "data", ",", "local", ")", "{", "var", "bubble", "=", "this", ".", "bubbleTrigger", "(", "event", ",", "data", ",", "local", ")", ";", "if", "(", "bubble", ")", "{", "this", ".", "bubbleOut", "(", "event", ",", "data", ",", "local", ")", ";", "this", ".", "bubbleIn", "(", "event", ",", "data", ",", "local", ")", ";", "}", "}" ]
Triggers an event bubbling upwards and also down into the component hirarchy. @method bubble @param {String} event Defines the name of the attached event @param {Object} data Defines the event data by trigger the attached event. @param {Boolean} local Defines the type (local or global) of the event.
[ "Triggers", "an", "event", "bubbling", "upwards", "and", "also", "down", "into", "the", "component", "hirarchy", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L2688-L2703
train
jsCow/jscow
dist/jscow.js
function (event, data, local) { var bubble = true; this.trigger(event, data, local); return bubble; }
javascript
function (event, data, local) { var bubble = true; this.trigger(event, data, local); return bubble; }
[ "function", "(", "event", ",", "data", ",", "local", ")", "{", "var", "bubble", "=", "true", ";", "this", ".", "trigger", "(", "event", ",", "data", ",", "local", ")", ";", "return", "bubble", ";", "}" ]
Triggers all event bubblings in the event handler. @method bubbleTrigger @param {String} event Defines the name of the attached event @param {Object} data Defines the event data by trigger the attached event. @param {Boolean} local Defines the type (local or global) of the event.
[ "Triggers", "all", "event", "bubblings", "in", "the", "event", "handler", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L2712-L2718
train
socialtables/geometry-utils
lib/utils.js
solveAngle
function solveAngle(a, b, c) { var temp = (a * a + b * b - c * c) / (2 * a * b); if (temp >= -1 && temp <= 1) { return radToDeg(Math.acos(temp)); } else { throw new Error("No angle solution for points " + a + " " + b + " " + c); } }
javascript
function solveAngle(a, b, c) { var temp = (a * a + b * b - c * c) / (2 * a * b); if (temp >= -1 && temp <= 1) { return radToDeg(Math.acos(temp)); } else { throw new Error("No angle solution for points " + a + " " + b + " " + c); } }
[ "function", "solveAngle", "(", "a", ",", "b", ",", "c", ")", "{", "var", "temp", "=", "(", "a", "*", "a", "+", "b", "*", "b", "-", "c", "*", "c", ")", "/", "(", "2", "*", "a", "*", "b", ")", ";", "if", "(", "temp", ">=", "-", "1", "&&", "temp", "<=", "1", ")", "{", "return", "radToDeg", "(", "Math", ".", "acos", "(", "temp", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"No angle solution for points \"", "+", "a", "+", "\" \"", "+", "b", "+", "\" \"", "+", "c", ")", ";", "}", "}" ]
Takes a, b, and c to be lengths of legs of a triangle. Uses the law of cosines to return the angle C, i.e. the corner across from leg c
[ "Takes", "a", "b", "and", "c", "to", "be", "lengths", "of", "legs", "of", "a", "triangle", ".", "Uses", "the", "law", "of", "cosines", "to", "return", "the", "angle", "C", "i", ".", "e", ".", "the", "corner", "across", "from", "leg", "c" ]
4dc13529696a52dbe2d2cfcad3204dd39fca2f88
https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/utils.js#L11-L19
train
socialtables/geometry-utils
lib/utils.js
area
function area(poly) { var i = -1, n = poly.length, a, b = poly[n - 1], area = 0; while (++i < n) { a = b; b = poly[i]; area += a.y * b.x - a.x * b.y; } return Math.abs(area * 0.5); }
javascript
function area(poly) { var i = -1, n = poly.length, a, b = poly[n - 1], area = 0; while (++i < n) { a = b; b = poly[i]; area += a.y * b.x - a.x * b.y; } return Math.abs(area * 0.5); }
[ "function", "area", "(", "poly", ")", "{", "var", "i", "=", "-", "1", ",", "n", "=", "poly", ".", "length", ",", "a", ",", "b", "=", "poly", "[", "n", "-", "1", "]", ",", "area", "=", "0", ";", "while", "(", "++", "i", "<", "n", ")", "{", "a", "=", "b", ";", "b", "=", "poly", "[", "i", "]", ";", "area", "+=", "a", ".", "y", "*", "b", ".", "x", "-", "a", ".", "x", "*", "b", ".", "y", ";", "}", "return", "Math", ".", "abs", "(", "area", "*", "0.5", ")", ";", "}" ]
Calculates area of a polygon. Ported from d3.js @param poly Object @returns {number} square units inside the polygon
[ "Calculates", "area", "of", "a", "polygon", ".", "Ported", "from", "d3", ".", "js" ]
4dc13529696a52dbe2d2cfcad3204dd39fca2f88
https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/utils.js#L196-L210
train
abubakir1997/anew
lib/store/combineStores.js
_loop
function _loop(i, storesLen) { var store = stores[i]; var getState = store.getState, name = store.anew.name, _store$dispatch = store.dispatch, reducers = _store$dispatch.reducers, effects = _store$dispatch.effects, actions = _store$dispatch.actions, _store$dispatch$batch = _store$dispatch.batch, done = _store$dispatch$batch.done, batches = _objectWithoutProperties(_store$dispatch$batch, ['done']); var getStoreState = function getStoreState() { return reduxStore.getState()[name]; }; /** * Merge into combined store */ reduxStore.dispatch.reducers[name] = reducers; reduxStore.dispatch.effects[name] = effects; reduxStore.dispatch.actions[name] = actions; reduxStore.dispatch.batch[name] = batches; reduxStore.getState[name] = getStoreState; /** * Update each store references */ store.subscribe = reduxStore.subscribe; store.anew.getBatches = function () { return reduxStore.anew.getBatches(); }; store.dispatch = function (action) { return reduxStore.dispatch(action); }; store.getState = getStoreState; /** * Redefine replace reducer */ store.replaceReducer = function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } anewStore.reducers[name] = nextReducer; reduxReducer = (0, _combineReducers2.default)(anewStore.reducers); reduxStore.dispatch({ type: '@@anew:RESET' }); }; /** * Reassign reducers, effects, and batch to maintain dispatch * object's shape per store. */ store.dispatch.persistor = reduxStore.persistor; store.dispatch.reducers = reducers; store.dispatch.effects = effects; store.dispatch.actions = actions; store.dispatch.batch = batches; store.dispatch.batch.done = done; /** * Reassign selectors to maintian getState * object's shape per store */ reduxStore.getState[name] = Object.assign(reduxStore.getState[name], getState); store.getState = Object.assign(store.getState, getState); /** * Assign Core */ store.anew.core = reduxStore; }
javascript
function _loop(i, storesLen) { var store = stores[i]; var getState = store.getState, name = store.anew.name, _store$dispatch = store.dispatch, reducers = _store$dispatch.reducers, effects = _store$dispatch.effects, actions = _store$dispatch.actions, _store$dispatch$batch = _store$dispatch.batch, done = _store$dispatch$batch.done, batches = _objectWithoutProperties(_store$dispatch$batch, ['done']); var getStoreState = function getStoreState() { return reduxStore.getState()[name]; }; /** * Merge into combined store */ reduxStore.dispatch.reducers[name] = reducers; reduxStore.dispatch.effects[name] = effects; reduxStore.dispatch.actions[name] = actions; reduxStore.dispatch.batch[name] = batches; reduxStore.getState[name] = getStoreState; /** * Update each store references */ store.subscribe = reduxStore.subscribe; store.anew.getBatches = function () { return reduxStore.anew.getBatches(); }; store.dispatch = function (action) { return reduxStore.dispatch(action); }; store.getState = getStoreState; /** * Redefine replace reducer */ store.replaceReducer = function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } anewStore.reducers[name] = nextReducer; reduxReducer = (0, _combineReducers2.default)(anewStore.reducers); reduxStore.dispatch({ type: '@@anew:RESET' }); }; /** * Reassign reducers, effects, and batch to maintain dispatch * object's shape per store. */ store.dispatch.persistor = reduxStore.persistor; store.dispatch.reducers = reducers; store.dispatch.effects = effects; store.dispatch.actions = actions; store.dispatch.batch = batches; store.dispatch.batch.done = done; /** * Reassign selectors to maintian getState * object's shape per store */ reduxStore.getState[name] = Object.assign(reduxStore.getState[name], getState); store.getState = Object.assign(store.getState, getState); /** * Assign Core */ store.anew.core = reduxStore; }
[ "function", "_loop", "(", "i", ",", "storesLen", ")", "{", "var", "store", "=", "stores", "[", "i", "]", ";", "var", "getState", "=", "store", ".", "getState", ",", "name", "=", "store", ".", "anew", ".", "name", ",", "_store$dispatch", "=", "store", ".", "dispatch", ",", "reducers", "=", "_store$dispatch", ".", "reducers", ",", "effects", "=", "_store$dispatch", ".", "effects", ",", "actions", "=", "_store$dispatch", ".", "actions", ",", "_store$dispatch$batch", "=", "_store$dispatch", ".", "batch", ",", "done", "=", "_store$dispatch$batch", ".", "done", ",", "batches", "=", "_objectWithoutProperties", "(", "_store$dispatch$batch", ",", "[", "'done'", "]", ")", ";", "var", "getStoreState", "=", "function", "getStoreState", "(", ")", "{", "return", "reduxStore", ".", "getState", "(", ")", "[", "name", "]", ";", "}", ";", "reduxStore", ".", "dispatch", ".", "reducers", "[", "name", "]", "=", "reducers", ";", "reduxStore", ".", "dispatch", ".", "effects", "[", "name", "]", "=", "effects", ";", "reduxStore", ".", "dispatch", ".", "actions", "[", "name", "]", "=", "actions", ";", "reduxStore", ".", "dispatch", ".", "batch", "[", "name", "]", "=", "batches", ";", "reduxStore", ".", "getState", "[", "name", "]", "=", "getStoreState", ";", "store", ".", "subscribe", "=", "reduxStore", ".", "subscribe", ";", "store", ".", "anew", ".", "getBatches", "=", "function", "(", ")", "{", "return", "reduxStore", ".", "anew", ".", "getBatches", "(", ")", ";", "}", ";", "store", ".", "dispatch", "=", "function", "(", "action", ")", "{", "return", "reduxStore", ".", "dispatch", "(", "action", ")", ";", "}", ";", "store", ".", "getState", "=", "getStoreState", ";", "store", ".", "replaceReducer", "=", "function", "replaceReducer", "(", "nextReducer", ")", "{", "if", "(", "typeof", "nextReducer", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Expected the nextReducer to be a function.'", ")", ";", "}", "anewStore", ".", "reducers", "[", "name", "]", "=", "nextReducer", ";", "reduxReducer", "=", "(", "0", ",", "_combineReducers2", ".", "default", ")", "(", "anewStore", ".", "reducers", ")", ";", "reduxStore", ".", "dispatch", "(", "{", "type", ":", "'@@anew:RESET'", "}", ")", ";", "}", ";", "store", ".", "dispatch", ".", "persistor", "=", "reduxStore", ".", "persistor", ";", "store", ".", "dispatch", ".", "reducers", "=", "reducers", ";", "store", ".", "dispatch", ".", "effects", "=", "effects", ";", "store", ".", "dispatch", ".", "actions", "=", "actions", ";", "store", ".", "dispatch", ".", "batch", "=", "batches", ";", "store", ".", "dispatch", ".", "batch", ".", "done", "=", "done", ";", "reduxStore", ".", "getState", "[", "name", "]", "=", "Object", ".", "assign", "(", "reduxStore", ".", "getState", "[", "name", "]", ",", "getState", ")", ";", "store", ".", "getState", "=", "Object", ".", "assign", "(", "store", ".", "getState", ",", "getState", ")", ";", "store", ".", "anew", ".", "core", "=", "reduxStore", ";", "}" ]
Populate dispatch reducers and effects and update redux dispatch reference
[ "Populate", "dispatch", "reducers", "and", "effects", "and", "update", "redux", "dispatch", "reference" ]
a79a01ea7b989184d5dddc0bd7de05efb2b02c8c
https://github.com/abubakir1997/anew/blob/a79a01ea7b989184d5dddc0bd7de05efb2b02c8c/lib/store/combineStores.js#L132-L206
train
josepot/redux-internal-state
src/ramda-custom.js
_slice
function _slice(args, from, to) { switch (arguments.length) { case 1: return _slice(args, 0, args.length); case 2: return _slice(args, from, args.length); default: var list = []; var idx = 0; var len = Math.max(0, Math.min(args.length, to) - from); while (idx < len) { list[idx] = args[from + idx]; idx += 1; } return list; } }
javascript
function _slice(args, from, to) { switch (arguments.length) { case 1: return _slice(args, 0, args.length); case 2: return _slice(args, from, args.length); default: var list = []; var idx = 0; var len = Math.max(0, Math.min(args.length, to) - from); while (idx < len) { list[idx] = args[from + idx]; idx += 1; } return list; } }
[ "function", "_slice", "(", "args", ",", "from", ",", "to", ")", "{", "switch", "(", "arguments", ".", "length", ")", "{", "case", "1", ":", "return", "_slice", "(", "args", ",", "0", ",", "args", ".", "length", ")", ";", "case", "2", ":", "return", "_slice", "(", "args", ",", "from", ",", "args", ".", "length", ")", ";", "default", ":", "var", "list", "=", "[", "]", ";", "var", "idx", "=", "0", ";", "var", "len", "=", "Math", ".", "max", "(", "0", ",", "Math", ".", "min", "(", "args", ".", "length", ",", "to", ")", "-", "from", ")", ";", "while", "(", "idx", "<", "len", ")", "{", "list", "[", "idx", "]", "=", "args", "[", "from", "+", "idx", "]", ";", "idx", "+=", "1", ";", "}", "return", "list", ";", "}", "}" ]
An optimized, private array `slice` implementation. @private @param {Arguments|Array} args The array or arguments object to consider. @param {Number} [from=0] The array index to slice from, inclusive. @param {Number} [to=args.length] The array index to slice to, exclusive. @return {Array} A new, sliced array. @example _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3] var firstThreeArgs = function(a, b, c, d) { return _slice(arguments, 0, 3); }; firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3]
[ "An", "optimized", "private", "array", "slice", "implementation", "." ]
9cee82b1c6fb9958c271bb840a7685f5b4d2e9bb
https://github.com/josepot/redux-internal-state/blob/9cee82b1c6fb9958c271bb840a7685f5b4d2e9bb/src/ramda-custom.js#L159-L175
train
reklatsmasters/btparse
lib/from.js
from
function from(arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) }
javascript
function from(arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) }
[ "function", "from", "(", "arg", ",", "encodingOrOffset", ",", "length", ")", "{", "if", "(", "typeof", "arg", "===", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'Argument must not be a number'", ")", "}", "return", "Buffer", "(", "arg", ",", "encodingOrOffset", ",", "length", ")", "}" ]
ported from `safe-buffer`
[ "ported", "from", "safe", "-", "buffer" ]
caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9
https://github.com/reklatsmasters/btparse/blob/caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9/lib/from.js#L6-L11
train
ryanseddon/bunyip
lib/localbrowsers.js
function(browser, data) { // Some browsers are platform specific so exit out if not available if(data[browser][process.platform]) { if(browser.indexOf("firefox") !== -1) { // Handles firefox, firefox aurora and firefox nightly cleanLaunchFirefox(browser, data); } else if(browser.indexOf("chrome") !== -1) { // Handles chrome and chrome canary cleanLaunchChrome(browser, data); } else if(browser.indexOf("opera") !== -1) { // Handles opera and opera next cleanLaunchOpera(browser, data); } else if(browser.indexOf("phantomjs") !== -1) { // Handles opera and opera next cleanLaunchPhantomjs(browser, data); } else { // Safari don't require special treatment data[browser].process = exec(data[browser][process.platform] + " " + url); } } }
javascript
function(browser, data) { // Some browsers are platform specific so exit out if not available if(data[browser][process.platform]) { if(browser.indexOf("firefox") !== -1) { // Handles firefox, firefox aurora and firefox nightly cleanLaunchFirefox(browser, data); } else if(browser.indexOf("chrome") !== -1) { // Handles chrome and chrome canary cleanLaunchChrome(browser, data); } else if(browser.indexOf("opera") !== -1) { // Handles opera and opera next cleanLaunchOpera(browser, data); } else if(browser.indexOf("phantomjs") !== -1) { // Handles opera and opera next cleanLaunchPhantomjs(browser, data); } else { // Safari don't require special treatment data[browser].process = exec(data[browser][process.platform] + " " + url); } } }
[ "function", "(", "browser", ",", "data", ")", "{", "if", "(", "data", "[", "browser", "]", "[", "process", ".", "platform", "]", ")", "{", "if", "(", "browser", ".", "indexOf", "(", "\"firefox\"", ")", "!==", "-", "1", ")", "{", "cleanLaunchFirefox", "(", "browser", ",", "data", ")", ";", "}", "else", "if", "(", "browser", ".", "indexOf", "(", "\"chrome\"", ")", "!==", "-", "1", ")", "{", "cleanLaunchChrome", "(", "browser", ",", "data", ")", ";", "}", "else", "if", "(", "browser", ".", "indexOf", "(", "\"opera\"", ")", "!==", "-", "1", ")", "{", "cleanLaunchOpera", "(", "browser", ",", "data", ")", ";", "}", "else", "if", "(", "browser", ".", "indexOf", "(", "\"phantomjs\"", ")", "!==", "-", "1", ")", "{", "cleanLaunchPhantomjs", "(", "browser", ",", "data", ")", ";", "}", "else", "{", "data", "[", "browser", "]", ".", "process", "=", "exec", "(", "data", "[", "browser", "]", "[", "process", ".", "platform", "]", "+", "\" \"", "+", "url", ")", ";", "}", "}", "}" ]
In order to get browsers to launch without error we need to pass specific flags to some of them
[ "In", "order", "to", "get", "browsers", "to", "launch", "without", "error", "we", "need", "to", "pass", "specific", "flags", "to", "some", "of", "them" ]
b2d05c0defb91615117316c69568e80acad76bb1
https://github.com/ryanseddon/bunyip/blob/b2d05c0defb91615117316c69568e80acad76bb1/lib/localbrowsers.js#L96-L116
train
Accusoft/framing
components.js
canInitialize
function canInitialize(dependencies, initialized) { return !dependencies || dependencies.length === 0 || dependencies.every(function (name) { return !!initialized[name]; }); }
javascript
function canInitialize(dependencies, initialized) { return !dependencies || dependencies.length === 0 || dependencies.every(function (name) { return !!initialized[name]; }); }
[ "function", "canInitialize", "(", "dependencies", ",", "initialized", ")", "{", "return", "!", "dependencies", "||", "dependencies", ".", "length", "===", "0", "||", "dependencies", ".", "every", "(", "function", "(", "name", ")", "{", "return", "!", "!", "initialized", "[", "name", "]", ";", "}", ")", ";", "}" ]
check if all dependencies for a component have initialized
[ "check", "if", "all", "dependencies", "for", "a", "component", "have", "initialized" ]
709e9a92b28a00a9439e08d3f0feba613a60d10e
https://github.com/Accusoft/framing/blob/709e9a92b28a00a9439e08d3f0feba613a60d10e/components.js#L363-L369
train
Accusoft/framing
components.js
done
function done(error) { if (error) { errors.push(error); } if (--initializing <= 0) { if (errors && errors.length) { var errorResult = new Error('Errors occurred during initialization.'); errorResult.initializationErrors = errors; callback(errorResult); } else { processPostInitializeQueue(postInitializeQueue, callback); } } }
javascript
function done(error) { if (error) { errors.push(error); } if (--initializing <= 0) { if (errors && errors.length) { var errorResult = new Error('Errors occurred during initialization.'); errorResult.initializationErrors = errors; callback(errorResult); } else { processPostInitializeQueue(postInitializeQueue, callback); } } }
[ "function", "done", "(", "error", ")", "{", "if", "(", "error", ")", "{", "errors", ".", "push", "(", "error", ")", ";", "}", "if", "(", "--", "initializing", "<=", "0", ")", "{", "if", "(", "errors", "&&", "errors", ".", "length", ")", "{", "var", "errorResult", "=", "new", "Error", "(", "'Errors occurred during initialization.'", ")", ";", "errorResult", ".", "initializationErrors", "=", "errors", ";", "callback", "(", "errorResult", ")", ";", "}", "else", "{", "processPostInitializeQueue", "(", "postInitializeQueue", ",", "callback", ")", ";", "}", "}", "}" ]
decrement initializing until all asynchronously initilizations have completed
[ "decrement", "initializing", "until", "all", "asynchronously", "initilizations", "have", "completed" ]
709e9a92b28a00a9439e08d3f0feba613a60d10e
https://github.com/Accusoft/framing/blob/709e9a92b28a00a9439e08d3f0feba613a60d10e/components.js#L428-L441
train
abubakir1997/anew
lib/store/utils/createPersistStore.js
createPersistStore
function createPersistStore(reduxStore) { var persistor = (0, _reduxPersist.persistStore)(reduxStore); var dispatch = persistor.dispatch, getState = persistor.getState; reduxStore.persistor = persistor; reduxStore.getState.persistor = getState; reduxStore.dispatch.persistor = dispatch; reduxStore.dispatch.persistor = Object.assign(reduxStore.dispatch.persistor, { flush: persistor.flush, pause: persistor.pause, persist: persistor.flush, purge: persistor.purge }); return reduxStore; }
javascript
function createPersistStore(reduxStore) { var persistor = (0, _reduxPersist.persistStore)(reduxStore); var dispatch = persistor.dispatch, getState = persistor.getState; reduxStore.persistor = persistor; reduxStore.getState.persistor = getState; reduxStore.dispatch.persistor = dispatch; reduxStore.dispatch.persistor = Object.assign(reduxStore.dispatch.persistor, { flush: persistor.flush, pause: persistor.pause, persist: persistor.flush, purge: persistor.purge }); return reduxStore; }
[ "function", "createPersistStore", "(", "reduxStore", ")", "{", "var", "persistor", "=", "(", "0", ",", "_reduxPersist", ".", "persistStore", ")", "(", "reduxStore", ")", ";", "var", "dispatch", "=", "persistor", ".", "dispatch", ",", "getState", "=", "persistor", ".", "getState", ";", "reduxStore", ".", "persistor", "=", "persistor", ";", "reduxStore", ".", "getState", ".", "persistor", "=", "getState", ";", "reduxStore", ".", "dispatch", ".", "persistor", "=", "dispatch", ";", "reduxStore", ".", "dispatch", ".", "persistor", "=", "Object", ".", "assign", "(", "reduxStore", ".", "dispatch", ".", "persistor", ",", "{", "flush", ":", "persistor", ".", "flush", ",", "pause", ":", "persistor", ".", "pause", ",", "persist", ":", "persistor", ".", "flush", ",", "purge", ":", "persistor", ".", "purge", "}", ")", ";", "return", "reduxStore", ";", "}" ]
Create persist store as a property inside the redux store @return { Object } Redux Store Object Shape
[ "Create", "persist", "store", "as", "a", "property", "inside", "the", "redux", "store" ]
a79a01ea7b989184d5dddc0bd7de05efb2b02c8c
https://github.com/abubakir1997/anew/blob/a79a01ea7b989184d5dddc0bd7de05efb2b02c8c/lib/store/utils/createPersistStore.js#L14-L31
train
mgmcintyre/grunt-php-cs-fixer
tasks/lib/phpcsfixer.js
function(paths) { var appends = []; if (grunt.option("quiet") || config.quiet) { appends.push("--quiet"); } if (grunt.option("verbose") || config.verbose) { appends.push("--verbose"); } if (grunt.option("rules") || config.rules) { var rules = _.isString(config.rules) ? config.rules.split(",") : config.rules; appends.push("--rules=" + rules.join(",")); } if (grunt.option("dryRun") || config.dryRun) { appends.push("--dry-run"); } if (grunt.option("diff") || config.diff) { appends.push("--diff"); } if (grunt.option("allowRisky") || config.allowRisky) { appends.push("--allow-risky yes"); } if (grunt.option("usingCache") || config.usingCache) { appends.push("--using-cache " + config.usingCache); } if (grunt.option("configfile") || config.configfile) { appends.push("--config=" + config.configfile); } var bin = path.normalize(config.bin), append = appends.join(" "), cmds = []; if (paths.length) { cmds = _.map(paths, function(thePath) { return bin + " fix " + thePath + " " + append; }); } if (grunt.option("configfile") || config.configfile) { cmds.push(bin + " fix " + append); } return cmds; }
javascript
function(paths) { var appends = []; if (grunt.option("quiet") || config.quiet) { appends.push("--quiet"); } if (grunt.option("verbose") || config.verbose) { appends.push("--verbose"); } if (grunt.option("rules") || config.rules) { var rules = _.isString(config.rules) ? config.rules.split(",") : config.rules; appends.push("--rules=" + rules.join(",")); } if (grunt.option("dryRun") || config.dryRun) { appends.push("--dry-run"); } if (grunt.option("diff") || config.diff) { appends.push("--diff"); } if (grunt.option("allowRisky") || config.allowRisky) { appends.push("--allow-risky yes"); } if (grunt.option("usingCache") || config.usingCache) { appends.push("--using-cache " + config.usingCache); } if (grunt.option("configfile") || config.configfile) { appends.push("--config=" + config.configfile); } var bin = path.normalize(config.bin), append = appends.join(" "), cmds = []; if (paths.length) { cmds = _.map(paths, function(thePath) { return bin + " fix " + thePath + " " + append; }); } if (grunt.option("configfile") || config.configfile) { cmds.push(bin + " fix " + append); } return cmds; }
[ "function", "(", "paths", ")", "{", "var", "appends", "=", "[", "]", ";", "if", "(", "grunt", ".", "option", "(", "\"quiet\"", ")", "||", "config", ".", "quiet", ")", "{", "appends", ".", "push", "(", "\"--quiet\"", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"verbose\"", ")", "||", "config", ".", "verbose", ")", "{", "appends", ".", "push", "(", "\"--verbose\"", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"rules\"", ")", "||", "config", ".", "rules", ")", "{", "var", "rules", "=", "_", ".", "isString", "(", "config", ".", "rules", ")", "?", "config", ".", "rules", ".", "split", "(", "\",\"", ")", ":", "config", ".", "rules", ";", "appends", ".", "push", "(", "\"--rules=\"", "+", "rules", ".", "join", "(", "\",\"", ")", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"dryRun\"", ")", "||", "config", ".", "dryRun", ")", "{", "appends", ".", "push", "(", "\"--dry-run\"", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"diff\"", ")", "||", "config", ".", "diff", ")", "{", "appends", ".", "push", "(", "\"--diff\"", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"allowRisky\"", ")", "||", "config", ".", "allowRisky", ")", "{", "appends", ".", "push", "(", "\"--allow-risky yes\"", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"usingCache\"", ")", "||", "config", ".", "usingCache", ")", "{", "appends", ".", "push", "(", "\"--using-cache \"", "+", "config", ".", "usingCache", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"configfile\"", ")", "||", "config", ".", "configfile", ")", "{", "appends", ".", "push", "(", "\"--config=\"", "+", "config", ".", "configfile", ")", ";", "}", "var", "bin", "=", "path", ".", "normalize", "(", "config", ".", "bin", ")", ",", "append", "=", "appends", ".", "join", "(", "\" \"", ")", ",", "cmds", "=", "[", "]", ";", "if", "(", "paths", ".", "length", ")", "{", "cmds", "=", "_", ".", "map", "(", "paths", ",", "function", "(", "thePath", ")", "{", "return", "bin", "+", "\" fix \"", "+", "thePath", "+", "\" \"", "+", "append", ";", "}", ")", ";", "}", "if", "(", "grunt", ".", "option", "(", "\"configfile\"", ")", "||", "config", ".", "configfile", ")", "{", "cmds", ".", "push", "(", "bin", "+", "\" fix \"", "+", "append", ")", ";", "}", "return", "cmds", ";", "}" ]
Builds phpunit command @return string
[ "Builds", "phpunit", "command" ]
5ce85ba3c73e54de75faf3dc1d3246dea4ddb084
https://github.com/mgmcintyre/grunt-php-cs-fixer/blob/5ce85ba3c73e54de75faf3dc1d3246dea4ddb084/tasks/lib/phpcsfixer.js#L40-L92
train
socialtables/geometry-utils
lib/shape.js
createPointObjects
function createPointObjects(array) { if (!array) { array = []; } var acc = array.reduce(function(accumulator, current) { if (current.x && current.y) { // Point accumulator.push(current); } else if (current.start && current.end && current.height) { // Arc // Consider an arc "flat enough" if its height is < the value times its length if (!current.interpolatedPoints) { current = new Arc(current.start, current.end, current.height); } var newPoints = current.interpolatedPoints({relative: 0.1}); accumulator = accumulator.concat(newPoints); } else if (current[0] && current[1]) { // x, y pair var pt = new Point(current[0], current[1]); accumulator.push(pt); } else { debug("don't know how to accommodate", current); } return accumulator; }, []); return acc; }
javascript
function createPointObjects(array) { if (!array) { array = []; } var acc = array.reduce(function(accumulator, current) { if (current.x && current.y) { // Point accumulator.push(current); } else if (current.start && current.end && current.height) { // Arc // Consider an arc "flat enough" if its height is < the value times its length if (!current.interpolatedPoints) { current = new Arc(current.start, current.end, current.height); } var newPoints = current.interpolatedPoints({relative: 0.1}); accumulator = accumulator.concat(newPoints); } else if (current[0] && current[1]) { // x, y pair var pt = new Point(current[0], current[1]); accumulator.push(pt); } else { debug("don't know how to accommodate", current); } return accumulator; }, []); return acc; }
[ "function", "createPointObjects", "(", "array", ")", "{", "if", "(", "!", "array", ")", "{", "array", "=", "[", "]", ";", "}", "var", "acc", "=", "array", ".", "reduce", "(", "function", "(", "accumulator", ",", "current", ")", "{", "if", "(", "current", ".", "x", "&&", "current", ".", "y", ")", "{", "accumulator", ".", "push", "(", "current", ")", ";", "}", "else", "if", "(", "current", ".", "start", "&&", "current", ".", "end", "&&", "current", ".", "height", ")", "{", "if", "(", "!", "current", ".", "interpolatedPoints", ")", "{", "current", "=", "new", "Arc", "(", "current", ".", "start", ",", "current", ".", "end", ",", "current", ".", "height", ")", ";", "}", "var", "newPoints", "=", "current", ".", "interpolatedPoints", "(", "{", "relative", ":", "0.1", "}", ")", ";", "accumulator", "=", "accumulator", ".", "concat", "(", "newPoints", ")", ";", "}", "else", "if", "(", "current", "[", "0", "]", "&&", "current", "[", "1", "]", ")", "{", "var", "pt", "=", "new", "Point", "(", "current", "[", "0", "]", ",", "current", "[", "1", "]", ")", ";", "accumulator", ".", "push", "(", "pt", ")", ";", "}", "else", "{", "debug", "(", "\"don't know how to accommodate\"", ",", "current", ")", ";", "}", "return", "accumulator", ";", "}", ",", "[", "]", ")", ";", "return", "acc", ";", "}" ]
Ensure that the array is one of Point objects. If they're already `Point`s, simply return a copy; if not, create the `Point`s, interpolate the `Arc`s, etc
[ "Ensure", "that", "the", "array", "is", "one", "of", "Point", "objects", ".", "If", "they", "re", "already", "Point", "s", "simply", "return", "a", "copy", ";", "if", "not", "create", "the", "Point", "s", "interpolate", "the", "Arc", "s", "etc" ]
4dc13529696a52dbe2d2cfcad3204dd39fca2f88
https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/shape.js#L11-L38
train
uyu423/node-qsb
index.js
esc
function esc(str) { if(typeof(str) !== "string") str = "" + str; str = str.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(res) { switch(res) { case "\0": return "\\0"; case "\n": return "\\n"; case "\r": return "\\r"; case "\b": return "\\b"; case "\t": return "\\t"; case "\x1a": return "\\Z"; default: return "\\"+res; } }); return "'"+str+"'"; }
javascript
function esc(str) { if(typeof(str) !== "string") str = "" + str; str = str.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(res) { switch(res) { case "\0": return "\\0"; case "\n": return "\\n"; case "\r": return "\\r"; case "\b": return "\\b"; case "\t": return "\\t"; case "\x1a": return "\\Z"; default: return "\\"+res; } }); return "'"+str+"'"; }
[ "function", "esc", "(", "str", ")", "{", "if", "(", "typeof", "(", "str", ")", "!==", "\"string\"", ")", "str", "=", "\"\"", "+", "str", ";", "str", "=", "str", ".", "replace", "(", "/", "[\\0\\n\\r\\b\\t\\\\\\'\\\"\\x1a]", "/", "g", ",", "function", "(", "res", ")", "{", "switch", "(", "res", ")", "{", "case", "\"\\0\"", ":", "\\0", "return", "\"\\\\0\"", ";", "\\\\", "case", "\"\\n\"", ":", "\\n", "return", "\"\\\\n\"", ";", "\\\\", "case", "\"\\r\"", ":", "\\r", "}", "}", ")", ";", "return", "\"\\\\r\"", ";", "}" ]
add Back Quote
[ "add", "Back", "Quote" ]
037d58178eafb0cbd39ae335215086ab6a3074cf
https://github.com/uyu423/node-qsb/blob/037d58178eafb0cbd39ae335215086ab6a3074cf/index.js#L8-L23
train
logikum/md-site-engine
source/readers/read-components.js
readComponents
function readComponents( componentPath, referenceFile, localeFile, layoutSegment, contentSegment, filingCabinet, renderer ) { logger.showInfo( '*** Reading components...' ); // Initialize the store. getComponents( componentPath, 0, '', referenceFile, localeFile, layoutSegment, contentSegment, filingCabinet.references, filingCabinet.documents, filingCabinet.layouts, filingCabinet.segments, filingCabinet.locales, renderer, '' ); }
javascript
function readComponents( componentPath, referenceFile, localeFile, layoutSegment, contentSegment, filingCabinet, renderer ) { logger.showInfo( '*** Reading components...' ); // Initialize the store. getComponents( componentPath, 0, '', referenceFile, localeFile, layoutSegment, contentSegment, filingCabinet.references, filingCabinet.documents, filingCabinet.layouts, filingCabinet.segments, filingCabinet.locales, renderer, '' ); }
[ "function", "readComponents", "(", "componentPath", ",", "referenceFile", ",", "localeFile", ",", "layoutSegment", ",", "contentSegment", ",", "filingCabinet", ",", "renderer", ")", "{", "logger", ".", "showInfo", "(", "'*** Reading components...'", ")", ";", "getComponents", "(", "componentPath", ",", "0", ",", "''", ",", "referenceFile", ",", "localeFile", ",", "layoutSegment", ",", "contentSegment", ",", "filingCabinet", ".", "references", ",", "filingCabinet", ".", "documents", ",", "filingCabinet", ".", "layouts", ",", "filingCabinet", ".", "segments", ",", "filingCabinet", ".", "locales", ",", "renderer", ",", "''", ")", ";", "}" ]
Reads all components. @param {string} componentPath - The path of the components directory. @param {string} referenceFile - The name of the reference files. @param {string} localeFile - The name of the default locale file. @param {string} layoutSegment - The name of the layout segment. @param {string} contentSegment - The name of the layout segment. @param {FilingCabinet} filingCabinet - The file manager object. @param {marked.Renderer} renderer - The custom markdown renderer.
[ "Reads", "all", "components", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/read-components.js#L22-L40
train
IanVS/eslint-filtered-fix
src/filtered-fix.js
makeFixer
function makeFixer(options) { if (typeof options === 'undefined') { return true; } if (typeof options === 'boolean') { return options; } const rulesToFix = options.rules; const fixWarnings = options.warnings; function ruleFixer(eslintMessage) { if (!rulesToFix) return true; if (rulesToFix.indexOf(eslintMessage.ruleId) !== -1) { return true; } return false; } function warningFixer(eslintMessage) { if (fixWarnings === false) { return eslintMessage.severity === 2; } return true; } return function (eslintMessage) { return ruleFixer(eslintMessage) && warningFixer(eslintMessage); }; }
javascript
function makeFixer(options) { if (typeof options === 'undefined') { return true; } if (typeof options === 'boolean') { return options; } const rulesToFix = options.rules; const fixWarnings = options.warnings; function ruleFixer(eslintMessage) { if (!rulesToFix) return true; if (rulesToFix.indexOf(eslintMessage.ruleId) !== -1) { return true; } return false; } function warningFixer(eslintMessage) { if (fixWarnings === false) { return eslintMessage.severity === 2; } return true; } return function (eslintMessage) { return ruleFixer(eslintMessage) && warningFixer(eslintMessage); }; }
[ "function", "makeFixer", "(", "options", ")", "{", "if", "(", "typeof", "options", "===", "'undefined'", ")", "{", "return", "true", ";", "}", "if", "(", "typeof", "options", "===", "'boolean'", ")", "{", "return", "options", ";", "}", "const", "rulesToFix", "=", "options", ".", "rules", ";", "const", "fixWarnings", "=", "options", ".", "warnings", ";", "function", "ruleFixer", "(", "eslintMessage", ")", "{", "if", "(", "!", "rulesToFix", ")", "return", "true", ";", "if", "(", "rulesToFix", ".", "indexOf", "(", "eslintMessage", ".", "ruleId", ")", "!==", "-", "1", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "function", "warningFixer", "(", "eslintMessage", ")", "{", "if", "(", "fixWarnings", "===", "false", ")", "{", "return", "eslintMessage", ".", "severity", "===", "2", ";", "}", "return", "true", ";", "}", "return", "function", "(", "eslintMessage", ")", "{", "return", "ruleFixer", "(", "eslintMessage", ")", "&&", "warningFixer", "(", "eslintMessage", ")", ";", "}", ";", "}" ]
Creates a fixing function or boolean that can be provided as eslint's `fix` option. @param {Object|boolean} options Either an options object, or a boolean @return {Function|boolean} `fix` option for eslint
[ "Creates", "a", "fixing", "function", "or", "boolean", "that", "can", "be", "provided", "as", "eslint", "s", "fix", "option", "." ]
8501cf8c3db4c18f7be0b0a9877ddbba7fd56a59
https://github.com/IanVS/eslint-filtered-fix/blob/8501cf8c3db4c18f7be0b0a9877ddbba7fd56a59/src/filtered-fix.js#L12-L44
train
localvoid/pck
benchmarks/browser/benchmark.js
createFunction
function createFunction() { // Lazy define. createFunction = function(args, body) { var result, anchor = freeDefine ? freeDefine.amd : Benchmark, prop = uid + 'createFunction'; runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}'); result = anchor[prop]; delete anchor[prop]; return result; }; // Fix JaegerMonkey bug. // For more information see http://bugzil.la/639720. createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function; return createFunction.apply(null, arguments); }
javascript
function createFunction() { // Lazy define. createFunction = function(args, body) { var result, anchor = freeDefine ? freeDefine.amd : Benchmark, prop = uid + 'createFunction'; runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}'); result = anchor[prop]; delete anchor[prop]; return result; }; // Fix JaegerMonkey bug. // For more information see http://bugzil.la/639720. createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function; return createFunction.apply(null, arguments); }
[ "function", "createFunction", "(", ")", "{", "createFunction", "=", "function", "(", "args", ",", "body", ")", "{", "var", "result", ",", "anchor", "=", "freeDefine", "?", "freeDefine", ".", "amd", ":", "Benchmark", ",", "prop", "=", "uid", "+", "'createFunction'", ";", "runScript", "(", "(", "freeDefine", "?", "'define.amd.'", ":", "'Benchmark.'", ")", "+", "prop", "+", "'=function('", "+", "args", "+", "'){'", "+", "body", "+", "'}'", ")", ";", "result", "=", "anchor", "[", "prop", "]", ";", "delete", "anchor", "[", "prop", "]", ";", "return", "result", ";", "}", ";", "createFunction", "=", "support", ".", "browser", "&&", "(", "createFunction", "(", "''", ",", "'return\"'", "+", "uid", "+", "'\"'", ")", "||", "_", ".", "noop", ")", "(", ")", "==", "uid", "?", "createFunction", ":", "Function", ";", "return", "createFunction", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}" ]
Creates a function from the given arguments string and body. @private @param {string} args The comma separated function arguments. @param {string} body The function body. @returns {Function} The new function.
[ "Creates", "a", "function", "from", "the", "given", "arguments", "string", "and", "body", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L510-L526
train
localvoid/pck
benchmarks/browser/benchmark.js
delay
function delay(bench, fn) { bench._timerId = _.delay(fn, bench.delay * 1e3); }
javascript
function delay(bench, fn) { bench._timerId = _.delay(fn, bench.delay * 1e3); }
[ "function", "delay", "(", "bench", ",", "fn", ")", "{", "bench", ".", "_timerId", "=", "_", ".", "delay", "(", "fn", ",", "bench", ".", "delay", "*", "1e3", ")", ";", "}" ]
Delay the execution of a function based on the benchmark's `delay` property. @private @param {Object} bench The benchmark instance. @param {Object} fn The function to execute.
[ "Delay", "the", "execution", "of", "a", "function", "based", "on", "the", "benchmark", "s", "delay", "property", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L535-L537
train
localvoid/pck
benchmarks/browser/benchmark.js
getMean
function getMean(sample) { return (_.reduce(sample, function(sum, x) { return sum + x; }) / sample.length) || 0; }
javascript
function getMean(sample) { return (_.reduce(sample, function(sum, x) { return sum + x; }) / sample.length) || 0; }
[ "function", "getMean", "(", "sample", ")", "{", "return", "(", "_", ".", "reduce", "(", "sample", ",", "function", "(", "sum", ",", "x", ")", "{", "return", "sum", "+", "x", ";", "}", ")", "/", "sample", ".", "length", ")", "||", "0", ";", "}" ]
Computes the arithmetic mean of a sample. @private @param {Array} sample The sample. @returns {number} The mean.
[ "Computes", "the", "arithmetic", "mean", "of", "a", "sample", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L569-L573
train
localvoid/pck
benchmarks/browser/benchmark.js
isStringable
function isStringable(value) { return _.isString(value) || (_.has(value, 'toString') && _.isFunction(value.toString)); }
javascript
function isStringable(value) { return _.isString(value) || (_.has(value, 'toString') && _.isFunction(value.toString)); }
[ "function", "isStringable", "(", "value", ")", "{", "return", "_", ".", "isString", "(", "value", ")", "||", "(", "_", ".", "has", "(", "value", ",", "'toString'", ")", "&&", "_", ".", "isFunction", "(", "value", ".", "toString", ")", ")", ";", "}" ]
Checks if a value can be safely coerced to a string. @private @param {*} value The value to check. @returns {boolean} Returns `true` if the value can be coerced, else `false`.
[ "Checks", "if", "a", "value", "can", "be", "safely", "coerced", "to", "a", "string", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L636-L638
train
localvoid/pck
benchmarks/browser/benchmark.js
execute
function execute() { var listeners, async = isAsync(bench); if (async) { // Use `getNext` as the first listener. bench.on('complete', getNext); listeners = bench.events.complete; listeners.splice(0, 0, listeners.pop()); } // Execute method. result[index] = _.isFunction(bench && bench[name]) ? bench[name].apply(bench, args) : undefined; // If synchronous return `true` until finished. return !async && getNext(); }
javascript
function execute() { var listeners, async = isAsync(bench); if (async) { // Use `getNext` as the first listener. bench.on('complete', getNext); listeners = bench.events.complete; listeners.splice(0, 0, listeners.pop()); } // Execute method. result[index] = _.isFunction(bench && bench[name]) ? bench[name].apply(bench, args) : undefined; // If synchronous return `true` until finished. return !async && getNext(); }
[ "function", "execute", "(", ")", "{", "var", "listeners", ",", "async", "=", "isAsync", "(", "bench", ")", ";", "if", "(", "async", ")", "{", "bench", ".", "on", "(", "'complete'", ",", "getNext", ")", ";", "listeners", "=", "bench", ".", "events", ".", "complete", ";", "listeners", ".", "splice", "(", "0", ",", "0", ",", "listeners", ".", "pop", "(", ")", ")", ";", "}", "result", "[", "index", "]", "=", "_", ".", "isFunction", "(", "bench", "&&", "bench", "[", "name", "]", ")", "?", "bench", "[", "name", "]", ".", "apply", "(", "bench", ",", "args", ")", ":", "undefined", ";", "return", "!", "async", "&&", "getNext", "(", ")", ";", "}" ]
Invokes the method of the current object and if synchronous, fetches the next.
[ "Invokes", "the", "method", "of", "the", "current", "object", "and", "if", "synchronous", "fetches", "the", "next", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L849-L863
train
localvoid/pck
benchmarks/browser/benchmark.js
getNext
function getNext(event) { var cycleEvent, last = bench, async = isAsync(last); if (async) { last.off('complete', getNext); last.emit('complete'); } // Emit "cycle" event. eventProps.type = 'cycle'; eventProps.target = last; cycleEvent = Event(eventProps); options.onCycle.call(benches, cycleEvent); // Choose next benchmark if not exiting early. if (!cycleEvent.aborted && raiseIndex() !== false) { bench = queued ? benches[0] : result[index]; if (isAsync(bench)) { delay(bench, execute); } else if (async) { // Resume execution if previously asynchronous but now synchronous. while (execute()) {} } else { // Continue synchronous execution. return true; } } else { // Emit "complete" event. eventProps.type = 'complete'; options.onComplete.call(benches, Event(eventProps)); } // When used as a listener `event.aborted = true` will cancel the rest of // the "complete" listeners because they were already called above and when // used as part of `getNext` the `return false` will exit the execution while-loop. if (event) { event.aborted = true; } else { return false; } }
javascript
function getNext(event) { var cycleEvent, last = bench, async = isAsync(last); if (async) { last.off('complete', getNext); last.emit('complete'); } // Emit "cycle" event. eventProps.type = 'cycle'; eventProps.target = last; cycleEvent = Event(eventProps); options.onCycle.call(benches, cycleEvent); // Choose next benchmark if not exiting early. if (!cycleEvent.aborted && raiseIndex() !== false) { bench = queued ? benches[0] : result[index]; if (isAsync(bench)) { delay(bench, execute); } else if (async) { // Resume execution if previously asynchronous but now synchronous. while (execute()) {} } else { // Continue synchronous execution. return true; } } else { // Emit "complete" event. eventProps.type = 'complete'; options.onComplete.call(benches, Event(eventProps)); } // When used as a listener `event.aborted = true` will cancel the rest of // the "complete" listeners because they were already called above and when // used as part of `getNext` the `return false` will exit the execution while-loop. if (event) { event.aborted = true; } else { return false; } }
[ "function", "getNext", "(", "event", ")", "{", "var", "cycleEvent", ",", "last", "=", "bench", ",", "async", "=", "isAsync", "(", "last", ")", ";", "if", "(", "async", ")", "{", "last", ".", "off", "(", "'complete'", ",", "getNext", ")", ";", "last", ".", "emit", "(", "'complete'", ")", ";", "}", "eventProps", ".", "type", "=", "'cycle'", ";", "eventProps", ".", "target", "=", "last", ";", "cycleEvent", "=", "Event", "(", "eventProps", ")", ";", "options", ".", "onCycle", ".", "call", "(", "benches", ",", "cycleEvent", ")", ";", "if", "(", "!", "cycleEvent", ".", "aborted", "&&", "raiseIndex", "(", ")", "!==", "false", ")", "{", "bench", "=", "queued", "?", "benches", "[", "0", "]", ":", "result", "[", "index", "]", ";", "if", "(", "isAsync", "(", "bench", ")", ")", "{", "delay", "(", "bench", ",", "execute", ")", ";", "}", "else", "if", "(", "async", ")", "{", "while", "(", "execute", "(", ")", ")", "{", "}", "}", "else", "{", "return", "true", ";", "}", "}", "else", "{", "eventProps", ".", "type", "=", "'complete'", ";", "options", ".", "onComplete", ".", "call", "(", "benches", ",", "Event", "(", "eventProps", ")", ")", ";", "}", "if", "(", "event", ")", "{", "event", ".", "aborted", "=", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Fetches the next bench or executes `onComplete` callback.
[ "Fetches", "the", "next", "bench", "or", "executes", "onComplete", "callback", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L868-L910
train
localvoid/pck
benchmarks/browser/benchmark.js
compare
function compare(other) { var bench = this; // Exit early if comparing the same benchmark. if (bench == other) { return 0; } var critical, zStat, sample1 = bench.stats.sample, sample2 = other.stats.sample, size1 = sample1.length, size2 = sample2.length, maxSize = max(size1, size2), minSize = min(size1, size2), u1 = getU(sample1, sample2), u2 = getU(sample2, sample1), u = min(u1, u2); function getScore(xA, sampleB) { return _.reduce(sampleB, function(total, xB) { return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5); }, 0); } function getU(sampleA, sampleB) { return _.reduce(sampleA, function(total, xA) { return total + getScore(xA, sampleB); }, 0); } function getZ(u) { return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12); } // Reject the null hypothesis the two samples come from the // same population (i.e. have the same median) if... if (size1 + size2 > 30) { // ...the z-stat is greater than 1.96 or less than -1.96 // http://www.statisticslectures.com/topics/mannwhitneyu/ zStat = getZ(u); return abs(zStat) > 1.96 ? (u == u1 ? 1 : -1) : 0; } // ...the U value is less than or equal the critical U value. critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3]; return u <= critical ? (u == u1 ? 1 : -1) : 0; }
javascript
function compare(other) { var bench = this; // Exit early if comparing the same benchmark. if (bench == other) { return 0; } var critical, zStat, sample1 = bench.stats.sample, sample2 = other.stats.sample, size1 = sample1.length, size2 = sample2.length, maxSize = max(size1, size2), minSize = min(size1, size2), u1 = getU(sample1, sample2), u2 = getU(sample2, sample1), u = min(u1, u2); function getScore(xA, sampleB) { return _.reduce(sampleB, function(total, xB) { return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5); }, 0); } function getU(sampleA, sampleB) { return _.reduce(sampleA, function(total, xA) { return total + getScore(xA, sampleB); }, 0); } function getZ(u) { return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12); } // Reject the null hypothesis the two samples come from the // same population (i.e. have the same median) if... if (size1 + size2 > 30) { // ...the z-stat is greater than 1.96 or less than -1.96 // http://www.statisticslectures.com/topics/mannwhitneyu/ zStat = getZ(u); return abs(zStat) > 1.96 ? (u == u1 ? 1 : -1) : 0; } // ...the U value is less than or equal the critical U value. critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3]; return u <= critical ? (u == u1 ? 1 : -1) : 0; }
[ "function", "compare", "(", "other", ")", "{", "var", "bench", "=", "this", ";", "if", "(", "bench", "==", "other", ")", "{", "return", "0", ";", "}", "var", "critical", ",", "zStat", ",", "sample1", "=", "bench", ".", "stats", ".", "sample", ",", "sample2", "=", "other", ".", "stats", ".", "sample", ",", "size1", "=", "sample1", ".", "length", ",", "size2", "=", "sample2", ".", "length", ",", "maxSize", "=", "max", "(", "size1", ",", "size2", ")", ",", "minSize", "=", "min", "(", "size1", ",", "size2", ")", ",", "u1", "=", "getU", "(", "sample1", ",", "sample2", ")", ",", "u2", "=", "getU", "(", "sample2", ",", "sample1", ")", ",", "u", "=", "min", "(", "u1", ",", "u2", ")", ";", "function", "getScore", "(", "xA", ",", "sampleB", ")", "{", "return", "_", ".", "reduce", "(", "sampleB", ",", "function", "(", "total", ",", "xB", ")", "{", "return", "total", "+", "(", "xB", ">", "xA", "?", "0", ":", "xB", "<", "xA", "?", "1", ":", "0.5", ")", ";", "}", ",", "0", ")", ";", "}", "function", "getU", "(", "sampleA", ",", "sampleB", ")", "{", "return", "_", ".", "reduce", "(", "sampleA", ",", "function", "(", "total", ",", "xA", ")", "{", "return", "total", "+", "getScore", "(", "xA", ",", "sampleB", ")", ";", "}", ",", "0", ")", ";", "}", "function", "getZ", "(", "u", ")", "{", "return", "(", "u", "-", "(", "(", "size1", "*", "size2", ")", "/", "2", ")", ")", "/", "sqrt", "(", "(", "size1", "*", "size2", "*", "(", "size1", "+", "size2", "+", "1", ")", ")", "/", "12", ")", ";", "}", "if", "(", "size1", "+", "size2", ">", "30", ")", "{", "zStat", "=", "getZ", "(", "u", ")", ";", "return", "abs", "(", "zStat", ")", ">", "1.96", "?", "(", "u", "==", "u1", "?", "1", ":", "-", "1", ")", ":", "0", ";", "}", "critical", "=", "maxSize", "<", "5", "||", "minSize", "<", "3", "?", "0", ":", "uTable", "[", "maxSize", "]", "[", "minSize", "-", "3", "]", ";", "return", "u", "<=", "critical", "?", "(", "u", "==", "u1", "?", "1", ":", "-", "1", ")", ":", "0", ";", "}" ]
Determines if a benchmark is faster than another. @memberOf Benchmark @param {Object} other The benchmark to compare. @returns {number} Returns `-1` if slower, `1` if faster, and `0` if indeterminate.
[ "Determines", "if", "a", "benchmark", "is", "faster", "than", "another", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L1391-L1436
train
localvoid/pck
benchmarks/browser/benchmark.js
interpolate
function interpolate(string) { // Replaces all occurrences of `#` with a unique number and template tokens with content. return _.template(string.replace(/\#/g, /\d+/.exec(templateData.uid)))(templateData); }
javascript
function interpolate(string) { // Replaces all occurrences of `#` with a unique number and template tokens with content. return _.template(string.replace(/\#/g, /\d+/.exec(templateData.uid)))(templateData); }
[ "function", "interpolate", "(", "string", ")", "{", "return", "_", ".", "template", "(", "string", ".", "replace", "(", "/", "\\#", "/", "g", ",", "/", "\\d+", "/", ".", "exec", "(", "templateData", ".", "uid", ")", ")", ")", "(", "templateData", ")", ";", "}" ]
Interpolates a given template string.
[ "Interpolates", "a", "given", "template", "string", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/benchmarks/browser/benchmark.js#L1781-L1784
train
logikum/md-site-engine
source/models/menu-tree.js
findItem
function findItem( path, items ) { var result = null; items.forEach( function ( item ) { if (!result && item instanceof MenuItem && item.paths.filter( function( value ) { return value === path; } ).length > 0) result = item; if (!result && item instanceof MenuNode) { var child = findItem( path, item.children ); if (child) result = child; } } ); return result; }
javascript
function findItem( path, items ) { var result = null; items.forEach( function ( item ) { if (!result && item instanceof MenuItem && item.paths.filter( function( value ) { return value === path; } ).length > 0) result = item; if (!result && item instanceof MenuNode) { var child = findItem( path, item.children ); if (child) result = child; } } ); return result; }
[ "function", "findItem", "(", "path", ",", "items", ")", "{", "var", "result", "=", "null", ";", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "!", "result", "&&", "item", "instanceof", "MenuItem", "&&", "item", ".", "paths", ".", "filter", "(", "function", "(", "value", ")", "{", "return", "value", "===", "path", ";", "}", ")", ".", "length", ">", "0", ")", "result", "=", "item", ";", "if", "(", "!", "result", "&&", "item", "instanceof", "MenuNode", ")", "{", "var", "child", "=", "findItem", "(", "path", ",", "item", ".", "children", ")", ";", "if", "(", "child", ")", "result", "=", "child", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
region Helper methods
[ "region", "Helper", "methods" ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/models/menu-tree.js#L55-L69
train
agco/elastic-harvesterjs
elastic-harvester.js
getAggregationFields
function getAggregationFields(query, aggParam, supplimentalBanList) { let retVal = []; const _aggParam = aggParam || 'aggregations'; if (!query[_aggParam]) { return retVal; } const _supplimentalBanList = supplimentalBanList || {}; _.each(query[_aggParam].split(','), (agg) => { assertAggNameIsAllowed(agg, _supplimentalBanList); _supplimentalBanList[agg] = true; let _type = query[`${agg}.type`]; !_type && (_type = 'terms'); const aggOptions = permittedAggOptions[_type]; _.each(aggOptions, (aggOption) => { const expectedOptionName = `${agg}.${aggOption}`; retVal.push(expectedOptionName); }); if (query[`${agg}.aggregations`]) { const nestedAggFields = getAggregationFields(query, `${agg}.aggregations`, _supplimentalBanList); retVal = retVal.concat(nestedAggFields); } }); return retVal; }
javascript
function getAggregationFields(query, aggParam, supplimentalBanList) { let retVal = []; const _aggParam = aggParam || 'aggregations'; if (!query[_aggParam]) { return retVal; } const _supplimentalBanList = supplimentalBanList || {}; _.each(query[_aggParam].split(','), (agg) => { assertAggNameIsAllowed(agg, _supplimentalBanList); _supplimentalBanList[agg] = true; let _type = query[`${agg}.type`]; !_type && (_type = 'terms'); const aggOptions = permittedAggOptions[_type]; _.each(aggOptions, (aggOption) => { const expectedOptionName = `${agg}.${aggOption}`; retVal.push(expectedOptionName); }); if (query[`${agg}.aggregations`]) { const nestedAggFields = getAggregationFields(query, `${agg}.aggregations`, _supplimentalBanList); retVal = retVal.concat(nestedAggFields); } }); return retVal; }
[ "function", "getAggregationFields", "(", "query", ",", "aggParam", ",", "supplimentalBanList", ")", "{", "let", "retVal", "=", "[", "]", ";", "const", "_aggParam", "=", "aggParam", "||", "'aggregations'", ";", "if", "(", "!", "query", "[", "_aggParam", "]", ")", "{", "return", "retVal", ";", "}", "const", "_supplimentalBanList", "=", "supplimentalBanList", "||", "{", "}", ";", "_", ".", "each", "(", "query", "[", "_aggParam", "]", ".", "split", "(", "','", ")", ",", "(", "agg", ")", "=>", "{", "assertAggNameIsAllowed", "(", "agg", ",", "_supplimentalBanList", ")", ";", "_supplimentalBanList", "[", "agg", "]", "=", "true", ";", "let", "_type", "=", "query", "[", "`", "${", "agg", "}", "`", "]", ";", "!", "_type", "&&", "(", "_type", "=", "'terms'", ")", ";", "const", "aggOptions", "=", "permittedAggOptions", "[", "_type", "]", ";", "_", ".", "each", "(", "aggOptions", ",", "(", "aggOption", ")", "=>", "{", "const", "expectedOptionName", "=", "`", "${", "agg", "}", "${", "aggOption", "}", "`", ";", "retVal", ".", "push", "(", "expectedOptionName", ")", ";", "}", ")", ";", "if", "(", "query", "[", "`", "${", "agg", "}", "`", "]", ")", "{", "const", "nestedAggFields", "=", "getAggregationFields", "(", "query", ",", "`", "${", "agg", "}", "`", ",", "_supplimentalBanList", ")", ";", "retVal", "=", "retVal", ".", "concat", "(", "nestedAggFields", ")", ";", "}", "}", ")", ";", "return", "retVal", ";", "}" ]
returns an array of all protected aggregationFields
[ "returns", "an", "array", "of", "all", "protected", "aggregationFields" ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L141-L167
train
agco/elastic-harvesterjs
elastic-harvester.js
getTopHitsResult
function getTopHitsResult(aggResponse, aggName, esResponse, aggregationObjects) { const aggLookup = {}; const linked = {}; // keeps track of all linked objects. type->id->true const typeLookup = {}; function getAggLookup(_aggLookup, _aggregationObjects) { _.each(_aggregationObjects, (aggObj) => { _aggLookup[aggObj.name] = aggObj; aggObj.aggregations && getAggLookup(_aggLookup, aggObj.aggregations); }); } getAggLookup(aggLookup, aggregationObjects); // dedupes already-linked entities. if (aggLookup[aggName] && aggLookup[aggName].include) { _.each(aggLookup[aggName].include.split(','), (linkProperty) => { if (_this.collectionLookup[linkProperty]) { const _type = inflect.pluralize(_this.collectionLookup[linkProperty]); typeLookup[linkProperty] = _type; esResponse.linked && _.each(esResponse.linked[_type] || [], (resource) => { linked[_type] = linked[_type] || {}; linked[_type][resource.id] = true; }); } }); } return _.map(aggResponse.hits.hits, (esReponseObj) => { if (aggLookup[aggName] && aggLookup[aggName].include) { _.each(aggLookup[aggName].include.split(','), (linkProperty) => { if (typeLookup[linkProperty]) { const _type = typeLookup[linkProperty]; // if this isn't already linked, link it. // TODO: links may be an array of objects, so treat it that way at all times. const hasLinks = !!(esReponseObj._source.links) && !!(esReponseObj._source.links[linkProperty]); if (hasLinks) { const entitiesToInclude = [].concat(unexpandSubentity(esReponseObj._source.links[linkProperty])); _.each(entitiesToInclude, (entityToInclude) => { const entityIsAlreadyIncluded = !!(linked[_type]) && !!(linked[_type][entityToInclude.id]); if (!entityIsAlreadyIncluded) { esResponse.linked = esResponse.linked || {}; esResponse.linked[_type] = esResponse.linked[_type] || []; esResponse.linked[_type] = esResponse.linked[_type].concat(entityToInclude); linked[_type] = linked[_type] || {}; linked[_type][entityToInclude.id] = true; } }); } } else { console.warn(`[Elastic-Harvest] ${linkProperty} is not in collectionLookup. ${linkProperty} was either ` + 'incorrectly specified by the end-user, or dev failed to include the relevant key in the lookup ' + 'provided to initialize elastic-harvest.'); } }); } return unexpandEntity(esReponseObj._source); }); }
javascript
function getTopHitsResult(aggResponse, aggName, esResponse, aggregationObjects) { const aggLookup = {}; const linked = {}; // keeps track of all linked objects. type->id->true const typeLookup = {}; function getAggLookup(_aggLookup, _aggregationObjects) { _.each(_aggregationObjects, (aggObj) => { _aggLookup[aggObj.name] = aggObj; aggObj.aggregations && getAggLookup(_aggLookup, aggObj.aggregations); }); } getAggLookup(aggLookup, aggregationObjects); // dedupes already-linked entities. if (aggLookup[aggName] && aggLookup[aggName].include) { _.each(aggLookup[aggName].include.split(','), (linkProperty) => { if (_this.collectionLookup[linkProperty]) { const _type = inflect.pluralize(_this.collectionLookup[linkProperty]); typeLookup[linkProperty] = _type; esResponse.linked && _.each(esResponse.linked[_type] || [], (resource) => { linked[_type] = linked[_type] || {}; linked[_type][resource.id] = true; }); } }); } return _.map(aggResponse.hits.hits, (esReponseObj) => { if (aggLookup[aggName] && aggLookup[aggName].include) { _.each(aggLookup[aggName].include.split(','), (linkProperty) => { if (typeLookup[linkProperty]) { const _type = typeLookup[linkProperty]; // if this isn't already linked, link it. // TODO: links may be an array of objects, so treat it that way at all times. const hasLinks = !!(esReponseObj._source.links) && !!(esReponseObj._source.links[linkProperty]); if (hasLinks) { const entitiesToInclude = [].concat(unexpandSubentity(esReponseObj._source.links[linkProperty])); _.each(entitiesToInclude, (entityToInclude) => { const entityIsAlreadyIncluded = !!(linked[_type]) && !!(linked[_type][entityToInclude.id]); if (!entityIsAlreadyIncluded) { esResponse.linked = esResponse.linked || {}; esResponse.linked[_type] = esResponse.linked[_type] || []; esResponse.linked[_type] = esResponse.linked[_type].concat(entityToInclude); linked[_type] = linked[_type] || {}; linked[_type][entityToInclude.id] = true; } }); } } else { console.warn(`[Elastic-Harvest] ${linkProperty} is not in collectionLookup. ${linkProperty} was either ` + 'incorrectly specified by the end-user, or dev failed to include the relevant key in the lookup ' + 'provided to initialize elastic-harvest.'); } }); } return unexpandEntity(esReponseObj._source); }); }
[ "function", "getTopHitsResult", "(", "aggResponse", ",", "aggName", ",", "esResponse", ",", "aggregationObjects", ")", "{", "const", "aggLookup", "=", "{", "}", ";", "const", "linked", "=", "{", "}", ";", "const", "typeLookup", "=", "{", "}", ";", "function", "getAggLookup", "(", "_aggLookup", ",", "_aggregationObjects", ")", "{", "_", ".", "each", "(", "_aggregationObjects", ",", "(", "aggObj", ")", "=>", "{", "_aggLookup", "[", "aggObj", ".", "name", "]", "=", "aggObj", ";", "aggObj", ".", "aggregations", "&&", "getAggLookup", "(", "_aggLookup", ",", "aggObj", ".", "aggregations", ")", ";", "}", ")", ";", "}", "getAggLookup", "(", "aggLookup", ",", "aggregationObjects", ")", ";", "if", "(", "aggLookup", "[", "aggName", "]", "&&", "aggLookup", "[", "aggName", "]", ".", "include", ")", "{", "_", ".", "each", "(", "aggLookup", "[", "aggName", "]", ".", "include", ".", "split", "(", "','", ")", ",", "(", "linkProperty", ")", "=>", "{", "if", "(", "_this", ".", "collectionLookup", "[", "linkProperty", "]", ")", "{", "const", "_type", "=", "inflect", ".", "pluralize", "(", "_this", ".", "collectionLookup", "[", "linkProperty", "]", ")", ";", "typeLookup", "[", "linkProperty", "]", "=", "_type", ";", "esResponse", ".", "linked", "&&", "_", ".", "each", "(", "esResponse", ".", "linked", "[", "_type", "]", "||", "[", "]", ",", "(", "resource", ")", "=>", "{", "linked", "[", "_type", "]", "=", "linked", "[", "_type", "]", "||", "{", "}", ";", "linked", "[", "_type", "]", "[", "resource", ".", "id", "]", "=", "true", ";", "}", ")", ";", "}", "}", ")", ";", "}", "return", "_", ".", "map", "(", "aggResponse", ".", "hits", ".", "hits", ",", "(", "esReponseObj", ")", "=>", "{", "if", "(", "aggLookup", "[", "aggName", "]", "&&", "aggLookup", "[", "aggName", "]", ".", "include", ")", "{", "_", ".", "each", "(", "aggLookup", "[", "aggName", "]", ".", "include", ".", "split", "(", "','", ")", ",", "(", "linkProperty", ")", "=>", "{", "if", "(", "typeLookup", "[", "linkProperty", "]", ")", "{", "const", "_type", "=", "typeLookup", "[", "linkProperty", "]", ";", "const", "hasLinks", "=", "!", "!", "(", "esReponseObj", ".", "_source", ".", "links", ")", "&&", "!", "!", "(", "esReponseObj", ".", "_source", ".", "links", "[", "linkProperty", "]", ")", ";", "if", "(", "hasLinks", ")", "{", "const", "entitiesToInclude", "=", "[", "]", ".", "concat", "(", "unexpandSubentity", "(", "esReponseObj", ".", "_source", ".", "links", "[", "linkProperty", "]", ")", ")", ";", "_", ".", "each", "(", "entitiesToInclude", ",", "(", "entityToInclude", ")", "=>", "{", "const", "entityIsAlreadyIncluded", "=", "!", "!", "(", "linked", "[", "_type", "]", ")", "&&", "!", "!", "(", "linked", "[", "_type", "]", "[", "entityToInclude", ".", "id", "]", ")", ";", "if", "(", "!", "entityIsAlreadyIncluded", ")", "{", "esResponse", ".", "linked", "=", "esResponse", ".", "linked", "||", "{", "}", ";", "esResponse", ".", "linked", "[", "_type", "]", "=", "esResponse", ".", "linked", "[", "_type", "]", "||", "[", "]", ";", "esResponse", ".", "linked", "[", "_type", "]", "=", "esResponse", ".", "linked", "[", "_type", "]", ".", "concat", "(", "entityToInclude", ")", ";", "linked", "[", "_type", "]", "=", "linked", "[", "_type", "]", "||", "{", "}", ";", "linked", "[", "_type", "]", "[", "entityToInclude", ".", "id", "]", "=", "true", ";", "}", "}", ")", ";", "}", "}", "else", "{", "console", ".", "warn", "(", "`", "${", "linkProperty", "}", "${", "linkProperty", "}", "`", "+", "'incorrectly specified by the end-user, or dev failed to include the relevant key in the lookup '", "+", "'provided to initialize elastic-harvest.'", ")", ";", "}", "}", ")", ";", "}", "return", "unexpandEntity", "(", "esReponseObj", ".", "_source", ")", ";", "}", ")", ";", "}" ]
Note that this is not currently named well - it also provides the "includes" functionality to top_hits.
[ "Note", "that", "this", "is", "not", "currently", "named", "well", "-", "it", "also", "provides", "the", "includes", "functionality", "to", "top_hits", "." ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L208-L271
train
agco/elastic-harvesterjs
elastic-harvester.js
createBuckets
function createBuckets(terms) { return _.map(terms, (term) => { // 1. see if there are other terms & if they have buckets. const retVal = { key: term.key, count: term.doc_count }; _.each(term, (aggResponse, responseKey) => { if (responseKey === 'key' || responseKey === 'doc_count') { return null; } else if (aggResponse.buckets) { retVal[responseKey] = createBuckets(aggResponse.buckets); } else if (aggResponse.hits && aggResponse.hits.hits) { // top_hits aggs result from nested query w/o reverse nesting. retVal[responseKey] = getTopHitsResult(aggResponse, responseKey, _esResponse, aggregationObjects); // to combine nested aggs w others, you have to un-nest them, & this takes up an aggregation-space. } else if (responseKey !== 'reverse_nesting' && aggResponse) { // stats & extended_stats aggs // This means it's the result of a nested stats or extended stats query. if (aggResponse[responseKey]) { retVal[responseKey] = aggResponse[responseKey]; } else { retVal[responseKey] = aggResponse; } } else if (responseKey === 'reverse_nesting') { _.each(aggResponse, (reverseNestedResponseProperty, reverseNestedResponseKey) => { if (reverseNestedResponseKey === 'doc_count') { return null; } else if (reverseNestedResponseProperty.buckets) { retVal[reverseNestedResponseKey] = createBuckets(reverseNestedResponseProperty.buckets); // this gets a little complicated because reverse-nested then renested subdocuments are .. // complicated (because the extra aggs for nesting throws things off). } else if (reverseNestedResponseProperty[reverseNestedResponseKey] && reverseNestedResponseProperty[reverseNestedResponseKey].buckets) { retVal[reverseNestedResponseKey] = createBuckets( reverseNestedResponseProperty[reverseNestedResponseKey].buckets); // this gets a little MORE complicated because of reverse-nested then renested top_hits aggs } else if (reverseNestedResponseProperty.hits && reverseNestedResponseProperty.hits.hits) { retVal[reverseNestedResponseKey] = getTopHitsResult(reverseNestedResponseProperty, reverseNestedResponseKey, _esResponse, aggregationObjects); // stats & extended_stats aggs } else if (reverseNestedResponseProperty) { // This means it's the result of a nested stats or extended stats query. if (reverseNestedResponseProperty[reverseNestedResponseKey]) { retVal[reverseNestedResponseKey] = reverseNestedResponseProperty[reverseNestedResponseKey]; } else { retVal[reverseNestedResponseKey] = reverseNestedResponseProperty; } } return null; }); } return null; }); return retVal; }); }
javascript
function createBuckets(terms) { return _.map(terms, (term) => { // 1. see if there are other terms & if they have buckets. const retVal = { key: term.key, count: term.doc_count }; _.each(term, (aggResponse, responseKey) => { if (responseKey === 'key' || responseKey === 'doc_count') { return null; } else if (aggResponse.buckets) { retVal[responseKey] = createBuckets(aggResponse.buckets); } else if (aggResponse.hits && aggResponse.hits.hits) { // top_hits aggs result from nested query w/o reverse nesting. retVal[responseKey] = getTopHitsResult(aggResponse, responseKey, _esResponse, aggregationObjects); // to combine nested aggs w others, you have to un-nest them, & this takes up an aggregation-space. } else if (responseKey !== 'reverse_nesting' && aggResponse) { // stats & extended_stats aggs // This means it's the result of a nested stats or extended stats query. if (aggResponse[responseKey]) { retVal[responseKey] = aggResponse[responseKey]; } else { retVal[responseKey] = aggResponse; } } else if (responseKey === 'reverse_nesting') { _.each(aggResponse, (reverseNestedResponseProperty, reverseNestedResponseKey) => { if (reverseNestedResponseKey === 'doc_count') { return null; } else if (reverseNestedResponseProperty.buckets) { retVal[reverseNestedResponseKey] = createBuckets(reverseNestedResponseProperty.buckets); // this gets a little complicated because reverse-nested then renested subdocuments are .. // complicated (because the extra aggs for nesting throws things off). } else if (reverseNestedResponseProperty[reverseNestedResponseKey] && reverseNestedResponseProperty[reverseNestedResponseKey].buckets) { retVal[reverseNestedResponseKey] = createBuckets( reverseNestedResponseProperty[reverseNestedResponseKey].buckets); // this gets a little MORE complicated because of reverse-nested then renested top_hits aggs } else if (reverseNestedResponseProperty.hits && reverseNestedResponseProperty.hits.hits) { retVal[reverseNestedResponseKey] = getTopHitsResult(reverseNestedResponseProperty, reverseNestedResponseKey, _esResponse, aggregationObjects); // stats & extended_stats aggs } else if (reverseNestedResponseProperty) { // This means it's the result of a nested stats or extended stats query. if (reverseNestedResponseProperty[reverseNestedResponseKey]) { retVal[reverseNestedResponseKey] = reverseNestedResponseProperty[reverseNestedResponseKey]; } else { retVal[reverseNestedResponseKey] = reverseNestedResponseProperty; } } return null; }); } return null; }); return retVal; }); }
[ "function", "createBuckets", "(", "terms", ")", "{", "return", "_", ".", "map", "(", "terms", ",", "(", "term", ")", "=>", "{", "const", "retVal", "=", "{", "key", ":", "term", ".", "key", ",", "count", ":", "term", ".", "doc_count", "}", ";", "_", ".", "each", "(", "term", ",", "(", "aggResponse", ",", "responseKey", ")", "=>", "{", "if", "(", "responseKey", "===", "'key'", "||", "responseKey", "===", "'doc_count'", ")", "{", "return", "null", ";", "}", "else", "if", "(", "aggResponse", ".", "buckets", ")", "{", "retVal", "[", "responseKey", "]", "=", "createBuckets", "(", "aggResponse", ".", "buckets", ")", ";", "}", "else", "if", "(", "aggResponse", ".", "hits", "&&", "aggResponse", ".", "hits", ".", "hits", ")", "{", "retVal", "[", "responseKey", "]", "=", "getTopHitsResult", "(", "aggResponse", ",", "responseKey", ",", "_esResponse", ",", "aggregationObjects", ")", ";", "}", "else", "if", "(", "responseKey", "!==", "'reverse_nesting'", "&&", "aggResponse", ")", "{", "if", "(", "aggResponse", "[", "responseKey", "]", ")", "{", "retVal", "[", "responseKey", "]", "=", "aggResponse", "[", "responseKey", "]", ";", "}", "else", "{", "retVal", "[", "responseKey", "]", "=", "aggResponse", ";", "}", "}", "else", "if", "(", "responseKey", "===", "'reverse_nesting'", ")", "{", "_", ".", "each", "(", "aggResponse", ",", "(", "reverseNestedResponseProperty", ",", "reverseNestedResponseKey", ")", "=>", "{", "if", "(", "reverseNestedResponseKey", "===", "'doc_count'", ")", "{", "return", "null", ";", "}", "else", "if", "(", "reverseNestedResponseProperty", ".", "buckets", ")", "{", "retVal", "[", "reverseNestedResponseKey", "]", "=", "createBuckets", "(", "reverseNestedResponseProperty", ".", "buckets", ")", ";", "}", "else", "if", "(", "reverseNestedResponseProperty", "[", "reverseNestedResponseKey", "]", "&&", "reverseNestedResponseProperty", "[", "reverseNestedResponseKey", "]", ".", "buckets", ")", "{", "retVal", "[", "reverseNestedResponseKey", "]", "=", "createBuckets", "(", "reverseNestedResponseProperty", "[", "reverseNestedResponseKey", "]", ".", "buckets", ")", ";", "}", "else", "if", "(", "reverseNestedResponseProperty", ".", "hits", "&&", "reverseNestedResponseProperty", ".", "hits", ".", "hits", ")", "{", "retVal", "[", "reverseNestedResponseKey", "]", "=", "getTopHitsResult", "(", "reverseNestedResponseProperty", ",", "reverseNestedResponseKey", ",", "_esResponse", ",", "aggregationObjects", ")", ";", "}", "else", "if", "(", "reverseNestedResponseProperty", ")", "{", "if", "(", "reverseNestedResponseProperty", "[", "reverseNestedResponseKey", "]", ")", "{", "retVal", "[", "reverseNestedResponseKey", "]", "=", "reverseNestedResponseProperty", "[", "reverseNestedResponseKey", "]", ";", "}", "else", "{", "retVal", "[", "reverseNestedResponseKey", "]", "=", "reverseNestedResponseProperty", ";", "}", "}", "return", "null", ";", "}", ")", ";", "}", "return", "null", ";", "}", ")", ";", "return", "retVal", ";", "}", ")", ";", "}" ]
Add in meta.aggregations field
[ "Add", "in", "meta", ".", "aggregations", "field" ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L286-L342
train
agco/elastic-harvesterjs
elastic-harvester.js
createCustomRoutingQueryString
function createCustomRoutingQueryString(pathToCustomRoutingKey, query) { const invalidRegexList = [/^ge=/, /^gt=/, /^ge=/, /^lt=/, /\*$/]; // array of invalid regex let customRoutingValue; if (!pathToCustomRoutingKey) return ''; // customRouting is not enabled for this type customRoutingValue = query[pathToCustomRoutingKey]; // fetch the value // filters like [ 'gt: '10', lt: '20' ] are not valid customRouting values but may show up if (typeof customRoutingValue !== 'string') return ''; // check for range and wildcard filters _.forEach(invalidRegexList, (invalidRegex) => { // if our value matches one of these regex, it's probably not the value we should be hashing for customRouting if (invalidRegex.test(customRoutingValue)) { customRoutingValue = ''; return false; } return true; }); return customRoutingValue ? `routing=${customRoutingValue}` : ''; }
javascript
function createCustomRoutingQueryString(pathToCustomRoutingKey, query) { const invalidRegexList = [/^ge=/, /^gt=/, /^ge=/, /^lt=/, /\*$/]; // array of invalid regex let customRoutingValue; if (!pathToCustomRoutingKey) return ''; // customRouting is not enabled for this type customRoutingValue = query[pathToCustomRoutingKey]; // fetch the value // filters like [ 'gt: '10', lt: '20' ] are not valid customRouting values but may show up if (typeof customRoutingValue !== 'string') return ''; // check for range and wildcard filters _.forEach(invalidRegexList, (invalidRegex) => { // if our value matches one of these regex, it's probably not the value we should be hashing for customRouting if (invalidRegex.test(customRoutingValue)) { customRoutingValue = ''; return false; } return true; }); return customRoutingValue ? `routing=${customRoutingValue}` : ''; }
[ "function", "createCustomRoutingQueryString", "(", "pathToCustomRoutingKey", ",", "query", ")", "{", "const", "invalidRegexList", "=", "[", "/", "^ge=", "/", ",", "/", "^gt=", "/", ",", "/", "^ge=", "/", ",", "/", "^lt=", "/", ",", "/", "\\*$", "/", "]", ";", "let", "customRoutingValue", ";", "if", "(", "!", "pathToCustomRoutingKey", ")", "return", "''", ";", "customRoutingValue", "=", "query", "[", "pathToCustomRoutingKey", "]", ";", "if", "(", "typeof", "customRoutingValue", "!==", "'string'", ")", "return", "''", ";", "_", ".", "forEach", "(", "invalidRegexList", ",", "(", "invalidRegex", ")", "=>", "{", "if", "(", "invalidRegex", ".", "test", "(", "customRoutingValue", ")", ")", "{", "customRoutingValue", "=", "''", ";", "return", "false", ";", "}", "return", "true", ";", "}", ")", ";", "return", "customRoutingValue", "?", "`", "${", "customRoutingValue", "}", "`", ":", "''", ";", "}" ]
Creates a custom routing query string parameter when provided with the pathToCustomRoutingKey and a map of query string parameters, it will create a custom routing query string parameter, that can be sent to elasticSearch. It return an empty string if it is unable to create one. It will validate: * that custom routing is turned on for this type. * the value to be used for custom routing is a string * the string doesn't end with wildcards * the string doesnt' have operators like ge, gt, le or lt @param pathToCustomRoutingKey string, the path to the custom routing key @param query map, of query strings from the request @returns string custom routing query string or '' if N/A
[ "Creates", "a", "custom", "routing", "query", "string", "parameter", "when", "provided", "with", "the", "pathToCustomRoutingKey", "and", "a", "map", "of", "query", "string", "parameters", "it", "will", "create", "a", "custom", "routing", "query", "string", "parameter", "that", "can", "be", "sent", "to", "elasticSearch", ".", "It", "return", "an", "empty", "string", "if", "it", "is", "unable", "to", "create", "one", "." ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L425-L446
train
agco/elastic-harvesterjs
elastic-harvester.js
unexpandEntity
function unexpandEntity(sourceObject, includeFields) { _.each(sourceObject.links || [], (val, key) => { if (!_.isArray(sourceObject.links[key])) { // I know the extra .toString seems unnecessary, but sometimes val.id is already an objectId, and other times its // a string. sourceObject.links[key] = val.id && val.id.toString() || val && val.toString && val.toString(); } else { _.each(sourceObject.links[key], (innerVal, innerKey) => { sourceObject.links[key][innerKey] = innerVal.id.toString(); }); } }); return (includeFields && includeFields.length) ? Util.includeFields(sourceObject, includeFields) : sourceObject; }
javascript
function unexpandEntity(sourceObject, includeFields) { _.each(sourceObject.links || [], (val, key) => { if (!_.isArray(sourceObject.links[key])) { // I know the extra .toString seems unnecessary, but sometimes val.id is already an objectId, and other times its // a string. sourceObject.links[key] = val.id && val.id.toString() || val && val.toString && val.toString(); } else { _.each(sourceObject.links[key], (innerVal, innerKey) => { sourceObject.links[key][innerKey] = innerVal.id.toString(); }); } }); return (includeFields && includeFields.length) ? Util.includeFields(sourceObject, includeFields) : sourceObject; }
[ "function", "unexpandEntity", "(", "sourceObject", ",", "includeFields", ")", "{", "_", ".", "each", "(", "sourceObject", ".", "links", "||", "[", "]", ",", "(", "val", ",", "key", ")", "=>", "{", "if", "(", "!", "_", ".", "isArray", "(", "sourceObject", ".", "links", "[", "key", "]", ")", ")", "{", "sourceObject", ".", "links", "[", "key", "]", "=", "val", ".", "id", "&&", "val", ".", "id", ".", "toString", "(", ")", "||", "val", "&&", "val", ".", "toString", "&&", "val", ".", "toString", "(", ")", ";", "}", "else", "{", "_", ".", "each", "(", "sourceObject", ".", "links", "[", "key", "]", ",", "(", "innerVal", ",", "innerKey", ")", "=>", "{", "sourceObject", ".", "links", "[", "key", "]", "[", "innerKey", "]", "=", "innerVal", ".", "id", ".", "toString", "(", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "(", "includeFields", "&&", "includeFields", ".", "length", ")", "?", "Util", ".", "includeFields", "(", "sourceObject", ",", "includeFields", ")", ":", "sourceObject", ";", "}" ]
Transforms an expanded ES source object to an unexpanded object
[ "Transforms", "an", "expanded", "ES", "source", "object", "to", "an", "unexpanded", "object" ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L537-L551
train
agco/elastic-harvesterjs
elastic-harvester.js
unexpandSubentity
function unexpandSubentity(subEntity) { if (_.isArray(subEntity)) { _.each(subEntity, (entity, index) => { subEntity[index] = unexpandSubentity(entity); }); } else { _.each(subEntity, (val, propertyName) => { if (_.isObject(val) && val.id) { subEntity.links = subEntity.links || {}; subEntity.links[propertyName] = val.id; delete subEntity[propertyName]; } }); } return subEntity; }
javascript
function unexpandSubentity(subEntity) { if (_.isArray(subEntity)) { _.each(subEntity, (entity, index) => { subEntity[index] = unexpandSubentity(entity); }); } else { _.each(subEntity, (val, propertyName) => { if (_.isObject(val) && val.id) { subEntity.links = subEntity.links || {}; subEntity.links[propertyName] = val.id; delete subEntity[propertyName]; } }); } return subEntity; }
[ "function", "unexpandSubentity", "(", "subEntity", ")", "{", "if", "(", "_", ".", "isArray", "(", "subEntity", ")", ")", "{", "_", ".", "each", "(", "subEntity", ",", "(", "entity", ",", "index", ")", "=>", "{", "subEntity", "[", "index", "]", "=", "unexpandSubentity", "(", "entity", ")", ";", "}", ")", ";", "}", "else", "{", "_", ".", "each", "(", "subEntity", ",", "(", "val", ",", "propertyName", ")", "=>", "{", "if", "(", "_", ".", "isObject", "(", "val", ")", "&&", "val", ".", "id", ")", "{", "subEntity", ".", "links", "=", "subEntity", ".", "links", "||", "{", "}", ";", "subEntity", ".", "links", "[", "propertyName", "]", "=", "val", ".", "id", ";", "delete", "subEntity", "[", "propertyName", "]", ";", "}", "}", ")", ";", "}", "return", "subEntity", ";", "}" ]
A sub-entity is a linked object returned by es as part of the source graph. They are expanded differently from primary entities, and must be unexpanded differently as well.
[ "A", "sub", "-", "entity", "is", "a", "linked", "object", "returned", "by", "es", "as", "part", "of", "the", "source", "graph", ".", "They", "are", "expanded", "differently", "from", "primary", "entities", "and", "must", "be", "unexpanded", "differently", "as", "well", "." ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L558-L574
train
agco/elastic-harvesterjs
elastic-harvester.js
groupNestedPredicates
function groupNestedPredicates(_nestedPredicates) { let maxDepth = 0; const nestedPredicateObj = {}; const nestedPredicateParts = _.map(_nestedPredicates, (predicateArr) => { const predicate = predicateArr[0]; const retVal = predicate.split('.'); nestedPredicateObj[predicate] = predicateArr[1]; retVal.length > maxDepth && (maxDepth = retVal.length); return retVal; }); const groups = {}; for (let i = 0; i < maxDepth; i++) { groups[i] = _.groupBy(nestedPredicateParts, (predicateParts) => { let retval = ''; for (let j = 0; j < i + 1; j++) { retval += (predicateParts[j] ? `${predicateParts[j]}.` : ''); } return retval.substr(0, retval.length - 1); }); } const completed = {}; const levels = {}; const paths = {}; // Simplifies the grouping for (let i = maxDepth - 1; i >= 0; i--) { _.each(groups[i], (values, key) => { _.each(values, (value) => { const strKey = value.join('.'); if (!completed[strKey] && values.length > 1) { (!levels[i] && (levels[i] = [])); levels[i].push(strKey); (completed[strKey] = true); paths[i] = key; } if (!completed[strKey] && i < 1) { (!levels[i] && (levels[i] = [])); levels[i].push(strKey); (completed[strKey] = true); paths[i] = key; } }); }); } return { groups: levels, paths, nestedPredicateObj }; }
javascript
function groupNestedPredicates(_nestedPredicates) { let maxDepth = 0; const nestedPredicateObj = {}; const nestedPredicateParts = _.map(_nestedPredicates, (predicateArr) => { const predicate = predicateArr[0]; const retVal = predicate.split('.'); nestedPredicateObj[predicate] = predicateArr[1]; retVal.length > maxDepth && (maxDepth = retVal.length); return retVal; }); const groups = {}; for (let i = 0; i < maxDepth; i++) { groups[i] = _.groupBy(nestedPredicateParts, (predicateParts) => { let retval = ''; for (let j = 0; j < i + 1; j++) { retval += (predicateParts[j] ? `${predicateParts[j]}.` : ''); } return retval.substr(0, retval.length - 1); }); } const completed = {}; const levels = {}; const paths = {}; // Simplifies the grouping for (let i = maxDepth - 1; i >= 0; i--) { _.each(groups[i], (values, key) => { _.each(values, (value) => { const strKey = value.join('.'); if (!completed[strKey] && values.length > 1) { (!levels[i] && (levels[i] = [])); levels[i].push(strKey); (completed[strKey] = true); paths[i] = key; } if (!completed[strKey] && i < 1) { (!levels[i] && (levels[i] = [])); levels[i].push(strKey); (completed[strKey] = true); paths[i] = key; } }); }); } return { groups: levels, paths, nestedPredicateObj }; }
[ "function", "groupNestedPredicates", "(", "_nestedPredicates", ")", "{", "let", "maxDepth", "=", "0", ";", "const", "nestedPredicateObj", "=", "{", "}", ";", "const", "nestedPredicateParts", "=", "_", ".", "map", "(", "_nestedPredicates", ",", "(", "predicateArr", ")", "=>", "{", "const", "predicate", "=", "predicateArr", "[", "0", "]", ";", "const", "retVal", "=", "predicate", ".", "split", "(", "'.'", ")", ";", "nestedPredicateObj", "[", "predicate", "]", "=", "predicateArr", "[", "1", "]", ";", "retVal", ".", "length", ">", "maxDepth", "&&", "(", "maxDepth", "=", "retVal", ".", "length", ")", ";", "return", "retVal", ";", "}", ")", ";", "const", "groups", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "maxDepth", ";", "i", "++", ")", "{", "groups", "[", "i", "]", "=", "_", ".", "groupBy", "(", "nestedPredicateParts", ",", "(", "predicateParts", ")", "=>", "{", "let", "retval", "=", "''", ";", "for", "(", "let", "j", "=", "0", ";", "j", "<", "i", "+", "1", ";", "j", "++", ")", "{", "retval", "+=", "(", "predicateParts", "[", "j", "]", "?", "`", "${", "predicateParts", "[", "j", "]", "}", "`", ":", "''", ")", ";", "}", "return", "retval", ".", "substr", "(", "0", ",", "retval", ".", "length", "-", "1", ")", ";", "}", ")", ";", "}", "const", "completed", "=", "{", "}", ";", "const", "levels", "=", "{", "}", ";", "const", "paths", "=", "{", "}", ";", "for", "(", "let", "i", "=", "maxDepth", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "_", ".", "each", "(", "groups", "[", "i", "]", ",", "(", "values", ",", "key", ")", "=>", "{", "_", ".", "each", "(", "values", ",", "(", "value", ")", "=>", "{", "const", "strKey", "=", "value", ".", "join", "(", "'.'", ")", ";", "if", "(", "!", "completed", "[", "strKey", "]", "&&", "values", ".", "length", ">", "1", ")", "{", "(", "!", "levels", "[", "i", "]", "&&", "(", "levels", "[", "i", "]", "=", "[", "]", ")", ")", ";", "levels", "[", "i", "]", ".", "push", "(", "strKey", ")", ";", "(", "completed", "[", "strKey", "]", "=", "true", ")", ";", "paths", "[", "i", "]", "=", "key", ";", "}", "if", "(", "!", "completed", "[", "strKey", "]", "&&", "i", "<", "1", ")", "{", "(", "!", "levels", "[", "i", "]", "&&", "(", "levels", "[", "i", "]", "=", "[", "]", ")", ")", ";", "levels", "[", "i", "]", ".", "push", "(", "strKey", ")", ";", "(", "completed", "[", "strKey", "]", "=", "true", ")", ";", "paths", "[", "i", "]", "=", "key", ";", "}", "}", ")", ";", "}", ")", ";", "}", "return", "{", "groups", ":", "levels", ",", "paths", ",", "nestedPredicateObj", "}", ";", "}" ]
Groups predicates at their lowest match level to simplify creating nested queries
[ "Groups", "predicates", "at", "their", "lowest", "match", "level", "to", "simplify", "creating", "nested", "queries" ]
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L666-L714
train
WildDogTeam/lib-js-wildangular
dist/wild-angular.js
function(indexOrItem) { this._assertNotDestroyed('$save'); var self = this; var item = self._resolveItem(indexOrItem); var key = self.$keyAt(item); if( key !== null ) { var ref = self.$ref().ref().child(key); var data = $wilddogUtils.toJSON(item); return $wilddogUtils.doSet(ref, data).then(function() { self.$$notify('child_changed', key); return ref; }); } else { return $wilddogUtils.reject('Invalid record; could determine key for '+indexOrItem); } }
javascript
function(indexOrItem) { this._assertNotDestroyed('$save'); var self = this; var item = self._resolveItem(indexOrItem); var key = self.$keyAt(item); if( key !== null ) { var ref = self.$ref().ref().child(key); var data = $wilddogUtils.toJSON(item); return $wilddogUtils.doSet(ref, data).then(function() { self.$$notify('child_changed', key); return ref; }); } else { return $wilddogUtils.reject('Invalid record; could determine key for '+indexOrItem); } }
[ "function", "(", "indexOrItem", ")", "{", "this", ".", "_assertNotDestroyed", "(", "'$save'", ")", ";", "var", "self", "=", "this", ";", "var", "item", "=", "self", ".", "_resolveItem", "(", "indexOrItem", ")", ";", "var", "key", "=", "self", ".", "$keyAt", "(", "item", ")", ";", "if", "(", "key", "!==", "null", ")", "{", "var", "ref", "=", "self", ".", "$ref", "(", ")", ".", "ref", "(", ")", ".", "child", "(", "key", ")", ";", "var", "data", "=", "$wilddogUtils", ".", "toJSON", "(", "item", ")", ";", "return", "$wilddogUtils", ".", "doSet", "(", "ref", ",", "data", ")", ".", "then", "(", "function", "(", ")", "{", "self", ".", "$$notify", "(", "'child_changed'", ",", "key", ")", ";", "return", "ref", ";", "}", ")", ";", "}", "else", "{", "return", "$wilddogUtils", ".", "reject", "(", "'Invalid record; could determine key for '", "+", "indexOrItem", ")", ";", "}", "}" ]
Pass either an item in the array or the index of an item and it will be saved back to Wilddog. While the array is read-only and its structure should not be changed, it is okay to modify properties on the objects it contains and then save those back individually. Returns a future which is resolved when the data has successfully saved to the server. The resolve callback will be passed a Wilddog ref representing the saved element. If passed an invalid index or an object which is not a record in this array, the promise will be rejected. @param {int|object} indexOrItem @returns a promise resolved after data is saved
[ "Pass", "either", "an", "item", "in", "the", "array", "or", "the", "index", "of", "an", "item", "and", "it", "will", "be", "saved", "back", "to", "Wilddog", ".", "While", "the", "array", "is", "read", "-", "only", "and", "its", "structure", "should", "not", "be", "changed", "it", "is", "okay", "to", "modify", "properties", "on", "the", "objects", "it", "contains", "and", "then", "save", "those", "back", "individually", "." ]
1df47bed3a0ad9336c8e4778190652fe9d61b542
https://github.com/WildDogTeam/lib-js-wildangular/blob/1df47bed3a0ad9336c8e4778190652fe9d61b542/dist/wild-angular.js#L146-L162
train
WildDogTeam/lib-js-wildangular
dist/wild-angular.js
function(indexOrItem) { this._assertNotDestroyed('$remove'); var key = this.$keyAt(indexOrItem); if( key !== null ) { var ref = this.$ref().ref().child(key); return $wilddogUtils.doRemove(ref).then(function() { return ref; }); } else { return $wilddogUtils.reject('Invalid record; could not determine key for '+indexOrItem); } }
javascript
function(indexOrItem) { this._assertNotDestroyed('$remove'); var key = this.$keyAt(indexOrItem); if( key !== null ) { var ref = this.$ref().ref().child(key); return $wilddogUtils.doRemove(ref).then(function() { return ref; }); } else { return $wilddogUtils.reject('Invalid record; could not determine key for '+indexOrItem); } }
[ "function", "(", "indexOrItem", ")", "{", "this", ".", "_assertNotDestroyed", "(", "'$remove'", ")", ";", "var", "key", "=", "this", ".", "$keyAt", "(", "indexOrItem", ")", ";", "if", "(", "key", "!==", "null", ")", "{", "var", "ref", "=", "this", ".", "$ref", "(", ")", ".", "ref", "(", ")", ".", "child", "(", "key", ")", ";", "return", "$wilddogUtils", ".", "doRemove", "(", "ref", ")", ".", "then", "(", "function", "(", ")", "{", "return", "ref", ";", "}", ")", ";", "}", "else", "{", "return", "$wilddogUtils", ".", "reject", "(", "'Invalid record; could not determine key for '", "+", "indexOrItem", ")", ";", "}", "}" ]
Pass either an existing item in this array or the index of that item and it will be removed both locally and in Wilddog. This should be used in place of Array.prototype.splice for removing items out of the array, as calling splice will not update the value on the server. Returns a future which is resolved when the data has successfully removed from the server. The resolve callback will be passed a Wilddog ref representing the deleted element. If passed an invalid index or an object which is not a record in this array, the promise will be rejected. @param {int|object} indexOrItem @returns a promise which resolves after data is removed
[ "Pass", "either", "an", "existing", "item", "in", "this", "array", "or", "the", "index", "of", "that", "item", "and", "it", "will", "be", "removed", "both", "locally", "and", "in", "Wilddog", ".", "This", "should", "be", "used", "in", "place", "of", "Array", ".", "prototype", ".", "splice", "for", "removing", "items", "out", "of", "the", "array", "as", "calling", "splice", "will", "not", "update", "the", "value", "on", "the", "server", "." ]
1df47bed3a0ad9336c8e4778190652fe9d61b542
https://github.com/WildDogTeam/lib-js-wildangular/blob/1df47bed3a0ad9336c8e4778190652fe9d61b542/dist/wild-angular.js#L178-L190
train
WildDogTeam/lib-js-wildangular
dist/wild-angular.js
function(profile) { var user = this.getUser(); if (user) { return this._q.when(user.updateProfile(profile)); } else { return this._q.reject("Cannot update profile since there is no logged in user."); } }
javascript
function(profile) { var user = this.getUser(); if (user) { return this._q.when(user.updateProfile(profile)); } else { return this._q.reject("Cannot update profile since there is no logged in user."); } }
[ "function", "(", "profile", ")", "{", "var", "user", "=", "this", ".", "getUser", "(", ")", ";", "if", "(", "user", ")", "{", "return", "this", ".", "_q", ".", "when", "(", "user", ".", "updateProfile", "(", "profile", ")", ")", ";", "}", "else", "{", "return", "this", ".", "_q", ".", "reject", "(", "\"Cannot update profile since there is no logged in user.\"", ")", ";", "}", "}" ]
Changes the profile for an user. @param {string} profile A new profile for the current user. @return {Promise<>} An empty promise fulfilled once the profile change is complete.
[ "Changes", "the", "profile", "for", "an", "user", "." ]
1df47bed3a0ad9336c8e4778190652fe9d61b542
https://github.com/WildDogTeam/lib-js-wildangular/blob/1df47bed3a0ad9336c8e4778190652fe9d61b542/dist/wild-angular.js#L1056-L1063
train
WildDogTeam/lib-js-wildangular
dist/wild-angular.js
WilddogObject
function WilddogObject(ref) { if( !(this instanceof WilddogObject) ) { return new WilddogObject(ref); } // These are private config props and functions used internally // they are collected here to reduce clutter in console.log and forEach this.$$conf = { // synchronizes data to Wilddog sync: new ObjectSyncManager(this, ref), // stores the Wilddog ref ref: ref, // synchronizes $scope variables with this object binding: new ThreeWayBinding(this), // stores observers registered with $watch listeners: [] }; // this bit of magic makes $$conf non-enumerable and non-configurable // and non-writable (its properties are still writable but the ref cannot be replaced) // we redundantly assign it above so the IDE can relax Object.defineProperty(this, '$$conf', { value: this.$$conf }); this.$id = $wilddogUtils.getKey(ref.ref()); this.$priority = null; $wilddogUtils.applyDefaults(this, this.$$defaults); // start synchronizing data with Wilddog this.$$conf.sync.init(); }
javascript
function WilddogObject(ref) { if( !(this instanceof WilddogObject) ) { return new WilddogObject(ref); } // These are private config props and functions used internally // they are collected here to reduce clutter in console.log and forEach this.$$conf = { // synchronizes data to Wilddog sync: new ObjectSyncManager(this, ref), // stores the Wilddog ref ref: ref, // synchronizes $scope variables with this object binding: new ThreeWayBinding(this), // stores observers registered with $watch listeners: [] }; // this bit of magic makes $$conf non-enumerable and non-configurable // and non-writable (its properties are still writable but the ref cannot be replaced) // we redundantly assign it above so the IDE can relax Object.defineProperty(this, '$$conf', { value: this.$$conf }); this.$id = $wilddogUtils.getKey(ref.ref()); this.$priority = null; $wilddogUtils.applyDefaults(this, this.$$defaults); // start synchronizing data with Wilddog this.$$conf.sync.init(); }
[ "function", "WilddogObject", "(", "ref", ")", "{", "if", "(", "!", "(", "this", "instanceof", "WilddogObject", ")", ")", "{", "return", "new", "WilddogObject", "(", "ref", ")", ";", "}", "this", ".", "$$conf", "=", "{", "sync", ":", "new", "ObjectSyncManager", "(", "this", ",", "ref", ")", ",", "ref", ":", "ref", ",", "binding", ":", "new", "ThreeWayBinding", "(", "this", ")", ",", "listeners", ":", "[", "]", "}", ";", "Object", ".", "defineProperty", "(", "this", ",", "'$$conf'", ",", "{", "value", ":", "this", ".", "$$conf", "}", ")", ";", "this", ".", "$id", "=", "$wilddogUtils", ".", "getKey", "(", "ref", ".", "ref", "(", ")", ")", ";", "this", ".", "$priority", "=", "null", ";", "$wilddogUtils", ".", "applyDefaults", "(", "this", ",", "this", ".", "$$defaults", ")", ";", "this", ".", "$$conf", ".", "sync", ".", "init", "(", ")", ";", "}" ]
Creates a synchronized object with 2-way bindings between Angular and Wilddog. @param {Wilddog} ref @returns {WilddogObject} @constructor
[ "Creates", "a", "synchronized", "object", "with", "2", "-", "way", "bindings", "between", "Angular", "and", "Wilddog", "." ]
1df47bed3a0ad9336c8e4778190652fe9d61b542
https://github.com/WildDogTeam/lib-js-wildangular/blob/1df47bed3a0ad9336c8e4778190652fe9d61b542/dist/wild-angular.js#L1180-L1211
train
WildDogTeam/lib-js-wildangular
dist/wild-angular.js
function () { var self = this; var ref = self.$ref(); var data = $wilddogUtils.toJSON(self); return $wilddogUtils.doSet(ref, data).then(function() { self.$$notify(); return self.$ref(); }); }
javascript
function () { var self = this; var ref = self.$ref(); var data = $wilddogUtils.toJSON(self); return $wilddogUtils.doSet(ref, data).then(function() { self.$$notify(); return self.$ref(); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "ref", "=", "self", ".", "$ref", "(", ")", ";", "var", "data", "=", "$wilddogUtils", ".", "toJSON", "(", "self", ")", ";", "return", "$wilddogUtils", ".", "doSet", "(", "ref", ",", "data", ")", ".", "then", "(", "function", "(", ")", "{", "self", ".", "$$notify", "(", ")", ";", "return", "self", ".", "$ref", "(", ")", ";", "}", ")", ";", "}" ]
Saves all data on the WilddogObject back to Wilddog. @returns a promise which will resolve after the save is completed.
[ "Saves", "all", "data", "on", "the", "WilddogObject", "back", "to", "Wilddog", "." ]
1df47bed3a0ad9336c8e4778190652fe9d61b542
https://github.com/WildDogTeam/lib-js-wildangular/blob/1df47bed3a0ad9336c8e4778190652fe9d61b542/dist/wild-angular.js#L1218-L1226
train
WildDogTeam/lib-js-wildangular
dist/wild-angular.js
function(fn, ctx, wait, maxWait) { var start, cancelTimer, args, runScheduledForNextTick; if( typeof(ctx) === 'number' ) { maxWait = wait; wait = ctx; ctx = null; } if( typeof wait !== 'number' ) { throw new Error('Must provide a valid integer for wait. Try 0 for a default'); } if( typeof(fn) !== 'function' ) { throw new Error('Must provide a valid function to debounce'); } if( !maxWait ) { maxWait = wait*10 || 100; } // clears the current wait timer and creates a new one // however, if maxWait is exceeded, calls runNow() on the next tick. function resetTimer() { if( cancelTimer ) { cancelTimer(); cancelTimer = null; } if( start && Date.now() - start > maxWait ) { if(!runScheduledForNextTick){ runScheduledForNextTick = true; utils.compile(runNow); } } else { if( !start ) { start = Date.now(); } cancelTimer = utils.wait(runNow, wait); } } // Clears the queue and invokes the debounced function with the most recent arguments function runNow() { cancelTimer = null; start = null; runScheduledForNextTick = false; fn.apply(ctx, args); } function debounced() { args = Array.prototype.slice.call(arguments, 0); resetTimer(); } debounced.running = function() { return start > 0; }; return debounced; }
javascript
function(fn, ctx, wait, maxWait) { var start, cancelTimer, args, runScheduledForNextTick; if( typeof(ctx) === 'number' ) { maxWait = wait; wait = ctx; ctx = null; } if( typeof wait !== 'number' ) { throw new Error('Must provide a valid integer for wait. Try 0 for a default'); } if( typeof(fn) !== 'function' ) { throw new Error('Must provide a valid function to debounce'); } if( !maxWait ) { maxWait = wait*10 || 100; } // clears the current wait timer and creates a new one // however, if maxWait is exceeded, calls runNow() on the next tick. function resetTimer() { if( cancelTimer ) { cancelTimer(); cancelTimer = null; } if( start && Date.now() - start > maxWait ) { if(!runScheduledForNextTick){ runScheduledForNextTick = true; utils.compile(runNow); } } else { if( !start ) { start = Date.now(); } cancelTimer = utils.wait(runNow, wait); } } // Clears the queue and invokes the debounced function with the most recent arguments function runNow() { cancelTimer = null; start = null; runScheduledForNextTick = false; fn.apply(ctx, args); } function debounced() { args = Array.prototype.slice.call(arguments, 0); resetTimer(); } debounced.running = function() { return start > 0; }; return debounced; }
[ "function", "(", "fn", ",", "ctx", ",", "wait", ",", "maxWait", ")", "{", "var", "start", ",", "cancelTimer", ",", "args", ",", "runScheduledForNextTick", ";", "if", "(", "typeof", "(", "ctx", ")", "===", "'number'", ")", "{", "maxWait", "=", "wait", ";", "wait", "=", "ctx", ";", "ctx", "=", "null", ";", "}", "if", "(", "typeof", "wait", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "'Must provide a valid integer for wait. Try 0 for a default'", ")", ";", "}", "if", "(", "typeof", "(", "fn", ")", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Must provide a valid function to debounce'", ")", ";", "}", "if", "(", "!", "maxWait", ")", "{", "maxWait", "=", "wait", "*", "10", "||", "100", ";", "}", "function", "resetTimer", "(", ")", "{", "if", "(", "cancelTimer", ")", "{", "cancelTimer", "(", ")", ";", "cancelTimer", "=", "null", ";", "}", "if", "(", "start", "&&", "Date", ".", "now", "(", ")", "-", "start", ">", "maxWait", ")", "{", "if", "(", "!", "runScheduledForNextTick", ")", "{", "runScheduledForNextTick", "=", "true", ";", "utils", ".", "compile", "(", "runNow", ")", ";", "}", "}", "else", "{", "if", "(", "!", "start", ")", "{", "start", "=", "Date", ".", "now", "(", ")", ";", "}", "cancelTimer", "=", "utils", ".", "wait", "(", "runNow", ",", "wait", ")", ";", "}", "}", "function", "runNow", "(", ")", "{", "cancelTimer", "=", "null", ";", "start", "=", "null", ";", "runScheduledForNextTick", "=", "false", ";", "fn", ".", "apply", "(", "ctx", ",", "args", ")", ";", "}", "function", "debounced", "(", ")", "{", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "resetTimer", "(", ")", ";", "}", "debounced", ".", "running", "=", "function", "(", ")", "{", "return", "start", ">", "0", ";", "}", ";", "return", "debounced", ";", "}" ]
A rudimentary debounce method @param {function} fn the function to debounce @param {object} [ctx] the `this` context to set in fn @param {int} wait number of milliseconds to pause before sending out after each invocation @param {int} [maxWait] max milliseconds to wait before sending out, defaults to wait * 10 or 100
[ "A", "rudimentary", "debounce", "method" ]
1df47bed3a0ad9336c8e4778190652fe9d61b542
https://github.com/WildDogTeam/lib-js-wildangular/blob/1df47bed3a0ad9336c8e4778190652fe9d61b542/dist/wild-angular.js#L1870-L1922
train
WildDogTeam/lib-js-wildangular
dist/wild-angular.js
runNow
function runNow() { cancelTimer = null; start = null; runScheduledForNextTick = false; fn.apply(ctx, args); }
javascript
function runNow() { cancelTimer = null; start = null; runScheduledForNextTick = false; fn.apply(ctx, args); }
[ "function", "runNow", "(", ")", "{", "cancelTimer", "=", "null", ";", "start", "=", "null", ";", "runScheduledForNextTick", "=", "false", ";", "fn", ".", "apply", "(", "ctx", ",", "args", ")", ";", "}" ]
Clears the queue and invokes the debounced function with the most recent arguments
[ "Clears", "the", "queue", "and", "invokes", "the", "debounced", "function", "with", "the", "most", "recent", "arguments" ]
1df47bed3a0ad9336c8e4778190652fe9d61b542
https://github.com/WildDogTeam/lib-js-wildangular/blob/1df47bed3a0ad9336c8e4778190652fe9d61b542/dist/wild-angular.js#L1906-L1911
train
jlamendo/sorrow
lib/otuMapArray.js
otuMapArray
function otuMapArray(data) { this.data = data; this.len = this.data.length; this.data[this.len] = []; for (var i = 0; i < this.len; i++) { this.data[this.len].push(i); } this.reset = function () { var _this = this; if (!this.data[this.len]) { this.data[this.len] = []; } for (var i = 0; i < this.len; i++) { this.data[this.len].push(i); } }; this.pop = function () { var _this = this; var index = this.rng(this.data[this.len].length); return this.data[this.data[this.len].splice(index, 1)]; }; this.rng = function (range) { var _this = this; if (range === 0) this.reset(); return randy.randInt(range); }; }
javascript
function otuMapArray(data) { this.data = data; this.len = this.data.length; this.data[this.len] = []; for (var i = 0; i < this.len; i++) { this.data[this.len].push(i); } this.reset = function () { var _this = this; if (!this.data[this.len]) { this.data[this.len] = []; } for (var i = 0; i < this.len; i++) { this.data[this.len].push(i); } }; this.pop = function () { var _this = this; var index = this.rng(this.data[this.len].length); return this.data[this.data[this.len].splice(index, 1)]; }; this.rng = function (range) { var _this = this; if (range === 0) this.reset(); return randy.randInt(range); }; }
[ "function", "otuMapArray", "(", "data", ")", "{", "this", ".", "data", "=", "data", ";", "this", ".", "len", "=", "this", ".", "data", ".", "length", ";", "this", ".", "data", "[", "this", ".", "len", "]", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "len", ";", "i", "++", ")", "{", "this", ".", "data", "[", "this", ".", "len", "]", ".", "push", "(", "i", ")", ";", "}", "this", ".", "reset", "=", "function", "(", ")", "{", "var", "_this", "=", "this", ";", "if", "(", "!", "this", ".", "data", "[", "this", ".", "len", "]", ")", "{", "this", ".", "data", "[", "this", ".", "len", "]", "=", "[", "]", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "len", ";", "i", "++", ")", "{", "this", ".", "data", "[", "this", ".", "len", "]", ".", "push", "(", "i", ")", ";", "}", "}", ";", "this", ".", "pop", "=", "function", "(", ")", "{", "var", "_this", "=", "this", ";", "var", "index", "=", "this", ".", "rng", "(", "this", ".", "data", "[", "this", ".", "len", "]", ".", "length", ")", ";", "return", "this", ".", "data", "[", "this", ".", "data", "[", "this", ".", "len", "]", ".", "splice", "(", "index", ",", "1", ")", "]", ";", "}", ";", "this", ".", "rng", "=", "function", "(", "range", ")", "{", "var", "_this", "=", "this", ";", "if", "(", "range", "===", "0", ")", "this", ".", "reset", "(", ")", ";", "return", "randy", ".", "randInt", "(", "range", ")", ";", "}", ";", "}" ]
cache.prototype.pop = cache.prototype.retrieve;
[ "cache", ".", "prototype", ".", "pop", "=", "cache", ".", "prototype", ".", "retrieve", ";" ]
1a76c2a90de9925bf27b5556a0fab8b6d6f2c1cc
https://github.com/jlamendo/sorrow/blob/1a76c2a90de9925bf27b5556a0fab8b6d6f2c1cc/lib/otuMapArray.js#L80-L110
train
clubedaentrega/log-sink
lib/prepareError.js
prepareStack
function prepareStack(stack) { let lines = stack.split('\n').slice(1) if (lines.length > 500) { // Stack too big, probably this is caused by stack overflow // Remove middle values let skipped = lines.length - 500, top = lines.slice(0, 250), bottom = lines.slice(-250) lines = top.concat('--- skipped ' + skipped + ' frames ---', bottom) } return lines.map(line => line.trim().replace(/^at /, '').replace(basePath, '.')) }
javascript
function prepareStack(stack) { let lines = stack.split('\n').slice(1) if (lines.length > 500) { // Stack too big, probably this is caused by stack overflow // Remove middle values let skipped = lines.length - 500, top = lines.slice(0, 250), bottom = lines.slice(-250) lines = top.concat('--- skipped ' + skipped + ' frames ---', bottom) } return lines.map(line => line.trim().replace(/^at /, '').replace(basePath, '.')) }
[ "function", "prepareStack", "(", "stack", ")", "{", "let", "lines", "=", "stack", ".", "split", "(", "'\\n'", ")", ".", "\\n", "slice", "(", "1", ")", "if", "(", "lines", ".", "length", ">", "500", ")", "{", "let", "skipped", "=", "lines", ".", "length", "-", "500", ",", "top", "=", "lines", ".", "slice", "(", "0", ",", "250", ")", ",", "bottom", "=", "lines", ".", "slice", "(", "-", "250", ")", "lines", "=", "top", ".", "concat", "(", "'--- skipped '", "+", "skipped", "+", "' frames ---'", ",", "bottom", ")", "}", "}" ]
Split each stack frame and normalize paths @param {string} stack @returns {Array<string>} @private
[ "Split", "each", "stack", "frame", "and", "normalize", "paths" ]
a448207928f130cd13a0a109138b0ff0b93d84c4
https://github.com/clubedaentrega/log-sink/blob/a448207928f130cd13a0a109138b0ff0b93d84c4/lib/prepareError.js#L111-L124
train
logikum/md-site-engine
source/readers/get-reference.js
getReference
function getReference( referenceFile ) { var text = ''; // Read references file. var referencePath = path.join( process.cwd(), referenceFile ); var stats = fs.statSync( referencePath ); if (stats && stats.isFile()) { text = fs.readFileSync( referencePath, { encoding: 'utf8' } ); // Find common root definitions (tilde references). var tildes = { }; var re = /^\s*\[(~\d*)]\s*:/g; var source = text.split( '\n' ); var target = [ ]; for (var i = 0; i < source.length; i++) { var line = source[ i ].trim(); // Search common root pattern. var result = re.exec( line ); if (result) // Save common root value. tildes[ result[ 1 ] ] = line.substring( line.indexOf( ':' ) + 1 ).trim(); else if (line[ 0 ] === '[') // Store reference link. target.push( line ); } text = target.join( '\n' ); // Replace tilde+number pairs with common roots. var noIndex = false; for (var attr in tildes) { if (tildes.hasOwnProperty( attr )) { if (attr === '~') noIndex = true; else { var re_n = new RegExp( ' ' + attr, 'g' ); var re_value = ' ' + tildes[ attr ]; text = text.replace( re_n, re_value ); } } } // Finally replace tildes with its common root. if (noIndex) text = text.replace( / ~/g, ' ' + tildes[ '~' ] ); } return text; }
javascript
function getReference( referenceFile ) { var text = ''; // Read references file. var referencePath = path.join( process.cwd(), referenceFile ); var stats = fs.statSync( referencePath ); if (stats && stats.isFile()) { text = fs.readFileSync( referencePath, { encoding: 'utf8' } ); // Find common root definitions (tilde references). var tildes = { }; var re = /^\s*\[(~\d*)]\s*:/g; var source = text.split( '\n' ); var target = [ ]; for (var i = 0; i < source.length; i++) { var line = source[ i ].trim(); // Search common root pattern. var result = re.exec( line ); if (result) // Save common root value. tildes[ result[ 1 ] ] = line.substring( line.indexOf( ':' ) + 1 ).trim(); else if (line[ 0 ] === '[') // Store reference link. target.push( line ); } text = target.join( '\n' ); // Replace tilde+number pairs with common roots. var noIndex = false; for (var attr in tildes) { if (tildes.hasOwnProperty( attr )) { if (attr === '~') noIndex = true; else { var re_n = new RegExp( ' ' + attr, 'g' ); var re_value = ' ' + tildes[ attr ]; text = text.replace( re_n, re_value ); } } } // Finally replace tildes with its common root. if (noIndex) text = text.replace( / ~/g, ' ' + tildes[ '~' ] ); } return text; }
[ "function", "getReference", "(", "referenceFile", ")", "{", "var", "text", "=", "''", ";", "var", "referencePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "referenceFile", ")", ";", "var", "stats", "=", "fs", ".", "statSync", "(", "referencePath", ")", ";", "if", "(", "stats", "&&", "stats", ".", "isFile", "(", ")", ")", "{", "text", "=", "fs", ".", "readFileSync", "(", "referencePath", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "var", "tildes", "=", "{", "}", ";", "var", "re", "=", "/", "^\\s*\\[(~\\d*)]\\s*:", "/", "g", ";", "var", "source", "=", "text", ".", "split", "(", "'\\n'", ")", ";", "\\n", "var", "target", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "source", ".", "length", ";", "i", "++", ")", "{", "var", "line", "=", "source", "[", "i", "]", ".", "trim", "(", ")", ";", "var", "result", "=", "re", ".", "exec", "(", "line", ")", ";", "if", "(", "result", ")", "tildes", "[", "result", "[", "1", "]", "]", "=", "line", ".", "substring", "(", "line", ".", "indexOf", "(", "':'", ")", "+", "1", ")", ".", "trim", "(", ")", ";", "else", "if", "(", "line", "[", "0", "]", "===", "'['", ")", "target", ".", "push", "(", "line", ")", ";", "}", "text", "=", "target", ".", "join", "(", "'\\n'", ")", ";", "\\n", "var", "noIndex", "=", "false", ";", "}", "for", "(", "var", "attr", "in", "tildes", ")", "{", "if", "(", "tildes", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "if", "(", "attr", "===", "'~'", ")", "noIndex", "=", "true", ";", "else", "{", "var", "re_n", "=", "new", "RegExp", "(", "' '", "+", "attr", ",", "'g'", ")", ";", "var", "re_value", "=", "' '", "+", "tildes", "[", "attr", "]", ";", "text", "=", "text", ".", "replace", "(", "re_n", ",", "re_value", ")", ";", "}", "}", "}", "}" ]
Reads the content of a reference file. @param {string} referenceFile - The path of the reference file. @returns {string} The list of reference links.
[ "Reads", "the", "content", "of", "a", "reference", "file", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/get-reference.js#L11-L57
train
abubakir1997/anew
lib/store/utils/createPersistConfig.js
createPersistConfig
function createPersistConfig(persist, name) { switch (typeof persist === 'undefined' ? 'undefined' : _typeof(persist)) { case 'boolean': if (persist) { persist = { key: name, storage: _storage2.default }; } break; case 'object': persist = _extends({ storage: _storage2.default }, persist, { key: name }); break; } return persist; }
javascript
function createPersistConfig(persist, name) { switch (typeof persist === 'undefined' ? 'undefined' : _typeof(persist)) { case 'boolean': if (persist) { persist = { key: name, storage: _storage2.default }; } break; case 'object': persist = _extends({ storage: _storage2.default }, persist, { key: name }); break; } return persist; }
[ "function", "createPersistConfig", "(", "persist", ",", "name", ")", "{", "switch", "(", "typeof", "persist", "===", "'undefined'", "?", "'undefined'", ":", "_typeof", "(", "persist", ")", ")", "{", "case", "'boolean'", ":", "if", "(", "persist", ")", "{", "persist", "=", "{", "key", ":", "name", ",", "storage", ":", "_storage2", ".", "default", "}", ";", "}", "break", ";", "case", "'object'", ":", "persist", "=", "_extends", "(", "{", "storage", ":", "_storage2", ".", "default", "}", ",", "persist", ",", "{", "key", ":", "name", "}", ")", ";", "break", ";", "}", "return", "persist", ";", "}" ]
Convert true presits to config object
[ "Convert", "true", "presits", "to", "config", "object" ]
a79a01ea7b989184d5dddc0bd7de05efb2b02c8c
https://github.com/abubakir1997/anew/blob/a79a01ea7b989184d5dddc0bd7de05efb2b02c8c/lib/store/utils/createPersistConfig.js#L22-L44
train
avigoldman/fuse-email
lib/events.js
getListener
function getListener(event, id) { if (hasListeners(event)) { var listeners = getListeners(event); if (_.has(listeners, id)) { return listeners[id]; } } return false; }
javascript
function getListener(event, id) { if (hasListeners(event)) { var listeners = getListeners(event); if (_.has(listeners, id)) { return listeners[id]; } } return false; }
[ "function", "getListener", "(", "event", ",", "id", ")", "{", "if", "(", "hasListeners", "(", "event", ")", ")", "{", "var", "listeners", "=", "getListeners", "(", "event", ")", ";", "if", "(", "_", ".", "has", "(", "listeners", ",", "id", ")", ")", "{", "return", "listeners", "[", "id", "]", ";", "}", "}", "return", "false", ";", "}" ]
returns the listener with the given id
[ "returns", "the", "listener", "with", "the", "given", "id" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/events.js#L136-L146
train
avigoldman/fuse-email
lib/events.js
addListener
function addListener(id, event, listener) { if (!hasListeners(event)) { context._events[event] = {}; } context._events[event][id] = listener; return id; }
javascript
function addListener(id, event, listener) { if (!hasListeners(event)) { context._events[event] = {}; } context._events[event][id] = listener; return id; }
[ "function", "addListener", "(", "id", ",", "event", ",", "listener", ")", "{", "if", "(", "!", "hasListeners", "(", "event", ")", ")", "{", "context", ".", "_events", "[", "event", "]", "=", "{", "}", ";", "}", "context", ".", "_events", "[", "event", "]", "[", "id", "]", "=", "listener", ";", "return", "id", ";", "}" ]
adds a listener to an event
[ "adds", "a", "listener", "to", "an", "event" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/events.js#L158-L166
train
theKashey/wipeNodeCache
src/index.js
wipeCache
function wipeCache(stubs, resolver, waveCallback, removeFromCache = removeFromCache_nodejs) { waveCallback = waveCallback || waveCallback_default; const cache = require.cache; wipeMap( cache, (cache, callback) => cache.forEach( moduleName => resolver(stubs, moduleName) && callback(moduleName) ), waveCallback, removeFromCache ); }
javascript
function wipeCache(stubs, resolver, waveCallback, removeFromCache = removeFromCache_nodejs) { waveCallback = waveCallback || waveCallback_default; const cache = require.cache; wipeMap( cache, (cache, callback) => cache.forEach( moduleName => resolver(stubs, moduleName) && callback(moduleName) ), waveCallback, removeFromCache ); }
[ "function", "wipeCache", "(", "stubs", ",", "resolver", ",", "waveCallback", ",", "removeFromCache", "=", "removeFromCache_nodejs", ")", "{", "waveCallback", "=", "waveCallback", "||", "waveCallback_default", ";", "const", "cache", "=", "require", ".", "cache", ";", "wipeMap", "(", "cache", ",", "(", "cache", ",", "callback", ")", "=>", "cache", ".", "forEach", "(", "moduleName", "=>", "resolver", "(", "stubs", ",", "moduleName", ")", "&&", "callback", "(", "moduleName", ")", ")", ",", "waveCallback", ",", "removeFromCache", ")", ";", "}" ]
Wipes node.js module cache. First it look for modules to wipe, and wipe them. Second it looks for users of that modules and wipe them to. Repeat. Use waveCallback to control secondary wave. @param {Object} stubs Any objects, which will just be passed as first parameter to resolver. @param {Function} resolver function(stubs, moduleName) which shall return true, if module must be wiped out. @param {Function} [waveCallback] function(moduleName) which shall return false, if parent module must not be wiped.
[ "Wipes", "node", ".", "js", "module", "cache", ".", "First", "it", "look", "for", "modules", "to", "wipe", "and", "wipe", "them", ".", "Second", "it", "looks", "for", "users", "of", "that", "modules", "and", "wipe", "them", "to", ".", "Repeat", ".", "Use", "waveCallback", "to", "control", "secondary", "wave", "." ]
082e6234e859cd0419f7b73d31501eed566abef6
https://github.com/theKashey/wipeNodeCache/blob/082e6234e859cd0419f7b73d31501eed566abef6/src/index.js#L70-L82
train
hflw/node-robot
examples/line-follower.js
function(){ scheduler.sequence(function(){ console.log("running"); motors.set({"A,B": 20, "C,D": 0}); //move left wheels }).wait(function(){ //wait until we moved off the line return colorSensor.value == ColorSensor.colors.WHITE; }).do(function(){ motors.set({"A,B": 0, "C,D": 20}); //move right wheels }).wait(function(){ //wait until we're back on the line if(colorSensor.value == ColorSensor.colors.BLUE) console.log("blue now"); return colorSensor.value == ColorSensor.colors.BLUE; }).wait(function(){ //now wait until we're off the line if(colorSensor.value == ColorSensor.colors.WHITE) console.log("now white"); return colorSensor.value == ColorSensor.colors.WHITE; }).do(function(){ motors.set({"A,B": 20, "C,D": 0}); //move left wheels }).wait(function(){ //wait until we're back on the line return colorSensor.value == ColorSensor.colors.BLUE; }).do(function(){ console.log("rescheduling"); this.schedule(); //reschedule the sequence now that we're back at the starting conditions }).schedule(); //schedule the sequence to be run }
javascript
function(){ scheduler.sequence(function(){ console.log("running"); motors.set({"A,B": 20, "C,D": 0}); //move left wheels }).wait(function(){ //wait until we moved off the line return colorSensor.value == ColorSensor.colors.WHITE; }).do(function(){ motors.set({"A,B": 0, "C,D": 20}); //move right wheels }).wait(function(){ //wait until we're back on the line if(colorSensor.value == ColorSensor.colors.BLUE) console.log("blue now"); return colorSensor.value == ColorSensor.colors.BLUE; }).wait(function(){ //now wait until we're off the line if(colorSensor.value == ColorSensor.colors.WHITE) console.log("now white"); return colorSensor.value == ColorSensor.colors.WHITE; }).do(function(){ motors.set({"A,B": 20, "C,D": 0}); //move left wheels }).wait(function(){ //wait until we're back on the line return colorSensor.value == ColorSensor.colors.BLUE; }).do(function(){ console.log("rescheduling"); this.schedule(); //reschedule the sequence now that we're back at the starting conditions }).schedule(); //schedule the sequence to be run }
[ "function", "(", ")", "{", "scheduler", ".", "sequence", "(", "function", "(", ")", "{", "console", ".", "log", "(", "\"running\"", ")", ";", "motors", ".", "set", "(", "{", "\"A,B\"", ":", "20", ",", "\"C,D\"", ":", "0", "}", ")", ";", "}", ")", ".", "wait", "(", "function", "(", ")", "{", "return", "colorSensor", ".", "value", "==", "ColorSensor", ".", "colors", ".", "WHITE", ";", "}", ")", ".", "do", "(", "function", "(", ")", "{", "motors", ".", "set", "(", "{", "\"A,B\"", ":", "0", ",", "\"C,D\"", ":", "20", "}", ")", ";", "}", ")", ".", "wait", "(", "function", "(", ")", "{", "if", "(", "colorSensor", ".", "value", "==", "ColorSensor", ".", "colors", ".", "BLUE", ")", "console", ".", "log", "(", "\"blue now\"", ")", ";", "return", "colorSensor", ".", "value", "==", "ColorSensor", ".", "colors", ".", "BLUE", ";", "}", ")", ".", "wait", "(", "function", "(", ")", "{", "if", "(", "colorSensor", ".", "value", "==", "ColorSensor", ".", "colors", ".", "WHITE", ")", "console", ".", "log", "(", "\"now white\"", ")", ";", "return", "colorSensor", ".", "value", "==", "ColorSensor", ".", "colors", ".", "WHITE", ";", "}", ")", ".", "do", "(", "function", "(", ")", "{", "motors", ".", "set", "(", "{", "\"A,B\"", ":", "20", ",", "\"C,D\"", ":", "0", "}", ")", ";", "}", ")", ".", "wait", "(", "function", "(", ")", "{", "return", "colorSensor", ".", "value", "==", "ColorSensor", ".", "colors", ".", "BLUE", ";", "}", ")", ".", "do", "(", "function", "(", ")", "{", "console", ".", "log", "(", "\"rescheduling\"", ")", ";", "this", ".", "schedule", "(", ")", ";", "}", ")", ".", "schedule", "(", ")", ";", "}" ]
this assumes we're following a blue line on a white background also assumes there is a wall at the end of the line we're following
[ "this", "assumes", "we", "re", "following", "a", "blue", "line", "on", "a", "white", "background", "also", "assumes", "there", "is", "a", "wall", "at", "the", "end", "of", "the", "line", "we", "re", "following" ]
39daf9f9e8d151566b8e3bdb45eea129596295d6
https://github.com/hflw/node-robot/blob/39daf9f9e8d151566b8e3bdb45eea129596295d6/examples/line-follower.js#L13-L56
train
Malvid/components-lookup
src/index.js
async function(fileName, fileExt, resolve, parse, cwd) { // Get an array of paths to tell the location of potential files const locations = resolve(fileName, fileExt) // Look for the data in the same directory as filePath const relativePath = await locatePath(locations, { cwd }) // Only continue with files if (relativePath == null) return null // Path to data must be absolute to read it const absolutePath = path.resolve(cwd, relativePath) // Load the file const contents = util.promisify(fs.readFile)(absolutePath, 'utf8') // Parse file contents with the given parser if (parse != null) { try { return parse(contents, absolutePath) } catch (err) { throw new Error(`Failed to parse '${ relativePath }'`) } } return contents }
javascript
async function(fileName, fileExt, resolve, parse, cwd) { // Get an array of paths to tell the location of potential files const locations = resolve(fileName, fileExt) // Look for the data in the same directory as filePath const relativePath = await locatePath(locations, { cwd }) // Only continue with files if (relativePath == null) return null // Path to data must be absolute to read it const absolutePath = path.resolve(cwd, relativePath) // Load the file const contents = util.promisify(fs.readFile)(absolutePath, 'utf8') // Parse file contents with the given parser if (parse != null) { try { return parse(contents, absolutePath) } catch (err) { throw new Error(`Failed to parse '${ relativePath }'`) } } return contents }
[ "async", "function", "(", "fileName", ",", "fileExt", ",", "resolve", ",", "parse", ",", "cwd", ")", "{", "const", "locations", "=", "resolve", "(", "fileName", ",", "fileExt", ")", "const", "relativePath", "=", "await", "locatePath", "(", "locations", ",", "{", "cwd", "}", ")", "if", "(", "relativePath", "==", "null", ")", "return", "null", "const", "absolutePath", "=", "path", ".", "resolve", "(", "cwd", ",", "relativePath", ")", "const", "contents", "=", "util", ".", "promisify", "(", "fs", ".", "readFile", ")", "(", "absolutePath", ",", "'utf8'", ")", "if", "(", "parse", "!=", "null", ")", "{", "try", "{", "return", "parse", "(", "contents", ",", "absolutePath", ")", "}", "catch", "(", "err", ")", "{", "throw", "new", "Error", "(", "`", "${", "relativePath", "}", "`", ")", "}", "}", "return", "contents", "}" ]
Locate and load a file. @public @param {String} fileName - File name of the component. @param {String} fileExt - File extension of the component. @param {Function} resolve - Function that returns an array of paths to tell the potential location of a file. @param {?Function} parse - Function that parses the contents of the file resolved by the resolve function. @param {String} cwd - The directory in which to search. Must be absolute. @returns {Promise<?String>} Contents of a file.
[ "Locate", "and", "load", "a", "file", "." ]
b605ce62b279ac52e377d65077185d175a1980e5
https://github.com/Malvid/components-lookup/blob/b605ce62b279ac52e377d65077185d175a1980e5/src/index.js#L23-L47
train
Malvid/components-lookup
src/index.js
async function(filePath, index, resolvers, opts) { // Use the filePath to generate a unique id const id = crypto.createHash('sha1').update(filePath).digest('hex') // File name and extension const { name: fileName, ext: fileExt } = path.parse(filePath) // Absolute directory path to the component const fileCwd = path.resolve(opts.cwd, path.dirname(filePath)) // Absolute preview URL const rawURL = '/' + rename(filePath, '.html') const processedURL = opts.url(rawURL) // Reuse data from resolver and add additional information const data = await pMap(resolvers, async (resolver, index) => { return Object.assign({}, resolver, { index, data: await getFile(fileName, fileExt, resolver.resolve, resolver.parse, fileCwd) }) }) return { index, id, name: fileName, src: filePath, url: processedURL, data } }
javascript
async function(filePath, index, resolvers, opts) { // Use the filePath to generate a unique id const id = crypto.createHash('sha1').update(filePath).digest('hex') // File name and extension const { name: fileName, ext: fileExt } = path.parse(filePath) // Absolute directory path to the component const fileCwd = path.resolve(opts.cwd, path.dirname(filePath)) // Absolute preview URL const rawURL = '/' + rename(filePath, '.html') const processedURL = opts.url(rawURL) // Reuse data from resolver and add additional information const data = await pMap(resolvers, async (resolver, index) => { return Object.assign({}, resolver, { index, data: await getFile(fileName, fileExt, resolver.resolve, resolver.parse, fileCwd) }) }) return { index, id, name: fileName, src: filePath, url: processedURL, data } }
[ "async", "function", "(", "filePath", ",", "index", ",", "resolvers", ",", "opts", ")", "{", "const", "id", "=", "crypto", ".", "createHash", "(", "'sha1'", ")", ".", "update", "(", "filePath", ")", ".", "digest", "(", "'hex'", ")", "const", "{", "name", ":", "fileName", ",", "ext", ":", "fileExt", "}", "=", "path", ".", "parse", "(", "filePath", ")", "const", "fileCwd", "=", "path", ".", "resolve", "(", "opts", ".", "cwd", ",", "path", ".", "dirname", "(", "filePath", ")", ")", "const", "rawURL", "=", "'/'", "+", "rename", "(", "filePath", ",", "'.html'", ")", "const", "processedURL", "=", "opts", ".", "url", "(", "rawURL", ")", "const", "data", "=", "await", "pMap", "(", "resolvers", ",", "async", "(", "resolver", ",", "index", ")", "=>", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "resolver", ",", "{", "index", ",", "data", ":", "await", "getFile", "(", "fileName", ",", "fileExt", ",", "resolver", ".", "resolve", ",", "resolver", ".", "parse", ",", "fileCwd", ")", "}", ")", "}", ")", "return", "{", "index", ",", "id", ",", "name", ":", "fileName", ",", "src", ":", "filePath", ",", "url", ":", "processedURL", ",", "data", "}", "}" ]
Gather information about a component. @public @param {String} filePath - Relative path to component. @param {Number} index - Index of the current element being processed. @param {Array} resolvers - Array of objects with functions that return an array of paths to tell the potential location of files. @param {Object} opts - Options. @returns {Promise<Object>} Information of a component.
[ "Gather", "information", "about", "a", "component", "." ]
b605ce62b279ac52e377d65077185d175a1980e5
https://github.com/Malvid/components-lookup/blob/b605ce62b279ac52e377d65077185d175a1980e5/src/index.js#L58-L92
train
SnapSearch/SnapSearch-Client-Node
src/Detector.js
caseInsensitiveLookup
function caseInsensitiveLookup (object, lookup) { lookup = lookup.toLowerCase(); for (var property in object) { if (object.hasOwnProperty(property) && lookup == property.toLowerCase()) { return object[property]; } } return undefined; }
javascript
function caseInsensitiveLookup (object, lookup) { lookup = lookup.toLowerCase(); for (var property in object) { if (object.hasOwnProperty(property) && lookup == property.toLowerCase()) { return object[property]; } } return undefined; }
[ "function", "caseInsensitiveLookup", "(", "object", ",", "lookup", ")", "{", "lookup", "=", "lookup", ".", "toLowerCase", "(", ")", ";", "for", "(", "var", "property", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "property", ")", "&&", "lookup", "==", "property", ".", "toLowerCase", "(", ")", ")", "{", "return", "object", "[", "property", "]", ";", "}", "}", "return", "undefined", ";", "}" ]
Looks up an object property in a case-insensitive manner, it will find the first property that matches. Although Node.js currently normalises request headers to lower case, this may not be true forever. The number of headers is pretty limited for any particular request. So this should add too much processing time. @param object object @param string lookup @return mixed Returns the property value or undefined if the lookup was not found.
[ "Looks", "up", "an", "object", "property", "in", "a", "case", "-", "insensitive", "manner", "it", "will", "find", "the", "first", "property", "that", "matches", ".", "Although", "Node", ".", "js", "currently", "normalises", "request", "headers", "to", "lower", "case", "this", "may", "not", "be", "true", "forever", ".", "The", "number", "of", "headers", "is", "pretty", "limited", "for", "any", "particular", "request", ".", "So", "this", "should", "add", "too", "much", "processing", "time", "." ]
e8cf4434d0f3a43d7ae12516f3438bd843b60830
https://github.com/SnapSearch/SnapSearch-Client-Node/blob/e8cf4434d0f3a43d7ae12516f3438bd843b60830/src/Detector.js#L381-L397
train
lennartcl/jsonm
src/packer.js
tryPackErrorKeys
function tryPackErrorKeys(object, results) { if (object instanceof Error) { results.push(packValue("message"), packValue("stack")); return true; } }
javascript
function tryPackErrorKeys(object, results) { if (object instanceof Error) { results.push(packValue("message"), packValue("stack")); return true; } }
[ "function", "tryPackErrorKeys", "(", "object", ",", "results", ")", "{", "if", "(", "object", "instanceof", "Error", ")", "{", "results", ".", "push", "(", "packValue", "(", "\"message\"", ")", ",", "packValue", "(", "\"stack\"", ")", ")", ";", "return", "true", ";", "}", "}" ]
Try pack and memoize an Error object. @returns false if the object was not an Error object
[ "Try", "pack", "and", "memoize", "an", "Error", "object", "." ]
27a58793ccc20a851152e5a3f182272c4c757471
https://github.com/lennartcl/jsonm/blob/27a58793ccc20a851152e5a3f182272c4c757471/src/packer.js#L142-L147
train
lennartcl/jsonm
src/packer.js
packValue
function packValue(value) { const result = memoizedMap.get(value); if (result == null) { if (value >= MIN_DICT_INDEX && value <= MAX_VERBATIM_INTEGER && Number.isInteger(value)) return -value; memoize(value); if (typeof value === "number") return String(value); if (/^[0-9\.]|^~/.test(value)) return `~${value}`; return value; } return result; }
javascript
function packValue(value) { const result = memoizedMap.get(value); if (result == null) { if (value >= MIN_DICT_INDEX && value <= MAX_VERBATIM_INTEGER && Number.isInteger(value)) return -value; memoize(value); if (typeof value === "number") return String(value); if (/^[0-9\.]|^~/.test(value)) return `~${value}`; return value; } return result; }
[ "function", "packValue", "(", "value", ")", "{", "const", "result", "=", "memoizedMap", ".", "get", "(", "value", ")", ";", "if", "(", "result", "==", "null", ")", "{", "if", "(", "value", ">=", "MIN_DICT_INDEX", "&&", "value", "<=", "MAX_VERBATIM_INTEGER", "&&", "Number", ".", "isInteger", "(", "value", ")", ")", "return", "-", "value", ";", "memoize", "(", "value", ")", ";", "if", "(", "typeof", "value", "===", "\"number\"", ")", "return", "String", "(", "value", ")", ";", "if", "(", "/", "^[0-9\\.]|^~", "/", ".", "test", "(", "value", ")", ")", "return", "`", "${", "value", "}", "`", ";", "return", "value", ";", "}", "return", "result", ";", "}" ]
Pack and memoize a scalar value.
[ "Pack", "and", "memoize", "a", "scalar", "value", "." ]
27a58793ccc20a851152e5a3f182272c4c757471
https://github.com/lennartcl/jsonm/blob/27a58793ccc20a851152e5a3f182272c4c757471/src/packer.js#L166-L181
train
lennartcl/jsonm
src/packer.js
memoize
function memoize(value, objectKey) { const oldValue = memoized[memoizedIndex]; if (oldValue !== undefined) { memoizedMap.delete(oldValue); memoizedObjectMap.delete(oldValue); } if (objectKey) memoizedObjectMap.set(objectKey, memoizedIndex); else memoizedMap.set(value, memoizedIndex); memoized[memoizedIndex] = value; memoizedIndex++; if (memoizedIndex >= maxDictSize + MIN_DICT_INDEX) memoizedIndex = MIN_DICT_INDEX; }
javascript
function memoize(value, objectKey) { const oldValue = memoized[memoizedIndex]; if (oldValue !== undefined) { memoizedMap.delete(oldValue); memoizedObjectMap.delete(oldValue); } if (objectKey) memoizedObjectMap.set(objectKey, memoizedIndex); else memoizedMap.set(value, memoizedIndex); memoized[memoizedIndex] = value; memoizedIndex++; if (memoizedIndex >= maxDictSize + MIN_DICT_INDEX) memoizedIndex = MIN_DICT_INDEX; }
[ "function", "memoize", "(", "value", ",", "objectKey", ")", "{", "const", "oldValue", "=", "memoized", "[", "memoizedIndex", "]", ";", "if", "(", "oldValue", "!==", "undefined", ")", "{", "memoizedMap", ".", "delete", "(", "oldValue", ")", ";", "memoizedObjectMap", ".", "delete", "(", "oldValue", ")", ";", "}", "if", "(", "objectKey", ")", "memoizedObjectMap", ".", "set", "(", "objectKey", ",", "memoizedIndex", ")", ";", "else", "memoizedMap", ".", "set", "(", "value", ",", "memoizedIndex", ")", ";", "memoized", "[", "memoizedIndex", "]", "=", "value", ";", "memoizedIndex", "++", ";", "if", "(", "memoizedIndex", ">=", "maxDictSize", "+", "MIN_DICT_INDEX", ")", "memoizedIndex", "=", "MIN_DICT_INDEX", ";", "}" ]
Memoize a value. @param value @param [map]
[ "Memoize", "a", "value", "." ]
27a58793ccc20a851152e5a3f182272c4c757471
https://github.com/lennartcl/jsonm/blob/27a58793ccc20a851152e5a3f182272c4c757471/src/packer.js#L189-L205
train
lammas/glsl-man
src/parser.js
daisy_chain
function daisy_chain(head, tail) { var result = head; for (var i = 0; i < tail.length; i++) { result = new node({ type: "binary", operator: tail[i][1], left: result, right: tail[i][3] }); } return result; }
javascript
function daisy_chain(head, tail) { var result = head; for (var i = 0; i < tail.length; i++) { result = new node({ type: "binary", operator: tail[i][1], left: result, right: tail[i][3] }); } return result; }
[ "function", "daisy_chain", "(", "head", ",", "tail", ")", "{", "var", "result", "=", "head", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "tail", ".", "length", ";", "i", "++", ")", "{", "result", "=", "new", "node", "(", "{", "type", ":", "\"binary\"", ",", "operator", ":", "tail", "[", "i", "]", "[", "1", "]", ",", "left", ":", "result", ",", "right", ":", "tail", "[", "i", "]", "[", "3", "]", "}", ")", ";", "}", "return", "result", ";", "}" ]
Helper function to daisy chain together a series of binary operations.
[ "Helper", "function", "to", "daisy", "chain", "together", "a", "series", "of", "binary", "operations", "." ]
3710089cdc813b71eb062a00920a765a18a634c7
https://github.com/lammas/glsl-man/blob/3710089cdc813b71eb062a00920a765a18a634c7/src/parser.js#L9426-L9437
train
lammas/glsl-man
src/parser.js
preprocessor_branch
function preprocessor_branch(if_directive, elif_directives, else_directive) { var elseList = elif_directives; if (else_directive) { elseList = elseList.concat([else_directive]); } var result = if_directive[0]; result.guarded_statements = if_directive[1].statements; var current_branch = result; for (var i = 0; i < elseList.length; i++) { current_branch.elseBody = elseList[i][0]; current_branch.elseBody.guarded_statements = elseList[i][1].statements; current_branch = current_branch.elseBody; } return result; }
javascript
function preprocessor_branch(if_directive, elif_directives, else_directive) { var elseList = elif_directives; if (else_directive) { elseList = elseList.concat([else_directive]); } var result = if_directive[0]; result.guarded_statements = if_directive[1].statements; var current_branch = result; for (var i = 0; i < elseList.length; i++) { current_branch.elseBody = elseList[i][0]; current_branch.elseBody.guarded_statements = elseList[i][1].statements; current_branch = current_branch.elseBody; } return result; }
[ "function", "preprocessor_branch", "(", "if_directive", ",", "elif_directives", ",", "else_directive", ")", "{", "var", "elseList", "=", "elif_directives", ";", "if", "(", "else_directive", ")", "{", "elseList", "=", "elseList", ".", "concat", "(", "[", "else_directive", "]", ")", ";", "}", "var", "result", "=", "if_directive", "[", "0", "]", ";", "result", ".", "guarded_statements", "=", "if_directive", "[", "1", "]", ".", "statements", ";", "var", "current_branch", "=", "result", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elseList", ".", "length", ";", "i", "++", ")", "{", "current_branch", ".", "elseBody", "=", "elseList", "[", "i", "]", "[", "0", "]", ";", "current_branch", ".", "elseBody", ".", "guarded_statements", "=", "elseList", "[", "i", "]", "[", "1", "]", ".", "statements", ";", "current_branch", "=", "current_branch", ".", "elseBody", ";", "}", "return", "result", ";", "}" ]
Generates AST Nodes for a preprocessor branch.
[ "Generates", "AST", "Nodes", "for", "a", "preprocessor", "branch", "." ]
3710089cdc813b71eb062a00920a765a18a634c7
https://github.com/lammas/glsl-man/blob/3710089cdc813b71eb062a00920a765a18a634c7/src/parser.js#L9440-L9457
train
nfroidure/Sounds
Sounds.js
Sounds
function Sounds(folder,loadCallback) { if(!folder) throw new Error('No folder given for sounds !') // sound is on by default this.muted=false; // contains sounds elements this.sounds={}; // contains sounds to load this.soundsToLoad=new Array(); // callback executed when each sounds are loaded this.loadedSounds=loadCallback; // detecting supported extensions var sound=document.createElement('audio'); this.exts=[]; if(sound.canPlayType('audio/ogg')) this.exts.push('ogg'); if(sound.canPlayType('audio/mp3')) this.exts.push('mp3'); if(sound.canPlayType('audio/x-midi')) this.exts.push('mid'); // folder containing sounds this.folder=folder; }
javascript
function Sounds(folder,loadCallback) { if(!folder) throw new Error('No folder given for sounds !') // sound is on by default this.muted=false; // contains sounds elements this.sounds={}; // contains sounds to load this.soundsToLoad=new Array(); // callback executed when each sounds are loaded this.loadedSounds=loadCallback; // detecting supported extensions var sound=document.createElement('audio'); this.exts=[]; if(sound.canPlayType('audio/ogg')) this.exts.push('ogg'); if(sound.canPlayType('audio/mp3')) this.exts.push('mp3'); if(sound.canPlayType('audio/x-midi')) this.exts.push('mid'); // folder containing sounds this.folder=folder; }
[ "function", "Sounds", "(", "folder", ",", "loadCallback", ")", "{", "if", "(", "!", "folder", ")", "throw", "new", "Error", "(", "'No folder given for sounds !'", ")", "this", ".", "muted", "=", "false", ";", "this", ".", "sounds", "=", "{", "}", ";", "this", ".", "soundsToLoad", "=", "new", "Array", "(", ")", ";", "this", ".", "loadedSounds", "=", "loadCallback", ";", "var", "sound", "=", "document", ".", "createElement", "(", "'audio'", ")", ";", "this", ".", "exts", "=", "[", "]", ";", "if", "(", "sound", ".", "canPlayType", "(", "'audio/ogg'", ")", ")", "this", ".", "exts", ".", "push", "(", "'ogg'", ")", ";", "if", "(", "sound", ".", "canPlayType", "(", "'audio/mp3'", ")", ")", "this", ".", "exts", ".", "push", "(", "'mp3'", ")", ";", "if", "(", "sound", ".", "canPlayType", "(", "'audio/x-midi'", ")", ")", "this", ".", "exts", ".", "push", "(", "'mid'", ")", ";", "this", ".", "folder", "=", "folder", ";", "}" ]
HTML5 Sounds manager
[ "HTML5", "Sounds", "manager" ]
38c9a344c88b5f065641e2ab31a907a12f195391
https://github.com/nfroidure/Sounds/blob/38c9a344c88b5f065641e2ab31a907a12f195391/Sounds.js#L2-L24
train
codekirei/columnize-array
lib/methods/bindState.js
bindState
function bindState(rows) { // build state from rows and immutable initState //---------------------------------------------------------- this.state = merge( {} , this.props.initState , {rows} ) // fill state arrays with init vals //---------------------------------------------------------- function initVals(map, ct) { while (ct--) map.forEach((v, k) => k.push(v())) } const cols = Math.ceil(this.props.arLen, rows) const colMap = new Map() colMap.set(this.state.widths, () => 0) initVals(colMap, cols) const rowMap = new Map() rowMap.set(this.state.indices, () => []) rowMap.set(this.state.strs, () => '') initVals(rowMap, rows) }
javascript
function bindState(rows) { // build state from rows and immutable initState //---------------------------------------------------------- this.state = merge( {} , this.props.initState , {rows} ) // fill state arrays with init vals //---------------------------------------------------------- function initVals(map, ct) { while (ct--) map.forEach((v, k) => k.push(v())) } const cols = Math.ceil(this.props.arLen, rows) const colMap = new Map() colMap.set(this.state.widths, () => 0) initVals(colMap, cols) const rowMap = new Map() rowMap.set(this.state.indices, () => []) rowMap.set(this.state.strs, () => '') initVals(rowMap, rows) }
[ "function", "bindState", "(", "rows", ")", "{", "this", ".", "state", "=", "merge", "(", "{", "}", ",", "this", ".", "props", ".", "initState", ",", "{", "rows", "}", ")", "function", "initVals", "(", "map", ",", "ct", ")", "{", "while", "(", "ct", "--", ")", "map", ".", "forEach", "(", "(", "v", ",", "k", ")", "=>", "k", ".", "push", "(", "v", "(", ")", ")", ")", "}", "const", "cols", "=", "Math", ".", "ceil", "(", "this", ".", "props", ".", "arLen", ",", "rows", ")", "const", "colMap", "=", "new", "Map", "(", ")", "colMap", ".", "set", "(", "this", ".", "state", ".", "widths", ",", "(", ")", "=>", "0", ")", "initVals", "(", "colMap", ",", "cols", ")", "const", "rowMap", "=", "new", "Map", "(", ")", "rowMap", ".", "set", "(", "this", ".", "state", ".", "indices", ",", "(", ")", "=>", "[", "]", ")", "rowMap", ".", "set", "(", "this", ".", "state", ".", "strs", ",", "(", ")", "=>", "''", ")", "initVals", "(", "rowMap", ",", "rows", ")", "}" ]
Constructs state object and binds to this.state. @param {Number} rows - row count of current state iteration @returns {undefined}
[ "Constructs", "state", "object", "and", "binds", "to", "this", ".", "state", "." ]
ba100d1d9cf707fa249a58fa177d6b26ec131278
https://github.com/codekirei/columnize-array/blob/ba100d1d9cf707fa249a58fa177d6b26ec131278/lib/methods/bindState.js#L13-L36
train
jokemmy/kiwiai
src/runServer.js
readServerConfig
function readServerConfig( server ) { try { const severConfig = getConfig( appSeverConfig ); return Right( Object.assign( server, severConfig )); } catch ( e ) { print( chalk.red( `Failed to read ${SEVER_CONFIG}.` ), e.message ); print(); return Left( null ); } }
javascript
function readServerConfig( server ) { try { const severConfig = getConfig( appSeverConfig ); return Right( Object.assign( server, severConfig )); } catch ( e ) { print( chalk.red( `Failed to read ${SEVER_CONFIG}.` ), e.message ); print(); return Left( null ); } }
[ "function", "readServerConfig", "(", "server", ")", "{", "try", "{", "const", "severConfig", "=", "getConfig", "(", "appSeverConfig", ")", ";", "return", "Right", "(", "Object", ".", "assign", "(", "server", ",", "severConfig", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "print", "(", "chalk", ".", "red", "(", "`", "${", "SEVER_CONFIG", "}", "`", ")", ",", "e", ".", "message", ")", ";", "print", "(", ")", ";", "return", "Left", "(", "null", ")", ";", "}", "}" ]
read config for develop server
[ "read", "config", "for", "develop", "server" ]
b5679e83d702bf8260b90d5c3e16425ad4666082
https://github.com/jokemmy/kiwiai/blob/b5679e83d702bf8260b90d5c3e16425ad4666082/src/runServer.js#L31-L43
train
jokemmy/kiwiai
src/runServer.js
readWebpackConfig
function readWebpackConfig( server ) { const devConfig = server.webpackConfig && server.webpackConfig.dev; const configFile = paths.resolveApp( devConfig ) || appWebpackDevConfig; try { assert( existsSync( configFile ), `File ${devConfig || WEBPACK_DEV_CONFIG} is not exsit.` ); const wpConfig = getConfig( configFile ); // plugins: function if ( is.Function( wpConfig.plugins )) { wpConfig.plugins = wpConfig.plugins( wpConfig ); } // plugins: not array if ( !is.Array( wpConfig.plugins )) { wpConfig.plugins = [wpConfig.plugins]; } // plugins: array in array wpConfig.plugins = flatten( wpConfig.plugins.map(( plugin ) => { return is.Function( plugin ) ? plugin( wpConfig ) : plugin; })); server.webpackDevConfig = wpConfig; watchFiles.push( configFile ); return Right( server ); } catch ( e ) { print( chalk.red( `Failed to read ${devConfig || WEBPACK_DEV_CONFIG}.` ), e.message ); print(); return Left( null ); } }
javascript
function readWebpackConfig( server ) { const devConfig = server.webpackConfig && server.webpackConfig.dev; const configFile = paths.resolveApp( devConfig ) || appWebpackDevConfig; try { assert( existsSync( configFile ), `File ${devConfig || WEBPACK_DEV_CONFIG} is not exsit.` ); const wpConfig = getConfig( configFile ); // plugins: function if ( is.Function( wpConfig.plugins )) { wpConfig.plugins = wpConfig.plugins( wpConfig ); } // plugins: not array if ( !is.Array( wpConfig.plugins )) { wpConfig.plugins = [wpConfig.plugins]; } // plugins: array in array wpConfig.plugins = flatten( wpConfig.plugins.map(( plugin ) => { return is.Function( plugin ) ? plugin( wpConfig ) : plugin; })); server.webpackDevConfig = wpConfig; watchFiles.push( configFile ); return Right( server ); } catch ( e ) { print( chalk.red( `Failed to read ${devConfig || WEBPACK_DEV_CONFIG}.` ), e.message ); print(); return Left( null ); } }
[ "function", "readWebpackConfig", "(", "server", ")", "{", "const", "devConfig", "=", "server", ".", "webpackConfig", "&&", "server", ".", "webpackConfig", ".", "dev", ";", "const", "configFile", "=", "paths", ".", "resolveApp", "(", "devConfig", ")", "||", "appWebpackDevConfig", ";", "try", "{", "assert", "(", "existsSync", "(", "configFile", ")", ",", "`", "${", "devConfig", "||", "WEBPACK_DEV_CONFIG", "}", "`", ")", ";", "const", "wpConfig", "=", "getConfig", "(", "configFile", ")", ";", "if", "(", "is", ".", "Function", "(", "wpConfig", ".", "plugins", ")", ")", "{", "wpConfig", ".", "plugins", "=", "wpConfig", ".", "plugins", "(", "wpConfig", ")", ";", "}", "if", "(", "!", "is", ".", "Array", "(", "wpConfig", ".", "plugins", ")", ")", "{", "wpConfig", ".", "plugins", "=", "[", "wpConfig", ".", "plugins", "]", ";", "}", "wpConfig", ".", "plugins", "=", "flatten", "(", "wpConfig", ".", "plugins", ".", "map", "(", "(", "plugin", ")", "=>", "{", "return", "is", ".", "Function", "(", "plugin", ")", "?", "plugin", "(", "wpConfig", ")", ":", "plugin", ";", "}", ")", ")", ";", "server", ".", "webpackDevConfig", "=", "wpConfig", ";", "watchFiles", ".", "push", "(", "configFile", ")", ";", "return", "Right", "(", "server", ")", ";", "}", "catch", "(", "e", ")", "{", "print", "(", "chalk", ".", "red", "(", "`", "${", "devConfig", "||", "WEBPACK_DEV_CONFIG", "}", "`", ")", ",", "e", ".", "message", ")", ";", "print", "(", ")", ";", "return", "Left", "(", "null", ")", ";", "}", "}" ]
read config for webpack dev server
[ "read", "config", "for", "webpack", "dev", "server" ]
b5679e83d702bf8260b90d5c3e16425ad4666082
https://github.com/jokemmy/kiwiai/blob/b5679e83d702bf8260b90d5c3e16425ad4666082/src/runServer.js#L46-L87
train
enmasseio/babble
lib/Babbler.js
Babbler
function Babbler (id) { if (!(this instanceof Babbler)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!id) { throw new Error('id required'); } this.id = id; this.listeners = []; // Array.<Listen> this.conversations = {}; // Array.<Array.<Conversation>> all open conversations this.connect(); // automatically connect to the local message bus }
javascript
function Babbler (id) { if (!(this instanceof Babbler)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!id) { throw new Error('id required'); } this.id = id; this.listeners = []; // Array.<Listen> this.conversations = {}; // Array.<Array.<Conversation>> all open conversations this.connect(); // automatically connect to the local message bus }
[ "function", "Babbler", "(", "id", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Babbler", ")", ")", "{", "throw", "new", "SyntaxError", "(", "'Constructor must be called with the new operator'", ")", ";", "}", "if", "(", "!", "id", ")", "{", "throw", "new", "Error", "(", "'id required'", ")", ";", "}", "this", ".", "id", "=", "id", ";", "this", ".", "listeners", "=", "[", "]", ";", "this", ".", "conversations", "=", "{", "}", ";", "this", ".", "connect", "(", ")", ";", "}" ]
append iif function to Block Babbler @param {String} id @constructor
[ "append", "iif", "function", "to", "Block", "Babbler" ]
6b7e84d7fb0df2d1129f0646b37a9d89d3da2539
https://github.com/enmasseio/babble/blob/6b7e84d7fb0df2d1129f0646b37a9d89d3da2539/lib/Babbler.js#L20-L34
train
Chris314/mongoose-permission
index.js
flattenAll
function flattenAll() { var result = []; for (var role in permissions) { result = result.concat(flatten(role)); } return uniq(result); }
javascript
function flattenAll() { var result = []; for (var role in permissions) { result = result.concat(flatten(role)); } return uniq(result); }
[ "function", "flattenAll", "(", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "role", "in", "permissions", ")", "{", "result", "=", "result", ".", "concat", "(", "flatten", "(", "role", ")", ")", ";", "}", "return", "uniq", "(", "result", ")", ";", "}" ]
FLatten the whole map
[ "FLatten", "the", "whole", "map" ]
2a32b942a23910363681d8395adb8212613e8826
https://github.com/Chris314/mongoose-permission/blob/2a32b942a23910363681d8395adb8212613e8826/index.js#L23-L29
train
Chris314/mongoose-permission
index.js
flatten
function flatten(role) { var children = permissions[role] || []; var result = [role]; for (var i in children) { result = result.concat(flatten(children[i])); } return result; }
javascript
function flatten(role) { var children = permissions[role] || []; var result = [role]; for (var i in children) { result = result.concat(flatten(children[i])); } return result; }
[ "function", "flatten", "(", "role", ")", "{", "var", "children", "=", "permissions", "[", "role", "]", "||", "[", "]", ";", "var", "result", "=", "[", "role", "]", ";", "for", "(", "var", "i", "in", "children", ")", "{", "result", "=", "result", ".", "concat", "(", "flatten", "(", "children", "[", "i", "]", ")", ")", ";", "}", "return", "result", ";", "}" ]
Flatten the map of a role
[ "Flatten", "the", "map", "of", "a", "role" ]
2a32b942a23910363681d8395adb8212613e8826
https://github.com/Chris314/mongoose-permission/blob/2a32b942a23910363681d8395adb8212613e8826/index.js#L33-L41
train
Chris314/mongoose-permission
index.js
getParent
function getParent(role) { var result = []; for (var parentRole in permissions) { if (permissions[parentRole].indexOf(role) > -1) { result.push(parentRole); result = result.concat(getParent(parentRole)); } } return result; }
javascript
function getParent(role) { var result = []; for (var parentRole in permissions) { if (permissions[parentRole].indexOf(role) > -1) { result.push(parentRole); result = result.concat(getParent(parentRole)); } } return result; }
[ "function", "getParent", "(", "role", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "parentRole", "in", "permissions", ")", "{", "if", "(", "permissions", "[", "parentRole", "]", ".", "indexOf", "(", "role", ")", ">", "-", "1", ")", "{", "result", ".", "push", "(", "parentRole", ")", ";", "result", "=", "result", ".", "concat", "(", "getParent", "(", "parentRole", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Remove parent permissions from flattenpermissions when subpermissions aren't found within it
[ "Remove", "parent", "permissions", "from", "flattenpermissions", "when", "subpermissions", "aren", "t", "found", "within", "it" ]
2a32b942a23910363681d8395adb8212613e8826
https://github.com/Chris314/mongoose-permission/blob/2a32b942a23910363681d8395adb8212613e8826/index.js#L44-L54
train
bluemathsoft/bm-common
lib/ops.js
iszero
function iszero(x, tolerance) { if (tolerance === void 0) { tolerance = constants_1.EPSILON; } // the 'less-than-equal' comparision is necessary for correct result // when tolerance = 0 return Math.abs(x) <= tolerance; }
javascript
function iszero(x, tolerance) { if (tolerance === void 0) { tolerance = constants_1.EPSILON; } // the 'less-than-equal' comparision is necessary for correct result // when tolerance = 0 return Math.abs(x) <= tolerance; }
[ "function", "iszero", "(", "x", ",", "tolerance", ")", "{", "if", "(", "tolerance", "===", "void", "0", ")", "{", "tolerance", "=", "constants_1", ".", "EPSILON", ";", "}", "return", "Math", ".", "abs", "(", "x", ")", "<=", "tolerance", ";", "}" ]
Check if input equals zero within given tolerance
[ "Check", "if", "input", "equals", "zero", "within", "given", "tolerance" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L40-L45
train
bluemathsoft/bm-common
lib/ops.js
isequal
function isequal(a, b, tolerance) { if (tolerance === void 0) { tolerance = constants_1.EPSILON; } return iszero(a - b, tolerance); }
javascript
function isequal(a, b, tolerance) { if (tolerance === void 0) { tolerance = constants_1.EPSILON; } return iszero(a - b, tolerance); }
[ "function", "isequal", "(", "a", ",", "b", ",", "tolerance", ")", "{", "if", "(", "tolerance", "===", "void", "0", ")", "{", "tolerance", "=", "constants_1", ".", "EPSILON", ";", "}", "return", "iszero", "(", "a", "-", "b", ",", "tolerance", ")", ";", "}" ]
Check if two input numbers are equal within given tolerance
[ "Check", "if", "two", "input", "numbers", "are", "equal", "within", "given", "tolerance" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L50-L53
train
bluemathsoft/bm-common
lib/ops.js
range
function range(a, b) { if (b === undefined) { b = a; a = 0; } b = Math.max(b, 0); var arr = []; for (var i = a; i < b; i++) { arr.push(i); } return new ndarray_1.NDArray(arr, { datatype: 'i32' }); }
javascript
function range(a, b) { if (b === undefined) { b = a; a = 0; } b = Math.max(b, 0); var arr = []; for (var i = a; i < b; i++) { arr.push(i); } return new ndarray_1.NDArray(arr, { datatype: 'i32' }); }
[ "function", "range", "(", "a", ",", "b", ")", "{", "if", "(", "b", "===", "undefined", ")", "{", "b", "=", "a", ";", "a", "=", "0", ";", "}", "b", "=", "Math", ".", "max", "(", "b", ",", "0", ")", ";", "var", "arr", "=", "[", "]", ";", "for", "(", "var", "i", "=", "a", ";", "i", "<", "b", ";", "i", "++", ")", "{", "arr", ".", "push", "(", "i", ")", ";", "}", "return", "new", "ndarray_1", ".", "NDArray", "(", "arr", ",", "{", "datatype", ":", "'i32'", "}", ")", ";", "}" ]
Generate array of integers within given range. If both a and b are specified then return [a,b) if only a is specifed then return [0,a)
[ "Generate", "array", "of", "integers", "within", "given", "range", ".", "If", "both", "a", "and", "b", "are", "specified", "then", "return", "[", "a", "b", ")", "if", "only", "a", "is", "specifed", "then", "return", "[", "0", "a", ")" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L70-L81
train
bluemathsoft/bm-common
lib/ops.js
eye
function eye(arg0, datatype) { var n, m; if (Array.isArray(arg0)) { n = arg0[0]; if (arg0.length > 1) { m = arg0[1]; } else { m = n; } } else { n = m = arg0; } var A = new ndarray_1.NDArray({ shape: [n, m], datatype: datatype, fill: 0 }); var ndiag = Math.min(n, m); for (var i = 0; i < ndiag; i++) { A.set(i, i, 1); } return A; }
javascript
function eye(arg0, datatype) { var n, m; if (Array.isArray(arg0)) { n = arg0[0]; if (arg0.length > 1) { m = arg0[1]; } else { m = n; } } else { n = m = arg0; } var A = new ndarray_1.NDArray({ shape: [n, m], datatype: datatype, fill: 0 }); var ndiag = Math.min(n, m); for (var i = 0; i < ndiag; i++) { A.set(i, i, 1); } return A; }
[ "function", "eye", "(", "arg0", ",", "datatype", ")", "{", "var", "n", ",", "m", ";", "if", "(", "Array", ".", "isArray", "(", "arg0", ")", ")", "{", "n", "=", "arg0", "[", "0", "]", ";", "if", "(", "arg0", ".", "length", ">", "1", ")", "{", "m", "=", "arg0", "[", "1", "]", ";", "}", "else", "{", "m", "=", "n", ";", "}", "}", "else", "{", "n", "=", "m", "=", "arg0", ";", "}", "var", "A", "=", "new", "ndarray_1", ".", "NDArray", "(", "{", "shape", ":", "[", "n", ",", "m", "]", ",", "datatype", ":", "datatype", ",", "fill", ":", "0", "}", ")", ";", "var", "ndiag", "=", "Math", ".", "min", "(", "n", ",", "m", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ndiag", ";", "i", "++", ")", "{", "A", ".", "set", "(", "i", ",", "i", ",", "1", ")", ";", "}", "return", "A", ";", "}" ]
Creates m-by-n Identity matrix ``` eye(2) // Creates 2x2 Identity matrix eye([2,2]) // Creates 2x2 Identity matrix eye([2,3]) // Create 2x3 Identity matrix with main diagonal set to 1 eye(2,'i32') // Creates 2x2 Identity matrix of 32-bit integers ```
[ "Creates", "m", "-", "by", "-", "n", "Identity", "matrix" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L93-L113
train
bluemathsoft/bm-common
lib/ops.js
zeros
function zeros(arg0, datatype) { var A; if (Array.isArray(arg0)) { A = new ndarray_1.NDArray({ shape: arg0, datatype: datatype }); } else { A = new ndarray_1.NDArray({ shape: [arg0], datatype: datatype }); } A.fill(0); return A; }
javascript
function zeros(arg0, datatype) { var A; if (Array.isArray(arg0)) { A = new ndarray_1.NDArray({ shape: arg0, datatype: datatype }); } else { A = new ndarray_1.NDArray({ shape: [arg0], datatype: datatype }); } A.fill(0); return A; }
[ "function", "zeros", "(", "arg0", ",", "datatype", ")", "{", "var", "A", ";", "if", "(", "Array", ".", "isArray", "(", "arg0", ")", ")", "{", "A", "=", "new", "ndarray_1", ".", "NDArray", "(", "{", "shape", ":", "arg0", ",", "datatype", ":", "datatype", "}", ")", ";", "}", "else", "{", "A", "=", "new", "ndarray_1", ".", "NDArray", "(", "{", "shape", ":", "[", "arg0", "]", ",", "datatype", ":", "datatype", "}", ")", ";", "}", "A", ".", "fill", "(", "0", ")", ";", "return", "A", ";", "}" ]
Creates NDArray filled with zeros ``` zeros(2) // Creates array of zeros of length 2 zeros([2,2,2]) // Create 2x2x2 matrix of zeros zeros(2,'i16') // Creates array of 2 16-bit integers filled with zeros ```
[ "Creates", "NDArray", "filled", "with", "zeros" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L135-L145
train
bluemathsoft/bm-common
lib/ops.js
empty
function empty(arg0, datatype) { var A; if (Array.isArray(arg0)) { A = new ndarray_1.NDArray({ shape: arg0, datatype: datatype }); } else { A = new ndarray_1.NDArray({ shape: [arg0], datatype: datatype }); } return A; }
javascript
function empty(arg0, datatype) { var A; if (Array.isArray(arg0)) { A = new ndarray_1.NDArray({ shape: arg0, datatype: datatype }); } else { A = new ndarray_1.NDArray({ shape: [arg0], datatype: datatype }); } return A; }
[ "function", "empty", "(", "arg0", ",", "datatype", ")", "{", "var", "A", ";", "if", "(", "Array", ".", "isArray", "(", "arg0", ")", ")", "{", "A", "=", "new", "ndarray_1", ".", "NDArray", "(", "{", "shape", ":", "arg0", ",", "datatype", ":", "datatype", "}", ")", ";", "}", "else", "{", "A", "=", "new", "ndarray_1", ".", "NDArray", "(", "{", "shape", ":", "[", "arg0", "]", ",", "datatype", ":", "datatype", "}", ")", ";", "}", "return", "A", ";", "}" ]
Creates empty NDArray of given shape or of given length if argument is a number
[ "Creates", "empty", "NDArray", "of", "given", "shape", "or", "of", "given", "length", "if", "argument", "is", "a", "number" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L151-L160
train
bluemathsoft/bm-common
lib/ops.js
cross
function cross(A, B) { if (A.shape.length !== 1 || B.shape.length !== 1) { throw new Error('A or B is not 1D'); } if (A.length < 3 || B.length < 3) { throw new Error('A or B is less than 3 in length'); } var a1 = A.getN(0); var a2 = A.getN(1); var a3 = A.getN(2); var b1 = B.getN(0); var b2 = B.getN(1); var b3 = B.getN(2); return new ndarray_1.NDArray([ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 ]); }
javascript
function cross(A, B) { if (A.shape.length !== 1 || B.shape.length !== 1) { throw new Error('A or B is not 1D'); } if (A.length < 3 || B.length < 3) { throw new Error('A or B is less than 3 in length'); } var a1 = A.getN(0); var a2 = A.getN(1); var a3 = A.getN(2); var b1 = B.getN(0); var b2 = B.getN(1); var b3 = B.getN(2); return new ndarray_1.NDArray([ a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1 ]); }
[ "function", "cross", "(", "A", ",", "B", ")", "{", "if", "(", "A", ".", "shape", ".", "length", "!==", "1", "||", "B", ".", "shape", ".", "length", "!==", "1", ")", "{", "throw", "new", "Error", "(", "'A or B is not 1D'", ")", ";", "}", "if", "(", "A", ".", "length", "<", "3", "||", "B", ".", "length", "<", "3", ")", "{", "throw", "new", "Error", "(", "'A or B is less than 3 in length'", ")", ";", "}", "var", "a1", "=", "A", ".", "getN", "(", "0", ")", ";", "var", "a2", "=", "A", ".", "getN", "(", "1", ")", ";", "var", "a3", "=", "A", ".", "getN", "(", "2", ")", ";", "var", "b1", "=", "B", ".", "getN", "(", "0", ")", ";", "var", "b2", "=", "B", ".", "getN", "(", "1", ")", ";", "var", "b3", "=", "B", ".", "getN", "(", "2", ")", ";", "return", "new", "ndarray_1", ".", "NDArray", "(", "[", "a2", "*", "b3", "-", "a3", "*", "b2", ",", "a3", "*", "b1", "-", "a1", "*", "b3", ",", "a1", "*", "b2", "-", "a2", "*", "b1", "]", ")", ";", "}" ]
Computes cross product of A and B Only defined for A and B to 1D vectors of length at least 3 Only first 3 elements of A and B are used
[ "Computes", "cross", "product", "of", "A", "and", "B", "Only", "defined", "for", "A", "and", "B", "to", "1D", "vectors", "of", "length", "at", "least", "3", "Only", "first", "3", "elements", "of", "A", "and", "B", "are", "used" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L195-L213
train
bluemathsoft/bm-common
lib/ops.js
length
function length(A) { if (A.shape.length !== 1) { throw new Error('A is not a 1D array'); } return Math.sqrt(dot(A, A)); }
javascript
function length(A) { if (A.shape.length !== 1) { throw new Error('A is not a 1D array'); } return Math.sqrt(dot(A, A)); }
[ "function", "length", "(", "A", ")", "{", "if", "(", "A", ".", "shape", ".", "length", "!==", "1", ")", "{", "throw", "new", "Error", "(", "'A is not a 1D array'", ")", ";", "}", "return", "Math", ".", "sqrt", "(", "dot", "(", "A", ",", "A", ")", ")", ";", "}" ]
Computes length or magnitude of A, where A is a 1D vector
[ "Computes", "length", "or", "magnitude", "of", "A", "where", "A", "is", "a", "1D", "vector" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L218-L223
train
bluemathsoft/bm-common
lib/ops.js
dir
function dir(A) { if (A.shape.length !== 1) { throw new Error('A is not a 1D array'); } return div(A, length(A)); }
javascript
function dir(A) { if (A.shape.length !== 1) { throw new Error('A is not a 1D array'); } return div(A, length(A)); }
[ "function", "dir", "(", "A", ")", "{", "if", "(", "A", ".", "shape", ".", "length", "!==", "1", ")", "{", "throw", "new", "Error", "(", "'A is not a 1D array'", ")", ";", "}", "return", "div", "(", "A", ",", "length", "(", "A", ")", ")", ";", "}" ]
Computes direction vector of A, where A is a 1D vector
[ "Computes", "direction", "vector", "of", "A", "where", "A", "is", "a", "1D", "vector" ]
0915b3aa3b9aab25925984b24ebdc98168ea6e07
https://github.com/bluemathsoft/bm-common/blob/0915b3aa3b9aab25925984b24ebdc98168ea6e07/lib/ops.js#L228-L233
train
enmasseio/babble
lib/block/IIf.js
IIf
function IIf (condition, trueBlock, falseBlock) { if (!(this instanceof IIf)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof condition === 'function') { this.condition = condition; } else if (condition instanceof RegExp) { this.condition = function (message, context) { return condition.test(message); } } else { this.condition = function (message, context) { return message == condition; } } if (trueBlock && !trueBlock.isBlock) { throw new TypeError('Parameter trueBlock must be a Block'); } if (falseBlock && !falseBlock.isBlock) { throw new TypeError('Parameter falseBlock must be a Block'); } this.trueBlock = trueBlock || null; this.falseBlock = falseBlock || null; }
javascript
function IIf (condition, trueBlock, falseBlock) { if (!(this instanceof IIf)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof condition === 'function') { this.condition = condition; } else if (condition instanceof RegExp) { this.condition = function (message, context) { return condition.test(message); } } else { this.condition = function (message, context) { return message == condition; } } if (trueBlock && !trueBlock.isBlock) { throw new TypeError('Parameter trueBlock must be a Block'); } if (falseBlock && !falseBlock.isBlock) { throw new TypeError('Parameter falseBlock must be a Block'); } this.trueBlock = trueBlock || null; this.falseBlock = falseBlock || null; }
[ "function", "IIf", "(", "condition", ",", "trueBlock", ",", "falseBlock", ")", "{", "if", "(", "!", "(", "this", "instanceof", "IIf", ")", ")", "{", "throw", "new", "SyntaxError", "(", "'Constructor must be called with the new operator'", ")", ";", "}", "if", "(", "typeof", "condition", "===", "'function'", ")", "{", "this", ".", "condition", "=", "condition", ";", "}", "else", "if", "(", "condition", "instanceof", "RegExp", ")", "{", "this", ".", "condition", "=", "function", "(", "message", ",", "context", ")", "{", "return", "condition", ".", "test", "(", "message", ")", ";", "}", "}", "else", "{", "this", ".", "condition", "=", "function", "(", "message", ",", "context", ")", "{", "return", "message", "==", "condition", ";", "}", "}", "if", "(", "trueBlock", "&&", "!", "trueBlock", ".", "isBlock", ")", "{", "throw", "new", "TypeError", "(", "'Parameter trueBlock must be a Block'", ")", ";", "}", "if", "(", "falseBlock", "&&", "!", "falseBlock", ".", "isBlock", ")", "{", "throw", "new", "TypeError", "(", "'Parameter falseBlock must be a Block'", ")", ";", "}", "this", ".", "trueBlock", "=", "trueBlock", "||", "null", ";", "this", ".", "falseBlock", "=", "falseBlock", "||", "null", ";", "}" ]
extend Block with function then IIf Create an iif block, which checks a condition and continues either with the trueBlock or the falseBlock. The input message is passed to the next block in the flow. Can be used as follows: - When `condition` evaluates true: - when `trueBlock` is provided, the flow continues with `trueBlock` - else, when there is a block connected to the IIf block, the flow continues with that block. - When `condition` evaluates false: - when `falseBlock` is provided, the flow continues with `falseBlock` Syntax: new IIf(condition, trueBlock) new IIf(condition, trueBlock [, falseBlock]) new IIf(condition).then(...) @param {Function | RegExp | *} condition A condition returning true or false In case of a function, the function is invoked as `condition(message, context)` and must return a boolean. In case of a RegExp, condition will be tested to return true. In other cases, non-strict equality is tested on the input. @param {Block} [trueBlock] @param {Block} [falseBlock] @constructor @extends {Block}
[ "extend", "Block", "with", "function", "then", "IIf", "Create", "an", "iif", "block", "which", "checks", "a", "condition", "and", "continues", "either", "with", "the", "trueBlock", "or", "the", "falseBlock", ".", "The", "input", "message", "is", "passed", "to", "the", "next", "block", "in", "the", "flow", "." ]
6b7e84d7fb0df2d1129f0646b37a9d89d3da2539
https://github.com/enmasseio/babble/blob/6b7e84d7fb0df2d1129f0646b37a9d89d3da2539/lib/block/IIf.js#L43-L72
train
co3moz/gluon
gluon.js
function () { return Token.destroy({ where: { code: req.get('token') } }).then(function (data) { return data; }).catch(function (err) { res.database(err) }); }
javascript
function () { return Token.destroy({ where: { code: req.get('token') } }).then(function (data) { return data; }).catch(function (err) { res.database(err) }); }
[ "function", "(", ")", "{", "return", "Token", ".", "destroy", "(", "{", "where", ":", "{", "code", ":", "req", ".", "get", "(", "'token'", ")", "}", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "data", ";", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "res", ".", "database", "(", "err", ")", "}", ")", ";", "}" ]
Removes token from owner @returns {Promise.<TResult>}
[ "Removes", "token", "from", "owner" ]
b6ca29330ce518b7f909755cad70a42f6add3fed
https://github.com/co3moz/gluon/blob/b6ca29330ce518b7f909755cad70a42f6add3fed/gluon.js#L174-L184
train
co3moz/gluon
gluon.js
function (roles) { roles.map(function (role) { return Role.findOrCreate({ where: { code: role, ownerId: req[options.auth.model].id }, defaults: { code: role, ownerId: req[options.auth.model].id } }).spread(function (role, created) { return role }).catch(function (err) { res.database(err) }); }); return Promise.all(roles); }
javascript
function (roles) { roles.map(function (role) { return Role.findOrCreate({ where: { code: role, ownerId: req[options.auth.model].id }, defaults: { code: role, ownerId: req[options.auth.model].id } }).spread(function (role, created) { return role }).catch(function (err) { res.database(err) }); }); return Promise.all(roles); }
[ "function", "(", "roles", ")", "{", "roles", ".", "map", "(", "function", "(", "role", ")", "{", "return", "Role", ".", "findOrCreate", "(", "{", "where", ":", "{", "code", ":", "role", ",", "ownerId", ":", "req", "[", "options", ".", "auth", ".", "model", "]", ".", "id", "}", ",", "defaults", ":", "{", "code", ":", "role", ",", "ownerId", ":", "req", "[", "options", ".", "auth", ".", "model", "]", ".", "id", "}", "}", ")", ".", "spread", "(", "function", "(", "role", ",", "created", ")", "{", "return", "role", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "res", ".", "database", "(", "err", ")", "}", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "roles", ")", ";", "}" ]
Adds a roles to owner @param {Array<String>} roles Which roles @returns {Promise.<Instance>}
[ "Adds", "a", "roles", "to", "owner" ]
b6ca29330ce518b7f909755cad70a42f6add3fed
https://github.com/co3moz/gluon/blob/b6ca29330ce518b7f909755cad70a42f6add3fed/gluon.js#L218-L238
train
co3moz/gluon
gluon.js
function (role) { return Role.destroy({ where: { code: role, ownerId: req[options.auth.model].id }, limit: 1 }).catch(function (err) { res.database(err) }); }
javascript
function (role) { return Role.destroy({ where: { code: role, ownerId: req[options.auth.model].id }, limit: 1 }).catch(function (err) { res.database(err) }); }
[ "function", "(", "role", ")", "{", "return", "Role", ".", "destroy", "(", "{", "where", ":", "{", "code", ":", "role", ",", "ownerId", ":", "req", "[", "options", ".", "auth", ".", "model", "]", ".", "id", "}", ",", "limit", ":", "1", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "res", ".", "database", "(", "err", ")", "}", ")", ";", "}" ]
Removes a role from owner @param {String} role Which role @returns {Promise.<Number>}
[ "Removes", "a", "role", "from", "owner" ]
b6ca29330ce518b7f909755cad70a42f6add3fed
https://github.com/co3moz/gluon/blob/b6ca29330ce518b7f909755cad70a42f6add3fed/gluon.js#L247-L257
train
co3moz/gluon
gluon.js
function (role) { return Role.count({ where: { code: role, ownerId: req[options.auth.model].id }, limit: 1 }).then(function (data) { return data == 1 }).catch(function (err) { res.database(err) }); }
javascript
function (role) { return Role.count({ where: { code: role, ownerId: req[options.auth.model].id }, limit: 1 }).then(function (data) { return data == 1 }).catch(function (err) { res.database(err) }); }
[ "function", "(", "role", ")", "{", "return", "Role", ".", "count", "(", "{", "where", ":", "{", "code", ":", "role", ",", "ownerId", ":", "req", "[", "options", ".", "auth", ".", "model", "]", ".", "id", "}", ",", "limit", ":", "1", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "data", "==", "1", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "res", ".", "database", "(", "err", ")", "}", ")", ";", "}" ]
Checks for role @param {String} role Which role @returns {Promise.<Boolean>}
[ "Checks", "for", "role" ]
b6ca29330ce518b7f909755cad70a42f6add3fed
https://github.com/co3moz/gluon/blob/b6ca29330ce518b7f909755cad70a42f6add3fed/gluon.js#L285-L297
train
co3moz/gluon
gluon.js
function (roles) { return Role.count({ where: { code: { $in: roles }, ownerId: req[options.auth.model].id } }).then(function (data) { return data == roles.length }).catch(function (err) { res.database(err) }); }
javascript
function (roles) { return Role.count({ where: { code: { $in: roles }, ownerId: req[options.auth.model].id } }).then(function (data) { return data == roles.length }).catch(function (err) { res.database(err) }); }
[ "function", "(", "roles", ")", "{", "return", "Role", ".", "count", "(", "{", "where", ":", "{", "code", ":", "{", "$in", ":", "roles", "}", ",", "ownerId", ":", "req", "[", "options", ".", "auth", ".", "model", "]", ".", "id", "}", "}", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "data", "==", "roles", ".", "length", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "res", ".", "database", "(", "err", ")", "}", ")", ";", "}" ]
Checks for roles @param {Array<String>} roles Which roles @returns {Promise.<Boolean>}
[ "Checks", "for", "roles" ]
b6ca29330ce518b7f909755cad70a42f6add3fed
https://github.com/co3moz/gluon/blob/b6ca29330ce518b7f909755cad70a42f6add3fed/gluon.js#L305-L318
train
reklatsmasters/btparse
lib/avltree.js
create
function create(key, value) { if (!Buffer.isBuffer(key)) { throw new TypeError('expected buffer') } return { key, value, left: null, right: null, height: 0 } }
javascript
function create(key, value) { if (!Buffer.isBuffer(key)) { throw new TypeError('expected buffer') } return { key, value, left: null, right: null, height: 0 } }
[ "function", "create", "(", "key", ",", "value", ")", "{", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "key", ")", ")", "{", "throw", "new", "TypeError", "(", "'expected buffer'", ")", "}", "return", "{", "key", ",", "value", ",", "left", ":", "null", ",", "right", ":", "null", ",", "height", ":", "0", "}", "}" ]
create new AVL tree node @returns {{key: null, value: null, height: number, left: null, right: null}}
[ "create", "new", "AVL", "tree", "node" ]
caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9
https://github.com/reklatsmasters/btparse/blob/caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9/lib/avltree.js#L15-L27
train
reklatsmasters/btparse
lib/avltree.js
compare
function compare(tree_key, key) { let buf if (Buffer.isBuffer(key)) { buf = key } else if (typeof key == 'string') { buf = Buffer.from(key) } else { throw new TypeError('Argument `key` must be a Buffer or a string') } return Buffer.compare(tree_key, buf) }
javascript
function compare(tree_key, key) { let buf if (Buffer.isBuffer(key)) { buf = key } else if (typeof key == 'string') { buf = Buffer.from(key) } else { throw new TypeError('Argument `key` must be a Buffer or a string') } return Buffer.compare(tree_key, buf) }
[ "function", "compare", "(", "tree_key", ",", "key", ")", "{", "let", "buf", "if", "(", "Buffer", ".", "isBuffer", "(", "key", ")", ")", "{", "buf", "=", "key", "}", "else", "if", "(", "typeof", "key", "==", "'string'", ")", "{", "buf", "=", "Buffer", ".", "from", "(", "key", ")", "}", "else", "{", "throw", "new", "TypeError", "(", "'Argument `key` must be a Buffer or a string'", ")", "}", "return", "Buffer", ".", "compare", "(", "tree_key", ",", "buf", ")", "}" ]
compare 2 keys @param tree_key {Buffer} @param key {string|Buffer} @returns {number}
[ "compare", "2", "keys" ]
caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9
https://github.com/reklatsmasters/btparse/blob/caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9/lib/avltree.js#L35-L47
train
reklatsmasters/btparse
lib/avltree.js
lookup
function lookup(tree, key) { if (!tree) { return null } switch (compare(tree.key, key)) { case 0: return tree case 1: return lookup(tree.right, key) case -1: return lookup(tree.left, key) default: break } }
javascript
function lookup(tree, key) { if (!tree) { return null } switch (compare(tree.key, key)) { case 0: return tree case 1: return lookup(tree.right, key) case -1: return lookup(tree.left, key) default: break } }
[ "function", "lookup", "(", "tree", ",", "key", ")", "{", "if", "(", "!", "tree", ")", "{", "return", "null", "}", "switch", "(", "compare", "(", "tree", ".", "key", ",", "key", ")", ")", "{", "case", "0", ":", "return", "tree", "case", "1", ":", "return", "lookup", "(", "tree", ".", "right", ",", "key", ")", "case", "-", "1", ":", "return", "lookup", "(", "tree", ".", "left", ",", "key", ")", "default", ":", "break", "}", "}" ]
search `key` in AVL tree @param tree {Object} @param key {Buffer|String} @returns {Buffer|Object|null}
[ "search", "key", "in", "AVL", "tree" ]
caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9
https://github.com/reklatsmasters/btparse/blob/caacdfd3cd24fb2e68d67f0dab64dd5ba8947ad9/lib/avltree.js#L55-L70
train
logikum/md-site-engine
source/models/metadata.js
function( definitions, path ) { //region Search engine properties /** * Gets the title of the document. * @type {string} * @readonly */ this.title = ''; /** * Gets the keywords of the document. * @type {string} * @readonly */ this.keywords = ''; /** * Gets the description of the document. * @type {string} * @readonly */ this.description = ''; //endregion //region Menu properties /** * Gets the text of the menu item. * @type {string} * @readonly */ this.text = ''; /** * Gets the order of the menu item. * @type {string} * @readonly */ this.order = 0; /** * Indicates whether the menu item is displayed. * @type {Boolean} * @readonly */ this.hidden = false; /** * Indicates whether the menu item is a leaf with hidden children, * i.e. a truncated menu node. * @type {Boolean} * @readonly */ this.umbel = false; //endregion //region Page properties /** * Gets the identifier of the content, it defaults to the path. * @type {string} * @readonly */ this.id = ''; /** * Gets the path of the content. * @type {string} * @readonly */ this.path = path; /** * Gets the name of a custom document for the content. * @type {string} * @readonly */ this.document = ''; /** * Gets the name of a custom layout for the content. * @type {string} * @readonly */ this.layout = ''; /** * Gets the token collection for the segments found on the content. * @type {object} * @readonly */ this.segments = { }; /** * Indicates whether the content is enabled for search. * @type {Boolean} * @readonly */ this.searchable = true; //endregion // Set the defined properties of the content. Object.assign( this, getMainProperties( definitions ) ); Object.assign( this.segments, getSegmentProperties( definitions ) ); // Set default identity. if (!this.id) this.id = path; // Immutable object. freeze( this ); }
javascript
function( definitions, path ) { //region Search engine properties /** * Gets the title of the document. * @type {string} * @readonly */ this.title = ''; /** * Gets the keywords of the document. * @type {string} * @readonly */ this.keywords = ''; /** * Gets the description of the document. * @type {string} * @readonly */ this.description = ''; //endregion //region Menu properties /** * Gets the text of the menu item. * @type {string} * @readonly */ this.text = ''; /** * Gets the order of the menu item. * @type {string} * @readonly */ this.order = 0; /** * Indicates whether the menu item is displayed. * @type {Boolean} * @readonly */ this.hidden = false; /** * Indicates whether the menu item is a leaf with hidden children, * i.e. a truncated menu node. * @type {Boolean} * @readonly */ this.umbel = false; //endregion //region Page properties /** * Gets the identifier of the content, it defaults to the path. * @type {string} * @readonly */ this.id = ''; /** * Gets the path of the content. * @type {string} * @readonly */ this.path = path; /** * Gets the name of a custom document for the content. * @type {string} * @readonly */ this.document = ''; /** * Gets the name of a custom layout for the content. * @type {string} * @readonly */ this.layout = ''; /** * Gets the token collection for the segments found on the content. * @type {object} * @readonly */ this.segments = { }; /** * Indicates whether the content is enabled for search. * @type {Boolean} * @readonly */ this.searchable = true; //endregion // Set the defined properties of the content. Object.assign( this, getMainProperties( definitions ) ); Object.assign( this.segments, getSegmentProperties( definitions ) ); // Set default identity. if (!this.id) this.id = path; // Immutable object. freeze( this ); }
[ "function", "(", "definitions", ",", "path", ")", "{", "this", ".", "title", "=", "''", ";", "this", ".", "keywords", "=", "''", ";", "this", ".", "description", "=", "''", ";", "this", ".", "text", "=", "''", ";", "this", ".", "order", "=", "0", ";", "this", ".", "hidden", "=", "false", ";", "this", ".", "umbel", "=", "false", ";", "this", ".", "id", "=", "''", ";", "this", ".", "path", "=", "path", ";", "this", ".", "document", "=", "''", ";", "this", ".", "layout", "=", "''", ";", "this", ".", "segments", "=", "{", "}", ";", "this", ".", "searchable", "=", "true", ";", "Object", ".", "assign", "(", "this", ",", "getMainProperties", "(", "definitions", ")", ")", ";", "Object", ".", "assign", "(", "this", ".", "segments", ",", "getSegmentProperties", "(", "definitions", ")", ")", ";", "if", "(", "!", "this", ".", "id", ")", "this", ".", "id", "=", "path", ";", "freeze", "(", "this", ")", ";", "}" ]
Represents the metadata of a content. @param {object} definitions - A collection of properties. @param {string} path - The path of the current content. @constructor
[ "Represents", "the", "metadata", "of", "a", "content", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/models/metadata.js#L35-L151
train
wangtao0101/parse-import-es6
src/parseImport.js
findLeadingComments
function findLeadingComments(comments, index, beginIndex, first) { const leadComments = []; if (first && ignoreComment.test(comments[index].raw)) { return leadComments; } let backIndex = index - 1; while (backIndex >= beginIndex && (comments[backIndex].loc.end.line + 1 === comments[backIndex + 1].loc.start.line || comments[backIndex].loc.end.line === comments[backIndex + 1].loc.start.line)) { if (first && ignoreComment.test(comments[backIndex].raw)) { break; } backIndex -= 1; } for (let ind = backIndex + 1; ind <= index; ind += 1) { leadComments.push(comments[ind]); } return leadComments; }
javascript
function findLeadingComments(comments, index, beginIndex, first) { const leadComments = []; if (first && ignoreComment.test(comments[index].raw)) { return leadComments; } let backIndex = index - 1; while (backIndex >= beginIndex && (comments[backIndex].loc.end.line + 1 === comments[backIndex + 1].loc.start.line || comments[backIndex].loc.end.line === comments[backIndex + 1].loc.start.line)) { if (first && ignoreComment.test(comments[backIndex].raw)) { break; } backIndex -= 1; } for (let ind = backIndex + 1; ind <= index; ind += 1) { leadComments.push(comments[ind]); } return leadComments; }
[ "function", "findLeadingComments", "(", "comments", ",", "index", ",", "beginIndex", ",", "first", ")", "{", "const", "leadComments", "=", "[", "]", ";", "if", "(", "first", "&&", "ignoreComment", ".", "test", "(", "comments", "[", "index", "]", ".", "raw", ")", ")", "{", "return", "leadComments", ";", "}", "let", "backIndex", "=", "index", "-", "1", ";", "while", "(", "backIndex", ">=", "beginIndex", "&&", "(", "comments", "[", "backIndex", "]", ".", "loc", ".", "end", ".", "line", "+", "1", "===", "comments", "[", "backIndex", "+", "1", "]", ".", "loc", ".", "start", ".", "line", "||", "comments", "[", "backIndex", "]", ".", "loc", ".", "end", ".", "line", "===", "comments", "[", "backIndex", "+", "1", "]", ".", "loc", ".", "start", ".", "line", ")", ")", "{", "if", "(", "first", "&&", "ignoreComment", ".", "test", "(", "comments", "[", "backIndex", "]", ".", "raw", ")", ")", "{", "break", ";", "}", "backIndex", "-=", "1", ";", "}", "for", "(", "let", "ind", "=", "backIndex", "+", "1", ";", "ind", "<=", "index", ";", "ind", "+=", "1", ")", "{", "leadComments", ".", "push", "(", "comments", "[", "ind", "]", ")", ";", "}", "return", "leadComments", ";", "}" ]
return leading comment list @param {*list<comment>} comments @param {*} the last match leading comment of one import @param {*} beginIndex the potential begin of the comment index of the import @param {*} first whether first import
[ "return", "leading", "comment", "list" ]
c0ada33342b07e58cba83c27b6f1d92e522f35ac
https://github.com/wangtao0101/parse-import-es6/blob/c0ada33342b07e58cba83c27b6f1d92e522f35ac/src/parseImport.js#L78-L96
train
ssmolkin1/my-little-schemer
src/prim/ops.js
loadTo
function loadTo(S) { /** * Takes a non-empty list as its argument and return the first member of the argument. * @param {list} l * @returns {*} * @example * // returns 1 * car([1, 2]); */ S.car = (l) => { if (S.isAtom(l) || S.isNull(l)) { throw new TypeError('The Law of Car: You can only take the car of a non-empty list.'); } let result = l[0]; // Clone there result if it is a list or an object to keep the function pure if (S.isList(result)) { result = result.slice(); } if (S.isObject(result)) { result = Object.assign({}, result); } return result; }; /** * Takes a non-empty list as its argument and returns a new list contaiting the same members * as the argument, except for the car. * @param {list} l * @return {list} * @example * // returns [2] * cdr([1, 2]); */ S.cdr = (l) => { if (S.isAtom(l) || S.isNull(l)) { throw new TypeError('The Law of Cdr: You can only take the cdr of a non-empty list.'); } return l.slice(1); }; /** * Takes two arguments, the second of which must be a list, and returns a new list comtaining * the first argument and the elements of the second argument. * @param {*} exp * @param {list} l * @returns {list} * @example * // returns ['cat', 'dog'] * cons('cat', ['dog']); */ S.cons = (exp, l) => { if (S.isAtom(l)) { throw new TypeError('The Law of Cons: The second argument must be a list.'); } const n = l.slice(0); n.unshift(exp); return n; }; /** * Takes any expression as its argument and returns the expression unevaluated. Should only * be used inside S-Expressions and jS-Expressions. * @param {*} exp * @returns {*} * @example * // returns ['cat', 'dog'] * evaluate(`(cons cat (dog))`); * * // returns ['cons', 'cat', ['dog']] * evaluate(`(quote (cons cat (dog)))`); */ S.quote = exp => exp; /** * Adds 1 to a number. * @param {number} n * @returns {number} * @example * // returns 2 * add1(1); */ S.add1 = (n) => { if (!S.isNumber(n)) { throw new TypeError('Arithmetic operations can only be done on numbers.'); } return n + 1; }; /** * Subtracts 1 from a number. * @param {number} n * @returns {number} * @example * // returns 1 * sub1(2); */ S.sub1 = (n) => { if (!S.isNumber(n)) { throw new TypeError('Arithmetic operations can only be done on numbers.'); } return n - 1; }; /** * The applicative order Y-combinator. * @param {function} le */ S.Y = le => (f => f(f))(f => le(x => (f(f))(x))); }
javascript
function loadTo(S) { /** * Takes a non-empty list as its argument and return the first member of the argument. * @param {list} l * @returns {*} * @example * // returns 1 * car([1, 2]); */ S.car = (l) => { if (S.isAtom(l) || S.isNull(l)) { throw new TypeError('The Law of Car: You can only take the car of a non-empty list.'); } let result = l[0]; // Clone there result if it is a list or an object to keep the function pure if (S.isList(result)) { result = result.slice(); } if (S.isObject(result)) { result = Object.assign({}, result); } return result; }; /** * Takes a non-empty list as its argument and returns a new list contaiting the same members * as the argument, except for the car. * @param {list} l * @return {list} * @example * // returns [2] * cdr([1, 2]); */ S.cdr = (l) => { if (S.isAtom(l) || S.isNull(l)) { throw new TypeError('The Law of Cdr: You can only take the cdr of a non-empty list.'); } return l.slice(1); }; /** * Takes two arguments, the second of which must be a list, and returns a new list comtaining * the first argument and the elements of the second argument. * @param {*} exp * @param {list} l * @returns {list} * @example * // returns ['cat', 'dog'] * cons('cat', ['dog']); */ S.cons = (exp, l) => { if (S.isAtom(l)) { throw new TypeError('The Law of Cons: The second argument must be a list.'); } const n = l.slice(0); n.unshift(exp); return n; }; /** * Takes any expression as its argument and returns the expression unevaluated. Should only * be used inside S-Expressions and jS-Expressions. * @param {*} exp * @returns {*} * @example * // returns ['cat', 'dog'] * evaluate(`(cons cat (dog))`); * * // returns ['cons', 'cat', ['dog']] * evaluate(`(quote (cons cat (dog)))`); */ S.quote = exp => exp; /** * Adds 1 to a number. * @param {number} n * @returns {number} * @example * // returns 2 * add1(1); */ S.add1 = (n) => { if (!S.isNumber(n)) { throw new TypeError('Arithmetic operations can only be done on numbers.'); } return n + 1; }; /** * Subtracts 1 from a number. * @param {number} n * @returns {number} * @example * // returns 1 * sub1(2); */ S.sub1 = (n) => { if (!S.isNumber(n)) { throw new TypeError('Arithmetic operations can only be done on numbers.'); } return n - 1; }; /** * The applicative order Y-combinator. * @param {function} le */ S.Y = le => (f => f(f))(f => le(x => (f(f))(x))); }
[ "function", "loadTo", "(", "S", ")", "{", "S", ".", "car", "=", "(", "l", ")", "=>", "{", "if", "(", "S", ".", "isAtom", "(", "l", ")", "||", "S", ".", "isNull", "(", "l", ")", ")", "{", "throw", "new", "TypeError", "(", "'The Law of Car: You can only take the car of a non-empty list.'", ")", ";", "}", "let", "result", "=", "l", "[", "0", "]", ";", "if", "(", "S", ".", "isList", "(", "result", ")", ")", "{", "result", "=", "result", ".", "slice", "(", ")", ";", "}", "if", "(", "S", ".", "isObject", "(", "result", ")", ")", "{", "result", "=", "Object", ".", "assign", "(", "{", "}", ",", "result", ")", ";", "}", "return", "result", ";", "}", ";", "S", ".", "cdr", "=", "(", "l", ")", "=>", "{", "if", "(", "S", ".", "isAtom", "(", "l", ")", "||", "S", ".", "isNull", "(", "l", ")", ")", "{", "throw", "new", "TypeError", "(", "'The Law of Cdr: You can only take the cdr of a non-empty list.'", ")", ";", "}", "return", "l", ".", "slice", "(", "1", ")", ";", "}", ";", "S", ".", "cons", "=", "(", "exp", ",", "l", ")", "=>", "{", "if", "(", "S", ".", "isAtom", "(", "l", ")", ")", "{", "throw", "new", "TypeError", "(", "'The Law of Cons: The second argument must be a list.'", ")", ";", "}", "const", "n", "=", "l", ".", "slice", "(", "0", ")", ";", "n", ".", "unshift", "(", "exp", ")", ";", "return", "n", ";", "}", ";", "S", ".", "quote", "=", "exp", "=>", "exp", ";", "S", ".", "add1", "=", "(", "n", ")", "=>", "{", "if", "(", "!", "S", ".", "isNumber", "(", "n", ")", ")", "{", "throw", "new", "TypeError", "(", "'Arithmetic operations can only be done on numbers.'", ")", ";", "}", "return", "n", "+", "1", ";", "}", ";", "S", ".", "sub1", "=", "(", "n", ")", "=>", "{", "if", "(", "!", "S", ".", "isNumber", "(", "n", ")", ")", "{", "throw", "new", "TypeError", "(", "'Arithmetic operations can only be done on numbers.'", ")", ";", "}", "return", "n", "-", "1", ";", "}", ";", "S", ".", "Y", "=", "le", "=>", "(", "f", "=>", "f", "(", "f", ")", ")", "(", "f", "=>", "le", "(", "x", "=>", "(", "f", "(", "f", ")", ")", "(", "x", ")", ")", ")", ";", "}" ]
Inserts methods into namespace @param {object} S The namepsace into which the methods are inserted. @returns {void}
[ "Inserts", "methods", "into", "namespace" ]
618b9e94ffd0cc7f45a458bdf9eaa14aa90956b3
https://github.com/ssmolkin1/my-little-schemer/blob/618b9e94ffd0cc7f45a458bdf9eaa14aa90956b3/src/prim/ops.js#L6-L124
train