id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
39,000 |
logikum/md-site-engine
|
source/readers/read-references.js
|
readReferences
|
function readReferences( componentPath, referenceFile, filingCabinet
) {
logger.showInfo( '*** Reading references...' );
// Initialize the store.
getReferences( componentPath, 0, '', referenceFile, filingCabinet.references
);
}
|
javascript
|
function readReferences( componentPath, referenceFile, filingCabinet
) {
logger.showInfo( '*** Reading references...' );
// Initialize the store.
getReferences( componentPath, 0, '', referenceFile, filingCabinet.references
);
}
|
[
"function",
"readReferences",
"(",
"componentPath",
",",
"referenceFile",
",",
"filingCabinet",
")",
"{",
"logger",
".",
"showInfo",
"(",
"'*** Reading references...'",
")",
";",
"// Initialize the store.",
"getReferences",
"(",
"componentPath",
",",
"0",
",",
"''",
",",
"referenceFile",
",",
"filingCabinet",
".",
"references",
")",
";",
"}"
] |
Read all references.
@param {string} componentPath - The path of the components directory.
@param {string} referenceFile - The name of the reference files.
@param {FilingCabinet} filingCabinet - The file manager object.
|
[
"Read",
"all",
"references",
"."
] |
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
|
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/read-references.js#L15-L22
|
39,001 |
logikum/md-site-engine
|
source/readers/read-references.js
|
getReferences
|
function getReferences( componentDir, level, levelPath, referenceFile, referenceDrawer ) {
// Read directory items.
var componentPath = path.join( process.cwd(), componentDir );
var items = fs.readdirSync( componentPath );
items.forEach( function ( item ) {
var itemPath = path.join( componentDir, item );
var prefix = levelPath === '' ? '' : levelPath + '/';
// Get item info.
var stats = fs.statSync( path.join( process.cwd(), itemPath ) );
if (stats.isDirectory()) {
// Get language specific references.
if (level === 0)
getReferences( itemPath, level + 1, prefix + item, referenceFile, referenceDrawer );
}
else if (stats.isFile()) {
var ext = path.extname( item );
if (ext === '.txt' && path.basename( item ) === referenceFile) {
// Read reference file.
var componentPath = prefix + path.basename( item, ext );
referenceDrawer.add( componentPath, getReference( itemPath ) );
logger.fileProcessed( 'Reference', itemPath );
}
}
} )
}
|
javascript
|
function getReferences( componentDir, level, levelPath, referenceFile, referenceDrawer ) {
// Read directory items.
var componentPath = path.join( process.cwd(), componentDir );
var items = fs.readdirSync( componentPath );
items.forEach( function ( item ) {
var itemPath = path.join( componentDir, item );
var prefix = levelPath === '' ? '' : levelPath + '/';
// Get item info.
var stats = fs.statSync( path.join( process.cwd(), itemPath ) );
if (stats.isDirectory()) {
// Get language specific references.
if (level === 0)
getReferences( itemPath, level + 1, prefix + item, referenceFile, referenceDrawer );
}
else if (stats.isFile()) {
var ext = path.extname( item );
if (ext === '.txt' && path.basename( item ) === referenceFile) {
// Read reference file.
var componentPath = prefix + path.basename( item, ext );
referenceDrawer.add( componentPath, getReference( itemPath ) );
logger.fileProcessed( 'Reference', itemPath );
}
}
} )
}
|
[
"function",
"getReferences",
"(",
"componentDir",
",",
"level",
",",
"levelPath",
",",
"referenceFile",
",",
"referenceDrawer",
")",
"{",
"// Read directory items.",
"var",
"componentPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"componentDir",
")",
";",
"var",
"items",
"=",
"fs",
".",
"readdirSync",
"(",
"componentPath",
")",
";",
"items",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"var",
"itemPath",
"=",
"path",
".",
"join",
"(",
"componentDir",
",",
"item",
")",
";",
"var",
"prefix",
"=",
"levelPath",
"===",
"''",
"?",
"''",
":",
"levelPath",
"+",
"'/'",
";",
"// Get item info.",
"var",
"stats",
"=",
"fs",
".",
"statSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"itemPath",
")",
")",
";",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"// Get language specific references.",
"if",
"(",
"level",
"===",
"0",
")",
"getReferences",
"(",
"itemPath",
",",
"level",
"+",
"1",
",",
"prefix",
"+",
"item",
",",
"referenceFile",
",",
"referenceDrawer",
")",
";",
"}",
"else",
"if",
"(",
"stats",
".",
"isFile",
"(",
")",
")",
"{",
"var",
"ext",
"=",
"path",
".",
"extname",
"(",
"item",
")",
";",
"if",
"(",
"ext",
"===",
"'.txt'",
"&&",
"path",
".",
"basename",
"(",
"item",
")",
"===",
"referenceFile",
")",
"{",
"// Read reference file.",
"var",
"componentPath",
"=",
"prefix",
"+",
"path",
".",
"basename",
"(",
"item",
",",
"ext",
")",
";",
"referenceDrawer",
".",
"add",
"(",
"componentPath",
",",
"getReference",
"(",
"itemPath",
")",
")",
";",
"logger",
".",
"fileProcessed",
"(",
"'Reference'",
",",
"itemPath",
")",
";",
"}",
"}",
"}",
")",
"}"
] |
Reads all references in a component sub-directory.
@param {string} componentDir - The path of the component sub-directory.
@param {number} level - The level depth compared to the components directory.
@param {string} levelPath - The base URL of the component sub-directory.
@param {string} referenceFile - The name of the reference files.
@param {ReferenceDrawer} referenceDrawer - The reference storage.
|
[
"Reads",
"all",
"references",
"in",
"a",
"component",
"sub",
"-",
"directory",
"."
] |
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
|
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/read-references.js#L32-L63
|
39,002 |
jsCow/jscow
|
src/__backups__/components/jscow-buttongroup.js
|
function() {
this.addController(jsCow.res.controller.buttongroup);
this.addModel(jsCow.res.model.buttongroup);
this.addView(jsCow.res.view.buttongroup);
return this;
}
|
javascript
|
function() {
this.addController(jsCow.res.controller.buttongroup);
this.addModel(jsCow.res.model.buttongroup);
this.addView(jsCow.res.view.buttongroup);
return this;
}
|
[
"function",
"(",
")",
"{",
"this",
".",
"addController",
"(",
"jsCow",
".",
"res",
".",
"controller",
".",
"buttongroup",
")",
";",
"this",
".",
"addModel",
"(",
"jsCow",
".",
"res",
".",
"model",
".",
"buttongroup",
")",
";",
"this",
".",
"addView",
"(",
"jsCow",
".",
"res",
".",
"view",
".",
"buttongroup",
")",
";",
"return",
"this",
";",
"}"
] |
The init method will be called by initializing the component.
The model, view and controller should be set within this method.
this.addController(jsCow.res.controller.buttongroup);
this.addModel(jsCow.res.model.buttongroup);
this.addView(jsCow.res.view.buttongroup);
@method init
@public
@return {Object} Instance of the component itself.
|
[
"The",
"init",
"method",
"will",
"be",
"called",
"by",
"initializing",
"the",
"component",
".",
"The",
"model",
"view",
"and",
"controller",
"should",
"be",
"set",
"within",
"this",
"method",
"."
] |
9fc242a470c34260b123b8c3935c929f1613182b
|
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/src/__backups__/components/jscow-buttongroup.js#L27-L34
|
|
39,003 |
nexdrew/all-stars
|
lib/fetchAuthors.js
|
fetchAuthors
|
function fetchAuthors (forPackages, opts) {
opts = normalizeOpts(opts)
// start with npmUser and email from registry
return fetchRegistry(forPackages, {}, opts)
.then(persons => {
// reduce duplicates and add pre-known aliases
return reduceDuplicates(persons, opts)
})
.then(persons => {
// add name, githubUser, and twitter from npm profile
return fetchProfiles(persons, opts)
})
.then(persons => {
// finish with name and email from github
return fetchGithub(persons, opts)
})
}
|
javascript
|
function fetchAuthors (forPackages, opts) {
opts = normalizeOpts(opts)
// start with npmUser and email from registry
return fetchRegistry(forPackages, {}, opts)
.then(persons => {
// reduce duplicates and add pre-known aliases
return reduceDuplicates(persons, opts)
})
.then(persons => {
// add name, githubUser, and twitter from npm profile
return fetchProfiles(persons, opts)
})
.then(persons => {
// finish with name and email from github
return fetchGithub(persons, opts)
})
}
|
[
"function",
"fetchAuthors",
"(",
"forPackages",
",",
"opts",
")",
"{",
"opts",
"=",
"normalizeOpts",
"(",
"opts",
")",
"// start with npmUser and email from registry",
"return",
"fetchRegistry",
"(",
"forPackages",
",",
"{",
"}",
",",
"opts",
")",
".",
"then",
"(",
"persons",
"=>",
"{",
"// reduce duplicates and add pre-known aliases",
"return",
"reduceDuplicates",
"(",
"persons",
",",
"opts",
")",
"}",
")",
".",
"then",
"(",
"persons",
"=>",
"{",
"// add name, githubUser, and twitter from npm profile",
"return",
"fetchProfiles",
"(",
"persons",
",",
"opts",
")",
"}",
")",
".",
"then",
"(",
"persons",
"=>",
"{",
"// finish with name and email from github",
"return",
"fetchGithub",
"(",
"persons",
",",
"opts",
")",
"}",
")",
"}"
] |
returns a Promise that resolves to fetched authors
|
[
"returns",
"a",
"Promise",
"that",
"resolves",
"to",
"fetched",
"authors"
] |
039c10840f95f6a099522aa494aa0734b3c9a5ba
|
https://github.com/nexdrew/all-stars/blob/039c10840f95f6a099522aa494aa0734b3c9a5ba/lib/fetchAuthors.js#L22-L38
|
39,004 |
tauren/tmpl-precompile
|
lib/colors.js
|
function (color, func) {
exports[color] = function(str) {
return func.apply(str);
};
String.prototype.__defineGetter__(color, func);
}
|
javascript
|
function (color, func) {
exports[color] = function(str) {
return func.apply(str);
};
String.prototype.__defineGetter__(color, func);
}
|
[
"function",
"(",
"color",
",",
"func",
")",
"{",
"exports",
"[",
"color",
"]",
"=",
"function",
"(",
"str",
")",
"{",
"return",
"func",
".",
"apply",
"(",
"str",
")",
";",
"}",
";",
"String",
".",
"prototype",
".",
"__defineGetter__",
"(",
"color",
",",
"func",
")",
";",
"}"
] |
prototypes the string object to have additional method calls that add terminal colors
|
[
"prototypes",
"the",
"string",
"object",
"to",
"have",
"additional",
"method",
"calls",
"that",
"add",
"terminal",
"colors"
] |
1df2f7b446446a1e6784b5a754f39eeb7055550e
|
https://github.com/tauren/tmpl-precompile/blob/1df2f7b446446a1e6784b5a754f39eeb7055550e/lib/colors.js#L30-L35
|
|
39,005 |
pex-gl/pex-color
|
index.js
|
create
|
function create(r, g, b, a) {
return [r || 0, g || 0, b || 0, (a === undefined) ? 1 : a];
}
|
javascript
|
function create(r, g, b, a) {
return [r || 0, g || 0, b || 0, (a === undefined) ? 1 : a];
}
|
[
"function",
"create",
"(",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
"{",
"return",
"[",
"r",
"||",
"0",
",",
"g",
"||",
"0",
",",
"b",
"||",
"0",
",",
"(",
"a",
"===",
"undefined",
")",
"?",
"1",
":",
"a",
"]",
";",
"}"
] |
RGBA color constructor function
@param {Number} [r=0] - red component (0..1)
@param {Number} [g=0] - green component (0..1)
@param {Number} [b=0] - blue component (0..1)
@param {Number} [a=1] - alpha component (0..1)
@return {Array} - RGBA color array [r,g,b,a] (0..1)
|
[
"RGBA",
"color",
"constructor",
"function"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L16-L18
|
39,006 |
pex-gl/pex-color
|
index.js
|
setRGB
|
function setRGB(color, r, g, b, a) {
color[0] = r;
color[1] = g;
color[2] = b;
color[3] = (a !== undefined) ? a : 1;
return color;
}
|
javascript
|
function setRGB(color, r, g, b, a) {
color[0] = r;
color[1] = g;
color[2] = b;
color[3] = (a !== undefined) ? a : 1;
return color;
}
|
[
"function",
"setRGB",
"(",
"color",
",",
"r",
",",
"g",
",",
"b",
",",
"a",
")",
"{",
"color",
"[",
"0",
"]",
"=",
"r",
";",
"color",
"[",
"1",
"]",
"=",
"g",
";",
"color",
"[",
"2",
"]",
"=",
"b",
";",
"color",
"[",
"3",
"]",
"=",
"(",
"a",
"!==",
"undefined",
")",
"?",
"a",
":",
"1",
";",
"return",
"color",
";",
"}"
] |
Updates a color based on r, g, b, a component values
@param {Array} color - RGBA color array [r,g,b,a] to update
@param {Number} r - red component (0..1)
@param {Number} g - green component (0..1)
@param {Number} b - blue component (0..1)
@param {Number} [a=1] - alpha component (0..1)
@return {Array} - updated RGBA color array [r,g,b,a] (0..1)
|
[
"Updates",
"a",
"color",
"based",
"on",
"r",
"g",
"b",
"a",
"component",
"values"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L79-L86
|
39,007 |
pex-gl/pex-color
|
index.js
|
fromHSV
|
function fromHSV(h, s, v, a) {
var color = create();
setHSV(color, h, s, v, a)
return color;
}
|
javascript
|
function fromHSV(h, s, v, a) {
var color = create();
setHSV(color, h, s, v, a)
return color;
}
|
[
"function",
"fromHSV",
"(",
"h",
",",
"s",
",",
"v",
",",
"a",
")",
"{",
"var",
"color",
"=",
"create",
"(",
")",
";",
"setHSV",
"(",
"color",
",",
"h",
",",
"s",
",",
"v",
",",
"a",
")",
"return",
"color",
";",
"}"
] |
Creates new color from hue, saturation and value
@param {Number} h - hue (0..1)
@param {Number} s - saturation (0..1)
@param {Number} v - value (0..1)
@param {Number} [a=1] - alpha (0..1)
@return {Array} - RGBA color array [r,g,b,a] (0..1)
|
[
"Creates",
"new",
"color",
"from",
"hue",
"saturation",
"and",
"value"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L119-L123
|
39,008 |
pex-gl/pex-color
|
index.js
|
setHSV
|
function setHSV(color, h, s, v, a) {
a = a || 1;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: color[0] = v; color[1] = t; color[2] = p; break;
case 1: color[0] = q; color[1] = v; color[2] = p; break;
case 2: color[0] = p; color[1] = v; color[2] = t; break;
case 3: color[0] = p; color[1] = q; color[2] = v; break;
case 4: color[0] = t; color[1] = p; color[2] = v; break;
case 5: color[0] = v; color[1] = p; color[2] = q; break;
}
color[3] = a;
return color;
}
|
javascript
|
function setHSV(color, h, s, v, a) {
a = a || 1;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: color[0] = v; color[1] = t; color[2] = p; break;
case 1: color[0] = q; color[1] = v; color[2] = p; break;
case 2: color[0] = p; color[1] = v; color[2] = t; break;
case 3: color[0] = p; color[1] = q; color[2] = v; break;
case 4: color[0] = t; color[1] = p; color[2] = v; break;
case 5: color[0] = v; color[1] = p; color[2] = q; break;
}
color[3] = a;
return color;
}
|
[
"function",
"setHSV",
"(",
"color",
",",
"h",
",",
"s",
",",
"v",
",",
"a",
")",
"{",
"a",
"=",
"a",
"||",
"1",
";",
"var",
"i",
"=",
"Math",
".",
"floor",
"(",
"h",
"*",
"6",
")",
";",
"var",
"f",
"=",
"h",
"*",
"6",
"-",
"i",
";",
"var",
"p",
"=",
"v",
"*",
"(",
"1",
"-",
"s",
")",
";",
"var",
"q",
"=",
"v",
"*",
"(",
"1",
"-",
"f",
"*",
"s",
")",
";",
"var",
"t",
"=",
"v",
"*",
"(",
"1",
"-",
"(",
"1",
"-",
"f",
")",
"*",
"s",
")",
";",
"switch",
"(",
"i",
"%",
"6",
")",
"{",
"case",
"0",
":",
"color",
"[",
"0",
"]",
"=",
"v",
";",
"color",
"[",
"1",
"]",
"=",
"t",
";",
"color",
"[",
"2",
"]",
"=",
"p",
";",
"break",
";",
"case",
"1",
":",
"color",
"[",
"0",
"]",
"=",
"q",
";",
"color",
"[",
"1",
"]",
"=",
"v",
";",
"color",
"[",
"2",
"]",
"=",
"p",
";",
"break",
";",
"case",
"2",
":",
"color",
"[",
"0",
"]",
"=",
"p",
";",
"color",
"[",
"1",
"]",
"=",
"v",
";",
"color",
"[",
"2",
"]",
"=",
"t",
";",
"break",
";",
"case",
"3",
":",
"color",
"[",
"0",
"]",
"=",
"p",
";",
"color",
"[",
"1",
"]",
"=",
"q",
";",
"color",
"[",
"2",
"]",
"=",
"v",
";",
"break",
";",
"case",
"4",
":",
"color",
"[",
"0",
"]",
"=",
"t",
";",
"color",
"[",
"1",
"]",
"=",
"p",
";",
"color",
"[",
"2",
"]",
"=",
"v",
";",
"break",
";",
"case",
"5",
":",
"color",
"[",
"0",
"]",
"=",
"v",
";",
"color",
"[",
"1",
"]",
"=",
"p",
";",
"color",
"[",
"2",
"]",
"=",
"q",
";",
"break",
";",
"}",
"color",
"[",
"3",
"]",
"=",
"a",
";",
"return",
"color",
";",
"}"
] |
Updates a color based on hue, saturation, value and alpha
@param {Array} color - RGBA color array [r,g,b,a] to update
@param {Number} h - hue (0..1)
@param {Number} s - saturation (0..1)
@param {Number} v - value (0..1)
@param {Number} [a=1] - alpha (0..1)
@return {Array} - updated RGBA color array [r,g,b,a] (0..1)
|
[
"Updates",
"a",
"color",
"based",
"on",
"hue",
"saturation",
"value",
"and",
"alpha"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L134-L154
|
39,009 |
pex-gl/pex-color
|
index.js
|
fromHSL
|
function fromHSL(h, s, l, a) {
var color = create();
setHSL(color, h, s, l, a);
return color;
}
|
javascript
|
function fromHSL(h, s, l, a) {
var color = create();
setHSL(color, h, s, l, a);
return color;
}
|
[
"function",
"fromHSL",
"(",
"h",
",",
"s",
",",
"l",
",",
"a",
")",
"{",
"var",
"color",
"=",
"create",
"(",
")",
";",
"setHSL",
"(",
"color",
",",
"h",
",",
"s",
",",
"l",
",",
"a",
")",
";",
"return",
"color",
";",
"}"
] |
Creates new color from hue, saturation, lightness and alpha
@param {Number} h - hue (0..1)
@param {Number} s - saturation (0..1)
@param {Number} l - lightness (0..1)
@param {Number} [a=1] - alpha (0..1)
@return {Array} - RGBA color array [r,g,b,a] (0..1)
|
[
"Creates",
"new",
"color",
"from",
"hue",
"saturation",
"lightness",
"and",
"alpha"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L195-L199
|
39,010 |
pex-gl/pex-color
|
index.js
|
setHSL
|
function setHSL(color, h, s, l, a) {
a = a || 1;
function hue2rgb(p, q, t) {
if (t < 0) { t += 1; }
if (t > 1) { t -= 1; }
if (t < 1/6) { return p + (q - p) * 6 * t; }
if (t < 1/2) { return q; }
if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
return p;
}
if (s === 0) {
color[0] = color[1] = color[2] = l; // achromatic
}
else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
color[0] = hue2rgb(p, q, h + 1/3);
color[1] = hue2rgb(p, q, h);
color[2] = hue2rgb(p, q, h - 1/3);
}
color[3] = a;
return color;
}
|
javascript
|
function setHSL(color, h, s, l, a) {
a = a || 1;
function hue2rgb(p, q, t) {
if (t < 0) { t += 1; }
if (t > 1) { t -= 1; }
if (t < 1/6) { return p + (q - p) * 6 * t; }
if (t < 1/2) { return q; }
if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; }
return p;
}
if (s === 0) {
color[0] = color[1] = color[2] = l; // achromatic
}
else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
color[0] = hue2rgb(p, q, h + 1/3);
color[1] = hue2rgb(p, q, h);
color[2] = hue2rgb(p, q, h - 1/3);
}
color[3] = a;
return color;
}
|
[
"function",
"setHSL",
"(",
"color",
",",
"h",
",",
"s",
",",
"l",
",",
"a",
")",
"{",
"a",
"=",
"a",
"||",
"1",
";",
"function",
"hue2rgb",
"(",
"p",
",",
"q",
",",
"t",
")",
"{",
"if",
"(",
"t",
"<",
"0",
")",
"{",
"t",
"+=",
"1",
";",
"}",
"if",
"(",
"t",
">",
"1",
")",
"{",
"t",
"-=",
"1",
";",
"}",
"if",
"(",
"t",
"<",
"1",
"/",
"6",
")",
"{",
"return",
"p",
"+",
"(",
"q",
"-",
"p",
")",
"*",
"6",
"*",
"t",
";",
"}",
"if",
"(",
"t",
"<",
"1",
"/",
"2",
")",
"{",
"return",
"q",
";",
"}",
"if",
"(",
"t",
"<",
"2",
"/",
"3",
")",
"{",
"return",
"p",
"+",
"(",
"q",
"-",
"p",
")",
"*",
"(",
"2",
"/",
"3",
"-",
"t",
")",
"*",
"6",
";",
"}",
"return",
"p",
";",
"}",
"if",
"(",
"s",
"===",
"0",
")",
"{",
"color",
"[",
"0",
"]",
"=",
"color",
"[",
"1",
"]",
"=",
"color",
"[",
"2",
"]",
"=",
"l",
";",
"// achromatic",
"}",
"else",
"{",
"var",
"q",
"=",
"l",
"<",
"0.5",
"?",
"l",
"*",
"(",
"1",
"+",
"s",
")",
":",
"l",
"+",
"s",
"-",
"l",
"*",
"s",
";",
"var",
"p",
"=",
"2",
"*",
"l",
"-",
"q",
";",
"color",
"[",
"0",
"]",
"=",
"hue2rgb",
"(",
"p",
",",
"q",
",",
"h",
"+",
"1",
"/",
"3",
")",
";",
"color",
"[",
"1",
"]",
"=",
"hue2rgb",
"(",
"p",
",",
"q",
",",
"h",
")",
";",
"color",
"[",
"2",
"]",
"=",
"hue2rgb",
"(",
"p",
",",
"q",
",",
"h",
"-",
"1",
"/",
"3",
")",
";",
"}",
"color",
"[",
"3",
"]",
"=",
"a",
";",
"return",
"color",
";",
"}"
] |
Updates a color based on hue, saturation, lightness and alpha
@param {Array} color - RGBA color array [r,g,b,a] to update
@param {Number} h - hue (0..1)
@param {Number} s - saturation (0..1)
@param {Number} l - lightness (0..1)
@param {Number} [a=1] - alpha (0..1)
@return {Array} - updated RGBA color array [r,g,b,a] (0..1)
|
[
"Updates",
"a",
"color",
"based",
"on",
"hue",
"saturation",
"lightness",
"and",
"alpha"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L210-L235
|
39,011 |
pex-gl/pex-color
|
index.js
|
getHex
|
function getHex(color) {
var c = [ color[0], color[1], color[2] ].map(function(val) {
return Math.floor(val * 255);
});
return "#" + ((c[2] | c[1] << 8 | c[0] << 16) | 1 << 24)
.toString(16)
.slice(1)
.toUpperCase();
}
|
javascript
|
function getHex(color) {
var c = [ color[0], color[1], color[2] ].map(function(val) {
return Math.floor(val * 255);
});
return "#" + ((c[2] | c[1] << 8 | c[0] << 16) | 1 << 24)
.toString(16)
.slice(1)
.toUpperCase();
}
|
[
"function",
"getHex",
"(",
"color",
")",
"{",
"var",
"c",
"=",
"[",
"color",
"[",
"0",
"]",
",",
"color",
"[",
"1",
"]",
",",
"color",
"[",
"2",
"]",
"]",
".",
"map",
"(",
"function",
"(",
"val",
")",
"{",
"return",
"Math",
".",
"floor",
"(",
"val",
"*",
"255",
")",
";",
"}",
")",
";",
"return",
"\"#\"",
"+",
"(",
"(",
"c",
"[",
"2",
"]",
"|",
"c",
"[",
"1",
"]",
"<<",
"8",
"|",
"c",
"[",
"0",
"]",
"<<",
"16",
")",
"|",
"1",
"<<",
"24",
")",
".",
"toString",
"(",
"16",
")",
".",
"slice",
"(",
"1",
")",
".",
"toUpperCase",
"(",
")",
";",
"}"
] |
Returns html hex representation of given color
@param {Array} color - RGBA color array [r,g,b,a]
@return {String} - html hex color including leading hash e.g. #FF0000
|
[
"Returns",
"html",
"hex",
"representation",
"of",
"given",
"color"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L305-L314
|
39,012 |
pex-gl/pex-color
|
index.js
|
fromXYZ
|
function fromXYZ(x, y, z) {
var color = create();
setXYZ(color, x, y, z);
return color;
}
|
javascript
|
function fromXYZ(x, y, z) {
var color = create();
setXYZ(color, x, y, z);
return color;
}
|
[
"function",
"fromXYZ",
"(",
"x",
",",
"y",
",",
"z",
")",
"{",
"var",
"color",
"=",
"create",
"(",
")",
";",
"setXYZ",
"(",
"color",
",",
"x",
",",
"y",
",",
"z",
")",
";",
"return",
"color",
";",
"}"
] |
Creates new color from XYZ values
@param {Number} x - x component (0..95)
@param {Number} y - y component (0..100)
@param {Number} z - z component (0..108)
@return {Array} - RGBA color array [r,g,b,a] (0..1)
|
[
"Creates",
"new",
"color",
"from",
"XYZ",
"values"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L323-L327
|
39,013 |
pex-gl/pex-color
|
index.js
|
setXYZ
|
function setXYZ(color, x, y, z) {
var r = x * 3.2406 + y * -1.5372 + z * -0.4986;
var g = x * -0.9689 + y * 1.8758 + z * 0.0415;
var b = x * 0.0557 + y * -0.2040 + z * 1.0570;
color[0] = fromXYZValue(r);
color[1] = fromXYZValue(g);
color[2] = fromXYZValue(b);
color[3] = 1.0;
return color;
}
|
javascript
|
function setXYZ(color, x, y, z) {
var r = x * 3.2406 + y * -1.5372 + z * -0.4986;
var g = x * -0.9689 + y * 1.8758 + z * 0.0415;
var b = x * 0.0557 + y * -0.2040 + z * 1.0570;
color[0] = fromXYZValue(r);
color[1] = fromXYZValue(g);
color[2] = fromXYZValue(b);
color[3] = 1.0;
return color;
}
|
[
"function",
"setXYZ",
"(",
"color",
",",
"x",
",",
"y",
",",
"z",
")",
"{",
"var",
"r",
"=",
"x",
"*",
"3.2406",
"+",
"y",
"*",
"-",
"1.5372",
"+",
"z",
"*",
"-",
"0.4986",
";",
"var",
"g",
"=",
"x",
"*",
"-",
"0.9689",
"+",
"y",
"*",
"1.8758",
"+",
"z",
"*",
"0.0415",
";",
"var",
"b",
"=",
"x",
"*",
"0.0557",
"+",
"y",
"*",
"-",
"0.2040",
"+",
"z",
"*",
"1.0570",
";",
"color",
"[",
"0",
"]",
"=",
"fromXYZValue",
"(",
"r",
")",
";",
"color",
"[",
"1",
"]",
"=",
"fromXYZValue",
"(",
"g",
")",
";",
"color",
"[",
"2",
"]",
"=",
"fromXYZValue",
"(",
"b",
")",
";",
"color",
"[",
"3",
"]",
"=",
"1.0",
";",
"return",
"color",
";",
"}"
] |
Updates a color based on x, y, z component values
@param {Array} color - RGBA color array [r,g,b,a] to update
@param {Number} x - x component (0..95)
@param {Number} y - y component (0..100)
@param {Number} z - z component (0..108)
@return {Array} - updated RGBA color array [r,g,b,a] (0..1)
|
[
"Updates",
"a",
"color",
"based",
"on",
"x",
"y",
"z",
"component",
"values"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L367-L378
|
39,014 |
pex-gl/pex-color
|
index.js
|
getXYZ
|
function getXYZ(color) {
var r = toXYZValue(color[0]);
var g = toXYZValue(color[1]);
var b = toXYZValue(color[2]);
return [
r * 0.4124 + g * 0.3576 + b * 0.1805,
r * 0.2126 + g * 0.7152 + b * 0.0722,
r * 0.0193 + g * 0.1192 + b * 0.9505
]
}
|
javascript
|
function getXYZ(color) {
var r = toXYZValue(color[0]);
var g = toXYZValue(color[1]);
var b = toXYZValue(color[2]);
return [
r * 0.4124 + g * 0.3576 + b * 0.1805,
r * 0.2126 + g * 0.7152 + b * 0.0722,
r * 0.0193 + g * 0.1192 + b * 0.9505
]
}
|
[
"function",
"getXYZ",
"(",
"color",
")",
"{",
"var",
"r",
"=",
"toXYZValue",
"(",
"color",
"[",
"0",
"]",
")",
";",
"var",
"g",
"=",
"toXYZValue",
"(",
"color",
"[",
"1",
"]",
")",
";",
"var",
"b",
"=",
"toXYZValue",
"(",
"color",
"[",
"2",
"]",
")",
";",
"return",
"[",
"r",
"*",
"0.4124",
"+",
"g",
"*",
"0.3576",
"+",
"b",
"*",
"0.1805",
",",
"r",
"*",
"0.2126",
"+",
"g",
"*",
"0.7152",
"+",
"b",
"*",
"0.0722",
",",
"r",
"*",
"0.0193",
"+",
"g",
"*",
"0.1192",
"+",
"b",
"*",
"0.9505",
"]",
"}"
] |
Returns XYZ representation of given color
@param {Array} color - RGBA color array [r,g,b,a]
@return {Array} - [x,y,z] (x:0..95, y:0..100, z:0..108)
|
[
"Returns",
"XYZ",
"representation",
"of",
"given",
"color"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L385-L395
|
39,015 |
pex-gl/pex-color
|
index.js
|
fromLab
|
function fromLab(l, a, b) {
var color = create();
setLab(color, l, a, b);
return color;
}
|
javascript
|
function fromLab(l, a, b) {
var color = create();
setLab(color, l, a, b);
return color;
}
|
[
"function",
"fromLab",
"(",
"l",
",",
"a",
",",
"b",
")",
"{",
"var",
"color",
"=",
"create",
"(",
")",
";",
"setLab",
"(",
"color",
",",
"l",
",",
"a",
",",
"b",
")",
";",
"return",
"color",
";",
"}"
] |
Creates new color from l,a,b component values
@param {Number} l - l component (0..100)
@param {Number} a - a component (-128..127)
@param {Number} b - b component (-128..127)
@return {Array} - RGBA color array [r,g,b,a] (0..1)
|
[
"Creates",
"new",
"color",
"from",
"l",
"a",
"b",
"component",
"values"
] |
b4b64e045fa9f1c4697099ed4f658dd289862c1c
|
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L404-L408
|
39,016 |
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",
"]",
";",
"//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",
")",
";",
"}"
] |
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
|
39,017 |
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",
"]",
";",
"//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",
")",
"]",
"}"
] |
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
|
39,018 |
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
|
39,019 |
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",
")",
"{",
"/** The generic Enum instance\n * @constructor\n */",
"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
|
39,020 |
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
|
39,021 |
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",
"}",
"`",
")",
"// 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",
"}",
"`",
")",
")",
")",
";",
"}"
] |
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
|
39,022 |
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
|
|
39,023 |
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
|
|
39,024 |
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
|
|
39,025 |
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ü",
";",
"gt",
"eine",
"neue",
"Kind",
"-",
"Komponente",
"der",
"aktuellen",
"Komponente",
"hinzu",
".",
"Die",
"hinzuzufü",
";",
"gende",
"Komponente",
"muss",
"bereits",
"als",
"Instanz",
"vorliegen",
"."
] |
9fc242a470c34260b123b8c3935c929f1613182b
|
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/dist/jscow.js#L552-L563
|
|
39,026 |
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",
")",
"{",
"// 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",
";",
"}"
] |
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
|
|
39,027 |
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
|
|
39,028 |
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
|
|
39,029 |
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
|
|
39,030 |
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
|
|
39,031 |
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
|
|
39,032 |
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",
")",
"{",
"// 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",
")",
";",
"}",
"}"
] |
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
|
|
39,033 |
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
|
|
39,034 |
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
|
39,035 |
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
|
39,036 |
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",
"]",
";",
"}",
";",
"/**\n * Merge into combined store\n */",
"reduxStore",
".",
"dispatch",
".",
"reducers",
"[",
"name",
"]",
"=",
"reducers",
";",
"reduxStore",
".",
"dispatch",
".",
"effects",
"[",
"name",
"]",
"=",
"effects",
";",
"reduxStore",
".",
"dispatch",
".",
"actions",
"[",
"name",
"]",
"=",
"actions",
";",
"reduxStore",
".",
"dispatch",
".",
"batch",
"[",
"name",
"]",
"=",
"batches",
";",
"reduxStore",
".",
"getState",
"[",
"name",
"]",
"=",
"getStoreState",
";",
"/**\n * Update each store references\n */",
"store",
".",
"subscribe",
"=",
"reduxStore",
".",
"subscribe",
";",
"store",
".",
"anew",
".",
"getBatches",
"=",
"function",
"(",
")",
"{",
"return",
"reduxStore",
".",
"anew",
".",
"getBatches",
"(",
")",
";",
"}",
";",
"store",
".",
"dispatch",
"=",
"function",
"(",
"action",
")",
"{",
"return",
"reduxStore",
".",
"dispatch",
"(",
"action",
")",
";",
"}",
";",
"store",
".",
"getState",
"=",
"getStoreState",
";",
"/**\n * Redefine replace reducer\n */",
"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'",
"}",
")",
";",
"}",
";",
"/**\n * Reassign reducers, effects, and batch to maintain dispatch\n * object's shape per store.\n */",
"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",
";",
"/**\n * Reassign selectors to maintian getState\n * object's shape per store\n */",
"reduxStore",
".",
"getState",
"[",
"name",
"]",
"=",
"Object",
".",
"assign",
"(",
"reduxStore",
".",
"getState",
"[",
"name",
"]",
",",
"getState",
")",
";",
"store",
".",
"getState",
"=",
"Object",
".",
"assign",
"(",
"store",
".",
"getState",
",",
"getState",
")",
";",
"/**\n * Assign Core\n */",
"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
|
39,037 |
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
|
39,038 |
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
|
39,039 |
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",
")",
"{",
"// 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",
")",
";",
"}",
"}",
"}"
] |
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
|
|
39,040 |
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
|
39,041 |
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
|
39,042 |
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
|
39,043 |
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
|
|
39,044 |
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",
")",
"{",
"// 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",
";",
"}"
] |
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
|
39,045 |
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\"",
":",
"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",
"+",
"\"'\"",
";",
"}"
] |
add Back Quote
|
[
"add",
"Back",
"Quote"
] |
037d58178eafb0cbd39ae335215086ab6a3074cf
|
https://github.com/uyu423/node-qsb/blob/037d58178eafb0cbd39ae335215086ab6a3074cf/index.js#L8-L23
|
39,046 |
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...'",
")",
";",
"// Initialize the store.",
"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
|
39,047 |
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
|
39,048 |
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",
"(",
")",
"{",
"// 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",
")",
";",
"}"
] |
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
|
39,049 |
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
|
39,050 |
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
|
39,051 |
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
|
39,052 |
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",
")",
"{",
"// 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",
"(",
")",
";",
"}"
] |
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
|
39,053 |
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'",
")",
";",
"}",
"// 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",
";",
"}",
"}"
] |
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
|
39,054 |
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",
";",
"// 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",
";",
"}"
] |
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
|
39,055 |
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",
")",
"{",
"// Replaces all occurrences of `#` with a unique number and template tokens with content.",
"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
|
39,056 |
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
|
39,057 |
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
|
39,058 |
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",
"=",
"{",
"}",
";",
"// 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",
"(",
"`",
"${",
"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
|
39,059 |
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",
")",
"=>",
"{",
"// 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",
";",
"}",
")",
";",
"}"
] |
Add in meta.aggregations field
|
[
"Add",
"in",
"meta",
".",
"aggregations",
"field"
] |
ffa6006d6ed4de0fb4f15759a89803a83929cbcc
|
https://github.com/agco/elastic-harvesterjs/blob/ffa6006d6ed4de0fb4f15759a89803a83929cbcc/elastic-harvester.js#L286-L342
|
39,060 |
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=",
"/",
",",
"/",
"\\*$",
"/",
"]",
";",
"// 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",
"?",
"`",
"${",
"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
|
39,061 |
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",
"]",
")",
")",
"{",
"// 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",
";",
"}"
] |
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
|
39,062 |
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
|
39,063 |
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",
"=",
"{",
"}",
";",
"// 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",
"}",
";",
"}"
] |
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
|
39,064 |
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
|
|
39,065 |
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
|
|
39,066 |
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
|
|
39,067 |
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",
")",
";",
"}",
"// 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",
"(",
")",
";",
"}"
] |
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
|
39,068 |
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
|
|
39,069 |
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",
";",
"}",
"// 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",
";",
"}"
] |
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
|
|
39,070 |
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
|
39,071 |
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
|
39,072 |
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'",
")",
".",
"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",
",",
"'.'",
")",
")",
"}"
] |
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
|
39,073 |
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",
"=",
"''",
";",
"// 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",
";",
"}"
] |
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
|
39,074 |
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
|
39,075 |
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
|
39,076 |
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
|
39,077 |
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
|
39,078 |
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",
"}",
")",
";",
"//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",
"}"
] |
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
|
|
39,079 |
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",
")",
"{",
"// 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",
"(",
"`",
"${",
"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
|
|
39,080 |
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",
")",
"{",
"// 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",
"}",
"}"
] |
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
|
|
39,081 |
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
|
39,082 |
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
|
39,083 |
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
|
39,084 |
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
|
39,085 |
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
|
39,086 |
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
|
39,087 |
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 !'",
")",
"// 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",
";",
"}"
] |
HTML5 Sounds manager
|
[
"HTML5",
"Sounds",
"manager"
] |
38c9a344c88b5f065641e2ab31a907a12f195391
|
https://github.com/nfroidure/Sounds/blob/38c9a344c88b5f065641e2ab31a907a12f195391/Sounds.js#L2-L24
|
39,088 |
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",
")",
"{",
"// 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",
")",
"}"
] |
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
|
39,089 |
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
|
39,090 |
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",
")",
";",
"// 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",
"(",
"`",
"${",
"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
|
39,091 |
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",
"=",
"[",
"]",
";",
"// Array.<Listen>",
"this",
".",
"conversations",
"=",
"{",
"}",
";",
"// Array.<Array.<Conversation>> all open conversations",
"this",
".",
"connect",
"(",
")",
";",
"// automatically connect to the local message bus",
"}"
] |
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
|
39,092 |
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
|
39,093 |
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
|
39,094 |
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
|
39,095 |
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",
";",
"}",
"// the 'less-than-equal' comparision is necessary for correct result",
"// when tolerance = 0",
"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
|
39,096 |
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
|
39,097 |
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
|
39,098 |
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
|
39,099 |
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.