repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
sorensen/event-proxy | event-proxy.js | proxy | function proxy(scope, map, emitter) {
var args = slice.call(arguments, 3)
, tmp = {}, len, name, methods, method, i
if (isArray(map)) {
len = map.length
while (len--) {
tmp[map[len]] = map[len]
}
map = tmp
}
for (name in map) {
methods = map[name]
if (!isArray(methods)) {
methods = [methods]
}
for (i = 0; i < methods.length; i++) {
method = methods[i]
if (typeof method === 'string') {
method = scope[method]
}
if (!method) {
throw new Error('Proxy: method `' + method + '` does not exist')
}
emitter[listener](name, bind.apply(scope, concat.apply([scope, method], args)))
}
}
} | javascript | function proxy(scope, map, emitter) {
var args = slice.call(arguments, 3)
, tmp = {}, len, name, methods, method, i
if (isArray(map)) {
len = map.length
while (len--) {
tmp[map[len]] = map[len]
}
map = tmp
}
for (name in map) {
methods = map[name]
if (!isArray(methods)) {
methods = [methods]
}
for (i = 0; i < methods.length; i++) {
method = methods[i]
if (typeof method === 'string') {
method = scope[method]
}
if (!method) {
throw new Error('Proxy: method `' + method + '` does not exist')
}
emitter[listener](name, bind.apply(scope, concat.apply([scope, method], args)))
}
}
} | [
"function",
"proxy",
"(",
"scope",
",",
"map",
",",
"emitter",
")",
"{",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"3",
")",
",",
"tmp",
"=",
"{",
"}",
",",
"len",
",",
"name",
",",
"methods",
",",
"method",
",",
"i",
"if",
"(",
"isArray",
"(",
"map",
")",
")",
"{",
"len",
"=",
"map",
".",
"length",
"while",
"(",
"len",
"--",
")",
"{",
"tmp",
"[",
"map",
"[",
"len",
"]",
"]",
"=",
"map",
"[",
"len",
"]",
"}",
"map",
"=",
"tmp",
"}",
"for",
"(",
"name",
"in",
"map",
")",
"{",
"methods",
"=",
"map",
"[",
"name",
"]",
"if",
"(",
"!",
"isArray",
"(",
"methods",
")",
")",
"{",
"methods",
"=",
"[",
"methods",
"]",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"methods",
".",
"length",
";",
"i",
"++",
")",
"{",
"method",
"=",
"methods",
"[",
"i",
"]",
"if",
"(",
"typeof",
"method",
"===",
"'string'",
")",
"{",
"method",
"=",
"scope",
"[",
"method",
"]",
"}",
"if",
"(",
"!",
"method",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Proxy: method `'",
"+",
"method",
"+",
"'` does not exist'",
")",
"}",
"emitter",
"[",
"listener",
"]",
"(",
"name",
",",
"bind",
".",
"apply",
"(",
"scope",
",",
"concat",
".",
"apply",
"(",
"[",
"scope",
",",
"method",
"]",
",",
"args",
")",
")",
")",
"}",
"}",
"}"
] | Setup all proxy methods, if an array is supplied for the methods
the event will be proxied to a method of the same name
Examples:
proxy()
@param {Object} scope of method calls
@param {Array|Objects} methods to bind
@param {Object} event emitting object
@param {...} additional arguments to be used on every method
@api public | [
"Setup",
"all",
"proxy",
"methods",
"if",
"an",
"array",
"is",
"supplied",
"for",
"the",
"methods",
"the",
"event",
"will",
"be",
"proxied",
"to",
"a",
"method",
"of",
"the",
"same",
"name"
] | 0e299607bb454b875b8d3102503285dde37ebd7a | https://github.com/sorensen/event-proxy/blob/0e299607bb454b875b8d3102503285dde37ebd7a/event-proxy.js#L72-L99 | train |
chip-js/fragments-js | src/binding.js | function() {
ElementController.call(this, this.observations);
this.observersEnabled = false;
this.listenersEnabled = false;
if (this.expression && this.updated !== Binding.prototype.updated) {
// An observer to observe value changes to the expression within a context
this.observer = this.watch(this.expression, this.updated);
}
this.created();
} | javascript | function() {
ElementController.call(this, this.observations);
this.observersEnabled = false;
this.listenersEnabled = false;
if (this.expression && this.updated !== Binding.prototype.updated) {
// An observer to observe value changes to the expression within a context
this.observer = this.watch(this.expression, this.updated);
}
this.created();
} | [
"function",
"(",
")",
"{",
"ElementController",
".",
"call",
"(",
"this",
",",
"this",
".",
"observations",
")",
";",
"this",
".",
"observersEnabled",
"=",
"false",
";",
"this",
".",
"listenersEnabled",
"=",
"false",
";",
"if",
"(",
"this",
".",
"expression",
"&&",
"this",
".",
"updated",
"!==",
"Binding",
".",
"prototype",
".",
"updated",
")",
"{",
"this",
".",
"observer",
"=",
"this",
".",
"watch",
"(",
"this",
".",
"expression",
",",
"this",
".",
"updated",
")",
";",
"}",
"this",
".",
"created",
"(",
")",
";",
"}"
] | Initialize a cloned binding. This happens after a compiled binding on a template is cloned for a view. | [
"Initialize",
"a",
"cloned",
"binding",
".",
"This",
"happens",
"after",
"a",
"compiled",
"binding",
"on",
"a",
"template",
"is",
"cloned",
"for",
"a",
"view",
"."
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/binding.js#L46-L56 | train |
|
chip-js/fragments-js | src/binding.js | initNodePath | function initNodePath(node, view) {
var path = [];
while (node !== view) {
var parent = node.parentNode;
path.unshift(indexOf.call(parent.childNodes, node));
node = parent;
}
return path;
} | javascript | function initNodePath(node, view) {
var path = [];
while (node !== view) {
var parent = node.parentNode;
path.unshift(indexOf.call(parent.childNodes, node));
node = parent;
}
return path;
} | [
"function",
"initNodePath",
"(",
"node",
",",
"view",
")",
"{",
"var",
"path",
"=",
"[",
"]",
";",
"while",
"(",
"node",
"!==",
"view",
")",
"{",
"var",
"parent",
"=",
"node",
".",
"parentNode",
";",
"path",
".",
"unshift",
"(",
"indexOf",
".",
"call",
"(",
"parent",
".",
"childNodes",
",",
"node",
")",
")",
";",
"node",
"=",
"parent",
";",
"}",
"return",
"path",
";",
"}"
] | Creates an array of indexes to help find the same element within a cloned view | [
"Creates",
"an",
"array",
"of",
"indexes",
"to",
"help",
"find",
"the",
"same",
"element",
"within",
"a",
"cloned",
"view"
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/binding.js#L172-L180 | train |
myfreeweb/broccoli-brotli | index.js | BrotliFilter | function BrotliFilter(inputNode, options) {
if (!(this instanceof BrotliFilter))
return new BrotliFilter(inputNode, options);
options = options || {};
this.brotliOptions = {
mode: options.mode || 0,
quality: options.quality || 11,
lgwin: options.lgwin || 22,
lgblock: options.lgblock || 0
};
this.keepUncompressed = options.keepUncompressed;
this.appendSuffix = (options.hasOwnProperty('appendSuffix') ?
options.appendSuffix :
true);
// Default file encoding is raw to handle binary files
this.inputEncoding = options.inputEncoding || null;
this.outputEncoding = options.outputEncoding || null;
if (this.keepUncompressed && !this.appendSuffix) {
throw new Error('Cannot keep uncompressed files without appending suffix. Filenames would be the same.');
}
Filter.call(this, inputNode, options);
} | javascript | function BrotliFilter(inputNode, options) {
if (!(this instanceof BrotliFilter))
return new BrotliFilter(inputNode, options);
options = options || {};
this.brotliOptions = {
mode: options.mode || 0,
quality: options.quality || 11,
lgwin: options.lgwin || 22,
lgblock: options.lgblock || 0
};
this.keepUncompressed = options.keepUncompressed;
this.appendSuffix = (options.hasOwnProperty('appendSuffix') ?
options.appendSuffix :
true);
// Default file encoding is raw to handle binary files
this.inputEncoding = options.inputEncoding || null;
this.outputEncoding = options.outputEncoding || null;
if (this.keepUncompressed && !this.appendSuffix) {
throw new Error('Cannot keep uncompressed files without appending suffix. Filenames would be the same.');
}
Filter.call(this, inputNode, options);
} | [
"function",
"BrotliFilter",
"(",
"inputNode",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"BrotliFilter",
")",
")",
"return",
"new",
"BrotliFilter",
"(",
"inputNode",
",",
"options",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"brotliOptions",
"=",
"{",
"mode",
":",
"options",
".",
"mode",
"||",
"0",
",",
"quality",
":",
"options",
".",
"quality",
"||",
"11",
",",
"lgwin",
":",
"options",
".",
"lgwin",
"||",
"22",
",",
"lgblock",
":",
"options",
".",
"lgblock",
"||",
"0",
"}",
";",
"this",
".",
"keepUncompressed",
"=",
"options",
".",
"keepUncompressed",
";",
"this",
".",
"appendSuffix",
"=",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'appendSuffix'",
")",
"?",
"options",
".",
"appendSuffix",
":",
"true",
")",
";",
"this",
".",
"inputEncoding",
"=",
"options",
".",
"inputEncoding",
"||",
"null",
";",
"this",
".",
"outputEncoding",
"=",
"options",
".",
"outputEncoding",
"||",
"null",
";",
"if",
"(",
"this",
".",
"keepUncompressed",
"&&",
"!",
"this",
".",
"appendSuffix",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Cannot keep uncompressed files without appending suffix. Filenames would be the same.'",
")",
";",
"}",
"Filter",
".",
"call",
"(",
"this",
",",
"inputNode",
",",
"options",
")",
";",
"}"
] | Brotli filter.
@constructor
@param {object} inputNode - Input node.
@param {object} options - Options. | [
"Brotli",
"filter",
"."
] | 07835b0726c59aba761cf4f83cd1c90cda0b2f4e | https://github.com/myfreeweb/broccoli-brotli/blob/07835b0726c59aba761cf4f83cd1c90cda0b2f4e/index.js#L20-L46 | train |
LabsRS-Dev/sdk | dist/dovemax-sdk.esm.js | function (o, cb) {
try {
var reader = new FileReader();
reader.onload = function (event) {
cb && cb(reader.result);
};
reader.readAsText(o);
} catch (error) {
throw error
}
} | javascript | function (o, cb) {
try {
var reader = new FileReader();
reader.onload = function (event) {
cb && cb(reader.result);
};
reader.readAsText(o);
} catch (error) {
throw error
}
} | [
"function",
"(",
"o",
",",
"cb",
")",
"{",
"try",
"{",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"reader",
".",
"onload",
"=",
"function",
"(",
"event",
")",
"{",
"cb",
"&&",
"cb",
"(",
"reader",
".",
"result",
")",
";",
"}",
";",
"reader",
".",
"readAsText",
"(",
"o",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"throw",
"error",
"}",
"}"
] | Blob data convert to String
@param o Blob obj
@param cb callback function | [
"Blob",
"data",
"convert",
"to",
"String"
] | 5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce | https://github.com/LabsRS-Dev/sdk/blob/5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce/dist/dovemax-sdk.esm.js#L17780-L17790 | train |
|
LabsRS-Dev/sdk | dist/dovemax-sdk.esm.js | function (param, allowTypes) {
var t$ = Tool;
allowTypes = allowTypes || [];
if (t$.isUndefinedOrNull(param)) { return [] }
if (allowTypes.findIndex(function (value, index, err) {
return value === t$.getType(param)
}) > -1) {
return [param]
}
if (t$.isArray(param)) { return param }
return []
} | javascript | function (param, allowTypes) {
var t$ = Tool;
allowTypes = allowTypes || [];
if (t$.isUndefinedOrNull(param)) { return [] }
if (allowTypes.findIndex(function (value, index, err) {
return value === t$.getType(param)
}) > -1) {
return [param]
}
if (t$.isArray(param)) { return param }
return []
} | [
"function",
"(",
"param",
",",
"allowTypes",
")",
"{",
"var",
"t$",
"=",
"Tool",
";",
"allowTypes",
"=",
"allowTypes",
"||",
"[",
"]",
";",
"if",
"(",
"t$",
".",
"isUndefinedOrNull",
"(",
"param",
")",
")",
"{",
"return",
"[",
"]",
"}",
"if",
"(",
"allowTypes",
".",
"findIndex",
"(",
"function",
"(",
"value",
",",
"index",
",",
"err",
")",
"{",
"return",
"value",
"===",
"t$",
".",
"getType",
"(",
"param",
")",
"}",
")",
">",
"-",
"1",
")",
"{",
"return",
"[",
"param",
"]",
"}",
"if",
"(",
"t$",
".",
"isArray",
"(",
"param",
")",
")",
"{",
"return",
"param",
"}",
"return",
"[",
"]",
"}"
] | param wrapper to Array | [
"param",
"wrapper",
"to",
"Array"
] | 5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce | https://github.com/LabsRS-Dev/sdk/blob/5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce/dist/dovemax-sdk.esm.js#L17810-L17821 | train |
|
LabsRS-Dev/sdk | dist/dovemax-sdk.esm.js | function (err) {
var msg = '';
var t$ = Tool;
try {
if (t$.isString(err)) {
msg = err;
} else if (t$.isError(err)) {
msg = err.message;
} else if (t$.isObject(err)) {
var errMsg = [];
for (var p in err) {
if (err.hasOwnProperty(p)) {
errMsg.push(p + '=' + err[p]);
}
}
if (errMsg.length === 0) {
msg = err;
} else {
msg = errMsg.join('\n');
}
} else {
msg += '[RTY_CANT_TYPE] = ' + t$.getType(err);
msg += JSON.stringify(err);
}
} catch (error) {
throw error
}
return msg
} | javascript | function (err) {
var msg = '';
var t$ = Tool;
try {
if (t$.isString(err)) {
msg = err;
} else if (t$.isError(err)) {
msg = err.message;
} else if (t$.isObject(err)) {
var errMsg = [];
for (var p in err) {
if (err.hasOwnProperty(p)) {
errMsg.push(p + '=' + err[p]);
}
}
if (errMsg.length === 0) {
msg = err;
} else {
msg = errMsg.join('\n');
}
} else {
msg += '[RTY_CANT_TYPE] = ' + t$.getType(err);
msg += JSON.stringify(err);
}
} catch (error) {
throw error
}
return msg
} | [
"function",
"(",
"err",
")",
"{",
"var",
"msg",
"=",
"''",
";",
"var",
"t$",
"=",
"Tool",
";",
"try",
"{",
"if",
"(",
"t$",
".",
"isString",
"(",
"err",
")",
")",
"{",
"msg",
"=",
"err",
";",
"}",
"else",
"if",
"(",
"t$",
".",
"isError",
"(",
"err",
")",
")",
"{",
"msg",
"=",
"err",
".",
"message",
";",
"}",
"else",
"if",
"(",
"t$",
".",
"isObject",
"(",
"err",
")",
")",
"{",
"var",
"errMsg",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"p",
"in",
"err",
")",
"{",
"if",
"(",
"err",
".",
"hasOwnProperty",
"(",
"p",
")",
")",
"{",
"errMsg",
".",
"push",
"(",
"p",
"+",
"'='",
"+",
"err",
"[",
"p",
"]",
")",
";",
"}",
"}",
"if",
"(",
"errMsg",
".",
"length",
"===",
"0",
")",
"{",
"msg",
"=",
"err",
";",
"}",
"else",
"{",
"msg",
"=",
"errMsg",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
"}",
"else",
"\\n",
"}",
"{",
"msg",
"+=",
"'[RTY_CANT_TYPE] = '",
"+",
"t$",
".",
"getType",
"(",
"err",
")",
";",
"msg",
"+=",
"JSON",
".",
"stringify",
"(",
"err",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"throw",
"error",
"}",
"}"
] | Format error string
@param err error object
@return String | [
"Format",
"error",
"string"
] | 5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce | https://github.com/LabsRS-Dev/sdk/blob/5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce/dist/dovemax-sdk.esm.js#L17833-L17862 | train |
|
LabsRS-Dev/sdk | dist/dovemax-sdk.esm.js | function (fileName, fileTypes) {
var _fileNameStr = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
if (fileTypes.indexOf(_fileNameStr) > -1) { return true }
return false
} | javascript | function (fileName, fileTypes) {
var _fileNameStr = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
if (fileTypes.indexOf(_fileNameStr) > -1) { return true }
return false
} | [
"function",
"(",
"fileName",
",",
"fileTypes",
")",
"{",
"var",
"_fileNameStr",
"=",
"fileName",
".",
"substring",
"(",
"fileName",
".",
"lastIndexOf",
"(",
"'.'",
")",
"+",
"1",
",",
"fileName",
".",
"length",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"fileTypes",
".",
"indexOf",
"(",
"_fileNameStr",
")",
">",
"-",
"1",
")",
"{",
"return",
"true",
"}",
"return",
"false",
"}"
] | Check fileName's type in the fileTypes
@param fileName String
@param fileTypes Array []
@return Boolean {true, false} | [
"Check",
"fileName",
"s",
"type",
"in",
"the",
"fileTypes"
] | 5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce | https://github.com/LabsRS-Dev/sdk/blob/5b73ec7e5c50be54cc4bedd34cc2ee0c47db06ce/dist/dovemax-sdk.esm.js#L17899-L17903 | train |
|
bluemathsoft/bm-linalg | lib/ops.js | outer | function outer(A, B) {
if (A.shape.length === 1) {
A.reshape([A.shape[0], 1]);
}
else if (A.shape.length === 2) {
if (A.shape[1] !== 1) {
throw new Error('A is not a column vector');
}
}
else {
throw new Error('A has invalid dimensions');
}
if (B.shape.length === 1) {
B.reshape([1, B.shape[0]]);
}
else if (B.shape.length === 2) {
if (B.shape[0] !== 1) {
throw new Error('B is not a row vector');
}
}
else {
throw new Error('B has invalid dimensions');
}
if (A.shape[0] !== B.shape[1]) {
throw new Error('Sizes of A and B are not compatible');
}
return matmul(A, B);
} | javascript | function outer(A, B) {
if (A.shape.length === 1) {
A.reshape([A.shape[0], 1]);
}
else if (A.shape.length === 2) {
if (A.shape[1] !== 1) {
throw new Error('A is not a column vector');
}
}
else {
throw new Error('A has invalid dimensions');
}
if (B.shape.length === 1) {
B.reshape([1, B.shape[0]]);
}
else if (B.shape.length === 2) {
if (B.shape[0] !== 1) {
throw new Error('B is not a row vector');
}
}
else {
throw new Error('B has invalid dimensions');
}
if (A.shape[0] !== B.shape[1]) {
throw new Error('Sizes of A and B are not compatible');
}
return matmul(A, B);
} | [
"function",
"outer",
"(",
"A",
",",
"B",
")",
"{",
"if",
"(",
"A",
".",
"shape",
".",
"length",
"===",
"1",
")",
"{",
"A",
".",
"reshape",
"(",
"[",
"A",
".",
"shape",
"[",
"0",
"]",
",",
"1",
"]",
")",
";",
"}",
"else",
"if",
"(",
"A",
".",
"shape",
".",
"length",
"===",
"2",
")",
"{",
"if",
"(",
"A",
".",
"shape",
"[",
"1",
"]",
"!==",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'A is not a column vector'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'A has invalid dimensions'",
")",
";",
"}",
"if",
"(",
"B",
".",
"shape",
".",
"length",
"===",
"1",
")",
"{",
"B",
".",
"reshape",
"(",
"[",
"1",
",",
"B",
".",
"shape",
"[",
"0",
"]",
"]",
")",
";",
"}",
"else",
"if",
"(",
"B",
".",
"shape",
".",
"length",
"===",
"2",
")",
"{",
"if",
"(",
"B",
".",
"shape",
"[",
"0",
"]",
"!==",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'B is not a row vector'",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'B has invalid dimensions'",
")",
";",
"}",
"if",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
"!==",
"B",
".",
"shape",
"[",
"1",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Sizes of A and B are not compatible'",
")",
";",
"}",
"return",
"matmul",
"(",
"A",
",",
"B",
")",
";",
"}"
] | Compute outer product of two vectors
@param A Vector of shape [m] or [m,1]
@param B Vector of shape [n] or [1,n]
@returns NDArray Matrix of dimension [m,n] | [
"Compute",
"outer",
"product",
"of",
"two",
"vectors"
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L354-L381 | train |
bluemathsoft/bm-linalg | lib/ops.js | cholesky | function cholesky(A) {
if (A.shape.length !== 2) {
throw new Error('A is not a matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var copyA = A.clone();
copyA.swapOrder();
lapack.potrf(copyA.data, copyA.shape[0]);
copyA.swapOrder();
return tril(copyA);
} | javascript | function cholesky(A) {
if (A.shape.length !== 2) {
throw new Error('A is not a matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var copyA = A.clone();
copyA.swapOrder();
lapack.potrf(copyA.data, copyA.shape[0]);
copyA.swapOrder();
return tril(copyA);
} | [
"function",
"cholesky",
"(",
"A",
")",
"{",
"if",
"(",
"A",
".",
"shape",
".",
"length",
"!==",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"'A is not a matrix'",
")",
";",
"}",
"if",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
"!==",
"A",
".",
"shape",
"[",
"1",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input is not square matrix'",
")",
";",
"}",
"var",
"copyA",
"=",
"A",
".",
"clone",
"(",
")",
";",
"copyA",
".",
"swapOrder",
"(",
")",
";",
"lapack",
".",
"potrf",
"(",
"copyA",
".",
"data",
",",
"copyA",
".",
"shape",
"[",
"0",
"]",
")",
";",
"copyA",
".",
"swapOrder",
"(",
")",
";",
"return",
"tril",
"(",
"copyA",
")",
";",
"}"
] | Perform Cholesky decomposition on given Matrix | [
"Perform",
"Cholesky",
"decomposition",
"on",
"given",
"Matrix"
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L386-L398 | train |
bluemathsoft/bm-linalg | lib/ops.js | lstsq | function lstsq(A, B, rcond) {
if (rcond === void 0) { rcond = -1; }
var copyA = A.clone();
var copyB = B.clone();
var is_1d = false;
if (copyB.shape.length === 1) {
copyB.reshape([copyB.shape[0], 1]);
is_1d = true;
}
var m;
var n;
m = copyA.shape[0];
n = copyA.shape[1];
var nrhs = copyB.shape[1];
copyA.swapOrder();
copyB.swapOrder();
var S = new common_1.NDArray({ shape: [Math.min(m, n)] });
var rank = lapack.gelsd(copyA.data, m, n, nrhs, rcond, copyB.data, S.data);
copyB.swapOrder();
// Residuals - TODO: test more
var residuals = new common_1.NDArray([]);
if (rank === n && m > n) {
var i = void 0;
if (is_1d) {
residuals = new common_1.NDArray({ shape: [1] });
var sum = 0;
for (i = n; i < m; i++) {
var K = copyB.shape[1];
for (var j = 0; j < K; j++) {
// TODO:Complex
sum += copyB.get(i, j) * copyB.get(i, j);
}
}
residuals.set(0, sum);
}
else {
residuals = new common_1.NDArray({ shape: [m - n] });
for (i = n; i < m; i++) {
var K = copyB.shape[1];
var sum = 0;
for (var j = 0; j < K; j++) {
// TODO:Complex
sum += copyB.get(i, j) * copyB.get(i, j);
}
residuals.set(i - n, sum);
}
}
}
return {
x: copyB,
residuals: residuals,
rank: rank,
singulars: S
};
} | javascript | function lstsq(A, B, rcond) {
if (rcond === void 0) { rcond = -1; }
var copyA = A.clone();
var copyB = B.clone();
var is_1d = false;
if (copyB.shape.length === 1) {
copyB.reshape([copyB.shape[0], 1]);
is_1d = true;
}
var m;
var n;
m = copyA.shape[0];
n = copyA.shape[1];
var nrhs = copyB.shape[1];
copyA.swapOrder();
copyB.swapOrder();
var S = new common_1.NDArray({ shape: [Math.min(m, n)] });
var rank = lapack.gelsd(copyA.data, m, n, nrhs, rcond, copyB.data, S.data);
copyB.swapOrder();
// Residuals - TODO: test more
var residuals = new common_1.NDArray([]);
if (rank === n && m > n) {
var i = void 0;
if (is_1d) {
residuals = new common_1.NDArray({ shape: [1] });
var sum = 0;
for (i = n; i < m; i++) {
var K = copyB.shape[1];
for (var j = 0; j < K; j++) {
// TODO:Complex
sum += copyB.get(i, j) * copyB.get(i, j);
}
}
residuals.set(0, sum);
}
else {
residuals = new common_1.NDArray({ shape: [m - n] });
for (i = n; i < m; i++) {
var K = copyB.shape[1];
var sum = 0;
for (var j = 0; j < K; j++) {
// TODO:Complex
sum += copyB.get(i, j) * copyB.get(i, j);
}
residuals.set(i - n, sum);
}
}
}
return {
x: copyB,
residuals: residuals,
rank: rank,
singulars: S
};
} | [
"function",
"lstsq",
"(",
"A",
",",
"B",
",",
"rcond",
")",
"{",
"if",
"(",
"rcond",
"===",
"void",
"0",
")",
"{",
"rcond",
"=",
"-",
"1",
";",
"}",
"var",
"copyA",
"=",
"A",
".",
"clone",
"(",
")",
";",
"var",
"copyB",
"=",
"B",
".",
"clone",
"(",
")",
";",
"var",
"is_1d",
"=",
"false",
";",
"if",
"(",
"copyB",
".",
"shape",
".",
"length",
"===",
"1",
")",
"{",
"copyB",
".",
"reshape",
"(",
"[",
"copyB",
".",
"shape",
"[",
"0",
"]",
",",
"1",
"]",
")",
";",
"is_1d",
"=",
"true",
";",
"}",
"var",
"m",
";",
"var",
"n",
";",
"m",
"=",
"copyA",
".",
"shape",
"[",
"0",
"]",
";",
"n",
"=",
"copyA",
".",
"shape",
"[",
"1",
"]",
";",
"var",
"nrhs",
"=",
"copyB",
".",
"shape",
"[",
"1",
"]",
";",
"copyA",
".",
"swapOrder",
"(",
")",
";",
"copyB",
".",
"swapOrder",
"(",
")",
";",
"var",
"S",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"Math",
".",
"min",
"(",
"m",
",",
"n",
")",
"]",
"}",
")",
";",
"var",
"rank",
"=",
"lapack",
".",
"gelsd",
"(",
"copyA",
".",
"data",
",",
"m",
",",
"n",
",",
"nrhs",
",",
"rcond",
",",
"copyB",
".",
"data",
",",
"S",
".",
"data",
")",
";",
"copyB",
".",
"swapOrder",
"(",
")",
";",
"var",
"residuals",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"[",
"]",
")",
";",
"if",
"(",
"rank",
"===",
"n",
"&&",
"m",
">",
"n",
")",
"{",
"var",
"i",
"=",
"void",
"0",
";",
"if",
"(",
"is_1d",
")",
"{",
"residuals",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"1",
"]",
"}",
")",
";",
"var",
"sum",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"n",
";",
"i",
"<",
"m",
";",
"i",
"++",
")",
"{",
"var",
"K",
"=",
"copyB",
".",
"shape",
"[",
"1",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"K",
";",
"j",
"++",
")",
"{",
"sum",
"+=",
"copyB",
".",
"get",
"(",
"i",
",",
"j",
")",
"*",
"copyB",
".",
"get",
"(",
"i",
",",
"j",
")",
";",
"}",
"}",
"residuals",
".",
"set",
"(",
"0",
",",
"sum",
")",
";",
"}",
"else",
"{",
"residuals",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"m",
"-",
"n",
"]",
"}",
")",
";",
"for",
"(",
"i",
"=",
"n",
";",
"i",
"<",
"m",
";",
"i",
"++",
")",
"{",
"var",
"K",
"=",
"copyB",
".",
"shape",
"[",
"1",
"]",
";",
"var",
"sum",
"=",
"0",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"K",
";",
"j",
"++",
")",
"{",
"sum",
"+=",
"copyB",
".",
"get",
"(",
"i",
",",
"j",
")",
"*",
"copyB",
".",
"get",
"(",
"i",
",",
"j",
")",
";",
"}",
"residuals",
".",
"set",
"(",
"i",
"-",
"n",
",",
"sum",
")",
";",
"}",
"}",
"}",
"return",
"{",
"x",
":",
"copyB",
",",
"residuals",
":",
"residuals",
",",
"rank",
":",
"rank",
",",
"singulars",
":",
"S",
"}",
";",
"}"
] | Return the least-squares solution to a linear matrix equation.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number of
linearly independent rows of `a` can be less than, equal to, or
greater than its number of linearly independent columns). If `a`
is square and of full rank, then `x` (but for round-off error) is
the "exact" solution of the equation.
@param A Coefficient matrix (m-by-n)
@param B Values on RHS of equation system. Could be array of length
m or it could be 2D with dimensions m-by-k
@param rcond Cut-off ratio for small singular values of `a` | [
"Return",
"the",
"least",
"-",
"squares",
"solution",
"to",
"a",
"linear",
"matrix",
"equation",
"."
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L503-L557 | train |
bluemathsoft/bm-linalg | lib/ops.js | slogdet | function slogdet(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var m = A.shape[0];
var copyA = A.clone();
copyA.swapOrder();
var ipiv = new common_1.NDArray({ shape: [m], datatype: 'i32' });
lapack.getrf(copyA.data, m, m, ipiv.data);
copyA.swapOrder();
// Multiply diagonal elements of Upper triangular matrix to get determinant
// For large matrices this value could get really big, hence we add
// natural logarithms of the diagonal elements and save the sign
// separately
var sign_acc = 1;
var log_acc = 0;
// Note: The pivot vector affects the sign of the determinant
// I do not understand why, but this is what numpy implementation does
for (var i = 0; i < m; i++) {
if (ipiv.get(i) !== i + 1) {
sign_acc = -sign_acc;
}
}
for (var i = 0; i < m; i++) {
var e = copyA.get(i, i);
// TODO:Complex
var e_abs = Math.abs(e);
var e_sign = e / e_abs;
sign_acc *= e_sign;
log_acc += Math.log(e_abs);
}
return [sign_acc, log_acc];
} | javascript | function slogdet(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var m = A.shape[0];
var copyA = A.clone();
copyA.swapOrder();
var ipiv = new common_1.NDArray({ shape: [m], datatype: 'i32' });
lapack.getrf(copyA.data, m, m, ipiv.data);
copyA.swapOrder();
// Multiply diagonal elements of Upper triangular matrix to get determinant
// For large matrices this value could get really big, hence we add
// natural logarithms of the diagonal elements and save the sign
// separately
var sign_acc = 1;
var log_acc = 0;
// Note: The pivot vector affects the sign of the determinant
// I do not understand why, but this is what numpy implementation does
for (var i = 0; i < m; i++) {
if (ipiv.get(i) !== i + 1) {
sign_acc = -sign_acc;
}
}
for (var i = 0; i < m; i++) {
var e = copyA.get(i, i);
// TODO:Complex
var e_abs = Math.abs(e);
var e_sign = e / e_abs;
sign_acc *= e_sign;
log_acc += Math.log(e_abs);
}
return [sign_acc, log_acc];
} | [
"function",
"slogdet",
"(",
"A",
")",
"{",
"if",
"(",
"A",
".",
"shape",
".",
"length",
"!==",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input is not matrix'",
")",
";",
"}",
"if",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
"!==",
"A",
".",
"shape",
"[",
"1",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input is not square matrix'",
")",
";",
"}",
"var",
"m",
"=",
"A",
".",
"shape",
"[",
"0",
"]",
";",
"var",
"copyA",
"=",
"A",
".",
"clone",
"(",
")",
";",
"copyA",
".",
"swapOrder",
"(",
")",
";",
"var",
"ipiv",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"m",
"]",
",",
"datatype",
":",
"'i32'",
"}",
")",
";",
"lapack",
".",
"getrf",
"(",
"copyA",
".",
"data",
",",
"m",
",",
"m",
",",
"ipiv",
".",
"data",
")",
";",
"copyA",
".",
"swapOrder",
"(",
")",
";",
"var",
"sign_acc",
"=",
"1",
";",
"var",
"log_acc",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"m",
";",
"i",
"++",
")",
"{",
"if",
"(",
"ipiv",
".",
"get",
"(",
"i",
")",
"!==",
"i",
"+",
"1",
")",
"{",
"sign_acc",
"=",
"-",
"sign_acc",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"m",
";",
"i",
"++",
")",
"{",
"var",
"e",
"=",
"copyA",
".",
"get",
"(",
"i",
",",
"i",
")",
";",
"var",
"e_abs",
"=",
"Math",
".",
"abs",
"(",
"e",
")",
";",
"var",
"e_sign",
"=",
"e",
"/",
"e_abs",
";",
"sign_acc",
"*=",
"e_sign",
";",
"log_acc",
"+=",
"Math",
".",
"log",
"(",
"e_abs",
")",
";",
"}",
"return",
"[",
"sign_acc",
",",
"log_acc",
"]",
";",
"}"
] | Compute sign and natural logarithm of the determinant of given Matrix
If an array has a very small or very large determinant, then a call to
`det` may overflow or underflow. This routine is more robust against such
issues, because it computes the logarithm of the determinant rather than
the determinant itself.
@param A Square matrix to compute sign and log-determinant of | [
"Compute",
"sign",
"and",
"natural",
"logarithm",
"of",
"the",
"determinant",
"of",
"given",
"Matrix",
"If",
"an",
"array",
"has",
"a",
"very",
"small",
"or",
"very",
"large",
"determinant",
"then",
"a",
"call",
"to",
"det",
"may",
"overflow",
"or",
"underflow",
".",
"This",
"routine",
"is",
"more",
"robust",
"against",
"such",
"issues",
"because",
"it",
"computes",
"the",
"logarithm",
"of",
"the",
"determinant",
"rather",
"than",
"the",
"determinant",
"itself",
"."
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L567-L602 | train |
bluemathsoft/bm-linalg | lib/ops.js | det | function det(A) {
var _a = slogdet(A), sign = _a[0], log = _a[1];
return sign * Math.exp(log);
} | javascript | function det(A) {
var _a = slogdet(A), sign = _a[0], log = _a[1];
return sign * Math.exp(log);
} | [
"function",
"det",
"(",
"A",
")",
"{",
"var",
"_a",
"=",
"slogdet",
"(",
"A",
")",
",",
"sign",
"=",
"_a",
"[",
"0",
"]",
",",
"log",
"=",
"_a",
"[",
"1",
"]",
";",
"return",
"sign",
"*",
"Math",
".",
"exp",
"(",
"log",
")",
";",
"}"
] | Compute determinant of a matrix
@param A Square matrix to compute determinant | [
"Compute",
"determinant",
"of",
"a",
"matrix"
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L608-L611 | train |
bluemathsoft/bm-linalg | lib/ops.js | tril | function tril(A, k) {
if (k === void 0) { k = 0; }
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
var copyA = A.clone();
for (var i = 0; i < copyA.shape[0]; i++) {
for (var j = 0; j < copyA.shape[1]; j++) {
if (i < j - k) {
copyA.set(i, j, 0);
}
}
}
return copyA;
} | javascript | function tril(A, k) {
if (k === void 0) { k = 0; }
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
var copyA = A.clone();
for (var i = 0; i < copyA.shape[0]; i++) {
for (var j = 0; j < copyA.shape[1]; j++) {
if (i < j - k) {
copyA.set(i, j, 0);
}
}
}
return copyA;
} | [
"function",
"tril",
"(",
"A",
",",
"k",
")",
"{",
"if",
"(",
"k",
"===",
"void",
"0",
")",
"{",
"k",
"=",
"0",
";",
"}",
"if",
"(",
"A",
".",
"shape",
".",
"length",
"!==",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input is not matrix'",
")",
";",
"}",
"var",
"copyA",
"=",
"A",
".",
"clone",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"copyA",
".",
"shape",
"[",
"0",
"]",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"copyA",
".",
"shape",
"[",
"1",
"]",
";",
"j",
"++",
")",
"{",
"if",
"(",
"i",
"<",
"j",
"-",
"k",
")",
"{",
"copyA",
".",
"set",
"(",
"i",
",",
"j",
",",
"0",
")",
";",
"}",
"}",
"}",
"return",
"copyA",
";",
"}"
] | Create Lower triangular matrix from given matrix | [
"Create",
"Lower",
"triangular",
"matrix",
"from",
"given",
"matrix"
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L636-L650 | train |
bluemathsoft/bm-linalg | lib/ops.js | qr | function qr(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
var _a = A.shape, m = _a[0], n = _a[1];
if (m === 0 || n === 0) {
throw new Error('Empty matrix');
}
var copyA = A.clone();
var minmn = Math.min(m, n);
copyA.swapOrder();
var tau = new common_1.NDArray({ shape: [minmn] });
lapack.geqrf(copyA.data, m, n, tau.data);
var r = copyA.clone();
r.swapOrder();
r = triu(r.get(':', ':' + minmn));
var q = copyA.get(':' + n);
lapack.orgqr(q.data, m, n, minmn, tau.data);
q.swapOrder();
return [q, r];
} | javascript | function qr(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
var _a = A.shape, m = _a[0], n = _a[1];
if (m === 0 || n === 0) {
throw new Error('Empty matrix');
}
var copyA = A.clone();
var minmn = Math.min(m, n);
copyA.swapOrder();
var tau = new common_1.NDArray({ shape: [minmn] });
lapack.geqrf(copyA.data, m, n, tau.data);
var r = copyA.clone();
r.swapOrder();
r = triu(r.get(':', ':' + minmn));
var q = copyA.get(':' + n);
lapack.orgqr(q.data, m, n, minmn, tau.data);
q.swapOrder();
return [q, r];
} | [
"function",
"qr",
"(",
"A",
")",
"{",
"if",
"(",
"A",
".",
"shape",
".",
"length",
"!==",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input is not matrix'",
")",
";",
"}",
"var",
"_a",
"=",
"A",
".",
"shape",
",",
"m",
"=",
"_a",
"[",
"0",
"]",
",",
"n",
"=",
"_a",
"[",
"1",
"]",
";",
"if",
"(",
"m",
"===",
"0",
"||",
"n",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Empty matrix'",
")",
";",
"}",
"var",
"copyA",
"=",
"A",
".",
"clone",
"(",
")",
";",
"var",
"minmn",
"=",
"Math",
".",
"min",
"(",
"m",
",",
"n",
")",
";",
"copyA",
".",
"swapOrder",
"(",
")",
";",
"var",
"tau",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"minmn",
"]",
"}",
")",
";",
"lapack",
".",
"geqrf",
"(",
"copyA",
".",
"data",
",",
"m",
",",
"n",
",",
"tau",
".",
"data",
")",
";",
"var",
"r",
"=",
"copyA",
".",
"clone",
"(",
")",
";",
"r",
".",
"swapOrder",
"(",
")",
";",
"r",
"=",
"triu",
"(",
"r",
".",
"get",
"(",
"':'",
",",
"':'",
"+",
"minmn",
")",
")",
";",
"var",
"q",
"=",
"copyA",
".",
"get",
"(",
"':'",
"+",
"n",
")",
";",
"lapack",
".",
"orgqr",
"(",
"q",
".",
"data",
",",
"m",
",",
"n",
",",
"minmn",
",",
"tau",
".",
"data",
")",
";",
"q",
".",
"swapOrder",
"(",
")",
";",
"return",
"[",
"q",
",",
"r",
"]",
";",
"}"
] | Compute QR decomposition of given Matrix | [
"Compute",
"QR",
"decomposition",
"of",
"given",
"Matrix"
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L674-L694 | train |
bluemathsoft/bm-linalg | lib/ops.js | eig | function eig(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var n = A.shape[0];
var copyA = A.clone();
copyA.swapOrder();
var _a = lapack.geev(copyA.data, n, true, true), WR = _a[0], WI = _a[1], VL = _a[2], VR = _a[3];
var eigval = new common_1.NDArray({ shape: [n] });
var eigvecL = new common_1.NDArray({ shape: [n, n] });
var eigvecR = new common_1.NDArray({ shape: [n, n] });
for (var i = 0; i < n; i++) {
if (common_1.iszero(WI[i])) {
eigval.set(i, WR[i]);
}
else {
eigval.set(i, new common_1.Complex(WR[i], WI[i]));
}
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n;) {
if (common_1.iszero(WI[j])) {
// We want to extract eigen-vectors in i'th column of VL and VR
eigvecL.set(i, j, VL[j * n + i]);
eigvecR.set(i, j, VR[j * n + i]);
j += 1;
}
else {
// i-th eigen vector will be complex and
// i+1-th eigen vector will be its conjugate
// There are n eigen-vectors for i'th eigen-value
eigvecL.set(i, j, new common_1.Complex(VL[j * n + i], VL[(j + 1) * n + i]));
eigvecL.set(i, j + 1, new common_1.Complex(VL[j * n + i], -VL[(j + 1) * n + i]));
eigvecR.set(i, j, new common_1.Complex(VR[j * n + i], VR[(j + 1) * n + i]));
eigvecR.set(i, j + 1, new common_1.Complex(VR[j * n + i], -VR[(j + 1) * n + i]));
j += 2;
}
}
}
return [eigval, eigvecL, eigvecR];
} | javascript | function eig(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var n = A.shape[0];
var copyA = A.clone();
copyA.swapOrder();
var _a = lapack.geev(copyA.data, n, true, true), WR = _a[0], WI = _a[1], VL = _a[2], VR = _a[3];
var eigval = new common_1.NDArray({ shape: [n] });
var eigvecL = new common_1.NDArray({ shape: [n, n] });
var eigvecR = new common_1.NDArray({ shape: [n, n] });
for (var i = 0; i < n; i++) {
if (common_1.iszero(WI[i])) {
eigval.set(i, WR[i]);
}
else {
eigval.set(i, new common_1.Complex(WR[i], WI[i]));
}
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n;) {
if (common_1.iszero(WI[j])) {
// We want to extract eigen-vectors in i'th column of VL and VR
eigvecL.set(i, j, VL[j * n + i]);
eigvecR.set(i, j, VR[j * n + i]);
j += 1;
}
else {
// i-th eigen vector will be complex and
// i+1-th eigen vector will be its conjugate
// There are n eigen-vectors for i'th eigen-value
eigvecL.set(i, j, new common_1.Complex(VL[j * n + i], VL[(j + 1) * n + i]));
eigvecL.set(i, j + 1, new common_1.Complex(VL[j * n + i], -VL[(j + 1) * n + i]));
eigvecR.set(i, j, new common_1.Complex(VR[j * n + i], VR[(j + 1) * n + i]));
eigvecR.set(i, j + 1, new common_1.Complex(VR[j * n + i], -VR[(j + 1) * n + i]));
j += 2;
}
}
}
return [eigval, eigvecL, eigvecR];
} | [
"function",
"eig",
"(",
"A",
")",
"{",
"if",
"(",
"A",
".",
"shape",
".",
"length",
"!==",
"2",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input is not matrix'",
")",
";",
"}",
"if",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
"!==",
"A",
".",
"shape",
"[",
"1",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Input is not square matrix'",
")",
";",
"}",
"var",
"n",
"=",
"A",
".",
"shape",
"[",
"0",
"]",
";",
"var",
"copyA",
"=",
"A",
".",
"clone",
"(",
")",
";",
"copyA",
".",
"swapOrder",
"(",
")",
";",
"var",
"_a",
"=",
"lapack",
".",
"geev",
"(",
"copyA",
".",
"data",
",",
"n",
",",
"true",
",",
"true",
")",
",",
"WR",
"=",
"_a",
"[",
"0",
"]",
",",
"WI",
"=",
"_a",
"[",
"1",
"]",
",",
"VL",
"=",
"_a",
"[",
"2",
"]",
",",
"VR",
"=",
"_a",
"[",
"3",
"]",
";",
"var",
"eigval",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"n",
"]",
"}",
")",
";",
"var",
"eigvecL",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"n",
",",
"n",
"]",
"}",
")",
";",
"var",
"eigvecR",
"=",
"new",
"common_1",
".",
"NDArray",
"(",
"{",
"shape",
":",
"[",
"n",
",",
"n",
"]",
"}",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"if",
"(",
"common_1",
".",
"iszero",
"(",
"WI",
"[",
"i",
"]",
")",
")",
"{",
"eigval",
".",
"set",
"(",
"i",
",",
"WR",
"[",
"i",
"]",
")",
";",
"}",
"else",
"{",
"eigval",
".",
"set",
"(",
"i",
",",
"new",
"common_1",
".",
"Complex",
"(",
"WR",
"[",
"i",
"]",
",",
"WI",
"[",
"i",
"]",
")",
")",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"n",
";",
")",
"{",
"if",
"(",
"common_1",
".",
"iszero",
"(",
"WI",
"[",
"j",
"]",
")",
")",
"{",
"eigvecL",
".",
"set",
"(",
"i",
",",
"j",
",",
"VL",
"[",
"j",
"*",
"n",
"+",
"i",
"]",
")",
";",
"eigvecR",
".",
"set",
"(",
"i",
",",
"j",
",",
"VR",
"[",
"j",
"*",
"n",
"+",
"i",
"]",
")",
";",
"j",
"+=",
"1",
";",
"}",
"else",
"{",
"eigvecL",
".",
"set",
"(",
"i",
",",
"j",
",",
"new",
"common_1",
".",
"Complex",
"(",
"VL",
"[",
"j",
"*",
"n",
"+",
"i",
"]",
",",
"VL",
"[",
"(",
"j",
"+",
"1",
")",
"*",
"n",
"+",
"i",
"]",
")",
")",
";",
"eigvecL",
".",
"set",
"(",
"i",
",",
"j",
"+",
"1",
",",
"new",
"common_1",
".",
"Complex",
"(",
"VL",
"[",
"j",
"*",
"n",
"+",
"i",
"]",
",",
"-",
"VL",
"[",
"(",
"j",
"+",
"1",
")",
"*",
"n",
"+",
"i",
"]",
")",
")",
";",
"eigvecR",
".",
"set",
"(",
"i",
",",
"j",
",",
"new",
"common_1",
".",
"Complex",
"(",
"VR",
"[",
"j",
"*",
"n",
"+",
"i",
"]",
",",
"VR",
"[",
"(",
"j",
"+",
"1",
")",
"*",
"n",
"+",
"i",
"]",
")",
")",
";",
"eigvecR",
".",
"set",
"(",
"i",
",",
"j",
"+",
"1",
",",
"new",
"common_1",
".",
"Complex",
"(",
"VR",
"[",
"j",
"*",
"n",
"+",
"i",
"]",
",",
"-",
"VR",
"[",
"(",
"j",
"+",
"1",
")",
"*",
"n",
"+",
"i",
"]",
")",
")",
";",
"j",
"+=",
"2",
";",
"}",
"}",
"}",
"return",
"[",
"eigval",
",",
"eigvecL",
",",
"eigvecR",
"]",
";",
"}"
] | Compute Eigen values and left, right eigen vectors of given Matrix | [
"Compute",
"Eigen",
"values",
"and",
"left",
"right",
"eigen",
"vectors",
"of",
"given",
"Matrix"
] | f4b96ec3f39480339898a587bf60b8aba0ad52bf | https://github.com/bluemathsoft/bm-linalg/blob/f4b96ec3f39480339898a587bf60b8aba0ad52bf/lib/ops.js#L699-L742 | train |
derek-duncan/postcss-responsify | index.js | processBreakpoint | function processBreakpoint(root, breakpointOption) {
if (breakpointOption && breakpointOption !== Object(breakpointOption)) {
throw new Error('Breakpoint must be of type Object.');
}
const processedBreakpoint = Object.assign({}, breakpointOption);
let atRule;
/* search current rules to see if one exists */
root.walkAtRules('media', rule => {
if (rule.params !== processedBreakpoint.mediaQuery) return;
atRule = rule;
});
/* if no rules exist, create a new one */
if (!atRule) {
atRule = postcss.atRule({
name: 'media',
params: processedBreakpoint.mediaQuery,
});
}
processedBreakpoint.atRule = atRule;
return processedBreakpoint;
} | javascript | function processBreakpoint(root, breakpointOption) {
if (breakpointOption && breakpointOption !== Object(breakpointOption)) {
throw new Error('Breakpoint must be of type Object.');
}
const processedBreakpoint = Object.assign({}, breakpointOption);
let atRule;
/* search current rules to see if one exists */
root.walkAtRules('media', rule => {
if (rule.params !== processedBreakpoint.mediaQuery) return;
atRule = rule;
});
/* if no rules exist, create a new one */
if (!atRule) {
atRule = postcss.atRule({
name: 'media',
params: processedBreakpoint.mediaQuery,
});
}
processedBreakpoint.atRule = atRule;
return processedBreakpoint;
} | [
"function",
"processBreakpoint",
"(",
"root",
",",
"breakpointOption",
")",
"{",
"if",
"(",
"breakpointOption",
"&&",
"breakpointOption",
"!==",
"Object",
"(",
"breakpointOption",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Breakpoint must be of type Object.'",
")",
";",
"}",
"const",
"processedBreakpoint",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"breakpointOption",
")",
";",
"let",
"atRule",
";",
"root",
".",
"walkAtRules",
"(",
"'media'",
",",
"rule",
"=>",
"{",
"if",
"(",
"rule",
".",
"params",
"!==",
"processedBreakpoint",
".",
"mediaQuery",
")",
"return",
";",
"atRule",
"=",
"rule",
";",
"}",
")",
";",
"if",
"(",
"!",
"atRule",
")",
"{",
"atRule",
"=",
"postcss",
".",
"atRule",
"(",
"{",
"name",
":",
"'media'",
",",
"params",
":",
"processedBreakpoint",
".",
"mediaQuery",
",",
"}",
")",
";",
"}",
"processedBreakpoint",
".",
"atRule",
"=",
"atRule",
";",
"return",
"processedBreakpoint",
";",
"}"
] | Processes a breakpoint option by creating a PostCSS @media atRule from the options
@param {Object} root Root postcss node
@param {Object} breakpointOption
@param {String} breakpointOption.name
@param {String} breakpointOption.mediaQuery
@return {Object} Processed breakpoint option | [
"Processes",
"a",
"breakpoint",
"option",
"by",
"creating",
"a",
"PostCSS"
] | 2e6a36386892d9c258986fdcd83401c2b3443593 | https://github.com/derek-duncan/postcss-responsify/blob/2e6a36386892d9c258986fdcd83401c2b3443593/index.js#L23-L47 | train |
derek-duncan/postcss-responsify | index.js | processBreakpoints | function processBreakpoints(root, breakpointsOption) {
if (breakpointsOption && !Array.isArray(breakpointsOption)) {
throw new Error('Breakpoints option must be of type Array.');
}
const defaultBreakpoints = [
{
prefix: 'xs-',
mediaQuery: '(max-width: 40em)',
},
{
prefix: 'sm-',
mediaQuery: '(min-width: 40em)',
},
{
prefix: 'md-',
mediaQuery: '(min-width: 52em)',
},
{
prefix: 'lg-',
mediaQuery: '(min-width: 64em)',
},
];
const mergedBreakpoints = merge([], defaultBreakpoints, breakpointsOption);
return mergedBreakpoints.map((breakpoint) => processBreakpoint(root, breakpoint));
} | javascript | function processBreakpoints(root, breakpointsOption) {
if (breakpointsOption && !Array.isArray(breakpointsOption)) {
throw new Error('Breakpoints option must be of type Array.');
}
const defaultBreakpoints = [
{
prefix: 'xs-',
mediaQuery: '(max-width: 40em)',
},
{
prefix: 'sm-',
mediaQuery: '(min-width: 40em)',
},
{
prefix: 'md-',
mediaQuery: '(min-width: 52em)',
},
{
prefix: 'lg-',
mediaQuery: '(min-width: 64em)',
},
];
const mergedBreakpoints = merge([], defaultBreakpoints, breakpointsOption);
return mergedBreakpoints.map((breakpoint) => processBreakpoint(root, breakpoint));
} | [
"function",
"processBreakpoints",
"(",
"root",
",",
"breakpointsOption",
")",
"{",
"if",
"(",
"breakpointsOption",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"breakpointsOption",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Breakpoints option must be of type Array.'",
")",
";",
"}",
"const",
"defaultBreakpoints",
"=",
"[",
"{",
"prefix",
":",
"'xs-'",
",",
"mediaQuery",
":",
"'(max-width: 40em)'",
",",
"}",
",",
"{",
"prefix",
":",
"'sm-'",
",",
"mediaQuery",
":",
"'(min-width: 40em)'",
",",
"}",
",",
"{",
"prefix",
":",
"'md-'",
",",
"mediaQuery",
":",
"'(min-width: 52em)'",
",",
"}",
",",
"{",
"prefix",
":",
"'lg-'",
",",
"mediaQuery",
":",
"'(min-width: 64em)'",
",",
"}",
",",
"]",
";",
"const",
"mergedBreakpoints",
"=",
"merge",
"(",
"[",
"]",
",",
"defaultBreakpoints",
",",
"breakpointsOption",
")",
";",
"return",
"mergedBreakpoints",
".",
"map",
"(",
"(",
"breakpoint",
")",
"=>",
"processBreakpoint",
"(",
"root",
",",
"breakpoint",
")",
")",
";",
"}"
] | Provides defaults for the breakpoints options and processes each one
@param {Object} root Root postcss node
@param {Array} breakpointsOption Array of breakpoint objects
@return {Array} Processed breakpoints option | [
"Provides",
"defaults",
"for",
"the",
"breakpoints",
"options",
"and",
"processes",
"each",
"one"
] | 2e6a36386892d9c258986fdcd83401c2b3443593 | https://github.com/derek-duncan/postcss-responsify/blob/2e6a36386892d9c258986fdcd83401c2b3443593/index.js#L55-L81 | train |
derek-duncan/postcss-responsify | index.js | createPrefixedRule | function createPrefixedRule(rule, prefix) {
const prefixLength = prefix.length;
const selectorStart = rule.selector.slice(1, prefixLength + 1);
const isAlreadyPrefixed = selectorStart === prefix;
if (isAlreadyPrefixed) return false;
return rule.clone({
selector: `.${prefix + rule.selector.substring(1)}`,
});
} | javascript | function createPrefixedRule(rule, prefix) {
const prefixLength = prefix.length;
const selectorStart = rule.selector.slice(1, prefixLength + 1);
const isAlreadyPrefixed = selectorStart === prefix;
if (isAlreadyPrefixed) return false;
return rule.clone({
selector: `.${prefix + rule.selector.substring(1)}`,
});
} | [
"function",
"createPrefixedRule",
"(",
"rule",
",",
"prefix",
")",
"{",
"const",
"prefixLength",
"=",
"prefix",
".",
"length",
";",
"const",
"selectorStart",
"=",
"rule",
".",
"selector",
".",
"slice",
"(",
"1",
",",
"prefixLength",
"+",
"1",
")",
";",
"const",
"isAlreadyPrefixed",
"=",
"selectorStart",
"===",
"prefix",
";",
"if",
"(",
"isAlreadyPrefixed",
")",
"return",
"false",
";",
"return",
"rule",
".",
"clone",
"(",
"{",
"selector",
":",
"`",
"${",
"prefix",
"+",
"rule",
".",
"selector",
".",
"substring",
"(",
"1",
")",
"}",
"`",
",",
"}",
")",
";",
"}"
] | Creates a PostCSS rule based on breakpoint options
@param {Object} rule PostCSS rule to duplicate
@param {Object} prefix Prefix for selector
@return {Object} Responsified PostCSS rule | [
"Creates",
"a",
"PostCSS",
"rule",
"based",
"on",
"breakpoint",
"options"
] | 2e6a36386892d9c258986fdcd83401c2b3443593 | https://github.com/derek-duncan/postcss-responsify/blob/2e6a36386892d9c258986fdcd83401c2b3443593/index.js#L89-L98 | train |
derek-duncan/postcss-responsify | index.js | responsifyRule | function responsifyRule(breakpoints) {
/**
* Closure function that handles each @responsive sub rule
* @param {Object} rule
*/
return (rule) => {
/* insert the base rule right before the @responsive rule */
const root = rule.parent.parent;
const clone = rule.clone();
root.insertBefore(rule.parent, clone);
const isValidSelector = rule.selector.charAt(0) === '.';
if (!isValidSelector) return; /* equivilent to continue; */
/* insert each responsive rule in its breakpoint's atRule */
breakpoints.forEach((breakpoint) => {
const responsiveRule = createPrefixedRule(rule, breakpoint.prefix);
if (responsiveRule) {
breakpoint.atRule.append(responsiveRule);
}
});
};
} | javascript | function responsifyRule(breakpoints) {
/**
* Closure function that handles each @responsive sub rule
* @param {Object} rule
*/
return (rule) => {
/* insert the base rule right before the @responsive rule */
const root = rule.parent.parent;
const clone = rule.clone();
root.insertBefore(rule.parent, clone);
const isValidSelector = rule.selector.charAt(0) === '.';
if (!isValidSelector) return; /* equivilent to continue; */
/* insert each responsive rule in its breakpoint's atRule */
breakpoints.forEach((breakpoint) => {
const responsiveRule = createPrefixedRule(rule, breakpoint.prefix);
if (responsiveRule) {
breakpoint.atRule.append(responsiveRule);
}
});
};
} | [
"function",
"responsifyRule",
"(",
"breakpoints",
")",
"{",
"return",
"(",
"rule",
")",
"=>",
"{",
"const",
"root",
"=",
"rule",
".",
"parent",
".",
"parent",
";",
"const",
"clone",
"=",
"rule",
".",
"clone",
"(",
")",
";",
"root",
".",
"insertBefore",
"(",
"rule",
".",
"parent",
",",
"clone",
")",
";",
"const",
"isValidSelector",
"=",
"rule",
".",
"selector",
".",
"charAt",
"(",
"0",
")",
"===",
"'.'",
";",
"if",
"(",
"!",
"isValidSelector",
")",
"return",
";",
"breakpoints",
".",
"forEach",
"(",
"(",
"breakpoint",
")",
"=>",
"{",
"const",
"responsiveRule",
"=",
"createPrefixedRule",
"(",
"rule",
",",
"breakpoint",
".",
"prefix",
")",
";",
"if",
"(",
"responsiveRule",
")",
"{",
"breakpoint",
".",
"atRule",
".",
"append",
"(",
"responsiveRule",
")",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
] | Build a new PostCSS rule for every responsive state
@param {Array} breakpoints The processed breakpoints the build the rules off of
@return {Function} | [
"Build",
"a",
"new",
"PostCSS",
"rule",
"for",
"every",
"responsive",
"state"
] | 2e6a36386892d9c258986fdcd83401c2b3443593 | https://github.com/derek-duncan/postcss-responsify/blob/2e6a36386892d9c258986fdcd83401c2b3443593/index.js#L105-L127 | train |
derek-duncan/postcss-responsify | index.js | loopResponsiveRules | function loopResponsiveRules(breakpoints) {
/**
* Closure function that handles each @responsive atRule
* @param {Object} rule
*/
return (rule) => {
const subRules = rule.nodes;
subRules.forEach(responsifyRule(breakpoints));
/* remove the @responsive structure since we've built the responsive rules we need */
rule.remove();
};
} | javascript | function loopResponsiveRules(breakpoints) {
/**
* Closure function that handles each @responsive atRule
* @param {Object} rule
*/
return (rule) => {
const subRules = rule.nodes;
subRules.forEach(responsifyRule(breakpoints));
/* remove the @responsive structure since we've built the responsive rules we need */
rule.remove();
};
} | [
"function",
"loopResponsiveRules",
"(",
"breakpoints",
")",
"{",
"return",
"(",
"rule",
")",
"=>",
"{",
"const",
"subRules",
"=",
"rule",
".",
"nodes",
";",
"subRules",
".",
"forEach",
"(",
"responsifyRule",
"(",
"breakpoints",
")",
")",
";",
"rule",
".",
"remove",
"(",
")",
";",
"}",
";",
"}"
] | Loops through all @responsive atRules in the css to find the rules that need to be responsified.
@param {Array} breakpoints The processed breakpoints to build the rules off of
@return {Function} | [
"Loops",
"through",
"all"
] | 2e6a36386892d9c258986fdcd83401c2b3443593 | https://github.com/derek-duncan/postcss-responsify/blob/2e6a36386892d9c258986fdcd83401c2b3443593/index.js#L134-L145 | train |
peerigon/alamid-schema | lib/processDefinition.js | processDefinition | function processDefinition(definition) {
var fields = [];
var types = {};
var key;
var fieldDefinition;
var type;
for (key in definition) {
if (definition.hasOwnProperty(key)) {
fields.push(key);
fieldDefinition = definition[key];
type = determineType(fieldDefinition);
// Normalize the type definition
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].type = type;
} else {
definition[key] = {
type: type
};
}
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].writable = fieldDefinition.hasOwnProperty("writable") ? fieldDefinition.writable : true;
} else {
definition[key].writable = true;
}
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].readable = fieldDefinition.hasOwnProperty("readable") ? fieldDefinition.readable : true;
} else {
definition[key].readable = true;
}
types[key] = type;
}
}
return {
fields: fields,
types: types
};
} | javascript | function processDefinition(definition) {
var fields = [];
var types = {};
var key;
var fieldDefinition;
var type;
for (key in definition) {
if (definition.hasOwnProperty(key)) {
fields.push(key);
fieldDefinition = definition[key];
type = determineType(fieldDefinition);
// Normalize the type definition
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].type = type;
} else {
definition[key] = {
type: type
};
}
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].writable = fieldDefinition.hasOwnProperty("writable") ? fieldDefinition.writable : true;
} else {
definition[key].writable = true;
}
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].readable = fieldDefinition.hasOwnProperty("readable") ? fieldDefinition.readable : true;
} else {
definition[key].readable = true;
}
types[key] = type;
}
}
return {
fields: fields,
types: types
};
} | [
"function",
"processDefinition",
"(",
"definition",
")",
"{",
"var",
"fields",
"=",
"[",
"]",
";",
"var",
"types",
"=",
"{",
"}",
";",
"var",
"key",
";",
"var",
"fieldDefinition",
";",
"var",
"type",
";",
"for",
"(",
"key",
"in",
"definition",
")",
"{",
"if",
"(",
"definition",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"fields",
".",
"push",
"(",
"key",
")",
";",
"fieldDefinition",
"=",
"definition",
"[",
"key",
"]",
";",
"type",
"=",
"determineType",
"(",
"fieldDefinition",
")",
";",
"if",
"(",
"value",
"(",
"fieldDefinition",
")",
".",
"getConstructor",
"(",
")",
"===",
"Object",
")",
"{",
"definition",
"[",
"key",
"]",
".",
"type",
"=",
"type",
";",
"}",
"else",
"{",
"definition",
"[",
"key",
"]",
"=",
"{",
"type",
":",
"type",
"}",
";",
"}",
"if",
"(",
"value",
"(",
"fieldDefinition",
")",
".",
"getConstructor",
"(",
")",
"===",
"Object",
")",
"{",
"definition",
"[",
"key",
"]",
".",
"writable",
"=",
"fieldDefinition",
".",
"hasOwnProperty",
"(",
"\"writable\"",
")",
"?",
"fieldDefinition",
".",
"writable",
":",
"true",
";",
"}",
"else",
"{",
"definition",
"[",
"key",
"]",
".",
"writable",
"=",
"true",
";",
"}",
"if",
"(",
"value",
"(",
"fieldDefinition",
")",
".",
"getConstructor",
"(",
")",
"===",
"Object",
")",
"{",
"definition",
"[",
"key",
"]",
".",
"readable",
"=",
"fieldDefinition",
".",
"hasOwnProperty",
"(",
"\"readable\"",
")",
"?",
"fieldDefinition",
".",
"readable",
":",
"true",
";",
"}",
"else",
"{",
"definition",
"[",
"key",
"]",
".",
"readable",
"=",
"true",
";",
"}",
"types",
"[",
"key",
"]",
"=",
"type",
";",
"}",
"}",
"return",
"{",
"fields",
":",
"fields",
",",
"types",
":",
"types",
"}",
";",
"}"
] | Normalizes the schema definition and extracts fields and types.
@param {Object} definition
@returns {Object} | [
"Normalizes",
"the",
"schema",
"definition",
"and",
"extracts",
"fields",
"and",
"types",
"."
] | 7faa6e826f485b33ccc2e41b86b5861c61184a3c | https://github.com/peerigon/alamid-schema/blob/7faa6e826f485b33ccc2e41b86b5861c61184a3c/lib/processDefinition.js#L12-L55 | train |
bustardcelly/grunt-forever | tasks/forever-task.js | findProcessWithIndex | function findProcessWithIndex( index, callback ) {
var i, process;
try {
forever.list(false, function(context, list) {
i = list ? list.length : 0;
while( --i > -1 ) {
process = list[i];
if( process.hasOwnProperty('file') &&
process.file === index ) {
break;
}
process = undefined;
}
callback.call(null, process);
});
}
catch( e ) {
error( 'Error in trying to find process ' + index + ' in forever. [REASON] :: ' + e.message );
callback.call(null, undefined);
}
} | javascript | function findProcessWithIndex( index, callback ) {
var i, process;
try {
forever.list(false, function(context, list) {
i = list ? list.length : 0;
while( --i > -1 ) {
process = list[i];
if( process.hasOwnProperty('file') &&
process.file === index ) {
break;
}
process = undefined;
}
callback.call(null, process);
});
}
catch( e ) {
error( 'Error in trying to find process ' + index + ' in forever. [REASON] :: ' + e.message );
callback.call(null, undefined);
}
} | [
"function",
"findProcessWithIndex",
"(",
"index",
",",
"callback",
")",
"{",
"var",
"i",
",",
"process",
";",
"try",
"{",
"forever",
".",
"list",
"(",
"false",
",",
"function",
"(",
"context",
",",
"list",
")",
"{",
"i",
"=",
"list",
"?",
"list",
".",
"length",
":",
"0",
";",
"while",
"(",
"--",
"i",
">",
"-",
"1",
")",
"{",
"process",
"=",
"list",
"[",
"i",
"]",
";",
"if",
"(",
"process",
".",
"hasOwnProperty",
"(",
"'file'",
")",
"&&",
"process",
".",
"file",
"===",
"index",
")",
"{",
"break",
";",
"}",
"process",
"=",
"undefined",
";",
"}",
"callback",
".",
"call",
"(",
"null",
",",
"process",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"error",
"(",
"'Error in trying to find process '",
"+",
"index",
"+",
"' in forever. [REASON] :: '",
"+",
"e",
".",
"message",
")",
";",
"callback",
".",
"call",
"(",
"null",
",",
"undefined",
")",
";",
"}",
"}"
] | Locates running process previously started by forever based on index file, and notifies callback. Will notify of undefined if not found, other wise the unformatted process object.
@param {String} index Index filename.
@param {Function} callback Delegate method to invoke with either the found process object or undefined if not found. | [
"Locates",
"running",
"process",
"previously",
"started",
"by",
"forever",
"based",
"on",
"index",
"file",
"and",
"notifies",
"callback",
".",
"Will",
"notify",
"of",
"undefined",
"if",
"not",
"found",
"other",
"wise",
"the",
"unformatted",
"process",
"object",
"."
] | ae91c2fa95229399b51c8bbd1d25ba9552d9669c | https://github.com/bustardcelly/grunt-forever/blob/ae91c2fa95229399b51c8bbd1d25ba9552d9669c/tasks/forever-task.js#L50-L70 | train |
bustardcelly/grunt-forever | tasks/forever-task.js | startForeverWithIndex | function startForeverWithIndex( index, doneCB ) {
log( 'Attempting to start ' + index + ' as daemon.');
var config;
var appendConfig = function(prop, value) {
log('Adding to config: ' + prop + ', ' + value);
if(value !== undefined) {
config[prop] = value;
}
};
done = doneCB || this.async();
findProcessWithIndex( index, function(process) {
// if found, be on our way without failing.
if( typeof process !== 'undefined' ) {
warn( index + ' is already running.');
log( forever.format(true, [process]) );
done();
}
else {
gruntRef.file.mkdir(logDir);
// 'forever start -o out.log -e err.log -c node -a -m 3 index.js';
config = {
command: commandName,
append: true,
max: 3,
killSignal: killSignal
};
appendConfig('errFile', errFile);
appendConfig('outFile', outFile);
appendConfig('logFile', logFile);
forever.startDaemon( index, config );
log( 'Logs can be found at ' + logDir + '.' );
done();
}
});
} | javascript | function startForeverWithIndex( index, doneCB ) {
log( 'Attempting to start ' + index + ' as daemon.');
var config;
var appendConfig = function(prop, value) {
log('Adding to config: ' + prop + ', ' + value);
if(value !== undefined) {
config[prop] = value;
}
};
done = doneCB || this.async();
findProcessWithIndex( index, function(process) {
// if found, be on our way without failing.
if( typeof process !== 'undefined' ) {
warn( index + ' is already running.');
log( forever.format(true, [process]) );
done();
}
else {
gruntRef.file.mkdir(logDir);
// 'forever start -o out.log -e err.log -c node -a -m 3 index.js';
config = {
command: commandName,
append: true,
max: 3,
killSignal: killSignal
};
appendConfig('errFile', errFile);
appendConfig('outFile', outFile);
appendConfig('logFile', logFile);
forever.startDaemon( index, config );
log( 'Logs can be found at ' + logDir + '.' );
done();
}
});
} | [
"function",
"startForeverWithIndex",
"(",
"index",
",",
"doneCB",
")",
"{",
"log",
"(",
"'Attempting to start '",
"+",
"index",
"+",
"' as daemon.'",
")",
";",
"var",
"config",
";",
"var",
"appendConfig",
"=",
"function",
"(",
"prop",
",",
"value",
")",
"{",
"log",
"(",
"'Adding to config: '",
"+",
"prop",
"+",
"', '",
"+",
"value",
")",
";",
"if",
"(",
"value",
"!==",
"undefined",
")",
"{",
"config",
"[",
"prop",
"]",
"=",
"value",
";",
"}",
"}",
";",
"done",
"=",
"doneCB",
"||",
"this",
".",
"async",
"(",
")",
";",
"findProcessWithIndex",
"(",
"index",
",",
"function",
"(",
"process",
")",
"{",
"if",
"(",
"typeof",
"process",
"!==",
"'undefined'",
")",
"{",
"warn",
"(",
"index",
"+",
"' is already running.'",
")",
";",
"log",
"(",
"forever",
".",
"format",
"(",
"true",
",",
"[",
"process",
"]",
")",
")",
";",
"done",
"(",
")",
";",
"}",
"else",
"{",
"gruntRef",
".",
"file",
".",
"mkdir",
"(",
"logDir",
")",
";",
"config",
"=",
"{",
"command",
":",
"commandName",
",",
"append",
":",
"true",
",",
"max",
":",
"3",
",",
"killSignal",
":",
"killSignal",
"}",
";",
"appendConfig",
"(",
"'errFile'",
",",
"errFile",
")",
";",
"appendConfig",
"(",
"'outFile'",
",",
"outFile",
")",
";",
"appendConfig",
"(",
"'logFile'",
",",
"logFile",
")",
";",
"forever",
".",
"startDaemon",
"(",
"index",
",",
"config",
")",
";",
"log",
"(",
"'Logs can be found at '",
"+",
"logDir",
"+",
"'.'",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Attempts to start process using the index file.
@param {String} index Filename. | [
"Attempts",
"to",
"start",
"process",
"using",
"the",
"index",
"file",
"."
] | ae91c2fa95229399b51c8bbd1d25ba9552d9669c | https://github.com/bustardcelly/grunt-forever/blob/ae91c2fa95229399b51c8bbd1d25ba9552d9669c/tasks/forever-task.js#L75-L110 | train |
bustardcelly/grunt-forever | tasks/forever-task.js | stopOnProcess | function stopOnProcess(index) {
log( 'Attempting to stop ' + index + '...' );
done = this.async();
findProcessWithIndex( index, function(process) {
if( typeof process !== 'undefined' ) {
log( forever.format(true,[process]) );
forever.stop( index )
.on('stop', function() {
done();
})
.on('error', function(message) {
error( 'Error stopping ' + index + '. [REASON] :: ' + message );
done(false);
});
}
else {
gruntRef.warn( index + ' not found in list of processes in forever.' );
done();
}
});
} | javascript | function stopOnProcess(index) {
log( 'Attempting to stop ' + index + '...' );
done = this.async();
findProcessWithIndex( index, function(process) {
if( typeof process !== 'undefined' ) {
log( forever.format(true,[process]) );
forever.stop( index )
.on('stop', function() {
done();
})
.on('error', function(message) {
error( 'Error stopping ' + index + '. [REASON] :: ' + message );
done(false);
});
}
else {
gruntRef.warn( index + ' not found in list of processes in forever.' );
done();
}
});
} | [
"function",
"stopOnProcess",
"(",
"index",
")",
"{",
"log",
"(",
"'Attempting to stop '",
"+",
"index",
"+",
"'...'",
")",
";",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"findProcessWithIndex",
"(",
"index",
",",
"function",
"(",
"process",
")",
"{",
"if",
"(",
"typeof",
"process",
"!==",
"'undefined'",
")",
"{",
"log",
"(",
"forever",
".",
"format",
"(",
"true",
",",
"[",
"process",
"]",
")",
")",
";",
"forever",
".",
"stop",
"(",
"index",
")",
".",
"on",
"(",
"'stop'",
",",
"function",
"(",
")",
"{",
"done",
"(",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"message",
")",
"{",
"error",
"(",
"'Error stopping '",
"+",
"index",
"+",
"'. [REASON] :: '",
"+",
"message",
")",
";",
"done",
"(",
"false",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"gruntRef",
".",
"warn",
"(",
"index",
"+",
"' not found in list of processes in forever.'",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Attempts to stop a process previously started associated with index.
@param {String} index Filename associated with previously started process. | [
"Attempts",
"to",
"stop",
"a",
"process",
"previously",
"started",
"associated",
"with",
"index",
"."
] | ae91c2fa95229399b51c8bbd1d25ba9552d9669c | https://github.com/bustardcelly/grunt-forever/blob/ae91c2fa95229399b51c8bbd1d25ba9552d9669c/tasks/forever-task.js#L115-L137 | train |
bustardcelly/grunt-forever | tasks/forever-task.js | restartOnProcess | function restartOnProcess( index ) {
log( 'Attempting to restart ' + index + '...' );
// generate delegate function to pass with proper contexts.
var startRequest = (function(context, index) {
return function(cb) {
startForeverWithIndex.call(context, index, cb);
};
}(this, index));
done = this.async();
findProcessWithIndex( index, function(process) {
if(typeof process !== 'undefined') {
log(forever.format(true,[process]));
forever.restart(index, false);
done();
}
else {
log(index + ' not found in list of processes in forever. Starting new instance...');
startRequest(done);
}
});
} | javascript | function restartOnProcess( index ) {
log( 'Attempting to restart ' + index + '...' );
// generate delegate function to pass with proper contexts.
var startRequest = (function(context, index) {
return function(cb) {
startForeverWithIndex.call(context, index, cb);
};
}(this, index));
done = this.async();
findProcessWithIndex( index, function(process) {
if(typeof process !== 'undefined') {
log(forever.format(true,[process]));
forever.restart(index, false);
done();
}
else {
log(index + ' not found in list of processes in forever. Starting new instance...');
startRequest(done);
}
});
} | [
"function",
"restartOnProcess",
"(",
"index",
")",
"{",
"log",
"(",
"'Attempting to restart '",
"+",
"index",
"+",
"'...'",
")",
";",
"var",
"startRequest",
"=",
"(",
"function",
"(",
"context",
",",
"index",
")",
"{",
"return",
"function",
"(",
"cb",
")",
"{",
"startForeverWithIndex",
".",
"call",
"(",
"context",
",",
"index",
",",
"cb",
")",
";",
"}",
";",
"}",
"(",
"this",
",",
"index",
")",
")",
";",
"done",
"=",
"this",
".",
"async",
"(",
")",
";",
"findProcessWithIndex",
"(",
"index",
",",
"function",
"(",
"process",
")",
"{",
"if",
"(",
"typeof",
"process",
"!==",
"'undefined'",
")",
"{",
"log",
"(",
"forever",
".",
"format",
"(",
"true",
",",
"[",
"process",
"]",
")",
")",
";",
"forever",
".",
"restart",
"(",
"index",
",",
"false",
")",
";",
"done",
"(",
")",
";",
"}",
"else",
"{",
"log",
"(",
"index",
"+",
"' not found in list of processes in forever. Starting new instance...'",
")",
";",
"startRequest",
"(",
"done",
")",
";",
"}",
"}",
")",
";",
"}"
] | Attempts to stop and restart a process previously started associated with index. If no process found as previously started, just starts a new one.
@param {String} index Filename associated with previously started process. | [
"Attempts",
"to",
"stop",
"and",
"restart",
"a",
"process",
"previously",
"started",
"associated",
"with",
"index",
".",
"If",
"no",
"process",
"found",
"as",
"previously",
"started",
"just",
"starts",
"a",
"new",
"one",
"."
] | ae91c2fa95229399b51c8bbd1d25ba9552d9669c | https://github.com/bustardcelly/grunt-forever/blob/ae91c2fa95229399b51c8bbd1d25ba9552d9669c/tasks/forever-task.js#L142-L164 | train |
atomantic/undermore | libs/es6-shim.js | function(target, source) {
if (!ES.TypeIsObject(target)) {
throw new TypeError('target must be an object');
}
return Array.prototype.reduce.call(arguments, function(target, source) {
if (!ES.TypeIsObject(source)) {
throw new TypeError('source must be an object');
}
return Object.keys(source).reduce(function(target, key) {
target[key] = source[key];
return target;
}, target);
});
} | javascript | function(target, source) {
if (!ES.TypeIsObject(target)) {
throw new TypeError('target must be an object');
}
return Array.prototype.reduce.call(arguments, function(target, source) {
if (!ES.TypeIsObject(source)) {
throw new TypeError('source must be an object');
}
return Object.keys(source).reduce(function(target, key) {
target[key] = source[key];
return target;
}, target);
});
} | [
"function",
"(",
"target",
",",
"source",
")",
"{",
"if",
"(",
"!",
"ES",
".",
"TypeIsObject",
"(",
"target",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'target must be an object'",
")",
";",
"}",
"return",
"Array",
".",
"prototype",
".",
"reduce",
".",
"call",
"(",
"arguments",
",",
"function",
"(",
"target",
",",
"source",
")",
"{",
"if",
"(",
"!",
"ES",
".",
"TypeIsObject",
"(",
"source",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'source must be an object'",
")",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"source",
")",
".",
"reduce",
"(",
"function",
"(",
"target",
",",
"key",
")",
"{",
"target",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"return",
"target",
";",
"}",
",",
"target",
")",
";",
"}",
")",
";",
"}"
] | 19.1.3.1 | [
"19",
".",
"1",
".",
"3",
".",
"1"
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/es6-shim.js#L783-L796 | train |
|
atomantic/undermore | libs/es6-shim.js | function(C) {
if (!ES.IsCallable(C)) {
throw new TypeError('bad promise constructor');
}
var capability = this;
var resolver = function(resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
};
capability.promise = ES.Construct(C, [resolver]);
// see https://bugs.ecmascript.org/show_bug.cgi?id=2478
if (!capability.promise._es6construct) {
throw new TypeError('bad promise constructor');
}
if (!(ES.IsCallable(capability.resolve) &&
ES.IsCallable(capability.reject))) {
throw new TypeError('bad promise constructor');
}
} | javascript | function(C) {
if (!ES.IsCallable(C)) {
throw new TypeError('bad promise constructor');
}
var capability = this;
var resolver = function(resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
};
capability.promise = ES.Construct(C, [resolver]);
// see https://bugs.ecmascript.org/show_bug.cgi?id=2478
if (!capability.promise._es6construct) {
throw new TypeError('bad promise constructor');
}
if (!(ES.IsCallable(capability.resolve) &&
ES.IsCallable(capability.reject))) {
throw new TypeError('bad promise constructor');
}
} | [
"function",
"(",
"C",
")",
"{",
"if",
"(",
"!",
"ES",
".",
"IsCallable",
"(",
"C",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'bad promise constructor'",
")",
";",
"}",
"var",
"capability",
"=",
"this",
";",
"var",
"resolver",
"=",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"capability",
".",
"resolve",
"=",
"resolve",
";",
"capability",
".",
"reject",
"=",
"reject",
";",
"}",
";",
"capability",
".",
"promise",
"=",
"ES",
".",
"Construct",
"(",
"C",
",",
"[",
"resolver",
"]",
")",
";",
"if",
"(",
"!",
"capability",
".",
"promise",
".",
"_es6construct",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'bad promise constructor'",
")",
";",
"}",
"if",
"(",
"!",
"(",
"ES",
".",
"IsCallable",
"(",
"capability",
".",
"resolve",
")",
"&&",
"ES",
".",
"IsCallable",
"(",
"capability",
".",
"reject",
")",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'bad promise constructor'",
")",
";",
"}",
"}"
] | "PromiseCapability" in the spec is what most promise implementations call a "deferred". | [
"PromiseCapability",
"in",
"the",
"spec",
"is",
"what",
"most",
"promise",
"implementations",
"call",
"a",
"deferred",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/es6-shim.js#L1091-L1109 | train |
|
atomantic/undermore | libs/es6-shim.js | Set | function Set() {
var set = this;
set = emulateES6construct(set);
if (!set._es6set) {
throw new TypeError('bad set');
}
defineProperties(set, {
'[[SetData]]': null,
'_storage': emptyObject()
});
// Optionally initialize map from iterable
var iterable = arguments[0];
if (iterable !== undefined && iterable !== null) {
var it = ES.GetIterator(iterable);
var adder = set.add;
if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }
while (true) {
var next = ES.IteratorNext(it);
if (next.done) { break; }
var nextItem = next.value;
adder.call(set, nextItem);
}
}
return set;
} | javascript | function Set() {
var set = this;
set = emulateES6construct(set);
if (!set._es6set) {
throw new TypeError('bad set');
}
defineProperties(set, {
'[[SetData]]': null,
'_storage': emptyObject()
});
// Optionally initialize map from iterable
var iterable = arguments[0];
if (iterable !== undefined && iterable !== null) {
var it = ES.GetIterator(iterable);
var adder = set.add;
if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }
while (true) {
var next = ES.IteratorNext(it);
if (next.done) { break; }
var nextItem = next.value;
adder.call(set, nextItem);
}
}
return set;
} | [
"function",
"Set",
"(",
")",
"{",
"var",
"set",
"=",
"this",
";",
"set",
"=",
"emulateES6construct",
"(",
"set",
")",
";",
"if",
"(",
"!",
"set",
".",
"_es6set",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'bad set'",
")",
";",
"}",
"defineProperties",
"(",
"set",
",",
"{",
"'[[SetData]]'",
":",
"null",
",",
"'_storage'",
":",
"emptyObject",
"(",
")",
"}",
")",
";",
"var",
"iterable",
"=",
"arguments",
"[",
"0",
"]",
";",
"if",
"(",
"iterable",
"!==",
"undefined",
"&&",
"iterable",
"!==",
"null",
")",
"{",
"var",
"it",
"=",
"ES",
".",
"GetIterator",
"(",
"iterable",
")",
";",
"var",
"adder",
"=",
"set",
".",
"add",
";",
"if",
"(",
"!",
"ES",
".",
"IsCallable",
"(",
"adder",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'bad set'",
")",
";",
"}",
"while",
"(",
"true",
")",
"{",
"var",
"next",
"=",
"ES",
".",
"IteratorNext",
"(",
"it",
")",
";",
"if",
"(",
"next",
".",
"done",
")",
"{",
"break",
";",
"}",
"var",
"nextItem",
"=",
"next",
".",
"value",
";",
"adder",
".",
"call",
"(",
"set",
",",
"nextItem",
")",
";",
"}",
"}",
"return",
"set",
";",
"}"
] | Creating a Map is expensive. To speed up the common case of Sets containing only string or numeric keys, we use an object as backing storage and lazily create a full Map only when required. | [
"Creating",
"a",
"Map",
"is",
"expensive",
".",
"To",
"speed",
"up",
"the",
"common",
"case",
"of",
"Sets",
"containing",
"only",
"string",
"or",
"numeric",
"keys",
"we",
"use",
"an",
"object",
"as",
"backing",
"storage",
"and",
"lazily",
"create",
"a",
"full",
"Map",
"only",
"when",
"required",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/es6-shim.js#L1676-L1702 | train |
atomantic/undermore | libs/es6-shim.js | ensureMap | function ensureMap(set) {
if (!set['[[SetData]]']) {
var m = set['[[SetData]]'] = new collectionShims.Map();
Object.keys(set._storage).forEach(function(k) {
// fast check for leading '$'
if (k.charCodeAt(0) === 36) {
k = k.substring(1);
} else {
k = +k;
}
m.set(k, k);
});
set._storage = null; // free old backing storage
}
} | javascript | function ensureMap(set) {
if (!set['[[SetData]]']) {
var m = set['[[SetData]]'] = new collectionShims.Map();
Object.keys(set._storage).forEach(function(k) {
// fast check for leading '$'
if (k.charCodeAt(0) === 36) {
k = k.substring(1);
} else {
k = +k;
}
m.set(k, k);
});
set._storage = null; // free old backing storage
}
} | [
"function",
"ensureMap",
"(",
"set",
")",
"{",
"if",
"(",
"!",
"set",
"[",
"'[[SetData]]'",
"]",
")",
"{",
"var",
"m",
"=",
"set",
"[",
"'[[SetData]]'",
"]",
"=",
"new",
"collectionShims",
".",
"Map",
"(",
")",
";",
"Object",
".",
"keys",
"(",
"set",
".",
"_storage",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"if",
"(",
"k",
".",
"charCodeAt",
"(",
"0",
")",
"===",
"36",
")",
"{",
"k",
"=",
"k",
".",
"substring",
"(",
"1",
")",
";",
"}",
"else",
"{",
"k",
"=",
"+",
"k",
";",
"}",
"m",
".",
"set",
"(",
"k",
",",
"k",
")",
";",
"}",
")",
";",
"set",
".",
"_storage",
"=",
"null",
";",
"}",
"}"
] | Switch from the object backing storage to a full Map. | [
"Switch",
"from",
"the",
"object",
"backing",
"storage",
"to",
"a",
"full",
"Map",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/es6-shim.js#L1715-L1729 | train |
petermbenjamin/exploitalert | src/details.js | details | function details(id) {
return new Promise((resolve, reject) => {
if (!id || id === '') throw new Error('id cannot be blank');
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
port: null,
path: `/view-details.html?id=${id}`,
headers: {},
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(body.toString());
});
});
req.on('error', reject);
req.end();
})
.then((html) => {
const $ = cheerio.load(html);
return $('pre').text();
})
.catch(err => err);
} | javascript | function details(id) {
return new Promise((resolve, reject) => {
if (!id || id === '') throw new Error('id cannot be blank');
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
port: null,
path: `/view-details.html?id=${id}`,
headers: {},
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(body.toString());
});
});
req.on('error', reject);
req.end();
})
.then((html) => {
const $ = cheerio.load(html);
return $('pre').text();
})
.catch(err => err);
} | [
"function",
"details",
"(",
"id",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"id",
"||",
"id",
"===",
"''",
")",
"throw",
"new",
"Error",
"(",
"'id cannot be blank'",
")",
";",
"const",
"options",
"=",
"{",
"method",
":",
"'GET'",
",",
"hostname",
":",
"'www.exploitalert.com'",
",",
"port",
":",
"null",
",",
"path",
":",
"`",
"${",
"id",
"}",
"`",
",",
"headers",
":",
"{",
"}",
",",
"}",
";",
"const",
"req",
"=",
"http",
".",
"request",
"(",
"options",
",",
"(",
"res",
")",
"=>",
"{",
"const",
"chunks",
"=",
"[",
"]",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"(",
"chunk",
")",
"=>",
"{",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"const",
"body",
"=",
"Buffer",
".",
"concat",
"(",
"chunks",
")",
";",
"resolve",
"(",
"body",
".",
"toString",
"(",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"reject",
")",
";",
"req",
".",
"end",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"(",
"html",
")",
"=>",
"{",
"const",
"$",
"=",
"cheerio",
".",
"load",
"(",
"html",
")",
";",
"return",
"$",
"(",
"'pre'",
")",
".",
"text",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"err",
"=>",
"err",
")",
";",
"}"
] | Get details of an exploit
@param {string} id - id of the exploit | [
"Get",
"details",
"of",
"an",
"exploit"
] | a250d497a6be13db968b72ab0139028d6d1744ac | https://github.com/petermbenjamin/exploitalert/blob/a250d497a6be13db968b72ab0139028d6d1744ac/src/details.js#L8-L40 | train |
infrabel/themes-gnap | raw/ace/mustache/js/classes/Page.js | function(data_dir) {
var data_files = {}
var format = new RegExp("([0-9a-z\\-_]+)\\.(json|csv)$" , "i");
//see if there's a folder for partial data relating to this page or layout
//if so iterate all json/csv files and load the data
var partial_data_folder = data_dir + "/"+$type +"s/partials/" + $name;
var stats;
if(fs.existsSync(partial_data_folder) && (stats = fs.statSync(partial_data_folder)) && stats.isDirectory()) {
var files = fs.readdirSync(partial_data_folder)
files.forEach(function (name) {
var filename;//file name, which we use as the variable name
if (! (filename = name.match(format)) ) return;
data_files[filename[1]] = partial_data_folder + "/" + name;
})
}
for(var var_name in data_files) if(data_files.hasOwnProperty(var_name)) {
var new_data
try {
if(data_files[var_name].match(/\.json$/i)) {
new_data = fs.readFileSync(data_files[var_name] , 'utf-8');
new_data = JSON.parse(new_data);
} else if(data_files[var_name].match(/\.csv$/i)) {
//load csv data into an array
var csv_data = require(data_files[var_name]);
//now convert it to json
var csv_header = csv_data[0];
var length = csv_data.length;
var json_data = []
for(var i = 1 ; i < length; i++) {
var csv_row = csv_data[i];
var json_row = {}
for(var j = 0; j < csv_row.length; j++) {
json_row[csv_header[j]] = csv_row[j];
}
//for example if we have "status":"pending" , add this to it as well : "pending":true
if("status" in json_row) json_row[json_row["status"].toLowerCase()] = true;
json_data.push(json_row);
}
new_data = json_data
}
} catch(e) {
console.log("Invalid JSON Data File : " + data_files[var_name]);
continue;
}
$vars[var_name.replace(/\./g , '_')] = new_data
//here we replace '.' with '_' in variable names, so template compiler can recognize it as a variable not an object
//for example change sidebar.navList to sidebar_navList , because sidebar is not an object
}
return true;
} | javascript | function(data_dir) {
var data_files = {}
var format = new RegExp("([0-9a-z\\-_]+)\\.(json|csv)$" , "i");
//see if there's a folder for partial data relating to this page or layout
//if so iterate all json/csv files and load the data
var partial_data_folder = data_dir + "/"+$type +"s/partials/" + $name;
var stats;
if(fs.existsSync(partial_data_folder) && (stats = fs.statSync(partial_data_folder)) && stats.isDirectory()) {
var files = fs.readdirSync(partial_data_folder)
files.forEach(function (name) {
var filename;//file name, which we use as the variable name
if (! (filename = name.match(format)) ) return;
data_files[filename[1]] = partial_data_folder + "/" + name;
})
}
for(var var_name in data_files) if(data_files.hasOwnProperty(var_name)) {
var new_data
try {
if(data_files[var_name].match(/\.json$/i)) {
new_data = fs.readFileSync(data_files[var_name] , 'utf-8');
new_data = JSON.parse(new_data);
} else if(data_files[var_name].match(/\.csv$/i)) {
//load csv data into an array
var csv_data = require(data_files[var_name]);
//now convert it to json
var csv_header = csv_data[0];
var length = csv_data.length;
var json_data = []
for(var i = 1 ; i < length; i++) {
var csv_row = csv_data[i];
var json_row = {}
for(var j = 0; j < csv_row.length; j++) {
json_row[csv_header[j]] = csv_row[j];
}
//for example if we have "status":"pending" , add this to it as well : "pending":true
if("status" in json_row) json_row[json_row["status"].toLowerCase()] = true;
json_data.push(json_row);
}
new_data = json_data
}
} catch(e) {
console.log("Invalid JSON Data File : " + data_files[var_name]);
continue;
}
$vars[var_name.replace(/\./g , '_')] = new_data
//here we replace '.' with '_' in variable names, so template compiler can recognize it as a variable not an object
//for example change sidebar.navList to sidebar_navList , because sidebar is not an object
}
return true;
} | [
"function",
"(",
"data_dir",
")",
"{",
"var",
"data_files",
"=",
"{",
"}",
"var",
"format",
"=",
"new",
"RegExp",
"(",
"\"([0-9a-z\\\\-_]+)\\\\.(json|csv)$\"",
",",
"\\\\",
")",
";",
"\\\\",
"\"i\"",
"var",
"partial_data_folder",
"=",
"data_dir",
"+",
"\"/\"",
"+",
"$type",
"+",
"\"s/partials/\"",
"+",
"$name",
";",
"var",
"stats",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"partial_data_folder",
")",
"&&",
"(",
"stats",
"=",
"fs",
".",
"statSync",
"(",
"partial_data_folder",
")",
")",
"&&",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"var",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"partial_data_folder",
")",
"files",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"var",
"filename",
";",
"if",
"(",
"!",
"(",
"filename",
"=",
"name",
".",
"match",
"(",
"format",
")",
")",
")",
"return",
";",
"data_files",
"[",
"filename",
"[",
"1",
"]",
"]",
"=",
"partial_data_folder",
"+",
"\"/\"",
"+",
"name",
";",
"}",
")",
"}",
"}"
] | This functions loads the data related to each page or layout
for a page we load all files in the related directory
for a layout we check the "datas-sources" attribute of our layout_file.json and load them
In your real world application you can load data only when it is needed according to each page inside controllers | [
"This",
"functions",
"loads",
"the",
"data",
"related",
"to",
"each",
"page",
"or",
"layout",
"for",
"a",
"page",
"we",
"load",
"all",
"files",
"in",
"the",
"related",
"directory",
"for",
"a",
"layout",
"we",
"check",
"the",
"datas",
"-",
"sources",
"attribute",
"of",
"our",
"layout_file",
".",
"json",
"and",
"load",
"them",
"In",
"your",
"real",
"world",
"application",
"you",
"can",
"load",
"data",
"only",
"when",
"it",
"is",
"needed",
"according",
"to",
"each",
"page",
"inside",
"controllers"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/mustache/js/classes/Page.js#L65-L126 | train |
|
RoganMurley/hitagi.js | src/world.js | function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'tickStart')) {
system.tickStart(dt);
}
}
);
} | javascript | function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'tickStart')) {
system.tickStart(dt);
}
}
);
} | [
"function",
"(",
"dt",
")",
"{",
"_",
".",
"each",
"(",
"systems",
",",
"function",
"(",
"system",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"system",
",",
"'tickStart'",
")",
")",
"{",
"system",
".",
"tickStart",
"(",
"dt",
")",
";",
"}",
"}",
")",
";",
"}"
] | Call all registered system's tick start function. | [
"Call",
"all",
"registered",
"system",
"s",
"tick",
"start",
"function",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/world.js#L126-L135 | train |
|
RoganMurley/hitagi.js | src/world.js | function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'update')) {
_.each(
entities,
function (entity) {
if (!_.isUndefined(entity)) {
_.each(system.update, function (func, id) {
if (entity.has(id)){
func(entity, dt);
}
});
}
}
);
}
}
);
} | javascript | function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'update')) {
_.each(
entities,
function (entity) {
if (!_.isUndefined(entity)) {
_.each(system.update, function (func, id) {
if (entity.has(id)){
func(entity, dt);
}
});
}
}
);
}
}
);
} | [
"function",
"(",
"dt",
")",
"{",
"_",
".",
"each",
"(",
"systems",
",",
"function",
"(",
"system",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"system",
",",
"'update'",
")",
")",
"{",
"_",
".",
"each",
"(",
"entities",
",",
"function",
"(",
"entity",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"entity",
")",
")",
"{",
"_",
".",
"each",
"(",
"system",
".",
"update",
",",
"function",
"(",
"func",
",",
"id",
")",
"{",
"if",
"(",
"entity",
".",
"has",
"(",
"id",
")",
")",
"{",
"func",
"(",
"entity",
",",
"dt",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Call all registered system's update function, passing a timestep. | [
"Call",
"all",
"registered",
"system",
"s",
"update",
"function",
"passing",
"a",
"timestep",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/world.js#L138-L158 | train |
|
RoganMurley/hitagi.js | src/world.js | function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'tickEnd')) {
system.tickEnd(dt);
}
}
);
} | javascript | function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'tickEnd')) {
system.tickEnd(dt);
}
}
);
} | [
"function",
"(",
"dt",
")",
"{",
"_",
".",
"each",
"(",
"systems",
",",
"function",
"(",
"system",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"system",
",",
"'tickEnd'",
")",
")",
"{",
"system",
".",
"tickEnd",
"(",
"dt",
")",
";",
"}",
"}",
")",
";",
"}"
] | Call all registered system's tick end function. | [
"Call",
"all",
"registered",
"system",
"s",
"tick",
"end",
"function",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/world.js#L161-L170 | train |
|
RoganMurley/hitagi.js | src/world.js | function (entity, just) {
_.each(
systems,
function (system) {
if (_.has(system, 'destroy')) {
_.each(system.destroy, function (func, id) {
if (entity.has(id)){
// Only remove from tracking systems.
if (!_.isUndefined(just)) {
if (id !== just) {
return;
}
}
// Perform the remove.
func(entity);
}
});
}
}
);
} | javascript | function (entity, just) {
_.each(
systems,
function (system) {
if (_.has(system, 'destroy')) {
_.each(system.destroy, function (func, id) {
if (entity.has(id)){
// Only remove from tracking systems.
if (!_.isUndefined(just)) {
if (id !== just) {
return;
}
}
// Perform the remove.
func(entity);
}
});
}
}
);
} | [
"function",
"(",
"entity",
",",
"just",
")",
"{",
"_",
".",
"each",
"(",
"systems",
",",
"function",
"(",
"system",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"system",
",",
"'destroy'",
")",
")",
"{",
"_",
".",
"each",
"(",
"system",
".",
"destroy",
",",
"function",
"(",
"func",
",",
"id",
")",
"{",
"if",
"(",
"entity",
".",
"has",
"(",
"id",
")",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"just",
")",
")",
"{",
"if",
"(",
"id",
"!==",
"just",
")",
"{",
"return",
";",
"}",
"}",
"func",
"(",
"entity",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Destroys an entity in all registered systems. If 'just' is given, just systems that deal with that component destroy the entity rather than all. | [
"Destroys",
"an",
"entity",
"in",
"all",
"registered",
"systems",
".",
"If",
"just",
"is",
"given",
"just",
"systems",
"that",
"deal",
"with",
"that",
"component",
"destroy",
"the",
"entity",
"rather",
"than",
"all",
"."
] | 6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053 | https://github.com/RoganMurley/hitagi.js/blob/6ad88d8df3af9b1708d70bb0c1f5a7a39ead9053/src/world.js#L200-L220 | train |
|
MeLlamoPablo/minimist-string | index.js | function(piece, quote_char) {
// Matches everything that is not a quote or \
var regex = new RegExp("[^" + quote_char + "\\\\]", 'g');
// Remove eveything that is not quote or \
var replaced = piece.replace(regex, '');
// Remove escaped quotes, then remove all remaining slashes, then count.
return replaced.replace(
new RegExp('(\\\\' + quote_char + ')', 'g'), ''
).replace(
/\\/g, ''
).length;
} | javascript | function(piece, quote_char) {
// Matches everything that is not a quote or \
var regex = new RegExp("[^" + quote_char + "\\\\]", 'g');
// Remove eveything that is not quote or \
var replaced = piece.replace(regex, '');
// Remove escaped quotes, then remove all remaining slashes, then count.
return replaced.replace(
new RegExp('(\\\\' + quote_char + ')', 'g'), ''
).replace(
/\\/g, ''
).length;
} | [
"function",
"(",
"piece",
",",
"quote_char",
")",
"{",
"var",
"regex",
"=",
"new",
"RegExp",
"(",
"\"[^\"",
"+",
"quote_char",
"+",
"\"\\\\\\\\]\"",
",",
"\\\\",
")",
";",
"\\\\",
"'g'",
"}"
] | Counts the number of unescaped quotes that the piece has.
@private
@param {string} piece The piece to evaluate.
@param {string} quote_char The quote character, either " or '.
@return {number} The number of unescaped quotes. | [
"Counts",
"the",
"number",
"of",
"unescaped",
"quotes",
"that",
"the",
"piece",
"has",
"."
] | befbe1a379166ba8942f80a6b1e1b538e9b27291 | https://github.com/MeLlamoPablo/minimist-string/blob/befbe1a379166ba8942f80a6b1e1b538e9b27291/index.js#L55-L66 | train |
|
MeLlamoPablo/minimist-string | index.js | function(piece, quote_char, position = 0) {
var i = position - 1; //-1 because we're incrementing it
do {
i = piece.indexOf(quote_char, i+1);
} while(piece.charAt(i-1) === '\\');
return i;
} | javascript | function(piece, quote_char, position = 0) {
var i = position - 1; //-1 because we're incrementing it
do {
i = piece.indexOf(quote_char, i+1);
} while(piece.charAt(i-1) === '\\');
return i;
} | [
"function",
"(",
"piece",
",",
"quote_char",
",",
"position",
"=",
"0",
")",
"{",
"var",
"i",
"=",
"position",
"-",
"1",
";",
"do",
"{",
"i",
"=",
"piece",
".",
"indexOf",
"(",
"quote_char",
",",
"i",
"+",
"1",
")",
";",
"}",
"while",
"(",
"piece",
".",
"charAt",
"(",
"i",
"-",
"1",
")",
"===",
"'\\\\'",
")",
";",
"\\\\",
"}"
] | Returns the index of the first unescaped quote in the piece
@private
@param {string} piece The piece to evaluate.
@param {string} quote_char The quote character, either " or '.
@param {number} [position=0] Where to begin looking in the string
@return {number} The index of the first quote. | [
"Returns",
"the",
"index",
"of",
"the",
"first",
"unescaped",
"quote",
"in",
"the",
"piece"
] | befbe1a379166ba8942f80a6b1e1b538e9b27291 | https://github.com/MeLlamoPablo/minimist-string/blob/befbe1a379166ba8942f80a6b1e1b538e9b27291/index.js#L114-L120 | train |
|
MeLlamoPablo/minimist-string | index.js | function(pieces, quote_char) {
var unclosed_quote = false;
var result = [];
for (var i = 0; i < pieces.length; i++) {
if (unclosed_quote) {
// Two scenarios. Either we have a closing quote or we don't.
if (hasQuote(pieces[i], quote_char)) {
// If it does, then there are two scenarios again:
// Either the closing quote is the last character,
// or there is text after it.
var q_index = getFirstQuote(pieces[i], quote_char);
if (q_index !== (pieces[i].length - 1)) {
// The closing quote is not the last character; there's text after it.
// We take that text and put it on the next piece.
pieces[i+1] =
pieces[i].substring(q_index + 1, pieces[i].length)
+ (typeof pieces[i+1] !== 'undefined'
? pieces[i+1] : '');
pieces[i] = pieces[i].substring(0, q_index+1);
}
// Now the two scenarios are reduced to one. The last character of the
// current piece will always be the last. We can now conclude that the
// unclosed quote is now closed.
result[result.length-1] =
result[result.length-1] + ' ' + pieces[i];
unclosed_quote = false;
} else {
// We don't have a closing quote. That means that the current piece is part
// of the current string. So we concatenate it to the last piece in
// result
result[result.length-1] =
result[result.length-1] + ' ' + pieces[i];
}
} else {
// Two scenarios. Either we have an opening quote or we don't.
if (hasQuote(pieces[i], quote_char)) {
// We have an opening quote.
// Three scenarios. We have one, two, or more than two
if (countQuotes(pieces[i], quote_char) === 1) {
// We have just one opening quote. We can safely add this piece to the
// good pieces and carry on iterating. Any further pieces will be
// concatenated with this one until the unclosed_quote gets closed.
result.push(pieces[i]);
unclosed_quote = true;
} else if (countQuotes(pieces[i], quote_char) === 2) {
// We have two quotes. However, we might have information after the
// closing quote that doesn't belong to the string, so we split:
var split = splitPiece(pieces[i], quote_char);
// Both parts are safe to push, but we make sure that part 2 exists.
result.push(split[0]);
if(split[1] !== '') result.push(split[1]);
} else {
// We have more than three quotes. We split them. The first part of
// each split is always safe to store in result because it's a full
// closed string. The second part can be on any of the three scenarios:
// one, two or three quotes. So we keep iterating until it's on the
// first or on the second.
var next = pieces[i];
do {
var split = splitPiece(next, quote_char);
result.push(split[0]);
next = split[1];
} while (countQuotes(next, quote_char) > 2);
// Now, the string that's left is in scenario 1 or 2.
// We follow the same procedure.
if(countQuotes(next, quote_char) === 1) {
result.push(next);
unclosed_quote = true;
} else if (countQuotes(next, quote_char) === 2) {
result.push(next);
} else {
// This shouldn't happen.
throw new Error('I\'m sorry, but minimist-string has encountered' +
'unexpected behaviour. This is porbably not your fault and' +
'just a bug. Please report it with the stack trace on the' +
'GitHub tracker.');
}
}
} else {
// We don't have a quote on this piece.
// We can safely move on to the next one.
result.push(pieces[i]);
}
}
}
return result;
} | javascript | function(pieces, quote_char) {
var unclosed_quote = false;
var result = [];
for (var i = 0; i < pieces.length; i++) {
if (unclosed_quote) {
// Two scenarios. Either we have a closing quote or we don't.
if (hasQuote(pieces[i], quote_char)) {
// If it does, then there are two scenarios again:
// Either the closing quote is the last character,
// or there is text after it.
var q_index = getFirstQuote(pieces[i], quote_char);
if (q_index !== (pieces[i].length - 1)) {
// The closing quote is not the last character; there's text after it.
// We take that text and put it on the next piece.
pieces[i+1] =
pieces[i].substring(q_index + 1, pieces[i].length)
+ (typeof pieces[i+1] !== 'undefined'
? pieces[i+1] : '');
pieces[i] = pieces[i].substring(0, q_index+1);
}
// Now the two scenarios are reduced to one. The last character of the
// current piece will always be the last. We can now conclude that the
// unclosed quote is now closed.
result[result.length-1] =
result[result.length-1] + ' ' + pieces[i];
unclosed_quote = false;
} else {
// We don't have a closing quote. That means that the current piece is part
// of the current string. So we concatenate it to the last piece in
// result
result[result.length-1] =
result[result.length-1] + ' ' + pieces[i];
}
} else {
// Two scenarios. Either we have an opening quote or we don't.
if (hasQuote(pieces[i], quote_char)) {
// We have an opening quote.
// Three scenarios. We have one, two, or more than two
if (countQuotes(pieces[i], quote_char) === 1) {
// We have just one opening quote. We can safely add this piece to the
// good pieces and carry on iterating. Any further pieces will be
// concatenated with this one until the unclosed_quote gets closed.
result.push(pieces[i]);
unclosed_quote = true;
} else if (countQuotes(pieces[i], quote_char) === 2) {
// We have two quotes. However, we might have information after the
// closing quote that doesn't belong to the string, so we split:
var split = splitPiece(pieces[i], quote_char);
// Both parts are safe to push, but we make sure that part 2 exists.
result.push(split[0]);
if(split[1] !== '') result.push(split[1]);
} else {
// We have more than three quotes. We split them. The first part of
// each split is always safe to store in result because it's a full
// closed string. The second part can be on any of the three scenarios:
// one, two or three quotes. So we keep iterating until it's on the
// first or on the second.
var next = pieces[i];
do {
var split = splitPiece(next, quote_char);
result.push(split[0]);
next = split[1];
} while (countQuotes(next, quote_char) > 2);
// Now, the string that's left is in scenario 1 or 2.
// We follow the same procedure.
if(countQuotes(next, quote_char) === 1) {
result.push(next);
unclosed_quote = true;
} else if (countQuotes(next, quote_char) === 2) {
result.push(next);
} else {
// This shouldn't happen.
throw new Error('I\'m sorry, but minimist-string has encountered' +
'unexpected behaviour. This is porbably not your fault and' +
'just a bug. Please report it with the stack trace on the' +
'GitHub tracker.');
}
}
} else {
// We don't have a quote on this piece.
// We can safely move on to the next one.
result.push(pieces[i]);
}
}
}
return result;
} | [
"function",
"(",
"pieces",
",",
"quote_char",
")",
"{",
"var",
"unclosed_quote",
"=",
"false",
";",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"pieces",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"unclosed_quote",
")",
"{",
"if",
"(",
"hasQuote",
"(",
"pieces",
"[",
"i",
"]",
",",
"quote_char",
")",
")",
"{",
"var",
"q_index",
"=",
"getFirstQuote",
"(",
"pieces",
"[",
"i",
"]",
",",
"quote_char",
")",
";",
"if",
"(",
"q_index",
"!==",
"(",
"pieces",
"[",
"i",
"]",
".",
"length",
"-",
"1",
")",
")",
"{",
"pieces",
"[",
"i",
"+",
"1",
"]",
"=",
"pieces",
"[",
"i",
"]",
".",
"substring",
"(",
"q_index",
"+",
"1",
",",
"pieces",
"[",
"i",
"]",
".",
"length",
")",
"+",
"(",
"typeof",
"pieces",
"[",
"i",
"+",
"1",
"]",
"!==",
"'undefined'",
"?",
"pieces",
"[",
"i",
"+",
"1",
"]",
":",
"''",
")",
";",
"pieces",
"[",
"i",
"]",
"=",
"pieces",
"[",
"i",
"]",
".",
"substring",
"(",
"0",
",",
"q_index",
"+",
"1",
")",
";",
"}",
"result",
"[",
"result",
".",
"length",
"-",
"1",
"]",
"=",
"result",
"[",
"result",
".",
"length",
"-",
"1",
"]",
"+",
"' '",
"+",
"pieces",
"[",
"i",
"]",
";",
"unclosed_quote",
"=",
"false",
";",
"}",
"else",
"{",
"result",
"[",
"result",
".",
"length",
"-",
"1",
"]",
"=",
"result",
"[",
"result",
".",
"length",
"-",
"1",
"]",
"+",
"' '",
"+",
"pieces",
"[",
"i",
"]",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"hasQuote",
"(",
"pieces",
"[",
"i",
"]",
",",
"quote_char",
")",
")",
"{",
"if",
"(",
"countQuotes",
"(",
"pieces",
"[",
"i",
"]",
",",
"quote_char",
")",
"===",
"1",
")",
"{",
"result",
".",
"push",
"(",
"pieces",
"[",
"i",
"]",
")",
";",
"unclosed_quote",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"countQuotes",
"(",
"pieces",
"[",
"i",
"]",
",",
"quote_char",
")",
"===",
"2",
")",
"{",
"var",
"split",
"=",
"splitPiece",
"(",
"pieces",
"[",
"i",
"]",
",",
"quote_char",
")",
";",
"result",
".",
"push",
"(",
"split",
"[",
"0",
"]",
")",
";",
"if",
"(",
"split",
"[",
"1",
"]",
"!==",
"''",
")",
"result",
".",
"push",
"(",
"split",
"[",
"1",
"]",
")",
";",
"}",
"else",
"{",
"var",
"next",
"=",
"pieces",
"[",
"i",
"]",
";",
"do",
"{",
"var",
"split",
"=",
"splitPiece",
"(",
"next",
",",
"quote_char",
")",
";",
"result",
".",
"push",
"(",
"split",
"[",
"0",
"]",
")",
";",
"next",
"=",
"split",
"[",
"1",
"]",
";",
"}",
"while",
"(",
"countQuotes",
"(",
"next",
",",
"quote_char",
")",
">",
"2",
")",
";",
"if",
"(",
"countQuotes",
"(",
"next",
",",
"quote_char",
")",
"===",
"1",
")",
"{",
"result",
".",
"push",
"(",
"next",
")",
";",
"unclosed_quote",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"countQuotes",
"(",
"next",
",",
"quote_char",
")",
"===",
"2",
")",
"{",
"result",
".",
"push",
"(",
"next",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'I\\'m sorry, but minimist-string has encountered'",
"+",
"\\'",
"+",
"'unexpected behaviour. This is porbably not your fault and'",
"+",
"'just a bug. Please report it with the stack trace on the'",
")",
";",
"}",
"}",
"}",
"else",
"'GitHub tracker.'",
"}",
"}",
"{",
"result",
".",
"push",
"(",
"pieces",
"[",
"i",
"]",
")",
";",
"}",
"}"
] | Detects strings in params and concatenates them into a single array element.
@private
@param {string[]} pieces An array with every piece of the cli sentence. Initially,
this is sentence.split(' ');
@param {string} quote_char The quote character, either " or '.
@returns {Array} The array with concatenated strings. | [
"Detects",
"strings",
"in",
"params",
"and",
"concatenates",
"them",
"into",
"a",
"single",
"array",
"element",
"."
] | befbe1a379166ba8942f80a6b1e1b538e9b27291 | https://github.com/MeLlamoPablo/minimist-string/blob/befbe1a379166ba8942f80a6b1e1b538e9b27291/index.js#L130-L220 | train |
|
zauni/pngmin | tasks/pngmin.js | runPngquant | function runPngquant(args, callback) {
grunt.log.debug('Trying to spawn "' + options.binary + '" with arguments: ');
grunt.log.debug(args.join(' '));
grunt.util.spawn({
cmd: options.binary,
args: args
}, callback);
} | javascript | function runPngquant(args, callback) {
grunt.log.debug('Trying to spawn "' + options.binary + '" with arguments: ');
grunt.log.debug(args.join(' '));
grunt.util.spawn({
cmd: options.binary,
args: args
}, callback);
} | [
"function",
"runPngquant",
"(",
"args",
",",
"callback",
")",
"{",
"grunt",
".",
"log",
".",
"debug",
"(",
"'Trying to spawn \"'",
"+",
"options",
".",
"binary",
"+",
"'\" with arguments: '",
")",
";",
"grunt",
".",
"log",
".",
"debug",
"(",
"args",
".",
"join",
"(",
"' '",
")",
")",
";",
"grunt",
".",
"util",
".",
"spawn",
"(",
"{",
"cmd",
":",
"options",
".",
"binary",
",",
"args",
":",
"args",
"}",
",",
"callback",
")",
";",
"}"
] | Runs pngquant binary
@param {Array} args Command line arguments
@param {Function} callback Callback | [
"Runs",
"pngquant",
"binary"
] | a687761878ad73fc4d4672347671dd75652db9c0 | https://github.com/zauni/pngmin/blob/a687761878ad73fc4d4672347671dd75652db9c0/tasks/pngmin.js#L29-L36 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/date-time/moment.js | addOrSubtractDurationFromMoment | function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
var ms = duration._milliseconds,
d = duration._days,
M = duration._months,
currentDate;
if (ms) {
mom._d.setTime(+mom + ms * isAdding);
}
if (d) {
mom.date(mom.date() + d * isAdding);
}
if (M) {
currentDate = mom.date();
mom.date(1)
.month(mom.month() + M * isAdding)
.date(Math.min(currentDate, mom.daysInMonth()));
}
} | javascript | function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
var ms = duration._milliseconds,
d = duration._days,
M = duration._months,
currentDate;
if (ms) {
mom._d.setTime(+mom + ms * isAdding);
}
if (d) {
mom.date(mom.date() + d * isAdding);
}
if (M) {
currentDate = mom.date();
mom.date(1)
.month(mom.month() + M * isAdding)
.date(Math.min(currentDate, mom.daysInMonth()));
}
} | [
"function",
"addOrSubtractDurationFromMoment",
"(",
"mom",
",",
"duration",
",",
"isAdding",
")",
"{",
"var",
"ms",
"=",
"duration",
".",
"_milliseconds",
",",
"d",
"=",
"duration",
".",
"_days",
",",
"M",
"=",
"duration",
".",
"_months",
",",
"currentDate",
";",
"if",
"(",
"ms",
")",
"{",
"mom",
".",
"_d",
".",
"setTime",
"(",
"+",
"mom",
"+",
"ms",
"*",
"isAdding",
")",
";",
"}",
"if",
"(",
"d",
")",
"{",
"mom",
".",
"date",
"(",
"mom",
".",
"date",
"(",
")",
"+",
"d",
"*",
"isAdding",
")",
";",
"}",
"if",
"(",
"M",
")",
"{",
"currentDate",
"=",
"mom",
".",
"date",
"(",
")",
";",
"mom",
".",
"date",
"(",
"1",
")",
".",
"month",
"(",
"mom",
".",
"month",
"(",
")",
"+",
"M",
"*",
"isAdding",
")",
".",
"date",
"(",
"Math",
".",
"min",
"(",
"currentDate",
",",
"mom",
".",
"daysInMonth",
"(",
")",
")",
")",
";",
"}",
"}"
] | helper function for _.addTime and _.subtractTime | [
"helper",
"function",
"for",
"_",
".",
"addTime",
"and",
"_",
".",
"subtractTime"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/date-time/moment.js#L292-L310 | train |
joshfire/woodman | lib/layouts/jsonlayout.js | function (config, loggerContext) {
config = config || {};
Layout.call(this, config, loggerContext);
this.compact = config.compact || false;
this.depth = config.depth || 2;
this.messageAsObject = config.messageAsObject || false;
} | javascript | function (config, loggerContext) {
config = config || {};
Layout.call(this, config, loggerContext);
this.compact = config.compact || false;
this.depth = config.depth || 2;
this.messageAsObject = config.messageAsObject || false;
} | [
"function",
"(",
"config",
",",
"loggerContext",
")",
"{",
"config",
"=",
"config",
"||",
"{",
"}",
";",
"Layout",
".",
"call",
"(",
"this",
",",
"config",
",",
"loggerContext",
")",
";",
"this",
".",
"compact",
"=",
"config",
".",
"compact",
"||",
"false",
";",
"this",
".",
"depth",
"=",
"config",
".",
"depth",
"||",
"2",
";",
"this",
".",
"messageAsObject",
"=",
"config",
".",
"messageAsObject",
"||",
"false",
";",
"}"
] | Lays out a log event as a JSON string
Configuration parameters that may be used:
- compact: to serialize compact JSON structures. the serialization rather
produces a "prettyprint" JSON structure by default.
- messageAsObject: to serialize the message as an object structure. The
message gets serialized as a string by default.
- depth: the depth to with message parameters should be serialized. Only
useful when "messageAsObject" is set.
@constructor
@extends {Layout} | [
"Lays",
"out",
"a",
"log",
"event",
"as",
"a",
"JSON",
"string"
] | fdc05de2124388780924980e6f27bf4483056d18 | https://github.com/joshfire/woodman/blob/fdc05de2124388780924980e6f27bf4483056d18/lib/layouts/jsonlayout.js#L39-L46 | train |
|
carsdotcom/windshieldjs | lib/handler.composer.js | requestHandlerComposer | function requestHandlerComposer(componentMap) {
const buildTemplateData = buildTemplateDataComposer(componentMap);
/**
* @async
* @callback {handler}
*
* Handles an incoming request to a Hapi route configured by a Windshield server.
* The request is handled with by using Windshield to produce a Handlebars
* template and a set of template source data, which are then passing into the
* Hapi Vision plugin to generate an HTML response.
*
* @param {Request} request - The Hapi request object
* @param {Toolkit} h - The Hapi response toolkit
* @returns {Promise<Response>} Promise that resolves with the response
*/
return async function handler(request, h) {
try {
const {template, data} = await buildTemplateData(request);
// The Hapi vision plugin adds the view() method to the response toolkit
const visionResponse = h.view(template, data);
const headers = data.attributes.headers || {};
// add headers to the response object one by one
return Object.entries(headers).reduce((vResponse, [key, value]) => {
return vResponse.header(key, value);
}, visionResponse);
} catch (err) {
request.server.log('error', err);
if (process.env.NODE_ENV === 'production') {
return err;
}
const errMsg = err.stack.replace(/\n/g, "<br>").replace(/ /g, " ");
return h.response(errMsg).code(500);
}
};
} | javascript | function requestHandlerComposer(componentMap) {
const buildTemplateData = buildTemplateDataComposer(componentMap);
/**
* @async
* @callback {handler}
*
* Handles an incoming request to a Hapi route configured by a Windshield server.
* The request is handled with by using Windshield to produce a Handlebars
* template and a set of template source data, which are then passing into the
* Hapi Vision plugin to generate an HTML response.
*
* @param {Request} request - The Hapi request object
* @param {Toolkit} h - The Hapi response toolkit
* @returns {Promise<Response>} Promise that resolves with the response
*/
return async function handler(request, h) {
try {
const {template, data} = await buildTemplateData(request);
// The Hapi vision plugin adds the view() method to the response toolkit
const visionResponse = h.view(template, data);
const headers = data.attributes.headers || {};
// add headers to the response object one by one
return Object.entries(headers).reduce((vResponse, [key, value]) => {
return vResponse.header(key, value);
}, visionResponse);
} catch (err) {
request.server.log('error', err);
if (process.env.NODE_ENV === 'production') {
return err;
}
const errMsg = err.stack.replace(/\n/g, "<br>").replace(/ /g, " ");
return h.response(errMsg).code(500);
}
};
} | [
"function",
"requestHandlerComposer",
"(",
"componentMap",
")",
"{",
"const",
"buildTemplateData",
"=",
"buildTemplateDataComposer",
"(",
"componentMap",
")",
";",
"return",
"async",
"function",
"handler",
"(",
"request",
",",
"h",
")",
"{",
"try",
"{",
"const",
"{",
"template",
",",
"data",
"}",
"=",
"await",
"buildTemplateData",
"(",
"request",
")",
";",
"const",
"visionResponse",
"=",
"h",
".",
"view",
"(",
"template",
",",
"data",
")",
";",
"const",
"headers",
"=",
"data",
".",
"attributes",
".",
"headers",
"||",
"{",
"}",
";",
"return",
"Object",
".",
"entries",
"(",
"headers",
")",
".",
"reduce",
"(",
"(",
"vResponse",
",",
"[",
"key",
",",
"value",
"]",
")",
"=>",
"{",
"return",
"vResponse",
".",
"header",
"(",
"key",
",",
"value",
")",
";",
"}",
",",
"visionResponse",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"request",
".",
"server",
".",
"log",
"(",
"'error'",
",",
"err",
")",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
")",
"{",
"return",
"err",
";",
"}",
"const",
"errMsg",
"=",
"err",
".",
"stack",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"\"<br>\"",
")",
".",
"replace",
"(",
"/",
" ",
"/",
"g",
",",
"\" \"",
")",
";",
"return",
"h",
".",
"response",
"(",
"errMsg",
")",
".",
"code",
"(",
"500",
")",
";",
"}",
"}",
";",
"}"
] | Composes a function that we can use as a Hapi route handler for Windshield.
We can't define the handler function at run-time because we won't know
all the required information until the Windshield plugin is registered. So
this function will build it for us when we're ready.
The resulting handler will use the Hapi Vision plugin to parse a template
with a set of data to produce an HTML page.
@param {ComponentMap} componentMap - Description of all available Windshield components
@returns {handler} - A Hapi route handler configured for Windshield | [
"Composes",
"a",
"function",
"that",
"we",
"can",
"use",
"as",
"a",
"Hapi",
"route",
"handler",
"for",
"Windshield",
"."
] | fddd841c5d9e09251437c9a30cc39700e5e4a1f6 | https://github.com/carsdotcom/windshieldjs/blob/fddd841c5d9e09251437c9a30cc39700e5e4a1f6/lib/handler.composer.js#L16-L59 | train |
atomantic/undermore | libs/lodash.js | baseCompareAscending | function baseCompareAscending(value, other) {
if (value !== other) {
if (value > other || typeof value == 'undefined') {
return 1;
}
if (value < other || typeof other == 'undefined') {
return -1;
}
}
return 0;
} | javascript | function baseCompareAscending(value, other) {
if (value !== other) {
if (value > other || typeof value == 'undefined') {
return 1;
}
if (value < other || typeof other == 'undefined') {
return -1;
}
}
return 0;
} | [
"function",
"baseCompareAscending",
"(",
"value",
",",
"other",
")",
"{",
"if",
"(",
"value",
"!==",
"other",
")",
"{",
"if",
"(",
"value",
">",
"other",
"||",
"typeof",
"value",
"==",
"'undefined'",
")",
"{",
"return",
"1",
";",
"}",
"if",
"(",
"value",
"<",
"other",
"||",
"typeof",
"other",
"==",
"'undefined'",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"return",
"0",
";",
"}"
] | The base implementation of `compareAscending` used to compare values and
sort them in ascending order without guaranteeing a stable sort.
@private
@param {*} value The value to compare to `other`.
@param {*} other The value to compare to `value`.
@returns {number} Returns the sort order indicator for `value`. | [
"The",
"base",
"implementation",
"of",
"compareAscending",
"used",
"to",
"compare",
"values",
"and",
"sort",
"them",
"in",
"ascending",
"order",
"without",
"guaranteeing",
"a",
"stable",
"sort",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L255-L265 | train |
atomantic/undermore | libs/lodash.js | compareMultipleAscending | function compareMultipleAscending(object, other) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length;
while (++index < length) {
var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
if (result) {
return result;
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value
// for `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
//
// This also ensures a stable sort in V8 and other engines.
// See https://code.google.com/p/v8/issues/detail?id=90
return object.index - other.index;
} | javascript | function compareMultipleAscending(object, other) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length;
while (++index < length) {
var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
if (result) {
return result;
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value
// for `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
//
// This also ensures a stable sort in V8 and other engines.
// See https://code.google.com/p/v8/issues/detail?id=90
return object.index - other.index;
} | [
"function",
"compareMultipleAscending",
"(",
"object",
",",
"other",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"objCriteria",
"=",
"object",
".",
"criteria",
",",
"othCriteria",
"=",
"other",
".",
"criteria",
",",
"length",
"=",
"objCriteria",
".",
"length",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"var",
"result",
"=",
"baseCompareAscending",
"(",
"objCriteria",
"[",
"index",
"]",
",",
"othCriteria",
"[",
"index",
"]",
")",
";",
"if",
"(",
"result",
")",
"{",
"return",
"result",
";",
"}",
"}",
"return",
"object",
".",
"index",
"-",
"other",
".",
"index",
";",
"}"
] | Used by `_.sortBy` to compare multiple properties of each element in a
collection and stable sort them in ascending order.
@private
@param {Object} object The object to compare to `other`.
@param {Object} other The object to compare to `object`.
@returns {number} Returns the sort order indicator for `object`. | [
"Used",
"by",
"_",
".",
"sortBy",
"to",
"compare",
"multiple",
"properties",
"of",
"each",
"element",
"in",
"a",
"collection",
"and",
"stable",
"sort",
"them",
"in",
"ascending",
"order",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L373-L392 | train |
atomantic/undermore | libs/lodash.js | arrayEachRight | function arrayEachRight(array, callback) {
var length = array ? array.length : 0;
while (length--) {
if (callback(array[length], length, array) === false) {
break;
}
}
return array;
} | javascript | function arrayEachRight(array, callback) {
var length = array ? array.length : 0;
while (length--) {
if (callback(array[length], length, array) === false) {
break;
}
}
return array;
} | [
"function",
"arrayEachRight",
"(",
"array",
",",
"callback",
")",
"{",
"var",
"length",
"=",
"array",
"?",
"array",
".",
"length",
":",
"0",
";",
"while",
"(",
"length",
"--",
")",
"{",
"if",
"(",
"callback",
"(",
"array",
"[",
"length",
"]",
",",
"length",
",",
"array",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"return",
"array",
";",
"}"
] | A specialized version of `_.forEachRight` for arrays without support for
callback shorthands or `this` binding.
@private
@param {Array} array The array to iterate over.
@param {Function} callback The function called per iteration.
@returns {Array} Returns `array`. | [
"A",
"specialized",
"version",
"of",
"_",
".",
"forEachRight",
"for",
"arrays",
"without",
"support",
"for",
"callback",
"shorthands",
"or",
"this",
"binding",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L854-L862 | train |
atomantic/undermore | libs/lodash.js | arrayMap | function arrayMap(array, callback) {
var index = -1,
length = array ? array.length >>> 0 : 0,
result = Array(length);
while (++index < length) {
result[index] = callback(array[index], index, array);
}
return result;
} | javascript | function arrayMap(array, callback) {
var index = -1,
length = array ? array.length >>> 0 : 0,
result = Array(length);
while (++index < length) {
result[index] = callback(array[index], index, array);
}
return result;
} | [
"function",
"arrayMap",
"(",
"array",
",",
"callback",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"array",
"?",
"array",
".",
"length",
">>>",
"0",
":",
"0",
",",
"result",
"=",
"Array",
"(",
"length",
")",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"result",
"[",
"index",
"]",
"=",
"callback",
"(",
"array",
"[",
"index",
"]",
",",
"index",
",",
"array",
")",
";",
"}",
"return",
"result",
";",
"}"
] | A specialized version of `_.map` for arrays without support for callback
shorthands or `this` binding.
@private
@param {Array} array The array to iterate over.
@param {Function} callback The function called per iteration.
@returns {Array} Returns the new mapped array. | [
"A",
"specialized",
"version",
"of",
"_",
".",
"map",
"for",
"arrays",
"without",
"support",
"for",
"callback",
"shorthands",
"or",
"this",
"binding",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L873-L882 | train |
atomantic/undermore | libs/lodash.js | baseClone | function baseClone(value, isDeep, callback, stackA, stackB) {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className]) {
return value;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case dateClass:
return new ctor(+value);
case numberClass:
case stringClass:
return new ctor(value);
case regexpClass:
result = ctor(value.source, reFlags.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
} else {
return value;
}
var isArr = isArray(value);
if (isDeep) {
// check for circular references and return corresponding clone
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
result = isArr ? ctor(value.length) : {};
}
else {
result = isArr ? slice(value) : assign({}, value);
}
// add array properties assigned by `RegExp#exec`
if (isArr) {
if (hasOwnProperty.call(value, 'index')) {
result.index = value.index;
}
if (hasOwnProperty.call(value, 'input')) {
result.input = value.input;
}
}
// exit for shallow clone
if (!isDeep) {
return result;
}
// add the source value to the stack of traversed objects
// and associate it with its clone
stackA.push(value);
stackB.push(result);
// recursively populate clone (susceptible to call stack limits)
(isArr ? arrayEach : baseForOwn)(value, function(valValue, key) {
result[key] = baseClone(valValue, isDeep, callback, stackA, stackB);
});
return result;
} | javascript | function baseClone(value, isDeep, callback, stackA, stackB) {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className]) {
return value;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case dateClass:
return new ctor(+value);
case numberClass:
case stringClass:
return new ctor(value);
case regexpClass:
result = ctor(value.source, reFlags.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
} else {
return value;
}
var isArr = isArray(value);
if (isDeep) {
// check for circular references and return corresponding clone
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
result = isArr ? ctor(value.length) : {};
}
else {
result = isArr ? slice(value) : assign({}, value);
}
// add array properties assigned by `RegExp#exec`
if (isArr) {
if (hasOwnProperty.call(value, 'index')) {
result.index = value.index;
}
if (hasOwnProperty.call(value, 'input')) {
result.input = value.input;
}
}
// exit for shallow clone
if (!isDeep) {
return result;
}
// add the source value to the stack of traversed objects
// and associate it with its clone
stackA.push(value);
stackB.push(result);
// recursively populate clone (susceptible to call stack limits)
(isArr ? arrayEach : baseForOwn)(value, function(valValue, key) {
result[key] = baseClone(valValue, isDeep, callback, stackA, stackB);
});
return result;
} | [
"function",
"baseClone",
"(",
"value",
",",
"isDeep",
",",
"callback",
",",
"stackA",
",",
"stackB",
")",
"{",
"if",
"(",
"callback",
")",
"{",
"var",
"result",
"=",
"callback",
"(",
"value",
")",
";",
"if",
"(",
"typeof",
"result",
"!=",
"'undefined'",
")",
"{",
"return",
"result",
";",
"}",
"}",
"var",
"isObj",
"=",
"isObject",
"(",
"value",
")",
";",
"if",
"(",
"isObj",
")",
"{",
"var",
"className",
"=",
"toString",
".",
"call",
"(",
"value",
")",
";",
"if",
"(",
"!",
"cloneableClasses",
"[",
"className",
"]",
")",
"{",
"return",
"value",
";",
"}",
"var",
"ctor",
"=",
"ctorByClass",
"[",
"className",
"]",
";",
"switch",
"(",
"className",
")",
"{",
"case",
"boolClass",
":",
"case",
"dateClass",
":",
"return",
"new",
"ctor",
"(",
"+",
"value",
")",
";",
"case",
"numberClass",
":",
"case",
"stringClass",
":",
"return",
"new",
"ctor",
"(",
"value",
")",
";",
"case",
"regexpClass",
":",
"result",
"=",
"ctor",
"(",
"value",
".",
"source",
",",
"reFlags",
".",
"exec",
"(",
"value",
")",
")",
";",
"result",
".",
"lastIndex",
"=",
"value",
".",
"lastIndex",
";",
"return",
"result",
";",
"}",
"}",
"else",
"{",
"return",
"value",
";",
"}",
"var",
"isArr",
"=",
"isArray",
"(",
"value",
")",
";",
"if",
"(",
"isDeep",
")",
"{",
"stackA",
"||",
"(",
"stackA",
"=",
"[",
"]",
")",
";",
"stackB",
"||",
"(",
"stackB",
"=",
"[",
"]",
")",
";",
"var",
"length",
"=",
"stackA",
".",
"length",
";",
"while",
"(",
"length",
"--",
")",
"{",
"if",
"(",
"stackA",
"[",
"length",
"]",
"==",
"value",
")",
"{",
"return",
"stackB",
"[",
"length",
"]",
";",
"}",
"}",
"result",
"=",
"isArr",
"?",
"ctor",
"(",
"value",
".",
"length",
")",
":",
"{",
"}",
";",
"}",
"else",
"{",
"result",
"=",
"isArr",
"?",
"slice",
"(",
"value",
")",
":",
"assign",
"(",
"{",
"}",
",",
"value",
")",
";",
"}",
"if",
"(",
"isArr",
")",
"{",
"if",
"(",
"hasOwnProperty",
".",
"call",
"(",
"value",
",",
"'index'",
")",
")",
"{",
"result",
".",
"index",
"=",
"value",
".",
"index",
";",
"}",
"if",
"(",
"hasOwnProperty",
".",
"call",
"(",
"value",
",",
"'input'",
")",
")",
"{",
"result",
".",
"input",
"=",
"value",
".",
"input",
";",
"}",
"}",
"if",
"(",
"!",
"isDeep",
")",
"{",
"return",
"result",
";",
"}",
"stackA",
".",
"push",
"(",
"value",
")",
";",
"stackB",
".",
"push",
"(",
"result",
")",
";",
"(",
"isArr",
"?",
"arrayEach",
":",
"baseForOwn",
")",
"(",
"value",
",",
"function",
"(",
"valValue",
",",
"key",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"baseClone",
"(",
"valValue",
",",
"isDeep",
",",
"callback",
",",
"stackA",
",",
"stackB",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | The base implementation of `_.clone` without argument juggling or support
for `this` binding.
@private
@param {*} value The value to clone.
@param {boolean} [isDeep=false] Specify a deep clone.
@param {Function} [callback] The function to customize cloning values.
@param {Array} [stackA=[]] Tracks traversed source objects.
@param {Array} [stackB=[]] Associates clones with source counterparts.
@returns {*} Returns the cloned value. | [
"The",
"base",
"implementation",
"of",
"_",
".",
"clone",
"without",
"argument",
"juggling",
"or",
"support",
"for",
"this",
"binding",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L940-L1012 | train |
atomantic/undermore | libs/lodash.js | baseEach | function baseEach(collection, callback) {
var index = -1,
iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
if (callback(iterable[index], index, collection) === false) {
break;
}
}
} else {
baseForOwn(collection, callback);
}
return collection;
} | javascript | function baseEach(collection, callback) {
var index = -1,
iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
if (callback(iterable[index], index, collection) === false) {
break;
}
}
} else {
baseForOwn(collection, callback);
}
return collection;
} | [
"function",
"baseEach",
"(",
"collection",
",",
"callback",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"iterable",
"=",
"collection",
",",
"length",
"=",
"collection",
"?",
"collection",
".",
"length",
":",
"0",
";",
"if",
"(",
"typeof",
"length",
"==",
"'number'",
"&&",
"length",
">",
"-",
"1",
"&&",
"length",
"<=",
"maxSafeInteger",
")",
"{",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"if",
"(",
"callback",
"(",
"iterable",
"[",
"index",
"]",
",",
"index",
",",
"collection",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"}",
"else",
"{",
"baseForOwn",
"(",
"collection",
",",
"callback",
")",
";",
"}",
"return",
"collection",
";",
"}"
] | The base implementation of `_.forEach` without support for callback
shorthands or `this` binding.
@private
@param {Array|Object|string} collection The collection to iterate over.
@param {Function} callback The function called per iteration.
@returns {Array|Object|string} Returns `collection`. | [
"The",
"base",
"implementation",
"of",
"_",
".",
"forEach",
"without",
"support",
"for",
"callback",
"shorthands",
"or",
"this",
"binding",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1219-L1234 | train |
atomantic/undermore | libs/lodash.js | baseEachRight | function baseEachRight(collection, callback) {
var iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (length--) {
if (callback(iterable[length], length, collection) === false) {
break;
}
}
} else {
baseForOwnRight(collection, callback);
}
return collection;
} | javascript | function baseEachRight(collection, callback) {
var iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (length--) {
if (callback(iterable[length], length, collection) === false) {
break;
}
}
} else {
baseForOwnRight(collection, callback);
}
return collection;
} | [
"function",
"baseEachRight",
"(",
"collection",
",",
"callback",
")",
"{",
"var",
"iterable",
"=",
"collection",
",",
"length",
"=",
"collection",
"?",
"collection",
".",
"length",
":",
"0",
";",
"if",
"(",
"typeof",
"length",
"==",
"'number'",
"&&",
"length",
">",
"-",
"1",
"&&",
"length",
"<=",
"maxSafeInteger",
")",
"{",
"while",
"(",
"length",
"--",
")",
"{",
"if",
"(",
"callback",
"(",
"iterable",
"[",
"length",
"]",
",",
"length",
",",
"collection",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"}",
"else",
"{",
"baseForOwnRight",
"(",
"collection",
",",
"callback",
")",
";",
"}",
"return",
"collection",
";",
"}"
] | The base implementation of `_.forEachRight` without support for callback
shorthands or `this` binding.
@private
@param {Array|Object|string} collection The collection to iterate over.
@param {Function} callback The function called per iteration.
@returns {Array|Object|string} Returns `collection`. | [
"The",
"base",
"implementation",
"of",
"_",
".",
"forEachRight",
"without",
"support",
"for",
"callback",
"shorthands",
"or",
"this",
"binding",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1245-L1259 | train |
atomantic/undermore | libs/lodash.js | baseFor | function baseFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
} | javascript | function baseFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
} | [
"function",
"baseFor",
"(",
"object",
",",
"callback",
",",
"keysFunc",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"props",
"=",
"keysFunc",
"(",
"object",
")",
",",
"length",
"=",
"props",
".",
"length",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"var",
"key",
"=",
"props",
"[",
"index",
"]",
";",
"if",
"(",
"callback",
"(",
"object",
"[",
"key",
"]",
",",
"key",
",",
"object",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"return",
"object",
";",
"}"
] | The base implementation of `baseForIn` and `baseForOwn` which iterates
over `object` properties returned by `keysFunc` executing the callback
for each property. Callbacks may exit iteration early by explicitly
returning `false`.
@private
@param {Object} object The object to iterate over.
@param {Function} callback The function called per iteration.
@param {Function} keysFunc The function to get the keys of `object`.
@returns {Object} Returns `object`. | [
"The",
"base",
"implementation",
"of",
"baseForIn",
"and",
"baseForOwn",
"which",
"iterates",
"over",
"object",
"properties",
"returned",
"by",
"keysFunc",
"executing",
"the",
"callback",
"for",
"each",
"property",
".",
"Callbacks",
"may",
"exit",
"iteration",
"early",
"by",
"explicitly",
"returning",
"false",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1338-L1350 | train |
atomantic/undermore | libs/lodash.js | baseForRight | function baseForRight(object, callback, keysFunc) {
var props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[length];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
} | javascript | function baseForRight(object, callback, keysFunc) {
var props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[length];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
} | [
"function",
"baseForRight",
"(",
"object",
",",
"callback",
",",
"keysFunc",
")",
"{",
"var",
"props",
"=",
"keysFunc",
"(",
"object",
")",
",",
"length",
"=",
"props",
".",
"length",
";",
"while",
"(",
"length",
"--",
")",
"{",
"var",
"key",
"=",
"props",
"[",
"length",
"]",
";",
"if",
"(",
"callback",
"(",
"object",
"[",
"key",
"]",
",",
"key",
",",
"object",
")",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"return",
"object",
";",
"}"
] | This function is like `baseFor` except that it iterates over properties
in the opposite order.
@private
@param {Object} object The object to iterate over.
@param {Function} callback The function called per iteration.
@param {Function} keysFunc The function to get the keys of `object`.
@returns {Object} Returns `object`. | [
"This",
"function",
"is",
"like",
"baseFor",
"except",
"that",
"it",
"iterates",
"over",
"properties",
"in",
"the",
"opposite",
"order",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1362-L1373 | train |
atomantic/undermore | libs/lodash.js | baseUniq | function baseUniq(array, isSorted, callback) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var index = -1,
indexOf = getIndexOf(),
prereq = !isSorted && indexOf === baseIndexOf,
isLarge = prereq && createCache && length >= 200,
isCommon = prereq && !isLarge,
result = [];
if (isLarge) {
var seen = createCache();
indexOf = cacheIndexOf;
} else {
seen = (callback && !isSorted) ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isCommon) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (callback) {
seen.push(computed);
}
result.push(value);
}
else if (isSorted) {
if (!index || seen !== computed) {
seen = computed;
result.push(value);
}
}
else if (indexOf(seen, computed) < 0) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
return result;
} | javascript | function baseUniq(array, isSorted, callback) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var index = -1,
indexOf = getIndexOf(),
prereq = !isSorted && indexOf === baseIndexOf,
isLarge = prereq && createCache && length >= 200,
isCommon = prereq && !isLarge,
result = [];
if (isLarge) {
var seen = createCache();
indexOf = cacheIndexOf;
} else {
seen = (callback && !isSorted) ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isCommon) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (callback) {
seen.push(computed);
}
result.push(value);
}
else if (isSorted) {
if (!index || seen !== computed) {
seen = computed;
result.push(value);
}
}
else if (indexOf(seen, computed) < 0) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
return result;
} | [
"function",
"baseUniq",
"(",
"array",
",",
"isSorted",
",",
"callback",
")",
"{",
"var",
"length",
"=",
"array",
"?",
"array",
".",
"length",
":",
"0",
";",
"if",
"(",
"!",
"length",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"index",
"=",
"-",
"1",
",",
"indexOf",
"=",
"getIndexOf",
"(",
")",
",",
"prereq",
"=",
"!",
"isSorted",
"&&",
"indexOf",
"===",
"baseIndexOf",
",",
"isLarge",
"=",
"prereq",
"&&",
"createCache",
"&&",
"length",
">=",
"200",
",",
"isCommon",
"=",
"prereq",
"&&",
"!",
"isLarge",
",",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"isLarge",
")",
"{",
"var",
"seen",
"=",
"createCache",
"(",
")",
";",
"indexOf",
"=",
"cacheIndexOf",
";",
"}",
"else",
"{",
"seen",
"=",
"(",
"callback",
"&&",
"!",
"isSorted",
")",
"?",
"[",
"]",
":",
"result",
";",
"}",
"outer",
":",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"var",
"value",
"=",
"array",
"[",
"index",
"]",
",",
"computed",
"=",
"callback",
"?",
"callback",
"(",
"value",
",",
"index",
",",
"array",
")",
":",
"value",
";",
"if",
"(",
"isCommon",
")",
"{",
"var",
"seenIndex",
"=",
"seen",
".",
"length",
";",
"while",
"(",
"seenIndex",
"--",
")",
"{",
"if",
"(",
"seen",
"[",
"seenIndex",
"]",
"===",
"computed",
")",
"{",
"continue",
"outer",
";",
"}",
"}",
"if",
"(",
"callback",
")",
"{",
"seen",
".",
"push",
"(",
"computed",
")",
";",
"}",
"result",
".",
"push",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"isSorted",
")",
"{",
"if",
"(",
"!",
"index",
"||",
"seen",
"!==",
"computed",
")",
"{",
"seen",
"=",
"computed",
";",
"result",
".",
"push",
"(",
"value",
")",
";",
"}",
"}",
"else",
"if",
"(",
"indexOf",
"(",
"seen",
",",
"computed",
")",
"<",
"0",
")",
"{",
"if",
"(",
"callback",
"||",
"isLarge",
")",
"{",
"seen",
".",
"push",
"(",
"computed",
")",
";",
"}",
"result",
".",
"push",
"(",
"value",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | The base implementation of `_.uniq` without support for callback shorthands
or `this` binding.
@private
@param {Array} array The array to process.
@param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
@param {Function} [callback] The function called per iteration.
@returns {Array} Returns the new duplicate-value-free array. | [
"The",
"base",
"implementation",
"of",
"_",
".",
"uniq",
"without",
"support",
"for",
"callback",
"shorthands",
"or",
"this",
"binding",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1674-L1723 | train |
atomantic/undermore | libs/lodash.js | createAggregator | function createAggregator(setter, initializer) {
return function(collection, callback, thisArg) {
var result = initializer ? initializer() : {};
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
var value = collection[index];
setter(result, value, callback(value, index, collection), collection);
}
} else {
baseEach(collection, function(value, key, collection) {
setter(result, value, callback(value, key, collection), collection);
});
}
return result;
};
} | javascript | function createAggregator(setter, initializer) {
return function(collection, callback, thisArg) {
var result = initializer ? initializer() : {};
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
var value = collection[index];
setter(result, value, callback(value, index, collection), collection);
}
} else {
baseEach(collection, function(value, key, collection) {
setter(result, value, callback(value, key, collection), collection);
});
}
return result;
};
} | [
"function",
"createAggregator",
"(",
"setter",
",",
"initializer",
")",
"{",
"return",
"function",
"(",
"collection",
",",
"callback",
",",
"thisArg",
")",
"{",
"var",
"result",
"=",
"initializer",
"?",
"initializer",
"(",
")",
":",
"{",
"}",
";",
"callback",
"=",
"lodash",
".",
"createCallback",
"(",
"callback",
",",
"thisArg",
",",
"3",
")",
";",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"collection",
"?",
"collection",
".",
"length",
":",
"0",
";",
"if",
"(",
"typeof",
"length",
"==",
"'number'",
"&&",
"length",
">",
"-",
"1",
"&&",
"length",
"<=",
"maxSafeInteger",
")",
"{",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"var",
"value",
"=",
"collection",
"[",
"index",
"]",
";",
"setter",
"(",
"result",
",",
"value",
",",
"callback",
"(",
"value",
",",
"index",
",",
"collection",
")",
",",
"collection",
")",
";",
"}",
"}",
"else",
"{",
"baseEach",
"(",
"collection",
",",
"function",
"(",
"value",
",",
"key",
",",
"collection",
")",
"{",
"setter",
"(",
"result",
",",
"value",
",",
"callback",
"(",
"value",
",",
"key",
",",
"collection",
")",
",",
"collection",
")",
";",
"}",
")",
";",
"}",
"return",
"result",
";",
"}",
";",
"}"
] | Creates a function that aggregates a collection, creating an accumulator
object composed from the results of running each element in the collection
through a callback. The given setter function sets the keys and values of
the accumulator object. If `initializer` is provided will be used to
initialize the accumulator object.
@private
@param {Function} setter The function to set keys and values of the accumulator object.
@param {Function} [initializer] The function to initialize the accumulator object.
@returns {Function} Returns the new aggregator function. | [
"Creates",
"a",
"function",
"that",
"aggregates",
"a",
"collection",
"creating",
"an",
"accumulator",
"object",
"composed",
"from",
"the",
"results",
"of",
"running",
"each",
"element",
"in",
"the",
"collection",
"through",
"a",
"callback",
".",
"The",
"given",
"setter",
"function",
"sets",
"the",
"keys",
"and",
"values",
"of",
"the",
"accumulator",
"object",
".",
"If",
"initializer",
"is",
"provided",
"will",
"be",
"used",
"to",
"initialize",
"the",
"accumulator",
"object",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1821-L1841 | train |
atomantic/undermore | libs/lodash.js | createPad | function createPad(string, length, chars) {
var strLength = string.length;
length = +length;
if (strLength >= length || !nativeIsFinite(length)) {
return '';
}
var padLength = length - strLength;
chars = chars == null ? ' ' : String(chars);
return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength);
} | javascript | function createPad(string, length, chars) {
var strLength = string.length;
length = +length;
if (strLength >= length || !nativeIsFinite(length)) {
return '';
}
var padLength = length - strLength;
chars = chars == null ? ' ' : String(chars);
return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength);
} | [
"function",
"createPad",
"(",
"string",
",",
"length",
",",
"chars",
")",
"{",
"var",
"strLength",
"=",
"string",
".",
"length",
";",
"length",
"=",
"+",
"length",
";",
"if",
"(",
"strLength",
">=",
"length",
"||",
"!",
"nativeIsFinite",
"(",
"length",
")",
")",
"{",
"return",
"''",
";",
"}",
"var",
"padLength",
"=",
"length",
"-",
"strLength",
";",
"chars",
"=",
"chars",
"==",
"null",
"?",
"' '",
":",
"String",
"(",
"chars",
")",
";",
"return",
"repeat",
"(",
"chars",
",",
"ceil",
"(",
"padLength",
"/",
"chars",
".",
"length",
")",
")",
".",
"slice",
"(",
"0",
",",
"padLength",
")",
";",
"}"
] | Creates the pad required for `string` based on the given padding length.
The `chars` string may be truncated if the number of padding characters
exceeds the padding length.
@private
@param {string} string The string to create padding for.
@param {number} [length=0] The padding length.
@param {string} [chars=' '] The string used as padding.
@returns {string} Returns the pad for `string`. | [
"Creates",
"the",
"pad",
"required",
"for",
"string",
"based",
"on",
"the",
"given",
"padding",
"length",
".",
"The",
"chars",
"string",
"may",
"be",
"truncated",
"if",
"the",
"number",
"of",
"padding",
"characters",
"exceeds",
"the",
"padding",
"length",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1872-L1882 | train |
atomantic/undermore | libs/lodash.js | createWrapper | function createWrapper(func, bitmask, arity, thisArg, partialArgs, partialRightArgs) {
var isBind = bitmask & BIND_FLAG,
isBindKey = bitmask & BIND_KEY_FLAG,
isPartial = bitmask & PARTIAL_FLAG,
isPartialRight = bitmask & PARTIAL_RIGHT_FLAG;
if (!isBindKey && !isFunction(func)) {
throw new TypeError(funcErrorText);
}
if (isPartial && !partialArgs.length) {
bitmask &= ~PARTIAL_FLAG;
isPartial = partialArgs = false;
}
if (isPartialRight && !partialRightArgs.length) {
bitmask &= ~PARTIAL_RIGHT_FLAG;
isPartialRight = partialRightArgs = false;
}
var data = !isBindKey && func[expando];
if (data && data !== true) {
// shallow clone `data`
data = slice(data);
// clone partial left arguments
if (data[4]) {
data[4] = slice(data[4]);
}
// clone partial right arguments
if (data[5]) {
data[5] = slice(data[5]);
}
// set arity if provided
if (typeof arity == 'number') {
data[2] = arity;
}
// set `thisArg` if not previously bound
var bound = data[1] & BIND_FLAG;
if (isBind && !bound) {
data[3] = thisArg;
}
// set if currying a bound function
if (!isBind && bound) {
bitmask |= CURRY_BOUND_FLAG;
}
// append partial left arguments
if (isPartial) {
if (data[4]) {
push.apply(data[4], partialArgs);
} else {
data[4] = partialArgs;
}
}
// prepend partial right arguments
if (isPartialRight) {
if (data[5]) {
unshift.apply(data[5], partialRightArgs);
} else {
data[5] = partialRightArgs;
}
}
// merge flags
data[1] |= bitmask;
return createWrapper.apply(null, data);
}
if (isPartial) {
var partialHolders = [];
}
if (isPartialRight) {
var partialRightHolders = [];
}
if (arity == null) {
arity = isBindKey ? 0 : func.length;
}
arity = nativeMax(arity, 0);
// fast path for `_.bind`
data = [func, bitmask, arity, thisArg, partialArgs, partialRightArgs, partialHolders, partialRightHolders];
return (bitmask == BIND_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG))
? baseBind(data)
: baseCreateWrapper(data);
} | javascript | function createWrapper(func, bitmask, arity, thisArg, partialArgs, partialRightArgs) {
var isBind = bitmask & BIND_FLAG,
isBindKey = bitmask & BIND_KEY_FLAG,
isPartial = bitmask & PARTIAL_FLAG,
isPartialRight = bitmask & PARTIAL_RIGHT_FLAG;
if (!isBindKey && !isFunction(func)) {
throw new TypeError(funcErrorText);
}
if (isPartial && !partialArgs.length) {
bitmask &= ~PARTIAL_FLAG;
isPartial = partialArgs = false;
}
if (isPartialRight && !partialRightArgs.length) {
bitmask &= ~PARTIAL_RIGHT_FLAG;
isPartialRight = partialRightArgs = false;
}
var data = !isBindKey && func[expando];
if (data && data !== true) {
// shallow clone `data`
data = slice(data);
// clone partial left arguments
if (data[4]) {
data[4] = slice(data[4]);
}
// clone partial right arguments
if (data[5]) {
data[5] = slice(data[5]);
}
// set arity if provided
if (typeof arity == 'number') {
data[2] = arity;
}
// set `thisArg` if not previously bound
var bound = data[1] & BIND_FLAG;
if (isBind && !bound) {
data[3] = thisArg;
}
// set if currying a bound function
if (!isBind && bound) {
bitmask |= CURRY_BOUND_FLAG;
}
// append partial left arguments
if (isPartial) {
if (data[4]) {
push.apply(data[4], partialArgs);
} else {
data[4] = partialArgs;
}
}
// prepend partial right arguments
if (isPartialRight) {
if (data[5]) {
unshift.apply(data[5], partialRightArgs);
} else {
data[5] = partialRightArgs;
}
}
// merge flags
data[1] |= bitmask;
return createWrapper.apply(null, data);
}
if (isPartial) {
var partialHolders = [];
}
if (isPartialRight) {
var partialRightHolders = [];
}
if (arity == null) {
arity = isBindKey ? 0 : func.length;
}
arity = nativeMax(arity, 0);
// fast path for `_.bind`
data = [func, bitmask, arity, thisArg, partialArgs, partialRightArgs, partialHolders, partialRightHolders];
return (bitmask == BIND_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG))
? baseBind(data)
: baseCreateWrapper(data);
} | [
"function",
"createWrapper",
"(",
"func",
",",
"bitmask",
",",
"arity",
",",
"thisArg",
",",
"partialArgs",
",",
"partialRightArgs",
")",
"{",
"var",
"isBind",
"=",
"bitmask",
"&",
"BIND_FLAG",
",",
"isBindKey",
"=",
"bitmask",
"&",
"BIND_KEY_FLAG",
",",
"isPartial",
"=",
"bitmask",
"&",
"PARTIAL_FLAG",
",",
"isPartialRight",
"=",
"bitmask",
"&",
"PARTIAL_RIGHT_FLAG",
";",
"if",
"(",
"!",
"isBindKey",
"&&",
"!",
"isFunction",
"(",
"func",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"funcErrorText",
")",
";",
"}",
"if",
"(",
"isPartial",
"&&",
"!",
"partialArgs",
".",
"length",
")",
"{",
"bitmask",
"&=",
"~",
"PARTIAL_FLAG",
";",
"isPartial",
"=",
"partialArgs",
"=",
"false",
";",
"}",
"if",
"(",
"isPartialRight",
"&&",
"!",
"partialRightArgs",
".",
"length",
")",
"{",
"bitmask",
"&=",
"~",
"PARTIAL_RIGHT_FLAG",
";",
"isPartialRight",
"=",
"partialRightArgs",
"=",
"false",
";",
"}",
"var",
"data",
"=",
"!",
"isBindKey",
"&&",
"func",
"[",
"expando",
"]",
";",
"if",
"(",
"data",
"&&",
"data",
"!==",
"true",
")",
"{",
"data",
"=",
"slice",
"(",
"data",
")",
";",
"if",
"(",
"data",
"[",
"4",
"]",
")",
"{",
"data",
"[",
"4",
"]",
"=",
"slice",
"(",
"data",
"[",
"4",
"]",
")",
";",
"}",
"if",
"(",
"data",
"[",
"5",
"]",
")",
"{",
"data",
"[",
"5",
"]",
"=",
"slice",
"(",
"data",
"[",
"5",
"]",
")",
";",
"}",
"if",
"(",
"typeof",
"arity",
"==",
"'number'",
")",
"{",
"data",
"[",
"2",
"]",
"=",
"arity",
";",
"}",
"var",
"bound",
"=",
"data",
"[",
"1",
"]",
"&",
"BIND_FLAG",
";",
"if",
"(",
"isBind",
"&&",
"!",
"bound",
")",
"{",
"data",
"[",
"3",
"]",
"=",
"thisArg",
";",
"}",
"if",
"(",
"!",
"isBind",
"&&",
"bound",
")",
"{",
"bitmask",
"|=",
"CURRY_BOUND_FLAG",
";",
"}",
"if",
"(",
"isPartial",
")",
"{",
"if",
"(",
"data",
"[",
"4",
"]",
")",
"{",
"push",
".",
"apply",
"(",
"data",
"[",
"4",
"]",
",",
"partialArgs",
")",
";",
"}",
"else",
"{",
"data",
"[",
"4",
"]",
"=",
"partialArgs",
";",
"}",
"}",
"if",
"(",
"isPartialRight",
")",
"{",
"if",
"(",
"data",
"[",
"5",
"]",
")",
"{",
"unshift",
".",
"apply",
"(",
"data",
"[",
"5",
"]",
",",
"partialRightArgs",
")",
";",
"}",
"else",
"{",
"data",
"[",
"5",
"]",
"=",
"partialRightArgs",
";",
"}",
"}",
"data",
"[",
"1",
"]",
"|=",
"bitmask",
";",
"return",
"createWrapper",
".",
"apply",
"(",
"null",
",",
"data",
")",
";",
"}",
"if",
"(",
"isPartial",
")",
"{",
"var",
"partialHolders",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"isPartialRight",
")",
"{",
"var",
"partialRightHolders",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"arity",
"==",
"null",
")",
"{",
"arity",
"=",
"isBindKey",
"?",
"0",
":",
"func",
".",
"length",
";",
"}",
"arity",
"=",
"nativeMax",
"(",
"arity",
",",
"0",
")",
";",
"data",
"=",
"[",
"func",
",",
"bitmask",
",",
"arity",
",",
"thisArg",
",",
"partialArgs",
",",
"partialRightArgs",
",",
"partialHolders",
",",
"partialRightHolders",
"]",
";",
"return",
"(",
"bitmask",
"==",
"BIND_FLAG",
"||",
"bitmask",
"==",
"(",
"BIND_FLAG",
"|",
"PARTIAL_FLAG",
")",
")",
"?",
"baseBind",
"(",
"data",
")",
":",
"baseCreateWrapper",
"(",
"data",
")",
";",
"}"
] | Creates a function that either curries or invokes `func` with an optional
`this` binding and partially applied arguments.
@private
@param {Function|string} func The function or method name to reference.
@param {number} bitmask The bitmask of flags to compose.
The bitmask may be composed of the following flags:
1 - `_.bind`
2 - `_.bindKey`
4 - `_.curry`
8 - `_.curry` (bound)
16 - `_.partial`
32 - `_.partialRight`
@param {number} [arity] The arity of `func`.
@param {*} [thisArg] The `this` binding of `func`.
@param {Array} [partialArgs] An array of arguments to prepend to those
provided to the new function.
@param {Array} [partialRightArgs] An array of arguments to append to those
provided to the new function.
@returns {Function} Returns the new function. | [
"Creates",
"a",
"function",
"that",
"either",
"curries",
"or",
"invokes",
"func",
"with",
"an",
"optional",
"this",
"binding",
"and",
"partially",
"applied",
"arguments",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L1906-L1985 | train |
atomantic/undermore | libs/lodash.js | shimKeys | function shimKeys(object) {
var keyIndex,
index = -1,
props = keysIn(object),
length = props.length,
objLength = length && object.length,
maxIndex = objLength - 1,
result = [];
var allowIndexes = typeof objLength == 'number' && objLength > 0 &&
(isArray(object) || (support.nonEnumArgs && isArguments(object)));
while (++index < length) {
var key = props[index];
if ((allowIndexes && (keyIndex = +key, keyIndex > -1 && keyIndex <= maxIndex && keyIndex % 1 == 0)) ||
hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
} | javascript | function shimKeys(object) {
var keyIndex,
index = -1,
props = keysIn(object),
length = props.length,
objLength = length && object.length,
maxIndex = objLength - 1,
result = [];
var allowIndexes = typeof objLength == 'number' && objLength > 0 &&
(isArray(object) || (support.nonEnumArgs && isArguments(object)));
while (++index < length) {
var key = props[index];
if ((allowIndexes && (keyIndex = +key, keyIndex > -1 && keyIndex <= maxIndex && keyIndex % 1 == 0)) ||
hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
} | [
"function",
"shimKeys",
"(",
"object",
")",
"{",
"var",
"keyIndex",
",",
"index",
"=",
"-",
"1",
",",
"props",
"=",
"keysIn",
"(",
"object",
")",
",",
"length",
"=",
"props",
".",
"length",
",",
"objLength",
"=",
"length",
"&&",
"object",
".",
"length",
",",
"maxIndex",
"=",
"objLength",
"-",
"1",
",",
"result",
"=",
"[",
"]",
";",
"var",
"allowIndexes",
"=",
"typeof",
"objLength",
"==",
"'number'",
"&&",
"objLength",
">",
"0",
"&&",
"(",
"isArray",
"(",
"object",
")",
"||",
"(",
"support",
".",
"nonEnumArgs",
"&&",
"isArguments",
"(",
"object",
")",
")",
")",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"var",
"key",
"=",
"props",
"[",
"index",
"]",
";",
"if",
"(",
"(",
"allowIndexes",
"&&",
"(",
"keyIndex",
"=",
"+",
"key",
",",
"keyIndex",
">",
"-",
"1",
"&&",
"keyIndex",
"<=",
"maxIndex",
"&&",
"keyIndex",
"%",
"1",
"==",
"0",
")",
")",
"||",
"hasOwnProperty",
".",
"call",
"(",
"object",
",",
"key",
")",
")",
"{",
"result",
".",
"push",
"(",
"key",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | A fallback implementation of `Object.keys` which creates an array of the
own enumerable property names of `object`.
@private
@param {Object} object The object to inspect.
@returns {Array} Returns the array of property names. | [
"A",
"fallback",
"implementation",
"of",
"Object",
".",
"keys",
"which",
"creates",
"an",
"array",
"of",
"the",
"own",
"enumerable",
"property",
"names",
"of",
"object",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L2059-L2079 | train |
atomantic/undermore | libs/lodash.js | findIndex | function findIndex(array, predicate, thisArg) {
var index = -1,
length = array ? array.length : 0;
predicate = lodash.createCallback(predicate, thisArg, 3);
while (++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
} | javascript | function findIndex(array, predicate, thisArg) {
var index = -1,
length = array ? array.length : 0;
predicate = lodash.createCallback(predicate, thisArg, 3);
while (++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
} | [
"function",
"findIndex",
"(",
"array",
",",
"predicate",
",",
"thisArg",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"array",
"?",
"array",
".",
"length",
":",
"0",
";",
"predicate",
"=",
"lodash",
".",
"createCallback",
"(",
"predicate",
",",
"thisArg",
",",
"3",
")",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"if",
"(",
"predicate",
"(",
"array",
"[",
"index",
"]",
",",
"index",
",",
"array",
")",
")",
"{",
"return",
"index",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] | This method is like `_.find` except that it returns the index of the first
element the predicate returns truthy for, instead of the element itself.
If a property name is provided for `predicate` the created "_.pluck" style
callback will return the property value of the given element.
If an object is provided for `predicate` the created "_.where" style callback
will return `true` for elements that have the properties of the given object,
else `false`.
@static
@memberOf _
@category Arrays
@param {Array} array The array to search.
@param {Function|Object|string} [predicate=identity] The function called
per iteration. If a property name or object is provided it will be used
to create a "_.pluck" or "_.where" style callback respectively.
@param {*} [thisArg] The `this` binding of `predicate`.
@returns {number} Returns the index of the found element, else `-1`.
@example
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40, 'blocked': true },
{ 'name': 'pebbles', 'age': 1 }
];
_.findIndex(characters, function(chr) {
return chr.age < 20;
});
// => 2
// using "_.where" callback shorthand
_.findIndex(characters, { 'age': 36 });
// => 0
// using "_.pluck" callback shorthand
_.findIndex(characters, 'blocked');
// => 1 | [
"This",
"method",
"is",
"like",
"_",
".",
"find",
"except",
"that",
"it",
"returns",
"the",
"index",
"of",
"the",
"first",
"element",
"the",
"predicate",
"returns",
"truthy",
"for",
"instead",
"of",
"the",
"element",
"itself",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L2319-L2330 | train |
atomantic/undermore | libs/lodash.js | rest | function rest(array, predicate, thisArg) {
if (typeof predicate != 'number' && predicate != null) {
var index = -1,
length = array ? array.length : 0,
n = 0;
predicate = lodash.createCallback(predicate, thisArg, 3);
while (++index < length && predicate(array[index], index, array)) {
n++;
}
} else if (predicate == null || thisArg) {
n = 1;
} else {
n = predicate < 0 ? 0 : predicate;
}
return slice(array, n);
} | javascript | function rest(array, predicate, thisArg) {
if (typeof predicate != 'number' && predicate != null) {
var index = -1,
length = array ? array.length : 0,
n = 0;
predicate = lodash.createCallback(predicate, thisArg, 3);
while (++index < length && predicate(array[index], index, array)) {
n++;
}
} else if (predicate == null || thisArg) {
n = 1;
} else {
n = predicate < 0 ? 0 : predicate;
}
return slice(array, n);
} | [
"function",
"rest",
"(",
"array",
",",
"predicate",
",",
"thisArg",
")",
"{",
"if",
"(",
"typeof",
"predicate",
"!=",
"'number'",
"&&",
"predicate",
"!=",
"null",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"array",
"?",
"array",
".",
"length",
":",
"0",
",",
"n",
"=",
"0",
";",
"predicate",
"=",
"lodash",
".",
"createCallback",
"(",
"predicate",
",",
"thisArg",
",",
"3",
")",
";",
"while",
"(",
"++",
"index",
"<",
"length",
"&&",
"predicate",
"(",
"array",
"[",
"index",
"]",
",",
"index",
",",
"array",
")",
")",
"{",
"n",
"++",
";",
"}",
"}",
"else",
"if",
"(",
"predicate",
"==",
"null",
"||",
"thisArg",
")",
"{",
"n",
"=",
"1",
";",
"}",
"else",
"{",
"n",
"=",
"predicate",
"<",
"0",
"?",
"0",
":",
"predicate",
";",
"}",
"return",
"slice",
"(",
"array",
",",
"n",
")",
";",
"}"
] | Gets all but the first element of `array`.
Note: The `n` and `predicate` arguments are deprecated; replace with
`_.drop` and `_.dropWhile` respectively.
@static
@memberOf _
@alias tail
@category Arrays
@param {Array} array The array to query.
@returns {Array} Returns the slice of `array`.
@example
_.rest([1, 2, 3]);
// => [2, 3] | [
"Gets",
"all",
"but",
"the",
"first",
"element",
"of",
"array",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L2794-L2810 | train |
atomantic/undermore | libs/lodash.js | slice | function slice(array, start, end) {
var index = -1,
length = array ? array.length : 0;
start = typeof start == 'undefined' ? 0 : (+start || 0);
if (start < 0) {
start = nativeMax(length + start, 0);
} else if (start > length) {
start = length;
}
end = typeof end == 'undefined' ? length : (+end || 0);
if (end < 0) {
end = nativeMax(length + end, 0);
} else if (end > length) {
end = length;
}
length = start > end ? 0 : (end - start);
var result = Array(length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
} | javascript | function slice(array, start, end) {
var index = -1,
length = array ? array.length : 0;
start = typeof start == 'undefined' ? 0 : (+start || 0);
if (start < 0) {
start = nativeMax(length + start, 0);
} else if (start > length) {
start = length;
}
end = typeof end == 'undefined' ? length : (+end || 0);
if (end < 0) {
end = nativeMax(length + end, 0);
} else if (end > length) {
end = length;
}
length = start > end ? 0 : (end - start);
var result = Array(length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
} | [
"function",
"slice",
"(",
"array",
",",
"start",
",",
"end",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"array",
"?",
"array",
".",
"length",
":",
"0",
";",
"start",
"=",
"typeof",
"start",
"==",
"'undefined'",
"?",
"0",
":",
"(",
"+",
"start",
"||",
"0",
")",
";",
"if",
"(",
"start",
"<",
"0",
")",
"{",
"start",
"=",
"nativeMax",
"(",
"length",
"+",
"start",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"start",
">",
"length",
")",
"{",
"start",
"=",
"length",
";",
"}",
"end",
"=",
"typeof",
"end",
"==",
"'undefined'",
"?",
"length",
":",
"(",
"+",
"end",
"||",
"0",
")",
";",
"if",
"(",
"end",
"<",
"0",
")",
"{",
"end",
"=",
"nativeMax",
"(",
"length",
"+",
"end",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"end",
">",
"length",
")",
"{",
"end",
"=",
"length",
";",
"}",
"length",
"=",
"start",
">",
"end",
"?",
"0",
":",
"(",
"end",
"-",
"start",
")",
";",
"var",
"result",
"=",
"Array",
"(",
"length",
")",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"result",
"[",
"index",
"]",
"=",
"array",
"[",
"start",
"+",
"index",
"]",
";",
"}",
"return",
"result",
";",
"}"
] | Slices `array` from the `start` index up to, but not including, the `end` index.
Note: This function is used instead of `Array#slice` to support node lists
in IE < 9 and to ensure dense arrays are returned.
@static
@memberOf _
@category Arrays
@param {Array} array The array to slice.
@param {number} [start=0] The start index.
@param {number} [end=array.length] The end index.
@returns {Array} Returns the slice of `array`. | [
"Slices",
"array",
"from",
"the",
"start",
"index",
"up",
"to",
"but",
"not",
"including",
"the",
"end",
"index",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L2826-L2849 | train |
atomantic/undermore | libs/lodash.js | size | function size(collection) {
var length = collection ? collection.length : 0;
return (typeof length == 'number' && length > -1 && length <= maxSafeInteger)
? length
: keys(collection).length;
} | javascript | function size(collection) {
var length = collection ? collection.length : 0;
return (typeof length == 'number' && length > -1 && length <= maxSafeInteger)
? length
: keys(collection).length;
} | [
"function",
"size",
"(",
"collection",
")",
"{",
"var",
"length",
"=",
"collection",
"?",
"collection",
".",
"length",
":",
"0",
";",
"return",
"(",
"typeof",
"length",
"==",
"'number'",
"&&",
"length",
">",
"-",
"1",
"&&",
"length",
"<=",
"maxSafeInteger",
")",
"?",
"length",
":",
"keys",
"(",
"collection",
")",
".",
"length",
";",
"}"
] | Gets the size of the collection by returning `collection.length` for arrays
and array-like objects or the number of own enumerable properties for objects.
@static
@memberOf _
@category Collections
@param {Array|Object|string} collection The collection to inspect.
@returns {number} Returns `collection.length` or number of own enumerable properties.
@example
_.size([1, 2]);
// => 2
_.size({ 'one': 1, 'two': 2, 'three': 3 });
// => 3
_.size('pebbles');
// => 7 | [
"Gets",
"the",
"size",
"of",
"the",
"collection",
"by",
"returning",
"collection",
".",
"length",
"for",
"arrays",
"and",
"array",
"-",
"like",
"objects",
"or",
"the",
"number",
"of",
"own",
"enumerable",
"properties",
"for",
"objects",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L4410-L4415 | train |
atomantic/undermore | libs/lodash.js | toArray | function toArray(collection) {
var length = collection && collection.length;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
return slice(collection);
}
return values(collection);
} | javascript | function toArray(collection) {
var length = collection && collection.length;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
return slice(collection);
}
return values(collection);
} | [
"function",
"toArray",
"(",
"collection",
")",
"{",
"var",
"length",
"=",
"collection",
"&&",
"collection",
".",
"length",
";",
"if",
"(",
"typeof",
"length",
"==",
"'number'",
"&&",
"length",
">",
"-",
"1",
"&&",
"length",
"<=",
"maxSafeInteger",
")",
"{",
"return",
"slice",
"(",
"collection",
")",
";",
"}",
"return",
"values",
"(",
"collection",
")",
";",
"}"
] | Converts `collection` to an array.
@static
@memberOf _
@category Collections
@param {Array|Object|string} collection The collection to convert.
@returns {Array} Returns the new converted array.
@example
(function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
// => [2, 3, 4] | [
"Converts",
"collection",
"to",
"an",
"array",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L4573-L4579 | train |
atomantic/undermore | libs/lodash.js | delay | function delay(func, wait) {
if (!isFunction(func)) {
throw new TypeError(funcErrorText);
}
var args = slice(arguments, 2);
return setTimeout(function() { func.apply(undefined, args); }, wait);
} | javascript | function delay(func, wait) {
if (!isFunction(func)) {
throw new TypeError(funcErrorText);
}
var args = slice(arguments, 2);
return setTimeout(function() { func.apply(undefined, args); }, wait);
} | [
"function",
"delay",
"(",
"func",
",",
"wait",
")",
"{",
"if",
"(",
"!",
"isFunction",
"(",
"func",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"funcErrorText",
")",
";",
"}",
"var",
"args",
"=",
"slice",
"(",
"arguments",
",",
"2",
")",
";",
"return",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"func",
".",
"apply",
"(",
"undefined",
",",
"args",
")",
";",
"}",
",",
"wait",
")",
";",
"}"
] | Executes the `func` function after `wait` milliseconds. Additional arguments
will be provided to `func` when it is invoked.
@static
@memberOf _
@category Functions
@param {Function} func The function to delay.
@param {number} wait The number of milliseconds to delay execution.
@param {...*} [args] Arguments to invoke the function with.
@returns {number} Returns the timer id.
@example
_.delay(function(text) { console.log(text); }, 1000, 'later');
// => logs 'later' after one second | [
"Executes",
"the",
"func",
"function",
"after",
"wait",
"milliseconds",
".",
"Additional",
"arguments",
"will",
"be",
"provided",
"to",
"func",
"when",
"it",
"is",
"invoked",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L5034-L5040 | train |
atomantic/undermore | libs/lodash.js | once | function once(func) {
var ran,
result;
if (!isFunction(func)) {
throw new TypeError(funcErrorText);
}
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
} | javascript | function once(func) {
var ran,
result;
if (!isFunction(func)) {
throw new TypeError(funcErrorText);
}
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
} | [
"function",
"once",
"(",
"func",
")",
"{",
"var",
"ran",
",",
"result",
";",
"if",
"(",
"!",
"isFunction",
"(",
"func",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"funcErrorText",
")",
";",
"}",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"ran",
")",
"{",
"return",
"result",
";",
"}",
"ran",
"=",
"true",
";",
"result",
"=",
"func",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"func",
"=",
"null",
";",
"return",
"result",
";",
"}",
";",
"}"
] | Creates a function that is restricted to execute `func` once. Repeat calls to
the function will return the value of the first call. The `func` is executed
with the `this` binding of the created function.
@static
@memberOf _
@category Functions
@param {Function} func The function to restrict.
@returns {Function} Returns the new restricted function.
@example
var initialize = _.once(createApplication);
initialize();
initialize();
// `initialize` executes `createApplication` once | [
"Creates",
"a",
"function",
"that",
"is",
"restricted",
"to",
"execute",
"func",
"once",
".",
"Repeat",
"calls",
"to",
"the",
"function",
"will",
"return",
"the",
"value",
"of",
"the",
"first",
"call",
".",
"The",
"func",
"is",
"executed",
"with",
"the",
"this",
"binding",
"of",
"the",
"created",
"function",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L5140-L5158 | train |
atomantic/undermore | libs/lodash.js | findKey | function findKey(object, predicate, thisArg) {
predicate = lodash.createCallback(predicate, thisArg, 3);
return baseFind(object, predicate, baseForOwn, true);
} | javascript | function findKey(object, predicate, thisArg) {
predicate = lodash.createCallback(predicate, thisArg, 3);
return baseFind(object, predicate, baseForOwn, true);
} | [
"function",
"findKey",
"(",
"object",
",",
"predicate",
",",
"thisArg",
")",
"{",
"predicate",
"=",
"lodash",
".",
"createCallback",
"(",
"predicate",
",",
"thisArg",
",",
"3",
")",
";",
"return",
"baseFind",
"(",
"object",
",",
"predicate",
",",
"baseForOwn",
",",
"true",
")",
";",
"}"
] | This method is like `_.findIndex` except that it returns the key of the
first element the predicate returns truthy for, instead of the element itself.
If a property name is provided for `predicate` the created "_.pluck" style
callback will return the property value of the given element.
If an object is provided for `predicate` the created "_.where" style callback
will return `true` for elements that have the properties of the given object,
else `false`.
@static
@memberOf _
@category Objects
@param {Object} object The object to search.
@param {Function|Object|string} [predicate=identity] The function called
per iteration. If a property name or object is provided it will be used
to create a "_.pluck" or "_.where" style callback respectively.
@param {*} [thisArg] The `this` binding of `predicate`.
@returns {string|undefined} Returns the key of the matched element, else `undefined`.
@example
var characters = {
'barney': { 'age': 36 },
'fred': { 'age': 40, 'blocked': true },
'pebbles': { 'age': 1 }
};
_.findKey(characters, function(chr) {
return chr.age < 40;
});
// => 'barney' (property order is not guaranteed across environments)
// using "_.where" callback shorthand
_.findKey(characters, { 'age': 1 });
// => 'pebbles'
// using "_.pluck" callback shorthand
_.findKey(characters, 'blocked');
// => 'fred' | [
"This",
"method",
"is",
"like",
"_",
".",
"findIndex",
"except",
"that",
"it",
"returns",
"the",
"key",
"of",
"the",
"first",
"element",
"the",
"predicate",
"returns",
"truthy",
"for",
"instead",
"of",
"the",
"element",
"itself",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L5584-L5587 | train |
atomantic/undermore | libs/lodash.js | isArguments | function isArguments(value) {
return (value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == argsClass) || false;
} | javascript | function isArguments(value) {
return (value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == argsClass) || false;
} | [
"function",
"isArguments",
"(",
"value",
")",
"{",
"return",
"(",
"value",
"&&",
"typeof",
"value",
"==",
"'object'",
"&&",
"typeof",
"value",
".",
"length",
"==",
"'number'",
"&&",
"toString",
".",
"call",
"(",
"value",
")",
"==",
"argsClass",
")",
"||",
"false",
";",
"}"
] | Checks if `value` is an `arguments` object.
@static
@memberOf _
@category Objects
@param {*} value The value to check.
@returns {boolean} Returns `true` if `value` is an `arguments` object, else `false`.
@example
(function() { return _.isArguments(arguments); })();
// => true
_.isArguments([1, 2, 3]);
// => false | [
"Checks",
"if",
"value",
"is",
"an",
"arguments",
"object",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L5855-L5858 | train |
atomantic/undermore | libs/lodash.js | isEmpty | function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var length = value.length;
if ((length > -1 && length <= maxSafeInteger) &&
(isArray(value) || isString(value) || isArguments(value) ||
(typeof value == 'object' && isFunction(value.splice)))) {
return !length;
}
baseForOwn(value, function() {
return (result = false);
});
return result;
} | javascript | function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var length = value.length;
if ((length > -1 && length <= maxSafeInteger) &&
(isArray(value) || isString(value) || isArguments(value) ||
(typeof value == 'object' && isFunction(value.splice)))) {
return !length;
}
baseForOwn(value, function() {
return (result = false);
});
return result;
} | [
"function",
"isEmpty",
"(",
"value",
")",
"{",
"var",
"result",
"=",
"true",
";",
"if",
"(",
"!",
"value",
")",
"{",
"return",
"result",
";",
"}",
"var",
"length",
"=",
"value",
".",
"length",
";",
"if",
"(",
"(",
"length",
">",
"-",
"1",
"&&",
"length",
"<=",
"maxSafeInteger",
")",
"&&",
"(",
"isArray",
"(",
"value",
")",
"||",
"isString",
"(",
"value",
")",
"||",
"isArguments",
"(",
"value",
")",
"||",
"(",
"typeof",
"value",
"==",
"'object'",
"&&",
"isFunction",
"(",
"value",
".",
"splice",
")",
")",
")",
")",
"{",
"return",
"!",
"length",
";",
"}",
"baseForOwn",
"(",
"value",
",",
"function",
"(",
")",
"{",
"return",
"(",
"result",
"=",
"false",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Checks if a collection is empty. A value is considered empty unless it is
an array, array-like object, or string with a length greater than `0` or
an object with own properties.
@static
@memberOf _
@category Objects
@param {Array|Object|string} value The value to inspect.
@returns {boolean} Returns `true` if `value` is empty, else `false`.
@example
_.isEmpty(null);
// => true
_.isEmpty(true);
// => true
_.isEmpty(1);
// => true
_.isEmpty([1, 2, 3]);
// => false
_.isEmpty({ 'a': 1 });
// => false | [
"Checks",
"if",
"a",
"collection",
"is",
"empty",
".",
"A",
"value",
"is",
"considered",
"empty",
"unless",
"it",
"is",
"an",
"array",
"array",
"-",
"like",
"object",
"or",
"string",
"with",
"a",
"length",
"greater",
"than",
"0",
"or",
"an",
"object",
"with",
"own",
"properties",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L5977-L5992 | train |
atomantic/undermore | libs/lodash.js | endsWith | function endsWith(string, target, position) {
string = string == null ? '' : String(string);
target = String(target);
var length = string.length;
position = (typeof position == 'undefined' ? length : nativeMin(position < 0 ? 0 : (+position || 0), length)) - target.length;
return position >= 0 && string.indexOf(target, position) == position;
} | javascript | function endsWith(string, target, position) {
string = string == null ? '' : String(string);
target = String(target);
var length = string.length;
position = (typeof position == 'undefined' ? length : nativeMin(position < 0 ? 0 : (+position || 0), length)) - target.length;
return position >= 0 && string.indexOf(target, position) == position;
} | [
"function",
"endsWith",
"(",
"string",
",",
"target",
",",
"position",
")",
"{",
"string",
"=",
"string",
"==",
"null",
"?",
"''",
":",
"String",
"(",
"string",
")",
";",
"target",
"=",
"String",
"(",
"target",
")",
";",
"var",
"length",
"=",
"string",
".",
"length",
";",
"position",
"=",
"(",
"typeof",
"position",
"==",
"'undefined'",
"?",
"length",
":",
"nativeMin",
"(",
"position",
"<",
"0",
"?",
"0",
":",
"(",
"+",
"position",
"||",
"0",
")",
",",
"length",
")",
")",
"-",
"target",
".",
"length",
";",
"return",
"position",
">=",
"0",
"&&",
"string",
".",
"indexOf",
"(",
"target",
",",
"position",
")",
"==",
"position",
";",
"}"
] | Checks if `string` ends with a given target string.
@static
@memberOf _
@category Strings
@param {string} [string=''] The string to search.
@param {string} [target] The string to search for.
@param {number} [position=string.length] The position to search from.
@returns {boolean} Returns `true` if the given string ends with the
target string, else `false`.
@example
_.endsWith('abc', 'c');
// => true
_.endsWith('abc', 'b');
// => false
_.endsWith('abc', 'b', 2);
// => true | [
"Checks",
"if",
"string",
"ends",
"with",
"a",
"given",
"target",
"string",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L6839-L6846 | train |
atomantic/undermore | libs/lodash.js | pad | function pad(string, length, chars) {
string = string == null ? '' : String(string);
length = +length;
var strLength = string.length;
if (strLength >= length || !nativeIsFinite(length)) {
return string;
}
var mid = (length - strLength) / 2,
leftLength = floor(mid),
rightLength = ceil(mid);
chars = createPad('', rightLength, chars);
return chars.slice(0, leftLength) + string + chars;
} | javascript | function pad(string, length, chars) {
string = string == null ? '' : String(string);
length = +length;
var strLength = string.length;
if (strLength >= length || !nativeIsFinite(length)) {
return string;
}
var mid = (length - strLength) / 2,
leftLength = floor(mid),
rightLength = ceil(mid);
chars = createPad('', rightLength, chars);
return chars.slice(0, leftLength) + string + chars;
} | [
"function",
"pad",
"(",
"string",
",",
"length",
",",
"chars",
")",
"{",
"string",
"=",
"string",
"==",
"null",
"?",
"''",
":",
"String",
"(",
"string",
")",
";",
"length",
"=",
"+",
"length",
";",
"var",
"strLength",
"=",
"string",
".",
"length",
";",
"if",
"(",
"strLength",
">=",
"length",
"||",
"!",
"nativeIsFinite",
"(",
"length",
")",
")",
"{",
"return",
"string",
";",
"}",
"var",
"mid",
"=",
"(",
"length",
"-",
"strLength",
")",
"/",
"2",
",",
"leftLength",
"=",
"floor",
"(",
"mid",
")",
",",
"rightLength",
"=",
"ceil",
"(",
"mid",
")",
";",
"chars",
"=",
"createPad",
"(",
"''",
",",
"rightLength",
",",
"chars",
")",
";",
"return",
"chars",
".",
"slice",
"(",
"0",
",",
"leftLength",
")",
"+",
"string",
"+",
"chars",
";",
"}"
] | Pads `string` on the left and right sides if it is shorter then the given
padding length. The `chars` string may be truncated if the number of padding
characters can't be evenly divided by the padding length.
@static
@memberOf _
@category Strings
@param {string} [string=''] The string to pad.
@param {number} [length=0] The padding length.
@param {string} [chars=' '] The string used as padding.
@returns {string} Returns the padded string.
@example
_.pad('abc', 8);
// => ' abc '
_.pad('abc', 8, '_-');
// => '_-abc_-_'
_.pad('abc', 3);
// => 'abc' | [
"Pads",
"string",
"on",
"the",
"left",
"and",
"right",
"sides",
"if",
"it",
"is",
"shorter",
"then",
"the",
"given",
"padding",
"length",
".",
"The",
"chars",
"string",
"may",
"be",
"truncated",
"if",
"the",
"number",
"of",
"padding",
"characters",
"can",
"t",
"be",
"evenly",
"divided",
"by",
"the",
"padding",
"length",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L6939-L6953 | train |
atomantic/undermore | libs/lodash.js | padLeft | function padLeft(string, length, chars) {
string = string == null ? '' : String(string);
return createPad(string, length, chars) + string;
} | javascript | function padLeft(string, length, chars) {
string = string == null ? '' : String(string);
return createPad(string, length, chars) + string;
} | [
"function",
"padLeft",
"(",
"string",
",",
"length",
",",
"chars",
")",
"{",
"string",
"=",
"string",
"==",
"null",
"?",
"''",
":",
"String",
"(",
"string",
")",
";",
"return",
"createPad",
"(",
"string",
",",
"length",
",",
"chars",
")",
"+",
"string",
";",
"}"
] | Pads `string` on the left side if it is shorter then the given padding
length. The `chars` string may be truncated if the number of padding
characters exceeds the padding length.
@static
@memberOf _
@category Strings
@param {string} [string=''] The string to pad.
@param {number} [length=0] The padding length.
@param {string} [chars=' '] The string used as padding.
@returns {string} Returns the padded string.
@example
_.padLeft('abc', 6);
// => ' abc'
_.padLeft('abc', 6, '_-');
// => '_-_abc'
_.padLeft('abc', 3);
// => 'abc' | [
"Pads",
"string",
"on",
"the",
"left",
"side",
"if",
"it",
"is",
"shorter",
"then",
"the",
"given",
"padding",
"length",
".",
"The",
"chars",
"string",
"may",
"be",
"truncated",
"if",
"the",
"number",
"of",
"padding",
"characters",
"exceeds",
"the",
"padding",
"length",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L6978-L6981 | train |
atomantic/undermore | libs/lodash.js | padRight | function padRight(string, length, chars) {
string = string == null ? '' : String(string);
return string + createPad(string, length, chars);
} | javascript | function padRight(string, length, chars) {
string = string == null ? '' : String(string);
return string + createPad(string, length, chars);
} | [
"function",
"padRight",
"(",
"string",
",",
"length",
",",
"chars",
")",
"{",
"string",
"=",
"string",
"==",
"null",
"?",
"''",
":",
"String",
"(",
"string",
")",
";",
"return",
"string",
"+",
"createPad",
"(",
"string",
",",
"length",
",",
"chars",
")",
";",
"}"
] | Pads `string` on the right side if it is shorter then the given padding
length. The `chars` string may be truncated if the number of padding
characters exceeds the padding length.
@static
@memberOf _
@category Strings
@param {string} [string=''] The string to pad.
@param {number} [length=0] The padding length.
@param {string} [chars=' '] The string used as padding.
@returns {string} Returns the padded string.
@example
_.padRight('abc', 6);
// => 'abc '
_.padRight('abc', 6, '_-');
// => 'abc_-_'
_.padRight('abc', 3);
// => 'abc' | [
"Pads",
"string",
"on",
"the",
"right",
"side",
"if",
"it",
"is",
"shorter",
"then",
"the",
"given",
"padding",
"length",
".",
"The",
"chars",
"string",
"may",
"be",
"truncated",
"if",
"the",
"number",
"of",
"padding",
"characters",
"exceeds",
"the",
"padding",
"length",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L7006-L7009 | train |
atomantic/undermore | libs/lodash.js | template | function template(string, data, options) {
// based on John Resig's `tmpl` implementation
// http://ejohn.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
var settings = lodash.templateSettings;
options = defaults({}, options, settings);
string = String(string == null ? '' : string);
var imports = defaults({}, options.imports, settings.imports),
importsKeys = keys(imports),
importsValues = values(imports);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// compile the regexp to match each delimiter
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// escape characters that cannot be included in string literals
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// replace delimiters with snippets
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// the JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value
return match;
});
source += "';\n";
// if `variable` is not specified, wrap a with-statement around the generated
// code to add the data object to the top of the scope chain
var variable = options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// cleanup code by stripping empty strings
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
// Use a `sourceURL` for easier debugging.
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
try {
var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
} catch(e) {
e.source = source;
throw e;
}
if (data) {
return result(data);
}
// provide the compiled function's source by its `toString` method, in
// supported environments, or the `source` property as a convenience for
// inlining compiled templates during the build process
result.source = source;
return result;
} | javascript | function template(string, data, options) {
// based on John Resig's `tmpl` implementation
// http://ejohn.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
var settings = lodash.templateSettings;
options = defaults({}, options, settings);
string = String(string == null ? '' : string);
var imports = defaults({}, options.imports, settings.imports),
importsKeys = keys(imports),
importsValues = values(imports);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// compile the regexp to match each delimiter
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// escape characters that cannot be included in string literals
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// replace delimiters with snippets
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// the JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value
return match;
});
source += "';\n";
// if `variable` is not specified, wrap a with-statement around the generated
// code to add the data object to the top of the scope chain
var variable = options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// cleanup code by stripping empty strings
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
// Use a `sourceURL` for easier debugging.
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
try {
var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
} catch(e) {
e.source = source;
throw e;
}
if (data) {
return result(data);
}
// provide the compiled function's source by its `toString` method, in
// supported environments, or the `source` property as a convenience for
// inlining compiled templates during the build process
result.source = source;
return result;
} | [
"function",
"template",
"(",
"string",
",",
"data",
",",
"options",
")",
"{",
"var",
"settings",
"=",
"lodash",
".",
"templateSettings",
";",
"options",
"=",
"defaults",
"(",
"{",
"}",
",",
"options",
",",
"settings",
")",
";",
"string",
"=",
"String",
"(",
"string",
"==",
"null",
"?",
"''",
":",
"string",
")",
";",
"var",
"imports",
"=",
"defaults",
"(",
"{",
"}",
",",
"options",
".",
"imports",
",",
"settings",
".",
"imports",
")",
",",
"importsKeys",
"=",
"keys",
"(",
"imports",
")",
",",
"importsValues",
"=",
"values",
"(",
"imports",
")",
";",
"var",
"isEscaping",
",",
"isEvaluating",
",",
"index",
"=",
"0",
",",
"interpolate",
"=",
"options",
".",
"interpolate",
"||",
"reNoMatch",
",",
"source",
"=",
"\"__p += '\"",
";",
"var",
"reDelimiters",
"=",
"RegExp",
"(",
"(",
"options",
".",
"escape",
"||",
"reNoMatch",
")",
".",
"source",
"+",
"'|'",
"+",
"interpolate",
".",
"source",
"+",
"'|'",
"+",
"(",
"interpolate",
"===",
"reInterpolate",
"?",
"reEsTemplate",
":",
"reNoMatch",
")",
".",
"source",
"+",
"'|'",
"+",
"(",
"options",
".",
"evaluate",
"||",
"reNoMatch",
")",
".",
"source",
"+",
"'|$'",
",",
"'g'",
")",
";",
"string",
".",
"replace",
"(",
"reDelimiters",
",",
"function",
"(",
"match",
",",
"escapeValue",
",",
"interpolateValue",
",",
"esTemplateValue",
",",
"evaluateValue",
",",
"offset",
")",
"{",
"interpolateValue",
"||",
"(",
"interpolateValue",
"=",
"esTemplateValue",
")",
";",
"source",
"+=",
"string",
".",
"slice",
"(",
"index",
",",
"offset",
")",
".",
"replace",
"(",
"reUnescapedString",
",",
"escapeStringChar",
")",
";",
"if",
"(",
"escapeValue",
")",
"{",
"isEscaping",
"=",
"true",
";",
"source",
"+=",
"\"' +\\n__e(\"",
"+",
"\\n",
"+",
"escapeValue",
";",
"}",
"\") +\\n'\"",
"\\n",
"if",
"(",
"evaluateValue",
")",
"{",
"isEvaluating",
"=",
"true",
";",
"source",
"+=",
"\"';\\n\"",
"+",
"\\n",
"+",
"evaluateValue",
";",
"}",
"\";\\n__p += '\"",
"}",
")",
";",
"\\n",
"if",
"(",
"interpolateValue",
")",
"{",
"source",
"+=",
"\"' +\\n((__t = (\"",
"+",
"\\n",
"+",
"interpolateValue",
";",
"}",
"\")) == null ? '' : __t) +\\n'\"",
"\\n",
"index",
"=",
"offset",
"+",
"match",
".",
"length",
";",
"return",
"match",
";",
"source",
"+=",
"\"';\\n\"",
";",
"\\n",
"var",
"variable",
"=",
"options",
".",
"variable",
";",
"if",
"(",
"!",
"variable",
")",
"{",
"source",
"=",
"'with (obj) {\\n'",
"+",
"\\n",
"+",
"source",
";",
"}",
"}"
] | Creates a compiled template function that can interpolate data properties
in "interpolate" delimiters, HTML-escaped interpolated data properties in
"escape" delimiters, and execute JavaScript in "evaluate" delimiters. If
a data object is provided the interpolated template string will be returned.
Data properties may be accessed as free variables in the template. If a
settings object is provided it will override `_.templateSettings` for the
template.
Note: In the development build, `_.template` utilizes `sourceURL`s for easier debugging.
See the [HTML5 Rocks article on sourcemaps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
for more details.
For more information on precompiling templates see
[Lo-Dash's custom builds documentation](http://lodash.com/custom-builds).
For more information on Chrome extension sandboxes see
[Chrome's extensions documentation](http://developer.chrome.com/stable/extensions/sandboxingEval.html).
@static
@memberOf _
@category Strings
@param {string} [string=''] The template string.
@param {Object} [data] The data object used to populate the template string.
@param {Object} [options] The options object.
@param {RegExp} [options.escape] The HTML "escape" delimiter.
@param {RegExp} [options.evaluate] The "evaluate" delimiter.
@param {Object} [options.imports] An object to import into the template as local variables.
@param {RegExp} [options.interpolate] The "interpolate" delimiter.
@param {string} [options.sourceURL] The `sourceURL` of the template's compiled source.
@param {string} [options.variable] The data object variable name.
@returns {Function|string} Returns the interpolated string if a data object
is provided, else the compiled template function.
@example
// using the "interpolate" delimiter to create a compiled template
var compiled = _.template('hello <%= name %>');
compiled({ 'name': 'fred' });
// => 'hello fred'
// using the HTML "escape" delimiter to escape data property values
_.template('<b><%- value %></b>', { 'value': '<script>' });
// => '<b><script></b>'
// using the "evaluate" delimiter to execute JavaScript and generate HTML
var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
_.template(list, { 'people': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'
// using the ES6 delimiter as an alternative to the default "interpolate" delimiter
_.template('hello ${ name }', { 'name': 'pebbles' });
// => 'hello pebbles'
// using the internal `print` function in "evaluate" delimiters
_.template('<% print("hello " + name); %>!', { 'name': 'barney' });
// => 'hello barney!'
// using a custom template delimiters
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
_.template('hello {{ name }}!', { 'name': 'mustache' });
// => 'hello mustache!'
// using the `imports` option to import jQuery
var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>';
_.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } });
// => '<li>fred</li><li>barney</li>'
// using the `sourceURL` option to specify a custom `sourceURL` for the template
var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
compiled(data);
// => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
// using the `variable` option to ensure a with-statement isn't used in the compiled template
var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
compiled.source;
// => function(data) {
var __t, __p = '', __e = _.escape;
__p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
return __p;
}
// using the `source` property to inline compiled templates for meaningful
// line numbers in error messages and a stack trace
fs.writeFileSync(path.join(cwd, 'jst.js'), '\
var JST = {\
"main": ' + _.template(mainText).source + '\
};\
'); | [
"Creates",
"a",
"compiled",
"template",
"function",
"that",
"can",
"interpolate",
"data",
"properties",
"in",
"interpolate",
"delimiters",
"HTML",
"-",
"escaped",
"interpolated",
"data",
"properties",
"in",
"escape",
"delimiters",
"and",
"execute",
"JavaScript",
"in",
"evaluate",
"delimiters",
".",
"If",
"a",
"data",
"object",
"is",
"provided",
"the",
"interpolated",
"template",
"string",
"will",
"be",
"returned",
".",
"Data",
"properties",
"may",
"be",
"accessed",
"as",
"free",
"variables",
"in",
"the",
"template",
".",
"If",
"a",
"settings",
"object",
"is",
"provided",
"it",
"will",
"override",
"_",
".",
"templateSettings",
"for",
"the",
"template",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L7190-L7292 | train |
atomantic/undermore | libs/lodash.js | truncate | function truncate(string, options) {
var length = 30,
omission = '...';
if (options && isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? +options.length || 0 : length;
omission = 'omission' in options ? String(options.omission) : omission;
}
else if (options != null) {
length = +options || 0;
}
string = string == null ? '' : String(string);
if (length >= string.length) {
return string;
}
var end = length - omission.length;
if (end < 1) {
return omission;
}
var result = string.slice(0, end);
if (separator == null) {
return result + omission;
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
newEnd,
substring = string.slice(0, end);
if (!separator.global) {
separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
newEnd = match.index;
}
result = result.slice(0, newEnd == null ? end : newEnd);
}
} else if (string.indexOf(separator, end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
} | javascript | function truncate(string, options) {
var length = 30,
omission = '...';
if (options && isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? +options.length || 0 : length;
omission = 'omission' in options ? String(options.omission) : omission;
}
else if (options != null) {
length = +options || 0;
}
string = string == null ? '' : String(string);
if (length >= string.length) {
return string;
}
var end = length - omission.length;
if (end < 1) {
return omission;
}
var result = string.slice(0, end);
if (separator == null) {
return result + omission;
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
newEnd,
substring = string.slice(0, end);
if (!separator.global) {
separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
newEnd = match.index;
}
result = result.slice(0, newEnd == null ? end : newEnd);
}
} else if (string.indexOf(separator, end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
} | [
"function",
"truncate",
"(",
"string",
",",
"options",
")",
"{",
"var",
"length",
"=",
"30",
",",
"omission",
"=",
"'...'",
";",
"if",
"(",
"options",
"&&",
"isObject",
"(",
"options",
")",
")",
"{",
"var",
"separator",
"=",
"'separator'",
"in",
"options",
"?",
"options",
".",
"separator",
":",
"separator",
";",
"length",
"=",
"'length'",
"in",
"options",
"?",
"+",
"options",
".",
"length",
"||",
"0",
":",
"length",
";",
"omission",
"=",
"'omission'",
"in",
"options",
"?",
"String",
"(",
"options",
".",
"omission",
")",
":",
"omission",
";",
"}",
"else",
"if",
"(",
"options",
"!=",
"null",
")",
"{",
"length",
"=",
"+",
"options",
"||",
"0",
";",
"}",
"string",
"=",
"string",
"==",
"null",
"?",
"''",
":",
"String",
"(",
"string",
")",
";",
"if",
"(",
"length",
">=",
"string",
".",
"length",
")",
"{",
"return",
"string",
";",
"}",
"var",
"end",
"=",
"length",
"-",
"omission",
".",
"length",
";",
"if",
"(",
"end",
"<",
"1",
")",
"{",
"return",
"omission",
";",
"}",
"var",
"result",
"=",
"string",
".",
"slice",
"(",
"0",
",",
"end",
")",
";",
"if",
"(",
"separator",
"==",
"null",
")",
"{",
"return",
"result",
"+",
"omission",
";",
"}",
"if",
"(",
"isRegExp",
"(",
"separator",
")",
")",
"{",
"if",
"(",
"string",
".",
"slice",
"(",
"end",
")",
".",
"search",
"(",
"separator",
")",
")",
"{",
"var",
"match",
",",
"newEnd",
",",
"substring",
"=",
"string",
".",
"slice",
"(",
"0",
",",
"end",
")",
";",
"if",
"(",
"!",
"separator",
".",
"global",
")",
"{",
"separator",
"=",
"RegExp",
"(",
"separator",
".",
"source",
",",
"(",
"reFlags",
".",
"exec",
"(",
"separator",
")",
"||",
"''",
")",
"+",
"'g'",
")",
";",
"}",
"separator",
".",
"lastIndex",
"=",
"0",
";",
"while",
"(",
"(",
"match",
"=",
"separator",
".",
"exec",
"(",
"substring",
")",
")",
")",
"{",
"newEnd",
"=",
"match",
".",
"index",
";",
"}",
"result",
"=",
"result",
".",
"slice",
"(",
"0",
",",
"newEnd",
"==",
"null",
"?",
"end",
":",
"newEnd",
")",
";",
"}",
"}",
"else",
"if",
"(",
"string",
".",
"indexOf",
"(",
"separator",
",",
"end",
")",
"!=",
"end",
")",
"{",
"var",
"index",
"=",
"result",
".",
"lastIndexOf",
"(",
"separator",
")",
";",
"if",
"(",
"index",
">",
"-",
"1",
")",
"{",
"result",
"=",
"result",
".",
"slice",
"(",
"0",
",",
"index",
")",
";",
"}",
"}",
"return",
"result",
"+",
"omission",
";",
"}"
] | Truncates `string` if it is longer than the given maximum string length.
The last characters of the truncated string will be replaced with the
omission string which defaults to "...".
@static
@memberOf _
@category Strings
@param {string} [string=''] The string to truncate.
@param {Object|number} [options] The options object or maximum string length.
@param {number} [options.length=30] The maximum string length.
@param {string} [options.omission='...'] The string used to indicate text is omitted.
@param {RegExp|string} [options.separator] The separator pattern to truncate to.
@returns {string} Returns the truncated string.
@example
_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'
_.truncate('hi-diddly-ho there, neighborino', 24);
// => 'hi-diddly-ho there, n...'
_.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' });
// => 'hi-diddly-ho there,...'
_.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ });
//=> 'hi-diddly-ho there...'
_.truncate('hi-diddly-ho there, neighborino', { 'omission': ' [...]' });
// => 'hi-diddly-ho there, neig [...]' | [
"Truncates",
"string",
"if",
"it",
"is",
"longer",
"than",
"the",
"given",
"maximum",
"string",
"length",
".",
"The",
"last",
"characters",
"of",
"the",
"truncated",
"string",
"will",
"be",
"replaced",
"with",
"the",
"omission",
"string",
"which",
"defaults",
"to",
"...",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L7412-L7458 | train |
atomantic/undermore | libs/lodash.js | createCallback | function createCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function' || func == null) {
return (typeof thisArg == 'undefined' || !('prototype' in func)) &&
func || baseCreateCallback(func, thisArg, argCount);
}
// handle "_.pluck" and "_.where" style callback shorthands
return type == 'object' ? matches(func) : property(func);
} | javascript | function createCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function' || func == null) {
return (typeof thisArg == 'undefined' || !('prototype' in func)) &&
func || baseCreateCallback(func, thisArg, argCount);
}
// handle "_.pluck" and "_.where" style callback shorthands
return type == 'object' ? matches(func) : property(func);
} | [
"function",
"createCallback",
"(",
"func",
",",
"thisArg",
",",
"argCount",
")",
"{",
"var",
"type",
"=",
"typeof",
"func",
";",
"if",
"(",
"type",
"==",
"'function'",
"||",
"func",
"==",
"null",
")",
"{",
"return",
"(",
"typeof",
"thisArg",
"==",
"'undefined'",
"||",
"!",
"(",
"'prototype'",
"in",
"func",
")",
")",
"&&",
"func",
"||",
"baseCreateCallback",
"(",
"func",
",",
"thisArg",
",",
"argCount",
")",
";",
"}",
"return",
"type",
"==",
"'object'",
"?",
"matches",
"(",
"func",
")",
":",
"property",
"(",
"func",
")",
";",
"}"
] | Creates a function bound to an optional `thisArg`. If `func` is a property
name the created callback will return the property value for a given element.
If `func` is an object the created callback will return `true` for elements
that contain the equivalent object properties, otherwise it will return `false`.
@static
@memberOf _
@alias callback
@category Utilities
@param {*} [func=identity] The value to convert to a callback.
@param {*} [thisArg] The `this` binding of the created callback.
@param {number} [argCount] The number of arguments the callback accepts.
@returns {Function} Returns the new function.
@example
var characters = [
{ 'name': 'barney', 'age': 36 },
{ 'name': 'fred', 'age': 40 }
];
// wrap to create custom callback shorthands
_.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
return !match ? func(callback, thisArg) : function(object) {
return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
};
});
_.filter(characters, 'age__gt38');
// => [{ 'name': 'fred', 'age': 40 }] | [
"Creates",
"a",
"function",
"bound",
"to",
"an",
"optional",
"thisArg",
".",
"If",
"func",
"is",
"a",
"property",
"name",
"the",
"created",
"callback",
"will",
"return",
"the",
"property",
"value",
"for",
"a",
"given",
"element",
".",
"If",
"func",
"is",
"an",
"object",
"the",
"created",
"callback",
"will",
"return",
"true",
"for",
"elements",
"that",
"contain",
"the",
"equivalent",
"object",
"properties",
"otherwise",
"it",
"will",
"return",
"false",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L7541-L7549 | train |
atomantic/undermore | libs/lodash.js | matches | function matches(source) {
var props = keys(source),
propsLength = props.length,
key = props[0],
value = propsLength && source[key];
// fast path the common case of providing an object with a single
// property containing a primitive value
if (propsLength == 1 && value === value && !isObject(value)) {
return function(object) {
if (!(object && hasOwnProperty.call(object, key))) {
return false;
}
// treat `-0` vs. `+0` as not equal
var other = object[key];
return value === other && (value !== 0 || (1 / value == 1 / other));
};
}
return function(object) {
var length = propsLength;
if (length && !object) {
return false;
}
var result = true;
while (length--) {
var key = props[length];
if (!(result = hasOwnProperty.call(object, key) &&
baseIsEqual(object[key], source[key], null, true))) {
break;
}
}
return result;
};
} | javascript | function matches(source) {
var props = keys(source),
propsLength = props.length,
key = props[0],
value = propsLength && source[key];
// fast path the common case of providing an object with a single
// property containing a primitive value
if (propsLength == 1 && value === value && !isObject(value)) {
return function(object) {
if (!(object && hasOwnProperty.call(object, key))) {
return false;
}
// treat `-0` vs. `+0` as not equal
var other = object[key];
return value === other && (value !== 0 || (1 / value == 1 / other));
};
}
return function(object) {
var length = propsLength;
if (length && !object) {
return false;
}
var result = true;
while (length--) {
var key = props[length];
if (!(result = hasOwnProperty.call(object, key) &&
baseIsEqual(object[key], source[key], null, true))) {
break;
}
}
return result;
};
} | [
"function",
"matches",
"(",
"source",
")",
"{",
"var",
"props",
"=",
"keys",
"(",
"source",
")",
",",
"propsLength",
"=",
"props",
".",
"length",
",",
"key",
"=",
"props",
"[",
"0",
"]",
",",
"value",
"=",
"propsLength",
"&&",
"source",
"[",
"key",
"]",
";",
"if",
"(",
"propsLength",
"==",
"1",
"&&",
"value",
"===",
"value",
"&&",
"!",
"isObject",
"(",
"value",
")",
")",
"{",
"return",
"function",
"(",
"object",
")",
"{",
"if",
"(",
"!",
"(",
"object",
"&&",
"hasOwnProperty",
".",
"call",
"(",
"object",
",",
"key",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"var",
"other",
"=",
"object",
"[",
"key",
"]",
";",
"return",
"value",
"===",
"other",
"&&",
"(",
"value",
"!==",
"0",
"||",
"(",
"1",
"/",
"value",
"==",
"1",
"/",
"other",
")",
")",
";",
"}",
";",
"}",
"return",
"function",
"(",
"object",
")",
"{",
"var",
"length",
"=",
"propsLength",
";",
"if",
"(",
"length",
"&&",
"!",
"object",
")",
"{",
"return",
"false",
";",
"}",
"var",
"result",
"=",
"true",
";",
"while",
"(",
"length",
"--",
")",
"{",
"var",
"key",
"=",
"props",
"[",
"length",
"]",
";",
"if",
"(",
"!",
"(",
"result",
"=",
"hasOwnProperty",
".",
"call",
"(",
"object",
",",
"key",
")",
"&&",
"baseIsEqual",
"(",
"object",
"[",
"key",
"]",
",",
"source",
"[",
"key",
"]",
",",
"null",
",",
"true",
")",
")",
")",
"{",
"break",
";",
"}",
"}",
"return",
"result",
";",
"}",
";",
"}"
] | Creates a "_.where" style predicate function which performs a deep comparison
between a given object and the `source` object, returning `true` if the given
object has equivalent property values, else `false`.
@static
@memberOf _
@category Utilities
@param {Object} source The object of property values to match.
@returns {Function} Returns the new function.
@example
var characters = [
{ 'name': 'fred', 'age': 40 },
{ 'name': 'barney', 'age': 36 }
];
var matchesAge = _.matches({ 'age': 36 });
_.filter(characters, matchesAge);
// => [{ 'name': 'barney', 'age': 36 }]
_.find(characters, matchesAge);
// => { 'name': 'barney', 'age': 36 } | [
"Creates",
"a",
"_",
".",
"where",
"style",
"predicate",
"function",
"which",
"performs",
"a",
"deep",
"comparison",
"between",
"a",
"given",
"object",
"and",
"the",
"source",
"object",
"returning",
"true",
"if",
"the",
"given",
"object",
"has",
"equivalent",
"property",
"values",
"else",
"false",
"."
] | 6c6d995460c25c1df087b465fdc4d21035b4c7b2 | https://github.com/atomantic/undermore/blob/6c6d995460c25c1df087b465fdc4d21035b4c7b2/libs/lodash.js#L7594-L7627 | train |
naturalatlas/geonames-reader | lib/formatters.js | function(line) {
return {
'id': Number(line[0]),
'geoname_id': Number(line[1]),
'isolanguage': String(line[2]),
'alternate_name': String(line[3]),
'is_preferred': Boolean(line[4]),
'is_short': Boolean(line[5]),
'is_colloquial': Boolean(line[5]),
'is_historic': Boolean(line[6]),
};
} | javascript | function(line) {
return {
'id': Number(line[0]),
'geoname_id': Number(line[1]),
'isolanguage': String(line[2]),
'alternate_name': String(line[3]),
'is_preferred': Boolean(line[4]),
'is_short': Boolean(line[5]),
'is_colloquial': Boolean(line[5]),
'is_historic': Boolean(line[6]),
};
} | [
"function",
"(",
"line",
")",
"{",
"return",
"{",
"'id'",
":",
"Number",
"(",
"line",
"[",
"0",
"]",
")",
",",
"'geoname_id'",
":",
"Number",
"(",
"line",
"[",
"1",
"]",
")",
",",
"'isolanguage'",
":",
"String",
"(",
"line",
"[",
"2",
"]",
")",
",",
"'alternate_name'",
":",
"String",
"(",
"line",
"[",
"3",
"]",
")",
",",
"'is_preferred'",
":",
"Boolean",
"(",
"line",
"[",
"4",
"]",
")",
",",
"'is_short'",
":",
"Boolean",
"(",
"line",
"[",
"5",
"]",
")",
",",
"'is_colloquial'",
":",
"Boolean",
"(",
"line",
"[",
"5",
"]",
")",
",",
"'is_historic'",
":",
"Boolean",
"(",
"line",
"[",
"6",
"]",
")",
",",
"}",
";",
"}"
] | "alternate names" table formatter.
[0] alternateNameId : the id of this alternate name, int
[1] geonameid : geonameId referring to id in table 'geoname', int
[2] isolanguage : iso 639 language code 2- or 3-characters; 4-characters 'post' for postal codes and 'iata','icao' and faac for airport codes, fr_1793 for French Revolution names, abbr for abbreviation, link for a website, varchar(7)
[3] alternate name : alternate name or name variant, varchar(200)
[4] isPreferredName : '1', if this alternate name is an official/preferred name
[5] isShortName : '1', if this is a short name like 'California' for 'State of California'
[6] isColloquial : '1', if this alternate name is a colloquial or slang term
[7] isHistoric : '1', if this alternate name is historic and was used in the past
@param {array} line
@return {object} | [
"alternate",
"names",
"table",
"formatter",
"."
] | 6902a5a5ee10c2552a1737c1e413cd39e3225b53 | https://github.com/naturalatlas/geonames-reader/blob/6902a5a5ee10c2552a1737c1e413cd39e3225b53/lib/formatters.js#L67-L78 | train |
|
naturalatlas/geonames-reader | lib/formatters.js | function(line) {
return {
'name': String(line[1]),
'country_code': String(line[0]),
'gmt_offset': Number(line[2]),
'dst_offset': Number(line[3]),
'raw_offset': Number(line[4])
};
} | javascript | function(line) {
return {
'name': String(line[1]),
'country_code': String(line[0]),
'gmt_offset': Number(line[2]),
'dst_offset': Number(line[3]),
'raw_offset': Number(line[4])
};
} | [
"function",
"(",
"line",
")",
"{",
"return",
"{",
"'name'",
":",
"String",
"(",
"line",
"[",
"1",
"]",
")",
",",
"'country_code'",
":",
"String",
"(",
"line",
"[",
"0",
"]",
")",
",",
"'gmt_offset'",
":",
"Number",
"(",
"line",
"[",
"2",
"]",
")",
",",
"'dst_offset'",
":",
"Number",
"(",
"line",
"[",
"3",
"]",
")",
",",
"'raw_offset'",
":",
"Number",
"(",
"line",
"[",
"4",
"]",
")",
"}",
";",
"}"
] | "timezones" table formatter.
[0] country_code
[1] id
[2] gmtOffset
[3] dstOffset
[4] rawOffset
@param {array} line
@return {object} | [
"timezones",
"table",
"formatter",
"."
] | 6902a5a5ee10c2552a1737c1e413cd39e3225b53 | https://github.com/naturalatlas/geonames-reader/blob/6902a5a5ee10c2552a1737c1e413cd39e3225b53/lib/formatters.js#L112-L120 | train |
|
naturalatlas/geonames-reader | lib/formatters.js | function(line) {
return {
'iso': String(line[0]),
'iso3': String(line[1]),
'iso_numeric': Number(line[2]),
'fips': String(line[3]),
'name': String(line[4]),
'capital': String(line[5]),
'area': Number(line[6]),
'population': Number(line[7]),
'continent': String(line[8]),
'tld': String(line[9]),
'currency_code': String(line[10]),
'currency_name': String(line[11]),
'phone': String(line[12]),
'postal_code_format': String(line[13]),
'postal_code_regex': String(line[14]),
'languages': String(line[15]),
'geoname_id': Number(line[16])
};
} | javascript | function(line) {
return {
'iso': String(line[0]),
'iso3': String(line[1]),
'iso_numeric': Number(line[2]),
'fips': String(line[3]),
'name': String(line[4]),
'capital': String(line[5]),
'area': Number(line[6]),
'population': Number(line[7]),
'continent': String(line[8]),
'tld': String(line[9]),
'currency_code': String(line[10]),
'currency_name': String(line[11]),
'phone': String(line[12]),
'postal_code_format': String(line[13]),
'postal_code_regex': String(line[14]),
'languages': String(line[15]),
'geoname_id': Number(line[16])
};
} | [
"function",
"(",
"line",
")",
"{",
"return",
"{",
"'iso'",
":",
"String",
"(",
"line",
"[",
"0",
"]",
")",
",",
"'iso3'",
":",
"String",
"(",
"line",
"[",
"1",
"]",
")",
",",
"'iso_numeric'",
":",
"Number",
"(",
"line",
"[",
"2",
"]",
")",
",",
"'fips'",
":",
"String",
"(",
"line",
"[",
"3",
"]",
")",
",",
"'name'",
":",
"String",
"(",
"line",
"[",
"4",
"]",
")",
",",
"'capital'",
":",
"String",
"(",
"line",
"[",
"5",
"]",
")",
",",
"'area'",
":",
"Number",
"(",
"line",
"[",
"6",
"]",
")",
",",
"'population'",
":",
"Number",
"(",
"line",
"[",
"7",
"]",
")",
",",
"'continent'",
":",
"String",
"(",
"line",
"[",
"8",
"]",
")",
",",
"'tld'",
":",
"String",
"(",
"line",
"[",
"9",
"]",
")",
",",
"'currency_code'",
":",
"String",
"(",
"line",
"[",
"10",
"]",
")",
",",
"'currency_name'",
":",
"String",
"(",
"line",
"[",
"11",
"]",
")",
",",
"'phone'",
":",
"String",
"(",
"line",
"[",
"12",
"]",
")",
",",
"'postal_code_format'",
":",
"String",
"(",
"line",
"[",
"13",
"]",
")",
",",
"'postal_code_regex'",
":",
"String",
"(",
"line",
"[",
"14",
"]",
")",
",",
"'languages'",
":",
"String",
"(",
"line",
"[",
"15",
"]",
")",
",",
"'geoname_id'",
":",
"Number",
"(",
"line",
"[",
"16",
"]",
")",
"}",
";",
"}"
] | "countries" table formatter.
[0] ISO
[1] ISO3
[2] ISO-Numeric
[3] fips
[4] Country
[5] Capital
[6] Area(in sq km)
[7] Population
[8] Continent
[9] tld
[10] CurrencyCode
[11] CurrencyName
[12] Phone
[13] Postal Code Format
[14] Postal Code Regex
[15] Languages
[16] geonameId
@param {array} line
@return {object} | [
"countries",
"table",
"formatter",
"."
] | 6902a5a5ee10c2552a1737c1e413cd39e3225b53 | https://github.com/naturalatlas/geonames-reader/blob/6902a5a5ee10c2552a1737c1e413cd39e3225b53/lib/formatters.js#L164-L184 | train |
|
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/ace-extra.js | function(name) {
var cookie = document.cookie, e, p = name + "=", b;
if ( !cookie )
return;
b = cookie.indexOf("; " + p);
if ( b == -1 ) {
b = cookie.indexOf(p);
if ( b != 0 )
return null;
} else {
b += 2;
}
e = cookie.indexOf(";", b);
if ( e == -1 )
e = cookie.length;
return decodeURIComponent( cookie.substring(b + p.length, e) );
} | javascript | function(name) {
var cookie = document.cookie, e, p = name + "=", b;
if ( !cookie )
return;
b = cookie.indexOf("; " + p);
if ( b == -1 ) {
b = cookie.indexOf(p);
if ( b != 0 )
return null;
} else {
b += 2;
}
e = cookie.indexOf(";", b);
if ( e == -1 )
e = cookie.length;
return decodeURIComponent( cookie.substring(b + p.length, e) );
} | [
"function",
"(",
"name",
")",
"{",
"var",
"cookie",
"=",
"document",
".",
"cookie",
",",
"e",
",",
"p",
"=",
"name",
"+",
"\"=\"",
",",
"b",
";",
"if",
"(",
"!",
"cookie",
")",
"return",
";",
"b",
"=",
"cookie",
".",
"indexOf",
"(",
"\"; \"",
"+",
"p",
")",
";",
"if",
"(",
"b",
"==",
"-",
"1",
")",
"{",
"b",
"=",
"cookie",
".",
"indexOf",
"(",
"p",
")",
";",
"if",
"(",
"b",
"!=",
"0",
")",
"return",
"null",
";",
"}",
"else",
"{",
"b",
"+=",
"2",
";",
"}",
"e",
"=",
"cookie",
".",
"indexOf",
"(",
"\";\"",
",",
"b",
")",
";",
"if",
"(",
"e",
"==",
"-",
"1",
")",
"e",
"=",
"cookie",
".",
"length",
";",
"return",
"decodeURIComponent",
"(",
"cookie",
".",
"substring",
"(",
"b",
"+",
"p",
".",
"length",
",",
"e",
")",
")",
";",
"}"
] | The following functions are from Cookie.js class in TinyMCE, Moxiecode, used under LGPL.
Get a cookie. | [
"The",
"following",
"functions",
"are",
"from",
"Cookie",
".",
"js",
"class",
"in",
"TinyMCE",
"Moxiecode",
"used",
"under",
"LGPL",
".",
"Get",
"a",
"cookie",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/ace-extra.js#L284-L308 | train |
|
peerigon/alamid-schema | lib/determineType.js | determineType | function determineType(obj) {
var type;
var typeValue;
var name;
if (value(obj).typeOf(Object)) {
type = obj.type || "Object";
} else {
type = obj;
}
typeValue = value(type);
if (typeValue.typeOf(String)) {
name = type.charAt(0).toUpperCase() + type.substring(1);
return supportedTypes.indexOf(name) === -1 ? "String" : name;
} else if (typeValue.typeOf(Function)) {
name = type.toString().match(fnName)[1];
} else if (typeValue.typeOf(Object)) {
if (type.type) {
name = type.type;
} else {
return "Object";
}
} else {
name = type.constructor.toString().match(fnName)[1];
}
if (supportedTypes.indexOf(name) === -1) {
throw new TypeError("Type '" + name + "' is not supported");
}
return name;
} | javascript | function determineType(obj) {
var type;
var typeValue;
var name;
if (value(obj).typeOf(Object)) {
type = obj.type || "Object";
} else {
type = obj;
}
typeValue = value(type);
if (typeValue.typeOf(String)) {
name = type.charAt(0).toUpperCase() + type.substring(1);
return supportedTypes.indexOf(name) === -1 ? "String" : name;
} else if (typeValue.typeOf(Function)) {
name = type.toString().match(fnName)[1];
} else if (typeValue.typeOf(Object)) {
if (type.type) {
name = type.type;
} else {
return "Object";
}
} else {
name = type.constructor.toString().match(fnName)[1];
}
if (supportedTypes.indexOf(name) === -1) {
throw new TypeError("Type '" + name + "' is not supported");
}
return name;
} | [
"function",
"determineType",
"(",
"obj",
")",
"{",
"var",
"type",
";",
"var",
"typeValue",
";",
"var",
"name",
";",
"if",
"(",
"value",
"(",
"obj",
")",
".",
"typeOf",
"(",
"Object",
")",
")",
"{",
"type",
"=",
"obj",
".",
"type",
"||",
"\"Object\"",
";",
"}",
"else",
"{",
"type",
"=",
"obj",
";",
"}",
"typeValue",
"=",
"value",
"(",
"type",
")",
";",
"if",
"(",
"typeValue",
".",
"typeOf",
"(",
"String",
")",
")",
"{",
"name",
"=",
"type",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"type",
".",
"substring",
"(",
"1",
")",
";",
"return",
"supportedTypes",
".",
"indexOf",
"(",
"name",
")",
"===",
"-",
"1",
"?",
"\"String\"",
":",
"name",
";",
"}",
"else",
"if",
"(",
"typeValue",
".",
"typeOf",
"(",
"Function",
")",
")",
"{",
"name",
"=",
"type",
".",
"toString",
"(",
")",
".",
"match",
"(",
"fnName",
")",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"typeValue",
".",
"typeOf",
"(",
"Object",
")",
")",
"{",
"if",
"(",
"type",
".",
"type",
")",
"{",
"name",
"=",
"type",
".",
"type",
";",
"}",
"else",
"{",
"return",
"\"Object\"",
";",
"}",
"}",
"else",
"{",
"name",
"=",
"type",
".",
"constructor",
".",
"toString",
"(",
")",
".",
"match",
"(",
"fnName",
")",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"supportedTypes",
".",
"indexOf",
"(",
"name",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Type '\"",
"+",
"name",
"+",
"\"' is not supported\"",
")",
";",
"}",
"return",
"name",
";",
"}"
] | Determine the type of an object. Inspired by mongoose.
@param {*} obj
@returns {string} | [
"Determine",
"the",
"type",
"of",
"an",
"object",
".",
"Inspired",
"by",
"mongoose",
"."
] | 7faa6e826f485b33ccc2e41b86b5861c61184a3c | https://github.com/peerigon/alamid-schema/blob/7faa6e826f485b33ccc2e41b86b5861c61184a3c/lib/determineType.js#L21-L54 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | buildSlotSegLevels | function buildSlotSegLevels(segs) {
var levels = [];
var i, seg;
var j;
for (i=0; i<segs.length; i++) {
seg = segs[i];
// go through all the levels and stop on the first level where there are no collisions
for (j=0; j<levels.length; j++) {
if (!computeSlotSegCollisions(seg, levels[j]).length) {
break;
}
}
(levels[j] || (levels[j] = [])).push(seg);
}
return levels;
} | javascript | function buildSlotSegLevels(segs) {
var levels = [];
var i, seg;
var j;
for (i=0; i<segs.length; i++) {
seg = segs[i];
// go through all the levels and stop on the first level where there are no collisions
for (j=0; j<levels.length; j++) {
if (!computeSlotSegCollisions(seg, levels[j]).length) {
break;
}
}
(levels[j] || (levels[j] = [])).push(seg);
}
return levels;
} | [
"function",
"buildSlotSegLevels",
"(",
"segs",
")",
"{",
"var",
"levels",
"=",
"[",
"]",
";",
"var",
"i",
",",
"seg",
";",
"var",
"j",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"segs",
".",
"length",
";",
"i",
"++",
")",
"{",
"seg",
"=",
"segs",
"[",
"i",
"]",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"levels",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"computeSlotSegCollisions",
"(",
"seg",
",",
"levels",
"[",
"j",
"]",
")",
".",
"length",
")",
"{",
"break",
";",
"}",
"}",
"(",
"levels",
"[",
"j",
"]",
"||",
"(",
"levels",
"[",
"j",
"]",
"=",
"[",
"]",
")",
")",
".",
"push",
"(",
"seg",
")",
";",
"}",
"return",
"levels",
";",
"}"
] | Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is left-to-right, or the rightmost if the calendar is right-to-left. | [
"Builds",
"an",
"array",
"of",
"segments",
"levels",
".",
"The",
"first",
"level",
"will",
"be",
"the",
"leftmost",
"tier",
"of",
"segments",
"if",
"the",
"calendar",
"is",
"left",
"-",
"to",
"-",
"right",
"or",
"the",
"rightmost",
"if",
"the",
"calendar",
"is",
"right",
"-",
"to",
"-",
"left",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4362-L4381 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | computeForwardSlotSegs | function computeForwardSlotSegs(levels) {
var i, level;
var j, seg;
var k;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
seg = level[j];
seg.forwardSegs = [];
for (k=i+1; k<levels.length; k++) {
computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
}
}
}
} | javascript | function computeForwardSlotSegs(levels) {
var i, level;
var j, seg;
var k;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
seg = level[j];
seg.forwardSegs = [];
for (k=i+1; k<levels.length; k++) {
computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
}
}
}
} | [
"function",
"computeForwardSlotSegs",
"(",
"levels",
")",
"{",
"var",
"i",
",",
"level",
";",
"var",
"j",
",",
"seg",
";",
"var",
"k",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"levels",
".",
"length",
";",
"i",
"++",
")",
"{",
"level",
"=",
"levels",
"[",
"i",
"]",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"level",
".",
"length",
";",
"j",
"++",
")",
"{",
"seg",
"=",
"level",
"[",
"j",
"]",
";",
"seg",
".",
"forwardSegs",
"=",
"[",
"]",
";",
"for",
"(",
"k",
"=",
"i",
"+",
"1",
";",
"k",
"<",
"levels",
".",
"length",
";",
"k",
"++",
")",
"{",
"computeSlotSegCollisions",
"(",
"seg",
",",
"levels",
"[",
"k",
"]",
",",
"seg",
".",
"forwardSegs",
")",
";",
"}",
"}",
"}",
"}"
] | For every segment, figure out the other segments that are in subsequent levels that also occupy the same vertical space. Accumulate in seg.forwardSegs | [
"For",
"every",
"segment",
"figure",
"out",
"the",
"other",
"segments",
"that",
"are",
"in",
"subsequent",
"levels",
"that",
"also",
"occupy",
"the",
"same",
"vertical",
"space",
".",
"Accumulate",
"in",
"seg",
".",
"forwardSegs"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4386-L4403 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | flattenSlotSegLevels | function flattenSlotSegLevels(levels) {
var segs = [];
var i, level;
var j;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
segs.push(level[j]);
}
}
return segs;
} | javascript | function flattenSlotSegLevels(levels) {
var segs = [];
var i, level;
var j;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
segs.push(level[j]);
}
}
return segs;
} | [
"function",
"flattenSlotSegLevels",
"(",
"levels",
")",
"{",
"var",
"segs",
"=",
"[",
"]",
";",
"var",
"i",
",",
"level",
";",
"var",
"j",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"levels",
".",
"length",
";",
"i",
"++",
")",
"{",
"level",
"=",
"levels",
"[",
"i",
"]",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"level",
".",
"length",
";",
"j",
"++",
")",
"{",
"segs",
".",
"push",
"(",
"level",
"[",
"j",
"]",
")",
";",
"}",
"}",
"return",
"segs",
";",
"}"
] | Outputs a flat array of segments, from lowest to highest level | [
"Outputs",
"a",
"flat",
"array",
"of",
"segments",
"from",
"lowest",
"to",
"highest",
"level"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4479-L4493 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | computeSlotSegCollisions | function computeSlotSegCollisions(seg, otherSegs, results) {
results = results || [];
for (var i=0; i<otherSegs.length; i++) {
if (isSlotSegCollision(seg, otherSegs[i])) {
results.push(otherSegs[i]);
}
}
return results;
} | javascript | function computeSlotSegCollisions(seg, otherSegs, results) {
results = results || [];
for (var i=0; i<otherSegs.length; i++) {
if (isSlotSegCollision(seg, otherSegs[i])) {
results.push(otherSegs[i]);
}
}
return results;
} | [
"function",
"computeSlotSegCollisions",
"(",
"seg",
",",
"otherSegs",
",",
"results",
")",
"{",
"results",
"=",
"results",
"||",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"otherSegs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isSlotSegCollision",
"(",
"seg",
",",
"otherSegs",
"[",
"i",
"]",
")",
")",
"{",
"results",
".",
"push",
"(",
"otherSegs",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"results",
";",
"}"
] | Find all the segments in `otherSegs` that vertically collide with `seg`. Append into an optionally-supplied `results` array and return. | [
"Find",
"all",
"the",
"segments",
"in",
"otherSegs",
"that",
"vertically",
"collide",
"with",
"seg",
".",
"Append",
"into",
"an",
"optionally",
"-",
"supplied",
"results",
"array",
"and",
"return",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4498-L4508 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | isSlotSegCollision | function isSlotSegCollision(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
} | javascript | function isSlotSegCollision(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
} | [
"function",
"isSlotSegCollision",
"(",
"seg1",
",",
"seg2",
")",
"{",
"return",
"seg1",
".",
"end",
">",
"seg2",
".",
"start",
"&&",
"seg1",
".",
"start",
"<",
"seg2",
".",
"end",
";",
"}"
] | Do these segments occupy the same vertical space? | [
"Do",
"these",
"segments",
"occupy",
"the",
"same",
"vertical",
"space?"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4512-L4514 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | compareForwardSlotSegs | function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
} | javascript | function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
} | [
"function",
"compareForwardSlotSegs",
"(",
"seg1",
",",
"seg2",
")",
"{",
"return",
"seg2",
".",
"forwardPressure",
"-",
"seg1",
".",
"forwardPressure",
"||",
"(",
"seg1",
".",
"backwardCoord",
"||",
"0",
")",
"-",
"(",
"seg2",
".",
"backwardCoord",
"||",
"0",
")",
"||",
"compareSlotSegs",
"(",
"seg1",
",",
"seg2",
")",
";",
"}"
] | A cmp function for determining which forward segment to rely on more when computing coordinates. | [
"A",
"cmp",
"function",
"for",
"determining",
"which",
"forward",
"segment",
"to",
"rely",
"on",
"more",
"when",
"computing",
"coordinates",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4518-L4525 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | eventElementHandlers | function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
} | javascript | function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
} | [
"function",
"eventElementHandlers",
"(",
"event",
",",
"eventElement",
")",
"{",
"eventElement",
".",
"click",
"(",
"function",
"(",
"ev",
")",
"{",
"if",
"(",
"!",
"eventElement",
".",
"hasClass",
"(",
"'ui-draggable-dragging'",
")",
"&&",
"!",
"eventElement",
".",
"hasClass",
"(",
"'ui-resizable-resizing'",
")",
")",
"{",
"return",
"trigger",
"(",
"'eventClick'",
",",
"this",
",",
"event",
",",
"ev",
")",
";",
"}",
"}",
")",
".",
"hover",
"(",
"function",
"(",
"ev",
")",
"{",
"trigger",
"(",
"'eventMouseover'",
",",
"this",
",",
"event",
",",
"ev",
")",
";",
"}",
",",
"function",
"(",
"ev",
")",
"{",
"trigger",
"(",
"'eventMouseout'",
",",
"this",
",",
"event",
",",
"ev",
")",
";",
"}",
")",
";",
"}"
] | attaches eventClick, eventMouseover, eventMouseout | [
"attaches",
"eventClick",
"eventMouseover",
"eventMouseout"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4687-L4705 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | cellOffsetToDayOffset | function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
} | javascript | function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
} | [
"function",
"cellOffsetToDayOffset",
"(",
"cellOffset",
")",
"{",
"var",
"day0",
"=",
"t",
".",
"visStart",
".",
"getDay",
"(",
")",
";",
"cellOffset",
"+=",
"dayToCellMap",
"[",
"day0",
"]",
";",
"return",
"Math",
".",
"floor",
"(",
"cellOffset",
"/",
"cellsPerWeek",
")",
"*",
"7",
"+",
"cellToDayMap",
"[",
"(",
"cellOffset",
"%",
"cellsPerWeek",
"+",
"cellsPerWeek",
")",
"%",
"cellsPerWeek",
"]",
"-",
"day0",
";",
"}"
] | cell offset -> day offset | [
"cell",
"offset",
"-",
">",
"day",
"offset"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4949-L4957 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | dayOffsetToCellOffset | function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
} | javascript | function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
} | [
"function",
"dayOffsetToCellOffset",
"(",
"dayOffset",
")",
"{",
"var",
"day0",
"=",
"t",
".",
"visStart",
".",
"getDay",
"(",
")",
";",
"dayOffset",
"+=",
"day0",
";",
"return",
"Math",
".",
"floor",
"(",
"dayOffset",
"/",
"7",
")",
"*",
"cellsPerWeek",
"+",
"dayToCellMap",
"[",
"(",
"dayOffset",
"%",
"7",
"+",
"7",
")",
"%",
"7",
"]",
"-",
"dayToCellMap",
"[",
"day0",
"]",
";",
"}"
] | day offset -> cell offset | [
"day",
"offset",
"-",
">",
"cell",
"offset"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L4985-L4993 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | renderTempDayEvent | function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
} | javascript | function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
} | [
"function",
"renderTempDayEvent",
"(",
"event",
",",
"adjustRow",
",",
"adjustTop",
")",
"{",
"var",
"segments",
"=",
"_renderDayEvents",
"(",
"[",
"event",
"]",
",",
"true",
",",
"false",
")",
";",
"var",
"elements",
"=",
"[",
"]",
";",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"if",
"(",
"segment",
".",
"row",
"===",
"adjustRow",
")",
"{",
"element",
".",
"css",
"(",
"'top'",
",",
"adjustTop",
")",
";",
"}",
"elements",
".",
"push",
"(",
"element",
"[",
"0",
"]",
")",
";",
"}",
")",
";",
"return",
"elements",
";",
"}"
] | Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers. Append this event element to the event container, which might already be populated with events. If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`. This hack is used to maintain continuity when user is manually resizing an event. Returns an array of DOM elements for the event. | [
"Render",
"an",
"event",
"on",
"the",
"calendar",
"but",
"don",
"t",
"report",
"them",
"anywhere",
"and",
"don",
"t",
"attach",
"mouse",
"handlers",
".",
"Append",
"this",
"event",
"element",
"to",
"the",
"event",
"container",
"which",
"might",
"already",
"be",
"populated",
"with",
"events",
".",
"If",
"an",
"event",
"s",
"segment",
"will",
"have",
"row",
"equal",
"to",
"adjustRow",
"then",
"explicitly",
"set",
"its",
"top",
"coordinate",
"to",
"adjustTop",
".",
"This",
"hack",
"is",
"used",
"to",
"maintain",
"continuity",
"when",
"user",
"is",
"manually",
"resizing",
"an",
"event",
".",
"Returns",
"an",
"array",
"of",
"DOM",
"elements",
"for",
"the",
"event",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5158-L5179 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | _renderDayEvents | function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
} | javascript | function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
} | [
"function",
"_renderDayEvents",
"(",
"events",
",",
"doAppend",
",",
"doRowHeights",
")",
"{",
"var",
"finalContainer",
"=",
"getDaySegmentContainer",
"(",
")",
";",
"var",
"renderContainer",
"=",
"doAppend",
"?",
"$",
"(",
"\"<div/>\"",
")",
":",
"finalContainer",
";",
"var",
"segments",
"=",
"buildSegments",
"(",
"events",
")",
";",
"var",
"html",
";",
"var",
"elements",
";",
"calculateHorizontals",
"(",
"segments",
")",
";",
"html",
"=",
"buildHTML",
"(",
"segments",
")",
";",
"renderContainer",
"[",
"0",
"]",
".",
"innerHTML",
"=",
"html",
";",
"elements",
"=",
"renderContainer",
".",
"children",
"(",
")",
";",
"if",
"(",
"doAppend",
")",
"{",
"finalContainer",
".",
"append",
"(",
"elements",
")",
";",
"}",
"resolveElements",
"(",
"segments",
",",
"elements",
")",
";",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"segment",
".",
"hsides",
"=",
"hsides",
"(",
"element",
",",
"true",
")",
";",
"}",
")",
";",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"element",
".",
"width",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"segment",
".",
"outerWidth",
"-",
"segment",
".",
"hsides",
")",
")",
";",
"}",
")",
";",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"segment",
".",
"outerHeight",
"=",
"element",
".",
"outerHeight",
"(",
"true",
")",
";",
"}",
")",
";",
"setVerticals",
"(",
"segments",
",",
"doRowHeights",
")",
";",
"return",
"segments",
";",
"}"
] | Render events onto the calendar. Only responsible for the VISUAL aspect. Not responsible for attaching handlers or calling callbacks. Set `doAppend` to `true` for rendering elements without clearing the existing container. Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow. | [
"Render",
"events",
"onto",
"the",
"calendar",
".",
"Only",
"responsible",
"for",
"the",
"VISUAL",
"aspect",
".",
"Not",
"responsible",
"for",
"attaching",
"handlers",
"or",
"calling",
"callbacks",
".",
"Set",
"doAppend",
"to",
"true",
"for",
"rendering",
"elements",
"without",
"clearing",
"the",
"existing",
"container",
".",
"Set",
"doRowHeights",
"to",
"allow",
"setting",
"the",
"height",
"of",
"each",
"row",
"to",
"compensate",
"for",
"vertical",
"event",
"overflow",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5186-L5245 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | buildSegments | function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
} | javascript | function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
} | [
"function",
"buildSegments",
"(",
"events",
")",
"{",
"var",
"segments",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"eventSegments",
"=",
"buildSegmentsForEvent",
"(",
"events",
"[",
"i",
"]",
")",
";",
"segments",
".",
"push",
".",
"apply",
"(",
"segments",
",",
"eventSegments",
")",
";",
"}",
"return",
"segments",
";",
"}"
] | Generate an array of "segments" for all events. | [
"Generate",
"an",
"array",
"of",
"segments",
"for",
"all",
"events",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5249-L5256 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | buildSegmentsForEvent | function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
} | javascript | function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
} | [
"function",
"buildSegmentsForEvent",
"(",
"event",
")",
"{",
"var",
"startDate",
"=",
"event",
".",
"start",
";",
"var",
"endDate",
"=",
"exclEndDay",
"(",
"event",
")",
";",
"var",
"segments",
"=",
"rangeToSegments",
"(",
"startDate",
",",
"endDate",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"segments",
"[",
"i",
"]",
".",
"event",
"=",
"event",
";",
"}",
"return",
"segments",
";",
"}"
] | Generate an array of segments for a single event. A "segment" is the same data structure that View.rangeToSegments produces, with the addition of the `event` property being set to reference the original event. | [
"Generate",
"an",
"array",
"of",
"segments",
"for",
"a",
"single",
"event",
".",
"A",
"segment",
"is",
"the",
"same",
"data",
"structure",
"that",
"View",
".",
"rangeToSegments",
"produces",
"with",
"the",
"addition",
"of",
"the",
"event",
"property",
"being",
"set",
"to",
"reference",
"the",
"original",
"event",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5262-L5270 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | calculateHorizontals | function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol);
var right = rightFunc(segment.rightCol);
segment.left = left;
segment.outerWidth = right - left;
}
} | javascript | function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol);
var right = rightFunc(segment.rightCol);
segment.left = left;
segment.outerWidth = right - left;
}
} | [
"function",
"calculateHorizontals",
"(",
"segments",
")",
"{",
"var",
"isRTL",
"=",
"opt",
"(",
"'isRTL'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"segment",
"=",
"segments",
"[",
"i",
"]",
";",
"var",
"leftFunc",
"=",
"(",
"isRTL",
"?",
"segment",
".",
"isEnd",
":",
"segment",
".",
"isStart",
")",
"?",
"colContentLeft",
":",
"colLeft",
";",
"var",
"rightFunc",
"=",
"(",
"isRTL",
"?",
"segment",
".",
"isStart",
":",
"segment",
".",
"isEnd",
")",
"?",
"colContentRight",
":",
"colRight",
";",
"var",
"left",
"=",
"leftFunc",
"(",
"segment",
".",
"leftCol",
")",
";",
"var",
"right",
"=",
"rightFunc",
"(",
"segment",
".",
"rightCol",
")",
";",
"segment",
".",
"left",
"=",
"left",
";",
"segment",
".",
"outerWidth",
"=",
"right",
"-",
"left",
";",
"}",
"}"
] | Sets the `left` and `outerWidth` property of each segment. These values are the desired dimensions for the eventual DOM elements. | [
"Sets",
"the",
"left",
"and",
"outerWidth",
"property",
"of",
"each",
"segment",
".",
"These",
"values",
"are",
"the",
"desired",
"dimensions",
"for",
"the",
"eventual",
"DOM",
"elements",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5275-L5293 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | buildHTML | function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
} | javascript | function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
} | [
"function",
"buildHTML",
"(",
"segments",
")",
"{",
"var",
"html",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"html",
"+=",
"buildHTMLForSegment",
"(",
"segments",
"[",
"i",
"]",
")",
";",
"}",
"return",
"html",
";",
"}"
] | Build a concatenated HTML string for an array of segments | [
"Build",
"a",
"concatenated",
"HTML",
"string",
"for",
"an",
"array",
"of",
"segments"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5297-L5303 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | setVerticals | function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
} | javascript | function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
} | [
"function",
"setVerticals",
"(",
"segments",
",",
"doRowHeights",
")",
"{",
"var",
"rowContentHeights",
"=",
"calculateVerticals",
"(",
"segments",
")",
";",
"var",
"rowContentElements",
"=",
"getRowContentElements",
"(",
")",
";",
"var",
"rowContentTops",
"=",
"[",
"]",
";",
"if",
"(",
"doRowHeights",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rowContentElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"rowContentElements",
"[",
"i",
"]",
".",
"height",
"(",
"rowContentHeights",
"[",
"i",
"]",
")",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"rowContentElements",
".",
"length",
";",
"i",
"++",
")",
"{",
"rowContentTops",
".",
"push",
"(",
"rowContentElements",
"[",
"i",
"]",
".",
"position",
"(",
")",
".",
"top",
")",
";",
"}",
"segmentElementEach",
"(",
"segments",
",",
"function",
"(",
"segment",
",",
"element",
")",
"{",
"element",
".",
"css",
"(",
"'top'",
",",
"rowContentTops",
"[",
"segment",
".",
"row",
"]",
"+",
"segment",
".",
"top",
")",
";",
"}",
")",
";",
"}"
] | Sets the "top" CSS property for each element. If `doRowHeights` is `true`, also sets each row's first cell to an explicit height, so that if elements vertically overflow, the cell expands vertically to compensate. | [
"Sets",
"the",
"top",
"CSS",
"property",
"for",
"each",
"element",
".",
"If",
"doRowHeights",
"is",
"true",
"also",
"sets",
"each",
"row",
"s",
"first",
"cell",
"to",
"an",
"explicit",
"height",
"so",
"that",
"if",
"elements",
"vertically",
"overflow",
"the",
"cell",
"expands",
"vertically",
"to",
"compensate",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5430-L5458 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | buildSegmentRows | function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
} | javascript | function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
} | [
"function",
"buildSegmentRows",
"(",
"segments",
")",
"{",
"var",
"rowCnt",
"=",
"getRowCnt",
"(",
")",
";",
"var",
"segmentRows",
"=",
"[",
"]",
";",
"var",
"segmentI",
";",
"var",
"segment",
";",
"var",
"rowI",
";",
"for",
"(",
"segmentI",
"=",
"0",
";",
"segmentI",
"<",
"segments",
".",
"length",
";",
"segmentI",
"++",
")",
"{",
"segment",
"=",
"segments",
"[",
"segmentI",
"]",
";",
"rowI",
"=",
"segment",
".",
"row",
";",
"if",
"(",
"segment",
".",
"element",
")",
"{",
"if",
"(",
"segmentRows",
"[",
"rowI",
"]",
")",
"{",
"segmentRows",
"[",
"rowI",
"]",
".",
"push",
"(",
"segment",
")",
";",
"}",
"else",
"{",
"segmentRows",
"[",
"rowI",
"]",
"=",
"[",
"segment",
"]",
";",
"}",
"}",
"}",
"for",
"(",
"rowI",
"=",
"0",
";",
"rowI",
"<",
"rowCnt",
";",
"rowI",
"++",
")",
"{",
"segmentRows",
"[",
"rowI",
"]",
"=",
"sortSegmentRow",
"(",
"segmentRows",
"[",
"rowI",
"]",
"||",
"[",
"]",
")",
";",
"}",
"return",
"segmentRows",
";",
"}"
] | Build an array of segment arrays, each representing the segments that will be in a row of the grid, sorted by which event should be closest to the top. | [
"Build",
"an",
"array",
"of",
"segment",
"arrays",
"each",
"representing",
"the",
"segments",
"that",
"will",
"be",
"in",
"a",
"row",
"of",
"the",
"grid",
"sorted",
"by",
"which",
"event",
"should",
"be",
"closest",
"to",
"the",
"top",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5510-L5541 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | sortSegmentRow | function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
} | javascript | function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
} | [
"function",
"sortSegmentRow",
"(",
"segments",
")",
"{",
"var",
"sortedSegments",
"=",
"[",
"]",
";",
"var",
"subrows",
"=",
"buildSegmentSubrows",
"(",
"segments",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"subrows",
".",
"length",
";",
"i",
"++",
")",
"{",
"sortedSegments",
".",
"push",
".",
"apply",
"(",
"sortedSegments",
",",
"subrows",
"[",
"i",
"]",
")",
";",
"}",
"return",
"sortedSegments",
";",
"}"
] | Sort an array of segments according to which segment should appear closest to the top | [
"Sort",
"an",
"array",
"of",
"segments",
"according",
"to",
"which",
"segment",
"should",
"appear",
"closest",
"to",
"the",
"top"
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5545-L5557 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | buildSegmentSubrows | function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
} | javascript | function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
} | [
"function",
"buildSegmentSubrows",
"(",
"segments",
")",
"{",
"segments",
".",
"sort",
"(",
"compareDaySegments",
")",
";",
"var",
"subrows",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"segment",
"=",
"segments",
"[",
"i",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"subrows",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"isDaySegmentCollision",
"(",
"segment",
",",
"subrows",
"[",
"j",
"]",
")",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"subrows",
"[",
"j",
"]",
")",
"{",
"subrows",
"[",
"j",
"]",
".",
"push",
"(",
"segment",
")",
";",
"}",
"else",
"{",
"subrows",
"[",
"j",
"]",
"=",
"[",
"segment",
"]",
";",
"}",
"}",
"return",
"subrows",
";",
"}"
] | Take an array of segments, which are all assumed to be in the same row, and sort into subrows. | [
"Take",
"an",
"array",
"of",
"segments",
"which",
"are",
"all",
"assumed",
"to",
"be",
"in",
"the",
"same",
"row",
"and",
"sort",
"into",
"subrows",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5562-L5589 | train |
infrabel/themes-gnap | raw/ace/assets/js/uncompressed/fullcalendar.js | getRowContentElements | function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
} | javascript | function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
} | [
"function",
"getRowContentElements",
"(",
")",
"{",
"var",
"i",
";",
"var",
"rowCnt",
"=",
"getRowCnt",
"(",
")",
";",
"var",
"rowDivs",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"rowCnt",
";",
"i",
"++",
")",
"{",
"rowDivs",
"[",
"i",
"]",
"=",
"allDayRow",
"(",
"i",
")",
".",
"find",
"(",
"'div.fc-day-content > div'",
")",
";",
"}",
"return",
"rowDivs",
";",
"}"
] | Return an array of jQuery objects for the placeholder content containers of each row. The content containers don't actually contain anything, but their dimensions should match the events that are overlaid on top. | [
"Return",
"an",
"array",
"of",
"jQuery",
"objects",
"for",
"the",
"placeholder",
"content",
"containers",
"of",
"each",
"row",
".",
"The",
"content",
"containers",
"don",
"t",
"actually",
"contain",
"anything",
"but",
"their",
"dimensions",
"should",
"match",
"the",
"events",
"that",
"are",
"overlaid",
"on",
"top",
"."
] | 9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9 | https://github.com/infrabel/themes-gnap/blob/9ffd0026b3908b75b42a9fb95cd6b5c6fe1b13d9/raw/ace/assets/js/uncompressed/fullcalendar.js#L5595-L5604 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.