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 |
---|---|---|---|---|---|---|---|---|---|---|---|
dcodeIO/MetaScript | MetaScript.js | function(sourceOrProgram, filename) {
if (!(this instanceof MetaScript)) {
__version = Array.prototype.join.call(arguments, '.');
return;
}
// Whether constructing from a meta program or, otherwise, a source
var isProgram = (sourceOrProgram+="").substring(0, 11) === 'MetaScript(';
/**
* Original source.
* @type {?string}
*/
this.source = isProgram ? null : sourceOrProgram;
/**
* Original source file name.
* @type {string}
*/
this.filename = filename || "main";
/**
* The compiled meta program's source.
* @type {string}
*/
this.program = isProgram ? sourceOrProgram : MetaScript.compile(sourceOrProgram);
} | javascript | function(sourceOrProgram, filename) {
if (!(this instanceof MetaScript)) {
__version = Array.prototype.join.call(arguments, '.');
return;
}
// Whether constructing from a meta program or, otherwise, a source
var isProgram = (sourceOrProgram+="").substring(0, 11) === 'MetaScript(';
/**
* Original source.
* @type {?string}
*/
this.source = isProgram ? null : sourceOrProgram;
/**
* Original source file name.
* @type {string}
*/
this.filename = filename || "main";
/**
* The compiled meta program's source.
* @type {string}
*/
this.program = isProgram ? sourceOrProgram : MetaScript.compile(sourceOrProgram);
} | [
"function",
"(",
"sourceOrProgram",
",",
"filename",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"MetaScript",
")",
")",
"{",
"__version",
"=",
"Array",
".",
"prototype",
".",
"join",
".",
"call",
"(",
"arguments",
",",
"'.'",
")",
";",
"return",
";",
"}",
"var",
"isProgram",
"=",
"(",
"sourceOrProgram",
"+=",
"\"\"",
")",
".",
"substring",
"(",
"0",
",",
"11",
")",
"===",
"'MetaScript('",
";",
"this",
".",
"source",
"=",
"isProgram",
"?",
"null",
":",
"sourceOrProgram",
";",
"this",
".",
"filename",
"=",
"filename",
"||",
"\"main\"",
";",
"this",
".",
"program",
"=",
"isProgram",
"?",
"sourceOrProgram",
":",
"MetaScript",
".",
"compile",
"(",
"sourceOrProgram",
")",
";",
"}"
] | Constructs a new MetaScript instance.
@exports MetaScript
@param {string} sourceOrProgram Source to compile or meta program to run
@param {string=} filename Source file name if known, defaults to `"main"`.
@constructor | [
"Constructs",
"a",
"new",
"MetaScript",
"instance",
"."
] | dc7caf5eae2f2b2467f6c6467203dbcd05f23549 | https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L38-L65 | train |
|
dcodeIO/MetaScript | MetaScript.js | evaluate | function evaluate(expr) {
if (expr.substring(0, 2) === '==') {
return 'write(JSON.stringify('+expr.substring(2).trim()+'));\n';
} else if (expr.substring(0, 1) === '=') {
return 'write('+expr.substring(1).trim()+');\n';
} else if (expr.substring(0, 3) === '...') {
expr = '//...\n'+expr.substring(3).trim()+'\n//.';
}
if (expr !== '') {
return expr+'\n';
}
return '';
} | javascript | function evaluate(expr) {
if (expr.substring(0, 2) === '==') {
return 'write(JSON.stringify('+expr.substring(2).trim()+'));\n';
} else if (expr.substring(0, 1) === '=') {
return 'write('+expr.substring(1).trim()+');\n';
} else if (expr.substring(0, 3) === '...') {
expr = '//...\n'+expr.substring(3).trim()+'\n//.';
}
if (expr !== '') {
return expr+'\n';
}
return '';
} | [
"function",
"evaluate",
"(",
"expr",
")",
"{",
"if",
"(",
"expr",
".",
"substring",
"(",
"0",
",",
"2",
")",
"===",
"'=='",
")",
"{",
"return",
"'write(JSON.stringify('",
"+",
"expr",
".",
"substring",
"(",
"2",
")",
".",
"trim",
"(",
")",
"+",
"'));\\n'",
";",
"}",
"else",
"\\n",
"if",
"(",
"expr",
".",
"substring",
"(",
"0",
",",
"1",
")",
"===",
"'='",
")",
"{",
"return",
"'write('",
"+",
"expr",
".",
"substring",
"(",
"1",
")",
".",
"trim",
"(",
")",
"+",
"');\\n'",
";",
"}",
"else",
"\\n",
"if",
"(",
"expr",
".",
"substring",
"(",
"0",
",",
"3",
")",
"===",
"'...'",
")",
"{",
"expr",
"=",
"'//...\\n'",
"+",
"\\n",
"+",
"expr",
".",
"substring",
"(",
"3",
")",
".",
"trim",
"(",
")",
";",
"}",
"}"
] | Evaluates a meta expression | [
"Evaluates",
"a",
"meta",
"expression"
] | dc7caf5eae2f2b2467f6c6467203dbcd05f23549 | https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L103-L115 | train |
dcodeIO/MetaScript | MetaScript.js | append | function append(source) {
if (s === '') return;
var index = 0,
expr = /\n/g,
s,
match;
while (match = expr.exec(source)) {
s = source.substring(index, match.index+1);
if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n');
index = match.index+1;
}
s = source.substring(index, source.length);
if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n');
} | javascript | function append(source) {
if (s === '') return;
var index = 0,
expr = /\n/g,
s,
match;
while (match = expr.exec(source)) {
s = source.substring(index, match.index+1);
if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n');
index = match.index+1;
}
s = source.substring(index, source.length);
if (s !== '') out.push(' write(\''+escapestr(s)+'\');\n');
} | [
"function",
"append",
"(",
"source",
")",
"{",
"if",
"(",
"s",
"===",
"''",
")",
"return",
";",
"var",
"index",
"=",
"0",
",",
"expr",
"=",
"/",
"\\n",
"/",
"g",
",",
"s",
",",
"match",
";",
"while",
"(",
"match",
"=",
"expr",
".",
"exec",
"(",
"source",
")",
")",
"{",
"s",
"=",
"source",
".",
"substring",
"(",
"index",
",",
"match",
".",
"index",
"+",
"1",
")",
";",
"if",
"(",
"s",
"!==",
"''",
")",
"out",
".",
"push",
"(",
"' write(\\''",
"+",
"\\'",
"+",
"escapestr",
"(",
"s",
")",
")",
";",
"'\\');\\n'",
"}",
"\\'",
"\\n",
"}"
] | Appends additional content to the program, if not empty | [
"Appends",
"additional",
"content",
"to",
"the",
"program",
"if",
"not",
"empty"
] | dc7caf5eae2f2b2467f6c6467203dbcd05f23549 | https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L118-L131 | train |
dcodeIO/MetaScript | MetaScript.js | indent | function indent(str, indent) {
if (typeof indent === 'number') {
var indent_str = '';
while (indent_str.length < indent) indent_str += ' ';
indent = indent_str;
}
var lines = str.split(/\n/);
for (var i=0; i<lines.length; i++) {
if (lines[i].trim() !== '')
lines[i] = indent + lines[i];
}
return lines.join("\n");
} | javascript | function indent(str, indent) {
if (typeof indent === 'number') {
var indent_str = '';
while (indent_str.length < indent) indent_str += ' ';
indent = indent_str;
}
var lines = str.split(/\n/);
for (var i=0; i<lines.length; i++) {
if (lines[i].trim() !== '')
lines[i] = indent + lines[i];
}
return lines.join("\n");
} | [
"function",
"indent",
"(",
"str",
",",
"indent",
")",
"{",
"if",
"(",
"typeof",
"indent",
"===",
"'number'",
")",
"{",
"var",
"indent_str",
"=",
"''",
";",
"while",
"(",
"indent_str",
".",
"length",
"<",
"indent",
")",
"indent_str",
"+=",
"' '",
";",
"indent",
"=",
"indent_str",
";",
"}",
"var",
"lines",
"=",
"str",
".",
"split",
"(",
"/",
"\\n",
"/",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"lines",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"lines",
"[",
"i",
"]",
".",
"trim",
"(",
")",
"!==",
"''",
")",
"lines",
"[",
"i",
"]",
"=",
"indent",
"+",
"lines",
"[",
"i",
"]",
";",
"}",
"return",
"lines",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"}"
] | Indents a block of text.
@function indent
@param {string} str Text to indent
@param {string|number} indent Whitespace text to use for indentation or the number of whitespaces to use
@returns {string} Indented text | [
"Indents",
"a",
"block",
"of",
"text",
"."
] | dc7caf5eae2f2b2467f6c6467203dbcd05f23549 | https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L317-L329 | train |
dcodeIO/MetaScript | MetaScript.js | include | function include(filename, absolute) {
filename = absolute
? filename
: __dirname + '/' + filename;
var _program = __program, // Previous meta program
_source = __source, // Previous source
_filename = __filename, // Previous source file
_dirname = __dirname, // Previous source directory
_indent = __; // Previous indentation level
var files;
if (/(?:^|[^\\])\*/.test(filename)) {
files = require("glob").sync(filename, { cwd : __dirname, nosort: true });
files.sort(naturalCompare); // Sort these naturally (e.g. int8 < int16)
} else {
files = [filename];
}
files.forEach(function(file) {
var source = require("fs").readFileSync(file)+"";
__program = MetaScript.compile(indent(source, __));
__source = source;
__filename = file;
__dirname = dirname(__filename);
__runProgram();
__program = _program;
__source = _source;
__filename = _filename;
__dirname = _dirname;
__ = _indent;
});
} | javascript | function include(filename, absolute) {
filename = absolute
? filename
: __dirname + '/' + filename;
var _program = __program, // Previous meta program
_source = __source, // Previous source
_filename = __filename, // Previous source file
_dirname = __dirname, // Previous source directory
_indent = __; // Previous indentation level
var files;
if (/(?:^|[^\\])\*/.test(filename)) {
files = require("glob").sync(filename, { cwd : __dirname, nosort: true });
files.sort(naturalCompare); // Sort these naturally (e.g. int8 < int16)
} else {
files = [filename];
}
files.forEach(function(file) {
var source = require("fs").readFileSync(file)+"";
__program = MetaScript.compile(indent(source, __));
__source = source;
__filename = file;
__dirname = dirname(__filename);
__runProgram();
__program = _program;
__source = _source;
__filename = _filename;
__dirname = _dirname;
__ = _indent;
});
} | [
"function",
"include",
"(",
"filename",
",",
"absolute",
")",
"{",
"filename",
"=",
"absolute",
"?",
"filename",
":",
"__dirname",
"+",
"'/'",
"+",
"filename",
";",
"var",
"_program",
"=",
"__program",
",",
"_source",
"=",
"__source",
",",
"_filename",
"=",
"__filename",
",",
"_dirname",
"=",
"__dirname",
",",
"_indent",
"=",
"__",
";",
"var",
"files",
";",
"if",
"(",
"/",
"(?:^|[^\\\\])\\*",
"/",
".",
"test",
"(",
"filename",
")",
")",
"{",
"files",
"=",
"require",
"(",
"\"glob\"",
")",
".",
"sync",
"(",
"filename",
",",
"{",
"cwd",
":",
"__dirname",
",",
"nosort",
":",
"true",
"}",
")",
";",
"files",
".",
"sort",
"(",
"naturalCompare",
")",
";",
"}",
"else",
"{",
"files",
"=",
"[",
"filename",
"]",
";",
"}",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"source",
"=",
"require",
"(",
"\"fs\"",
")",
".",
"readFileSync",
"(",
"file",
")",
"+",
"\"\"",
";",
"__program",
"=",
"MetaScript",
".",
"compile",
"(",
"indent",
"(",
"source",
",",
"__",
")",
")",
";",
"__source",
"=",
"source",
";",
"__filename",
"=",
"file",
";",
"__dirname",
"=",
"dirname",
"(",
"__filename",
")",
";",
"__runProgram",
"(",
")",
";",
"__program",
"=",
"_program",
";",
"__source",
"=",
"_source",
";",
"__filename",
"=",
"_filename",
";",
"__dirname",
"=",
"_dirname",
";",
"__",
"=",
"_indent",
";",
"}",
")",
";",
"}"
] | Includes another source file.
@function include
@param {string} filename File to include. May be a glob expression on node.js.
@param {boolean} absolute Whether the path is absolute, defaults to `false` for a relative path | [
"Includes",
"another",
"source",
"file",
"."
] | dc7caf5eae2f2b2467f6c6467203dbcd05f23549 | https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L337-L366 | train |
dcodeIO/MetaScript | MetaScript.js | escapestr | function escapestr(s) {
return s.replace(/\\/g, '\\\\')
.replace(/'/g, '\\\'')
.replace(/"/g, '\\"')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
} | javascript | function escapestr(s) {
return s.replace(/\\/g, '\\\\')
.replace(/'/g, '\\\'')
.replace(/"/g, '\\"')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
} | [
"function",
"escapestr",
"(",
"s",
")",
"{",
"return",
"s",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'\\\\\\\\'",
")",
".",
"\\\\",
"\\\\",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"'\\\\\\''",
")",
".",
"\\\\",
"\\'",
".",
"replace",
"(",
"/",
"\"",
"/",
"g",
",",
"'\\\\\"'",
")",
";",
"}"
] | Escaoes a string to be used inside of a single or double quote enclosed JavaScript string.
@function escapestr
@param {string} s String to escape
@returns {string} Escaped string | [
"Escaoes",
"a",
"string",
"to",
"be",
"used",
"inside",
"of",
"a",
"single",
"or",
"double",
"quote",
"enclosed",
"JavaScript",
"string",
"."
] | dc7caf5eae2f2b2467f6c6467203dbcd05f23549 | https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L374-L380 | train |
dcodeIO/MetaScript | MetaScript.js | __err2code | function __err2code(program, err) {
if (typeof err.stack !== 'string')
return indent(program, 4);
var match = /<anonymous>:(\d+):(\d+)\)/.exec(err.stack);
if (!match) {
return indent(program, 4);
}
var line = parseInt(match[1], 10)-1,
start = line - 3,
end = line + 4,
lines = program.split("\n");
if (start < 0) start = 0;
if (end > lines.length) end = lines.length;
var code = [];
start = 0; end = lines.length;
while (start < end) {
code.push(start === line ? "--> "+lines[start] : " "+lines[start]);
start++;
}
return indent(code.join('\n'), 4);
} | javascript | function __err2code(program, err) {
if (typeof err.stack !== 'string')
return indent(program, 4);
var match = /<anonymous>:(\d+):(\d+)\)/.exec(err.stack);
if (!match) {
return indent(program, 4);
}
var line = parseInt(match[1], 10)-1,
start = line - 3,
end = line + 4,
lines = program.split("\n");
if (start < 0) start = 0;
if (end > lines.length) end = lines.length;
var code = [];
start = 0; end = lines.length;
while (start < end) {
code.push(start === line ? "--> "+lines[start] : " "+lines[start]);
start++;
}
return indent(code.join('\n'), 4);
} | [
"function",
"__err2code",
"(",
"program",
",",
"err",
")",
"{",
"if",
"(",
"typeof",
"err",
".",
"stack",
"!==",
"'string'",
")",
"return",
"indent",
"(",
"program",
",",
"4",
")",
";",
"var",
"match",
"=",
"/",
"<anonymous>:(\\d+):(\\d+)\\)",
"/",
".",
"exec",
"(",
"err",
".",
"stack",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
"indent",
"(",
"program",
",",
"4",
")",
";",
"}",
"var",
"line",
"=",
"parseInt",
"(",
"match",
"[",
"1",
"]",
",",
"10",
")",
"-",
"1",
",",
"start",
"=",
"line",
"-",
"3",
",",
"end",
"=",
"line",
"+",
"4",
",",
"lines",
"=",
"program",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"\\n",
"if",
"(",
"start",
"<",
"0",
")",
"start",
"=",
"0",
";",
"if",
"(",
"end",
">",
"lines",
".",
"length",
")",
"end",
"=",
"lines",
".",
"length",
";",
"var",
"code",
"=",
"[",
"]",
";",
"start",
"=",
"0",
";",
"end",
"=",
"lines",
".",
"length",
";",
"while",
"(",
"start",
"<",
"end",
")",
"{",
"code",
".",
"push",
"(",
"start",
"===",
"line",
"?",
"\"",
"+",
"lines",
"[",
"start",
"]",
":",
"\" \"",
"+",
"lines",
"[",
"start",
"]",
")",
";",
"start",
"++",
";",
"}",
"}"
] | Generates a code view of eval'ed code from an Error.
@param {string} program Failed program
@param {!Error} err Error caught
@returns {string} Code view
@inner
@private | [
"Generates",
"a",
"code",
"view",
"of",
"eval",
"ed",
"code",
"from",
"an",
"Error",
"."
] | dc7caf5eae2f2b2467f6c6467203dbcd05f23549 | https://github.com/dcodeIO/MetaScript/blob/dc7caf5eae2f2b2467f6c6467203dbcd05f23549/MetaScript.js#L408-L428 | train |
ExpressenAB/exp-amqp-connection | index.js | function(callback) {
bootstrap(behaviour, (bootstrapErr, bootstrapRes) => {
if (bootstrapErr) api.emit("error", bootstrapErr);
if (bootstrapRes && bootstrapRes.virgin) {
bootstrapRes.connection.on("error", (err) => api.emit("error", err));
bootstrapRes.connection.on("close", (why) => api.emit("error", why));
api.emit("connected");
bootstrapRes.pubChannel.on("error", (err) => api.emit("error", err));
bootstrapRes.subChannel.on("error", (err) => api.emit("error", err));
bootstrapRes.pubChannel.assertExchange(behaviour.exchange, "topic");
}
callback(bootstrapErr, bootstrapRes);
});
} | javascript | function(callback) {
bootstrap(behaviour, (bootstrapErr, bootstrapRes) => {
if (bootstrapErr) api.emit("error", bootstrapErr);
if (bootstrapRes && bootstrapRes.virgin) {
bootstrapRes.connection.on("error", (err) => api.emit("error", err));
bootstrapRes.connection.on("close", (why) => api.emit("error", why));
api.emit("connected");
bootstrapRes.pubChannel.on("error", (err) => api.emit("error", err));
bootstrapRes.subChannel.on("error", (err) => api.emit("error", err));
bootstrapRes.pubChannel.assertExchange(behaviour.exchange, "topic");
}
callback(bootstrapErr, bootstrapRes);
});
} | [
"function",
"(",
"callback",
")",
"{",
"bootstrap",
"(",
"behaviour",
",",
"(",
"bootstrapErr",
",",
"bootstrapRes",
")",
"=>",
"{",
"if",
"(",
"bootstrapErr",
")",
"api",
".",
"emit",
"(",
"\"error\"",
",",
"bootstrapErr",
")",
";",
"if",
"(",
"bootstrapRes",
"&&",
"bootstrapRes",
".",
"virgin",
")",
"{",
"bootstrapRes",
".",
"connection",
".",
"on",
"(",
"\"error\"",
",",
"(",
"err",
")",
"=>",
"api",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
")",
";",
"bootstrapRes",
".",
"connection",
".",
"on",
"(",
"\"close\"",
",",
"(",
"why",
")",
"=>",
"api",
".",
"emit",
"(",
"\"error\"",
",",
"why",
")",
")",
";",
"api",
".",
"emit",
"(",
"\"connected\"",
")",
";",
"bootstrapRes",
".",
"pubChannel",
".",
"on",
"(",
"\"error\"",
",",
"(",
"err",
")",
"=>",
"api",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
")",
";",
"bootstrapRes",
".",
"subChannel",
".",
"on",
"(",
"\"error\"",
",",
"(",
"err",
")",
"=>",
"api",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
")",
";",
"bootstrapRes",
".",
"pubChannel",
".",
"assertExchange",
"(",
"behaviour",
".",
"exchange",
",",
"\"topic\"",
")",
";",
"}",
"callback",
"(",
"bootstrapErr",
",",
"bootstrapRes",
")",
";",
"}",
")",
";",
"}"
] | get connnection and add event listeners if it's brand new. | [
"get",
"connnection",
"and",
"add",
"event",
"listeners",
"if",
"it",
"s",
"brand",
"new",
"."
] | 999240feee6f0861ddd7404b58b3e6600bd36062 | https://github.com/ExpressenAB/exp-amqp-connection/blob/999240feee6f0861ddd7404b58b3e6600bd36062/index.js#L35-L48 | train |
|
healthsparq/ember-fountainhead | lib/create-dirs.js | mkdirSync | function mkdirSync(dirPath) {
// Get relative path to output
const relativePath = dirPath.replace(`${CWD}${pathSep}`, '');
const dirs = relativePath.split(pathSep);
let currentDir = CWD;
// Check if each dir exists, and if not, create it
dirs.forEach(dir => {
currentDir = path.resolve(currentDir, dir);
if(!fs.existsSync(currentDir)) {
fs.mkdirSync(currentDir);
}
});
} | javascript | function mkdirSync(dirPath) {
// Get relative path to output
const relativePath = dirPath.replace(`${CWD}${pathSep}`, '');
const dirs = relativePath.split(pathSep);
let currentDir = CWD;
// Check if each dir exists, and if not, create it
dirs.forEach(dir => {
currentDir = path.resolve(currentDir, dir);
if(!fs.existsSync(currentDir)) {
fs.mkdirSync(currentDir);
}
});
} | [
"function",
"mkdirSync",
"(",
"dirPath",
")",
"{",
"const",
"relativePath",
"=",
"dirPath",
".",
"replace",
"(",
"`",
"${",
"CWD",
"}",
"${",
"pathSep",
"}",
"`",
",",
"''",
")",
";",
"const",
"dirs",
"=",
"relativePath",
".",
"split",
"(",
"pathSep",
")",
";",
"let",
"currentDir",
"=",
"CWD",
";",
"dirs",
".",
"forEach",
"(",
"dir",
"=>",
"{",
"currentDir",
"=",
"path",
".",
"resolve",
"(",
"currentDir",
",",
"dir",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"currentDir",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"currentDir",
")",
";",
"}",
"}",
")",
";",
"}"
] | Synchronous mkdir that handles creating a potentially nested directory
@method mkdirSync
@param {string} dirPath Directory path to create, can be nested
@return {undefined} | [
"Synchronous",
"mkdir",
"that",
"handles",
"creating",
"a",
"potentially",
"nested",
"directory"
] | 3577546719b251385ca1093f812889590459205a | https://github.com/healthsparq/ember-fountainhead/blob/3577546719b251385ca1093f812889590459205a/lib/create-dirs.js#L26-L39 | train |
mia-js/mia-js-core | lib/baseModel/lib/baseModel.js | function (values, options, callback) {
var deferred = Q.defer();
var args = ArgumentHelpers.prepareArguments(options, callback)
, wrapper = {};
options = args.options;
callback = Qext.makeNodeResolver(deferred, args.callback);
//Check for mongo's another possible syntax with '$' operators, e.g. '$set', '$setOnInsert' and set wrapper
values = values || {};
for (var element in values) {
if (element.match(/\$/i)) {
wrapper[element] = values[element];
options.flat = options.flat != undefined ? options.flat : true
}
}
// If nothing to wrap just validate values
if (_.isEmpty(wrapper)) {
ModelValidator.validate(values, this.prototype, options, function (err, validatedValues) {
callback(err, validatedValues);
});
}
else {
// If wrapping elements like $set, $inc etc found, validate each and rewrite to values
values = {};
var errors = {};
var wrapperOptions = {};
for (var wrapperElem in wrapper) {
wrapperOptions = _.clone(options);
if (options && options.partial && _.isObject(options.partial)) {
if (options.partial[wrapperElem] !== undefined) {
wrapperOptions['partial'] = options.partial[wrapperElem];
}
}
if (options && options.validate && _.isObject(options.validate)) {
if (options.validate[wrapperElem] !== undefined) {
wrapperOptions['validate'] = options.validate[wrapperElem];
}
}
if (options.validate && options.validate[wrapperElem] === false) {
values[wrapperElem] = wrapper[wrapperElem];
}
else {
ModelValidator.validate(wrapper[wrapperElem], this.prototype, wrapperOptions, function (err, validatedValues) {
if (err) {
errors = err;
}
values[wrapperElem] = validatedValues;
});
}
}
if (_.isEmpty(errors)) {
errors = null;
}
callback(errors, values);
}
return deferred.promise;
} | javascript | function (values, options, callback) {
var deferred = Q.defer();
var args = ArgumentHelpers.prepareArguments(options, callback)
, wrapper = {};
options = args.options;
callback = Qext.makeNodeResolver(deferred, args.callback);
//Check for mongo's another possible syntax with '$' operators, e.g. '$set', '$setOnInsert' and set wrapper
values = values || {};
for (var element in values) {
if (element.match(/\$/i)) {
wrapper[element] = values[element];
options.flat = options.flat != undefined ? options.flat : true
}
}
// If nothing to wrap just validate values
if (_.isEmpty(wrapper)) {
ModelValidator.validate(values, this.prototype, options, function (err, validatedValues) {
callback(err, validatedValues);
});
}
else {
// If wrapping elements like $set, $inc etc found, validate each and rewrite to values
values = {};
var errors = {};
var wrapperOptions = {};
for (var wrapperElem in wrapper) {
wrapperOptions = _.clone(options);
if (options && options.partial && _.isObject(options.partial)) {
if (options.partial[wrapperElem] !== undefined) {
wrapperOptions['partial'] = options.partial[wrapperElem];
}
}
if (options && options.validate && _.isObject(options.validate)) {
if (options.validate[wrapperElem] !== undefined) {
wrapperOptions['validate'] = options.validate[wrapperElem];
}
}
if (options.validate && options.validate[wrapperElem] === false) {
values[wrapperElem] = wrapper[wrapperElem];
}
else {
ModelValidator.validate(wrapper[wrapperElem], this.prototype, wrapperOptions, function (err, validatedValues) {
if (err) {
errors = err;
}
values[wrapperElem] = validatedValues;
});
}
}
if (_.isEmpty(errors)) {
errors = null;
}
callback(errors, values);
}
return deferred.promise;
} | [
"function",
"(",
"values",
",",
"options",
",",
"callback",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"var",
"args",
"=",
"ArgumentHelpers",
".",
"prepareArguments",
"(",
"options",
",",
"callback",
")",
",",
"wrapper",
"=",
"{",
"}",
";",
"options",
"=",
"args",
".",
"options",
";",
"callback",
"=",
"Qext",
".",
"makeNodeResolver",
"(",
"deferred",
",",
"args",
".",
"callback",
")",
";",
"values",
"=",
"values",
"||",
"{",
"}",
";",
"for",
"(",
"var",
"element",
"in",
"values",
")",
"{",
"if",
"(",
"element",
".",
"match",
"(",
"/",
"\\$",
"/",
"i",
")",
")",
"{",
"wrapper",
"[",
"element",
"]",
"=",
"values",
"[",
"element",
"]",
";",
"options",
".",
"flat",
"=",
"options",
".",
"flat",
"!=",
"undefined",
"?",
"options",
".",
"flat",
":",
"true",
"}",
"}",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"wrapper",
")",
")",
"{",
"ModelValidator",
".",
"validate",
"(",
"values",
",",
"this",
".",
"prototype",
",",
"options",
",",
"function",
"(",
"err",
",",
"validatedValues",
")",
"{",
"callback",
"(",
"err",
",",
"validatedValues",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"values",
"=",
"{",
"}",
";",
"var",
"errors",
"=",
"{",
"}",
";",
"var",
"wrapperOptions",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"wrapperElem",
"in",
"wrapper",
")",
"{",
"wrapperOptions",
"=",
"_",
".",
"clone",
"(",
"options",
")",
";",
"if",
"(",
"options",
"&&",
"options",
".",
"partial",
"&&",
"_",
".",
"isObject",
"(",
"options",
".",
"partial",
")",
")",
"{",
"if",
"(",
"options",
".",
"partial",
"[",
"wrapperElem",
"]",
"!==",
"undefined",
")",
"{",
"wrapperOptions",
"[",
"'partial'",
"]",
"=",
"options",
".",
"partial",
"[",
"wrapperElem",
"]",
";",
"}",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"validate",
"&&",
"_",
".",
"isObject",
"(",
"options",
".",
"validate",
")",
")",
"{",
"if",
"(",
"options",
".",
"validate",
"[",
"wrapperElem",
"]",
"!==",
"undefined",
")",
"{",
"wrapperOptions",
"[",
"'validate'",
"]",
"=",
"options",
".",
"validate",
"[",
"wrapperElem",
"]",
";",
"}",
"}",
"if",
"(",
"options",
".",
"validate",
"&&",
"options",
".",
"validate",
"[",
"wrapperElem",
"]",
"===",
"false",
")",
"{",
"values",
"[",
"wrapperElem",
"]",
"=",
"wrapper",
"[",
"wrapperElem",
"]",
";",
"}",
"else",
"{",
"ModelValidator",
".",
"validate",
"(",
"wrapper",
"[",
"wrapperElem",
"]",
",",
"this",
".",
"prototype",
",",
"wrapperOptions",
",",
"function",
"(",
"err",
",",
"validatedValues",
")",
"{",
"if",
"(",
"err",
")",
"{",
"errors",
"=",
"err",
";",
"}",
"values",
"[",
"wrapperElem",
"]",
"=",
"validatedValues",
";",
"}",
")",
";",
"}",
"}",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"errors",
")",
")",
"{",
"errors",
"=",
"null",
";",
"}",
"callback",
"(",
"errors",
",",
"values",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Validates provided 'values' against this model.
@param values
@param callback | [
"Validates",
"provided",
"values",
"against",
"this",
"model",
"."
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L202-L265 | train |
|
mia-js/mia-js-core | lib/baseModel/lib/baseModel.js | function (callback) {
var self = this;
var deferred = Q.defer();
callback = Qext.makeNodeResolver(deferred, callback);
var breakExec = {};
Async.waterfall([
function (next) {
if (!self.collectionName) {
next({
name: 'InternalError',
err: "collectionName property is not set for model " + self.identity
});
} else {
var dbName = self.dbName || Shared.config("environment.defaultMongoDatabase");
var db = self.db(dbName);
if (db) {
next(null, db);
}
else {
next({
name: 'InternalError',
err: "No connection to database " + self.identity
});
}
}
},
function (db, next) {
if (!db || _.isEmpty(db)) {
Logger.error("No db connection");
next("No db connection");
}
else {
//try to get exiting collection
db.collection(self.collectionName, {strict: true}, function (err, collection) {
if (!err) {
//collection exists already
self._collection = collection;
//do not apply indexes to exiting collection, since this operation is time consuming
next(breakExec, collection);
}
else {
var collectionOptions = self.collectionOptions || {};
db.createCollection(self.collectionName, collectionOptions, function (err, collection) {
if (!err) {
next(null, collection);
}
else {
db.collection(self.collectionName, {strict: true}, function (err, collection) {
if (!err) {
//collection exists already
self._collection = collection;
//do not apply indexes to exiting collection, since this operation is time consuming
next(breakExec, collection);
}
else {
Logger.error(err);
next(err);
}
});
}
});
}
});
}
},
function (collection, next) {
//store new collection
self._collection = collection;
if (_skipDatabaseIndexingOnNewCollections()) {
return next(null, collection);
}
//apply all indexes on collection
self.ensureAllIndexes(function (err) {
next(err, collection);
});
},
function (collection, next) {
//return collection
next(null, collection);
}
], function (err, collection) {
if (!err || err === breakExec) {
callback(null, collection);
}
else {
callback(err);
}
});
return deferred.promise;
} | javascript | function (callback) {
var self = this;
var deferred = Q.defer();
callback = Qext.makeNodeResolver(deferred, callback);
var breakExec = {};
Async.waterfall([
function (next) {
if (!self.collectionName) {
next({
name: 'InternalError',
err: "collectionName property is not set for model " + self.identity
});
} else {
var dbName = self.dbName || Shared.config("environment.defaultMongoDatabase");
var db = self.db(dbName);
if (db) {
next(null, db);
}
else {
next({
name: 'InternalError',
err: "No connection to database " + self.identity
});
}
}
},
function (db, next) {
if (!db || _.isEmpty(db)) {
Logger.error("No db connection");
next("No db connection");
}
else {
//try to get exiting collection
db.collection(self.collectionName, {strict: true}, function (err, collection) {
if (!err) {
//collection exists already
self._collection = collection;
//do not apply indexes to exiting collection, since this operation is time consuming
next(breakExec, collection);
}
else {
var collectionOptions = self.collectionOptions || {};
db.createCollection(self.collectionName, collectionOptions, function (err, collection) {
if (!err) {
next(null, collection);
}
else {
db.collection(self.collectionName, {strict: true}, function (err, collection) {
if (!err) {
//collection exists already
self._collection = collection;
//do not apply indexes to exiting collection, since this operation is time consuming
next(breakExec, collection);
}
else {
Logger.error(err);
next(err);
}
});
}
});
}
});
}
},
function (collection, next) {
//store new collection
self._collection = collection;
if (_skipDatabaseIndexingOnNewCollections()) {
return next(null, collection);
}
//apply all indexes on collection
self.ensureAllIndexes(function (err) {
next(err, collection);
});
},
function (collection, next) {
//return collection
next(null, collection);
}
], function (err, collection) {
if (!err || err === breakExec) {
callback(null, collection);
}
else {
callback(err);
}
});
return deferred.promise;
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"callback",
"=",
"Qext",
".",
"makeNodeResolver",
"(",
"deferred",
",",
"callback",
")",
";",
"var",
"breakExec",
"=",
"{",
"}",
";",
"Async",
".",
"waterfall",
"(",
"[",
"function",
"(",
"next",
")",
"{",
"if",
"(",
"!",
"self",
".",
"collectionName",
")",
"{",
"next",
"(",
"{",
"name",
":",
"'InternalError'",
",",
"err",
":",
"\"collectionName property is not set for model \"",
"+",
"self",
".",
"identity",
"}",
")",
";",
"}",
"else",
"{",
"var",
"dbName",
"=",
"self",
".",
"dbName",
"||",
"Shared",
".",
"config",
"(",
"\"environment.defaultMongoDatabase\"",
")",
";",
"var",
"db",
"=",
"self",
".",
"db",
"(",
"dbName",
")",
";",
"if",
"(",
"db",
")",
"{",
"next",
"(",
"null",
",",
"db",
")",
";",
"}",
"else",
"{",
"next",
"(",
"{",
"name",
":",
"'InternalError'",
",",
"err",
":",
"\"No connection to database \"",
"+",
"self",
".",
"identity",
"}",
")",
";",
"}",
"}",
"}",
",",
"function",
"(",
"db",
",",
"next",
")",
"{",
"if",
"(",
"!",
"db",
"||",
"_",
".",
"isEmpty",
"(",
"db",
")",
")",
"{",
"Logger",
".",
"error",
"(",
"\"No db connection\"",
")",
";",
"next",
"(",
"\"No db connection\"",
")",
";",
"}",
"else",
"{",
"db",
".",
"collection",
"(",
"self",
".",
"collectionName",
",",
"{",
"strict",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"self",
".",
"_collection",
"=",
"collection",
";",
"next",
"(",
"breakExec",
",",
"collection",
")",
";",
"}",
"else",
"{",
"var",
"collectionOptions",
"=",
"self",
".",
"collectionOptions",
"||",
"{",
"}",
";",
"db",
".",
"createCollection",
"(",
"self",
".",
"collectionName",
",",
"collectionOptions",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"next",
"(",
"null",
",",
"collection",
")",
";",
"}",
"else",
"{",
"db",
".",
"collection",
"(",
"self",
".",
"collectionName",
",",
"{",
"strict",
":",
"true",
"}",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"self",
".",
"_collection",
"=",
"collection",
";",
"next",
"(",
"breakExec",
",",
"collection",
")",
";",
"}",
"else",
"{",
"Logger",
".",
"error",
"(",
"err",
")",
";",
"next",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
",",
"function",
"(",
"collection",
",",
"next",
")",
"{",
"self",
".",
"_collection",
"=",
"collection",
";",
"if",
"(",
"_skipDatabaseIndexingOnNewCollections",
"(",
")",
")",
"{",
"return",
"next",
"(",
"null",
",",
"collection",
")",
";",
"}",
"self",
".",
"ensureAllIndexes",
"(",
"function",
"(",
"err",
")",
"{",
"next",
"(",
"err",
",",
"collection",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"collection",
",",
"next",
")",
"{",
"next",
"(",
"null",
",",
"collection",
")",
";",
"}",
"]",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"if",
"(",
"!",
"err",
"||",
"err",
"===",
"breakExec",
")",
"{",
"callback",
"(",
"null",
",",
"collection",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Gets the collection of this model. Collection is specified in the 'collectionName' property of the model. | [
"Gets",
"the",
"collection",
"of",
"this",
"model",
".",
"Collection",
"is",
"specified",
"in",
"the",
"collectionName",
"property",
"of",
"the",
"model",
"."
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L286-L381 | train |
|
mia-js/mia-js-core | lib/baseModel/lib/baseModel.js | function (arguments) {
var argData = ArgumentHelpers.prepareCallback(arguments);
var callback = argData.callback;
var args = argData.arguments;
if (callback) {
args.pop();
}
return args;
} | javascript | function (arguments) {
var argData = ArgumentHelpers.prepareCallback(arguments);
var callback = argData.callback;
var args = argData.arguments;
if (callback) {
args.pop();
}
return args;
} | [
"function",
"(",
"arguments",
")",
"{",
"var",
"argData",
"=",
"ArgumentHelpers",
".",
"prepareCallback",
"(",
"arguments",
")",
";",
"var",
"callback",
"=",
"argData",
".",
"callback",
";",
"var",
"args",
"=",
"argData",
".",
"arguments",
";",
"if",
"(",
"callback",
")",
"{",
"args",
".",
"pop",
"(",
")",
";",
"}",
"return",
"args",
";",
"}"
] | Removes callback function from arguments and returns the arguments
@param {Object} arguments
@returns {Array}
@private | [
"Removes",
"callback",
"function",
"from",
"arguments",
"and",
"returns",
"the",
"arguments"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L389-L397 | train |
|
mia-js/mia-js-core | lib/baseModel/lib/baseModel.js | function (functionName, arguments) {
var self = this;
var args = self._getArgs(arguments);
var callback = self._getCallback(arguments);
return self._generic(functionName, args)
.nodeify(callback);
} | javascript | function (functionName, arguments) {
var self = this;
var args = self._getArgs(arguments);
var callback = self._getCallback(arguments);
return self._generic(functionName, args)
.nodeify(callback);
} | [
"function",
"(",
"functionName",
",",
"arguments",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"args",
"=",
"self",
".",
"_getArgs",
"(",
"arguments",
")",
";",
"var",
"callback",
"=",
"self",
".",
"_getCallback",
"(",
"arguments",
")",
";",
"return",
"self",
".",
"_generic",
"(",
"functionName",
",",
"args",
")",
".",
"nodeify",
"(",
"callback",
")",
";",
"}"
] | Calls generic driver functions
@param {String} functionName
@param {Object} arguments
@returns {*}
@private | [
"Calls",
"generic",
"driver",
"functions"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L417-L424 | train |
|
mia-js/mia-js-core | lib/baseModel/lib/baseModel.js | function (args) {
var shardKey = this.prototype.shardKey;
var query = !_.isUndefined(args[0]) ? args[0] : {};
var options = !_.isUndefined(args[1]) ? args[1] : {};
var ignoreShardKey = MemberHelpers.getPathPropertyValue(options, 'ignoreShardKey') ? true : false;
var missingFields = [];
if (!_.isUndefined(shardKey) && !_.isUndefined(query) && !ignoreShardKey) {
for (let shardKeyField in shardKey) {
if (!query.hasOwnProperty(shardKeyField)) {
missingFields.push(shardKeyField);
}
}
}
return new Q.Promise(function (resolve, reject) {
if (!_.isEmpty(missingFields)) {
return reject("Query doesn't contain the shard key or parts of it. Missing fields: " + missingFields.join(', '));
}
return resolve();
});
} | javascript | function (args) {
var shardKey = this.prototype.shardKey;
var query = !_.isUndefined(args[0]) ? args[0] : {};
var options = !_.isUndefined(args[1]) ? args[1] : {};
var ignoreShardKey = MemberHelpers.getPathPropertyValue(options, 'ignoreShardKey') ? true : false;
var missingFields = [];
if (!_.isUndefined(shardKey) && !_.isUndefined(query) && !ignoreShardKey) {
for (let shardKeyField in shardKey) {
if (!query.hasOwnProperty(shardKeyField)) {
missingFields.push(shardKeyField);
}
}
}
return new Q.Promise(function (resolve, reject) {
if (!_.isEmpty(missingFields)) {
return reject("Query doesn't contain the shard key or parts of it. Missing fields: " + missingFields.join(', '));
}
return resolve();
});
} | [
"function",
"(",
"args",
")",
"{",
"var",
"shardKey",
"=",
"this",
".",
"prototype",
".",
"shardKey",
";",
"var",
"query",
"=",
"!",
"_",
".",
"isUndefined",
"(",
"args",
"[",
"0",
"]",
")",
"?",
"args",
"[",
"0",
"]",
":",
"{",
"}",
";",
"var",
"options",
"=",
"!",
"_",
".",
"isUndefined",
"(",
"args",
"[",
"1",
"]",
")",
"?",
"args",
"[",
"1",
"]",
":",
"{",
"}",
";",
"var",
"ignoreShardKey",
"=",
"MemberHelpers",
".",
"getPathPropertyValue",
"(",
"options",
",",
"'ignoreShardKey'",
")",
"?",
"true",
":",
"false",
";",
"var",
"missingFields",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"shardKey",
")",
"&&",
"!",
"_",
".",
"isUndefined",
"(",
"query",
")",
"&&",
"!",
"ignoreShardKey",
")",
"{",
"for",
"(",
"let",
"shardKeyField",
"in",
"shardKey",
")",
"{",
"if",
"(",
"!",
"query",
".",
"hasOwnProperty",
"(",
"shardKeyField",
")",
")",
"{",
"missingFields",
".",
"push",
"(",
"shardKeyField",
")",
";",
"}",
"}",
"}",
"return",
"new",
"Q",
".",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"missingFields",
")",
")",
"{",
"return",
"reject",
"(",
"\"Query doesn't contain the shard key or parts of it. Missing fields: \"",
"+",
"missingFields",
".",
"join",
"(",
"', '",
")",
")",
";",
"}",
"return",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}"
] | Checks whether there is a shard key and if it is in the query
@param {Object} args
@returns {*}
@private | [
"Checks",
"whether",
"there",
"is",
"a",
"shard",
"key",
"and",
"if",
"it",
"is",
"in",
"the",
"query"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/baseModel/lib/baseModel.js#L469-L491 | train |
|
jbaicoianu/elation | components/utils/scripts/events.js | function(event) {
if (typeof event.touches != 'undefined' && event.touches.length > 0) {
var c = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
} else {
var c = {
x: (event.pageX || (event.clientX + document.body.scrollLeft)),
y: (event.pageY || (event.clientY + document.body.scrollTop))
};
}
return c;
} | javascript | function(event) {
if (typeof event.touches != 'undefined' && event.touches.length > 0) {
var c = {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
} else {
var c = {
x: (event.pageX || (event.clientX + document.body.scrollLeft)),
y: (event.pageY || (event.clientY + document.body.scrollTop))
};
}
return c;
} | [
"function",
"(",
"event",
")",
"{",
"if",
"(",
"typeof",
"event",
".",
"touches",
"!=",
"'undefined'",
"&&",
"event",
".",
"touches",
".",
"length",
">",
"0",
")",
"{",
"var",
"c",
"=",
"{",
"x",
":",
"event",
".",
"touches",
"[",
"0",
"]",
".",
"pageX",
",",
"y",
":",
"event",
".",
"touches",
"[",
"0",
"]",
".",
"pageY",
"}",
";",
"}",
"else",
"{",
"var",
"c",
"=",
"{",
"x",
":",
"(",
"event",
".",
"pageX",
"||",
"(",
"event",
".",
"clientX",
"+",
"document",
".",
"body",
".",
"scrollLeft",
")",
")",
",",
"y",
":",
"(",
"event",
".",
"pageY",
"||",
"(",
"event",
".",
"clientY",
"+",
"document",
".",
"body",
".",
"scrollTop",
")",
")",
"}",
";",
"}",
"return",
"c",
";",
"}"
] | returns mouse or all finger touch coords | [
"returns",
"mouse",
"or",
"all",
"finger",
"touch",
"coords"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/events.js#L397-L411 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/swaggerDocs.js | function (bodySchemaModels, defName) {
for (var i in bodySchemaModels) {
if (bodySchemaModels[i]["name"] == defName) {
return bodySchemaModels[i];
}
}
return null;
} | javascript | function (bodySchemaModels, defName) {
for (var i in bodySchemaModels) {
if (bodySchemaModels[i]["name"] == defName) {
return bodySchemaModels[i];
}
}
return null;
} | [
"function",
"(",
"bodySchemaModels",
",",
"defName",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"bodySchemaModels",
")",
"{",
"if",
"(",
"bodySchemaModels",
"[",
"i",
"]",
"[",
"\"name\"",
"]",
"==",
"defName",
")",
"{",
"return",
"bodySchemaModels",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Create swagger compatible schema for body parameters
@param bodySchemaModels
@param obj
@param defName
@returns {{bodySchemaModels: *, attributes: {}}}
@private | [
"Create",
"swagger",
"compatible",
"schema",
"for",
"body",
"parameters"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/swaggerDocs.js#L20-L27 | train |
|
mia-js/mia-js-core | lib/modelValidator/lib/modelValidator.js | function (values, schema) {
var publicList = find(schema, 'public')
, arrElem;
for (var value in values) {
if (publicList[value]) {
if (_.isArray(publicList[value])) {
for (var thisArrayElem in publicList[value]) {
if (!_.isArray(values[value])) {
// Delete values due to it should be an array defined in schema
delete(values[value]);
}
else {
for (var thisValue in values[value]) {
values[value][thisValue] = unsetPublicSet(values[value][thisValue], publicList[value][thisArrayElem]);
if (_.isEmpty(values[value][thisValue])) {
(values[value]).splice(thisValue);
}
}
if (_.isEmpty(values[value])) {
delete(values[value]);
}
}
}
}
else {
if (publicList[value].public) {
if (publicList[value].public == false || (publicList[value].public.hasOwnProperty('set') && publicList[value].public.set != true)) {
delete(values[value]);
}
}
}
}
}
return values;
} | javascript | function (values, schema) {
var publicList = find(schema, 'public')
, arrElem;
for (var value in values) {
if (publicList[value]) {
if (_.isArray(publicList[value])) {
for (var thisArrayElem in publicList[value]) {
if (!_.isArray(values[value])) {
// Delete values due to it should be an array defined in schema
delete(values[value]);
}
else {
for (var thisValue in values[value]) {
values[value][thisValue] = unsetPublicSet(values[value][thisValue], publicList[value][thisArrayElem]);
if (_.isEmpty(values[value][thisValue])) {
(values[value]).splice(thisValue);
}
}
if (_.isEmpty(values[value])) {
delete(values[value]);
}
}
}
}
else {
if (publicList[value].public) {
if (publicList[value].public == false || (publicList[value].public.hasOwnProperty('set') && publicList[value].public.set != true)) {
delete(values[value]);
}
}
}
}
}
return values;
} | [
"function",
"(",
"values",
",",
"schema",
")",
"{",
"var",
"publicList",
"=",
"find",
"(",
"schema",
",",
"'public'",
")",
",",
"arrElem",
";",
"for",
"(",
"var",
"value",
"in",
"values",
")",
"{",
"if",
"(",
"publicList",
"[",
"value",
"]",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"publicList",
"[",
"value",
"]",
")",
")",
"{",
"for",
"(",
"var",
"thisArrayElem",
"in",
"publicList",
"[",
"value",
"]",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"values",
"[",
"value",
"]",
")",
")",
"{",
"delete",
"(",
"values",
"[",
"value",
"]",
")",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"thisValue",
"in",
"values",
"[",
"value",
"]",
")",
"{",
"values",
"[",
"value",
"]",
"[",
"thisValue",
"]",
"=",
"unsetPublicSet",
"(",
"values",
"[",
"value",
"]",
"[",
"thisValue",
"]",
",",
"publicList",
"[",
"value",
"]",
"[",
"thisArrayElem",
"]",
")",
";",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"values",
"[",
"value",
"]",
"[",
"thisValue",
"]",
")",
")",
"{",
"(",
"values",
"[",
"value",
"]",
")",
".",
"splice",
"(",
"thisValue",
")",
";",
"}",
"}",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"values",
"[",
"value",
"]",
")",
")",
"{",
"delete",
"(",
"values",
"[",
"value",
"]",
")",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"publicList",
"[",
"value",
"]",
".",
"public",
")",
"{",
"if",
"(",
"publicList",
"[",
"value",
"]",
".",
"public",
"==",
"false",
"||",
"(",
"publicList",
"[",
"value",
"]",
".",
"public",
".",
"hasOwnProperty",
"(",
"'set'",
")",
"&&",
"publicList",
"[",
"value",
"]",
".",
"public",
".",
"set",
"!=",
"true",
")",
")",
"{",
"delete",
"(",
"values",
"[",
"value",
"]",
")",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"values",
";",
"}"
] | Remove values where schema setting public.set false
@param values
@param schema
@returns {*} | [
"Remove",
"values",
"where",
"schema",
"setting",
"public",
".",
"set",
"false"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L724-L763 | train |
|
mia-js/mia-js-core | lib/modelValidator/lib/modelValidator.js | function (values, schema, options) {
var virtualList = find(schema, 'virtual');
//Set default value for virtual if not exists in values
if (options && options.query === true) {
}
else {
for (var virtual in virtualList) {
if (_.isArray(virtualList[virtual])) {
for (var thisVirtual in virtualList[virtual]) {
if (_.isArray(values[virtual])) {
for (var thisValue in values[virtual]) {
setVirtuals(values[virtual][thisValue], virtualList[virtual][thisVirtual], options);
}
}
}
}
else {
if (values[virtual] === undefined && virtualList[virtual] && virtualList[virtual].hasOwnProperty('default') && options && options.partial !== true) {
values[virtual] = (virtualList[virtual]).default;
}
}
}
}
for (var value in values) {
if (virtualList[value] && virtualList[value].virtual) {
var setFunction = virtualList[value].virtual;
//Check for setter and getter
if (virtualList[value].virtual.set) {
setFunction = virtualList[value].virtual.set;
}
//Check conditions and apply virtual
rulesMatch(value, values[value], setFunction, null, function (err, data) {
if (!err) {
if (_.isFunction(setFunction)) {
var virtualResult = setFunction(values[value]);
if (_.isObject(virtualResult) && !_.isEmpty(virtualResult)) {
//Check if virtual values does not exists in given values list. Do not overwrite given
for (var vValue in virtualResult) {
{
if (vValue == 'this') {
virtualResult[value] = virtualResult[vValue];
delete(virtualResult[vValue]);
}
else {
// Prevent overwrite of given values
if (values[vValue] !== undefined) {
delete(virtualResult[vValue]);
}
}
}
}
values = _.assign(values, virtualResult);
}
}
}
});
}
}
return values;
} | javascript | function (values, schema, options) {
var virtualList = find(schema, 'virtual');
//Set default value for virtual if not exists in values
if (options && options.query === true) {
}
else {
for (var virtual in virtualList) {
if (_.isArray(virtualList[virtual])) {
for (var thisVirtual in virtualList[virtual]) {
if (_.isArray(values[virtual])) {
for (var thisValue in values[virtual]) {
setVirtuals(values[virtual][thisValue], virtualList[virtual][thisVirtual], options);
}
}
}
}
else {
if (values[virtual] === undefined && virtualList[virtual] && virtualList[virtual].hasOwnProperty('default') && options && options.partial !== true) {
values[virtual] = (virtualList[virtual]).default;
}
}
}
}
for (var value in values) {
if (virtualList[value] && virtualList[value].virtual) {
var setFunction = virtualList[value].virtual;
//Check for setter and getter
if (virtualList[value].virtual.set) {
setFunction = virtualList[value].virtual.set;
}
//Check conditions and apply virtual
rulesMatch(value, values[value], setFunction, null, function (err, data) {
if (!err) {
if (_.isFunction(setFunction)) {
var virtualResult = setFunction(values[value]);
if (_.isObject(virtualResult) && !_.isEmpty(virtualResult)) {
//Check if virtual values does not exists in given values list. Do not overwrite given
for (var vValue in virtualResult) {
{
if (vValue == 'this') {
virtualResult[value] = virtualResult[vValue];
delete(virtualResult[vValue]);
}
else {
// Prevent overwrite of given values
if (values[vValue] !== undefined) {
delete(virtualResult[vValue]);
}
}
}
}
values = _.assign(values, virtualResult);
}
}
}
});
}
}
return values;
} | [
"function",
"(",
"values",
",",
"schema",
",",
"options",
")",
"{",
"var",
"virtualList",
"=",
"find",
"(",
"schema",
",",
"'virtual'",
")",
";",
"if",
"(",
"options",
"&&",
"options",
".",
"query",
"===",
"true",
")",
"{",
"}",
"else",
"{",
"for",
"(",
"var",
"virtual",
"in",
"virtualList",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"virtualList",
"[",
"virtual",
"]",
")",
")",
"{",
"for",
"(",
"var",
"thisVirtual",
"in",
"virtualList",
"[",
"virtual",
"]",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"values",
"[",
"virtual",
"]",
")",
")",
"{",
"for",
"(",
"var",
"thisValue",
"in",
"values",
"[",
"virtual",
"]",
")",
"{",
"setVirtuals",
"(",
"values",
"[",
"virtual",
"]",
"[",
"thisValue",
"]",
",",
"virtualList",
"[",
"virtual",
"]",
"[",
"thisVirtual",
"]",
",",
"options",
")",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"values",
"[",
"virtual",
"]",
"===",
"undefined",
"&&",
"virtualList",
"[",
"virtual",
"]",
"&&",
"virtualList",
"[",
"virtual",
"]",
".",
"hasOwnProperty",
"(",
"'default'",
")",
"&&",
"options",
"&&",
"options",
".",
"partial",
"!==",
"true",
")",
"{",
"values",
"[",
"virtual",
"]",
"=",
"(",
"virtualList",
"[",
"virtual",
"]",
")",
".",
"default",
";",
"}",
"}",
"}",
"}",
"for",
"(",
"var",
"value",
"in",
"values",
")",
"{",
"if",
"(",
"virtualList",
"[",
"value",
"]",
"&&",
"virtualList",
"[",
"value",
"]",
".",
"virtual",
")",
"{",
"var",
"setFunction",
"=",
"virtualList",
"[",
"value",
"]",
".",
"virtual",
";",
"if",
"(",
"virtualList",
"[",
"value",
"]",
".",
"virtual",
".",
"set",
")",
"{",
"setFunction",
"=",
"virtualList",
"[",
"value",
"]",
".",
"virtual",
".",
"set",
";",
"}",
"rulesMatch",
"(",
"value",
",",
"values",
"[",
"value",
"]",
",",
"setFunction",
",",
"null",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"setFunction",
")",
")",
"{",
"var",
"virtualResult",
"=",
"setFunction",
"(",
"values",
"[",
"value",
"]",
")",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"virtualResult",
")",
"&&",
"!",
"_",
".",
"isEmpty",
"(",
"virtualResult",
")",
")",
"{",
"for",
"(",
"var",
"vValue",
"in",
"virtualResult",
")",
"{",
"{",
"if",
"(",
"vValue",
"==",
"'this'",
")",
"{",
"virtualResult",
"[",
"value",
"]",
"=",
"virtualResult",
"[",
"vValue",
"]",
";",
"delete",
"(",
"virtualResult",
"[",
"vValue",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"values",
"[",
"vValue",
"]",
"!==",
"undefined",
")",
"{",
"delete",
"(",
"virtualResult",
"[",
"vValue",
"]",
")",
";",
"}",
"}",
"}",
"}",
"values",
"=",
"_",
".",
"assign",
"(",
"values",
",",
"virtualResult",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}",
"}",
"return",
"values",
";",
"}"
] | Apply virtual functions defined in schema
@param values
@param model
@param options
@returns {*} | [
"Apply",
"virtual",
"functions",
"defined",
"in",
"schema"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L772-L840 | train |
|
mia-js/mia-js-core | lib/modelValidator/lib/modelValidator.js | function (model, filter, value) {
if (!_.isString(filter)) {
return null;
}
if (model.data) {
var list = findKeys(model.data, filter)
, values = [];
for (var res in list) {
if (value === undefined || list[res][filter] === value) {
values.push(res);
}
}
}
//return _.isEmpty(values) ? undefined : values;
//Changed to return empty array instead of 'undefined'. Do not change back, otherwise some functions working with arrays do not work properly.
return values;
} | javascript | function (model, filter, value) {
if (!_.isString(filter)) {
return null;
}
if (model.data) {
var list = findKeys(model.data, filter)
, values = [];
for (var res in list) {
if (value === undefined || list[res][filter] === value) {
values.push(res);
}
}
}
//return _.isEmpty(values) ? undefined : values;
//Changed to return empty array instead of 'undefined'. Do not change back, otherwise some functions working with arrays do not work properly.
return values;
} | [
"function",
"(",
"model",
",",
"filter",
",",
"value",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"filter",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"model",
".",
"data",
")",
"{",
"var",
"list",
"=",
"findKeys",
"(",
"model",
".",
"data",
",",
"filter",
")",
",",
"values",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"res",
"in",
"list",
")",
"{",
"if",
"(",
"value",
"===",
"undefined",
"||",
"list",
"[",
"res",
"]",
"[",
"filter",
"]",
"===",
"value",
")",
"{",
"values",
".",
"push",
"(",
"res",
")",
";",
"}",
"}",
"}",
"return",
"values",
";",
"}"
] | Finds all nodes with filter property in given model and returns array list of nodes
@param model
@param filter
@returns {*} | [
"Finds",
"all",
"nodes",
"with",
"filter",
"property",
"in",
"given",
"model",
"and",
"returns",
"array",
"list",
"of",
"nodes"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L977-L997 | train |
|
mia-js/mia-js-core | lib/modelValidator/lib/modelValidator.js | function (schema) {
var extendList = find(schema, 'extend');
for (var extendElem in extendList) {
if (extendList[extendElem] && extendList[extendElem].extend && _.isFunction(extendList[extendElem].extend)) {
schema[extendElem] = extendList[extendElem].extend();
}
}
return schema;
} | javascript | function (schema) {
var extendList = find(schema, 'extend');
for (var extendElem in extendList) {
if (extendList[extendElem] && extendList[extendElem].extend && _.isFunction(extendList[extendElem].extend)) {
schema[extendElem] = extendList[extendElem].extend();
}
}
return schema;
} | [
"function",
"(",
"schema",
")",
"{",
"var",
"extendList",
"=",
"find",
"(",
"schema",
",",
"'extend'",
")",
";",
"for",
"(",
"var",
"extendElem",
"in",
"extendList",
")",
"{",
"if",
"(",
"extendList",
"[",
"extendElem",
"]",
"&&",
"extendList",
"[",
"extendElem",
"]",
".",
"extend",
"&&",
"_",
".",
"isFunction",
"(",
"extendList",
"[",
"extendElem",
"]",
".",
"extend",
")",
")",
"{",
"schema",
"[",
"extendElem",
"]",
"=",
"extendList",
"[",
"extendElem",
"]",
".",
"extend",
"(",
")",
";",
"}",
"}",
"return",
"schema",
";",
"}"
] | Extend schema by dynamic functions. Write a function that defined the schema settings for a node
@param schema
@returns {*} | [
"Extend",
"schema",
"by",
"dynamic",
"functions",
".",
"Write",
"a",
"function",
"that",
"defined",
"the",
"schema",
"settings",
"for",
"a",
"node"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/modelValidator/lib/modelValidator.js#L1004-L1013 | train |
|
jonschlinkert/plasma | index.js | name | function name(fp, options) {
var opts = options || {};
if (typeof opts.namespace === 'function') {
return opts.namespace(fp, opts);
}
if (typeof opts.namespace === false) {
return fp;
}
var ext = path.extname(fp);
return path.basename(fp, ext);
} | javascript | function name(fp, options) {
var opts = options || {};
if (typeof opts.namespace === 'function') {
return opts.namespace(fp, opts);
}
if (typeof opts.namespace === false) {
return fp;
}
var ext = path.extname(fp);
return path.basename(fp, ext);
} | [
"function",
"name",
"(",
"fp",
",",
"options",
")",
"{",
"var",
"opts",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"typeof",
"opts",
".",
"namespace",
"===",
"'function'",
")",
"{",
"return",
"opts",
".",
"namespace",
"(",
"fp",
",",
"opts",
")",
";",
"}",
"if",
"(",
"typeof",
"opts",
".",
"namespace",
"===",
"false",
")",
"{",
"return",
"fp",
";",
"}",
"var",
"ext",
"=",
"path",
".",
"extname",
"(",
"fp",
")",
";",
"return",
"path",
".",
"basename",
"(",
"fp",
",",
"ext",
")",
";",
"}"
] | Default `namespace` function. Pass a function on `options.namespace`
to customize.
@param {String} `fp`
@param {Object} `opts`
@return {String}
@api private | [
"Default",
"namespace",
"function",
".",
"Pass",
"a",
"function",
"on",
"options",
".",
"namespace",
"to",
"customize",
"."
] | 573027b52817ceb2f1295779bc2b3bceefa74d11 | https://github.com/jonschlinkert/plasma/blob/573027b52817ceb2f1295779bc2b3bceefa74d11/index.js#L229-L239 | train |
jonschlinkert/plasma | index.js | read | function read(fp, opts) {
if (opts && opts.read) {
return opts.read(fp, opts);
}
return readData.call(this, fp, opts);
} | javascript | function read(fp, opts) {
if (opts && opts.read) {
return opts.read(fp, opts);
}
return readData.call(this, fp, opts);
} | [
"function",
"read",
"(",
"fp",
",",
"opts",
")",
"{",
"if",
"(",
"opts",
"&&",
"opts",
".",
"read",
")",
"{",
"return",
"opts",
".",
"read",
"(",
"fp",
",",
"opts",
")",
";",
"}",
"return",
"readData",
".",
"call",
"(",
"this",
",",
"fp",
",",
"opts",
")",
";",
"}"
] | Default `read` function. Pass a function on `options.read`
to customize.
@param {String} `fp`
@param {Object} `opts`
@return {String}
@api private | [
"Default",
"read",
"function",
".",
"Pass",
"a",
"function",
"on",
"options",
".",
"read",
"to",
"customize",
"."
] | 573027b52817ceb2f1295779bc2b3bceefa74d11 | https://github.com/jonschlinkert/plasma/blob/573027b52817ceb2f1295779bc2b3bceefa74d11/index.js#L251-L256 | train |
jonschlinkert/plasma | index.js | readData | function readData(fp, options) {
// shallow clone options
var opts = utils.extend({}, options);
// get the loader for this file.
var ext = opts.lang || path.extname(fp);
if (ext && ext.charAt(0) !== '.') {
ext = '.' + ext;
}
if (!this.dataLoaders.hasOwnProperty(ext)) {
return this.dataLoader('read')(fp, opts);
}
return this.dataLoader(ext)(fp, opts);
} | javascript | function readData(fp, options) {
// shallow clone options
var opts = utils.extend({}, options);
// get the loader for this file.
var ext = opts.lang || path.extname(fp);
if (ext && ext.charAt(0) !== '.') {
ext = '.' + ext;
}
if (!this.dataLoaders.hasOwnProperty(ext)) {
return this.dataLoader('read')(fp, opts);
}
return this.dataLoader(ext)(fp, opts);
} | [
"function",
"readData",
"(",
"fp",
",",
"options",
")",
"{",
"var",
"opts",
"=",
"utils",
".",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"var",
"ext",
"=",
"opts",
".",
"lang",
"||",
"path",
".",
"extname",
"(",
"fp",
")",
";",
"if",
"(",
"ext",
"&&",
"ext",
".",
"charAt",
"(",
"0",
")",
"!==",
"'.'",
")",
"{",
"ext",
"=",
"'.'",
"+",
"ext",
";",
"}",
"if",
"(",
"!",
"this",
".",
"dataLoaders",
".",
"hasOwnProperty",
"(",
"ext",
")",
")",
"{",
"return",
"this",
".",
"dataLoader",
"(",
"'read'",
")",
"(",
"fp",
",",
"opts",
")",
";",
"}",
"return",
"this",
".",
"dataLoader",
"(",
"ext",
")",
"(",
"fp",
",",
"opts",
")",
";",
"}"
] | Utility for reading data files.
@param {String} `fp` Filepath to read.
@param {Object} `options` Options to pass to [js-yaml]
@api private | [
"Utility",
"for",
"reading",
"data",
"files",
"."
] | 573027b52817ceb2f1295779bc2b3bceefa74d11 | https://github.com/jonschlinkert/plasma/blob/573027b52817ceb2f1295779bc2b3bceefa74d11/index.js#L266-L278 | train |
jbaicoianu/elation | components/utils/scripts/ajaxlib.js | function() {
if (common.inlinescripts.length > 0) {
var script_text = '';
for (var i = 0; i < common.inlinescripts.length; i++) {
if (!common.inlinescripts[i] || typeof common.inlinescripts[i] == 'undefined')
continue;
else
script_text += common.inlinescripts[i] + '\n';
}
try {
eval(script_text);
} catch(e) {
batch.callback(script_text);
}
}
} | javascript | function() {
if (common.inlinescripts.length > 0) {
var script_text = '';
for (var i = 0; i < common.inlinescripts.length; i++) {
if (!common.inlinescripts[i] || typeof common.inlinescripts[i] == 'undefined')
continue;
else
script_text += common.inlinescripts[i] + '\n';
}
try {
eval(script_text);
} catch(e) {
batch.callback(script_text);
}
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"common",
".",
"inlinescripts",
".",
"length",
">",
"0",
")",
"{",
"var",
"script_text",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"common",
".",
"inlinescripts",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"common",
".",
"inlinescripts",
"[",
"i",
"]",
"||",
"typeof",
"common",
".",
"inlinescripts",
"[",
"i",
"]",
"==",
"'undefined'",
")",
"continue",
";",
"else",
"script_text",
"+=",
"common",
".",
"inlinescripts",
"[",
"i",
"]",
"+",
"'\\n'",
";",
"}",
"\\n",
"}",
"}"
] | Execute all inline scripts | [
"Execute",
"all",
"inline",
"scripts"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/ajaxlib.js#L229-L244 | train |
|
healthsparq/ember-fountainhead | lib/generate-fountainhead-data.js | saveObjectToJSON | function saveObjectToJSON(filePath, data) {
try {
data = JSON.stringify(data, null, 2);
writeFileSync(filePath, data, { encoding: 'utf8' });
return true;
} catch(ex) {
console.warn('Unable to save class JSON');
return false;
}
// NOTE: ASYNC REQUIRES PROMISIFYING ALL OPERATIONS
// fs.writeFile(filePath, data, err => {
// if (err) { console.warn(`Unable to save ${filePath}`); }
// });
} | javascript | function saveObjectToJSON(filePath, data) {
try {
data = JSON.stringify(data, null, 2);
writeFileSync(filePath, data, { encoding: 'utf8' });
return true;
} catch(ex) {
console.warn('Unable to save class JSON');
return false;
}
// NOTE: ASYNC REQUIRES PROMISIFYING ALL OPERATIONS
// fs.writeFile(filePath, data, err => {
// if (err) { console.warn(`Unable to save ${filePath}`); }
// });
} | [
"function",
"saveObjectToJSON",
"(",
"filePath",
",",
"data",
")",
"{",
"try",
"{",
"data",
"=",
"JSON",
".",
"stringify",
"(",
"data",
",",
"null",
",",
"2",
")",
";",
"writeFileSync",
"(",
"filePath",
",",
"data",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"console",
".",
"warn",
"(",
"'Unable to save class JSON'",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Call to handle saving data to a file. Requires a file path and data to save.
If data is not a string, it will be stringified
@method saveObjectToJSON
@param {string} filePath Path to save file at
@param {Object|string} data Data to save in file
@return {boolean} True for successful operation, false for failures | [
"Call",
"to",
"handle",
"saving",
"data",
"to",
"a",
"file",
".",
"Requires",
"a",
"file",
"path",
"and",
"data",
"to",
"save",
".",
"If",
"data",
"is",
"not",
"a",
"string",
"it",
"will",
"be",
"stringified"
] | 3577546719b251385ca1093f812889590459205a | https://github.com/healthsparq/ember-fountainhead/blob/3577546719b251385ca1093f812889590459205a/lib/generate-fountainhead-data.js#L58-L72 | train |
kuzzleio/kuzzle-common-objects | lib/utils/assertType.js | assertObject | function assertObject(attr, data) {
if (data === null || data === undefined) {
return null;
}
if (typeof data !== 'object' || Array.isArray(data)) {
throw new ParseError(`Attribute ${attr} must be of type "object"`);
}
return data;
} | javascript | function assertObject(attr, data) {
if (data === null || data === undefined) {
return null;
}
if (typeof data !== 'object' || Array.isArray(data)) {
throw new ParseError(`Attribute ${attr} must be of type "object"`);
}
return data;
} | [
"function",
"assertObject",
"(",
"attr",
",",
"data",
")",
"{",
"if",
"(",
"data",
"===",
"null",
"||",
"data",
"===",
"undefined",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"typeof",
"data",
"!==",
"'object'",
"||",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
"{",
"throw",
"new",
"ParseError",
"(",
"`",
"${",
"attr",
"}",
"`",
")",
";",
"}",
"return",
"data",
";",
"}"
] | Throws if the provided data is not an object.
Returns the unmodified data if validated
@throws
@param {string} attr - tested attribute name
@param {*} data
@return {object} | [
"Throws",
"if",
"the",
"provided",
"data",
"is",
"not",
"an",
"object",
".",
"Returns",
"the",
"unmodified",
"data",
"if",
"validated"
] | 7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2 | https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L14-L24 | train |
kuzzleio/kuzzle-common-objects | lib/utils/assertType.js | assertArray | function assertArray(attr, data, type) {
if (data === null || data === undefined) {
return [];
}
if (!Array.isArray(data)) {
throw new ParseError(`Attribute ${attr} must be of type "array"`);
}
const clone = [];
for (const d of data) {
if (d !== undefined && d !== null) {
if (typeof d !== type) {
throw new ParseError(`Attribute ${attr} must contain only values of type "${type}"`);
}
clone.push(d);
}
}
return clone;
} | javascript | function assertArray(attr, data, type) {
if (data === null || data === undefined) {
return [];
}
if (!Array.isArray(data)) {
throw new ParseError(`Attribute ${attr} must be of type "array"`);
}
const clone = [];
for (const d of data) {
if (d !== undefined && d !== null) {
if (typeof d !== type) {
throw new ParseError(`Attribute ${attr} must contain only values of type "${type}"`);
}
clone.push(d);
}
}
return clone;
} | [
"function",
"assertArray",
"(",
"attr",
",",
"data",
",",
"type",
")",
"{",
"if",
"(",
"data",
"===",
"null",
"||",
"data",
"===",
"undefined",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
"{",
"throw",
"new",
"ParseError",
"(",
"`",
"${",
"attr",
"}",
"`",
")",
";",
"}",
"const",
"clone",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"d",
"of",
"data",
")",
"{",
"if",
"(",
"d",
"!==",
"undefined",
"&&",
"d",
"!==",
"null",
")",
"{",
"if",
"(",
"typeof",
"d",
"!==",
"type",
")",
"{",
"throw",
"new",
"ParseError",
"(",
"`",
"${",
"attr",
"}",
"${",
"type",
"}",
"`",
")",
";",
"}",
"clone",
".",
"push",
"(",
"d",
")",
";",
"}",
"}",
"return",
"clone",
";",
"}"
] | Throws if the provided data is not an array containing exclusively
values of the specified "type"
Returns a clone of the provided array if valid
@throws
@param {string} attr - tested attribute name
@param {*} data
@return {array} | [
"Throws",
"if",
"the",
"provided",
"data",
"is",
"not",
"an",
"array",
"containing",
"exclusively",
"values",
"of",
"the",
"specified",
"type",
"Returns",
"a",
"clone",
"of",
"the",
"provided",
"array",
"if",
"valid"
] | 7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2 | https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L36-L58 | train |
kuzzleio/kuzzle-common-objects | lib/utils/assertType.js | assertUniTypeObject | function assertUniTypeObject(attr, data, type) {
data = assertObject(attr, data);
if (data === null) {
return null;
}
Object.keys(data).forEach(key => {
if (type === undefined) {
type = typeof data[key];
}
type = type.toLowerCase();
let msg = `Attribute ${attr} must be of type "object" and have all its properties of type ${type}.`
+ `\nExpected "${attr}.${key}" to be of type "${type}", but go "${typeof data[key]}".`;
switch (type) {
case 'array':
if (!Array.isArray(data[key])) {
throw new ParseError(msg);
}
break;
default:
if (typeof data[key] !== type) {
throw new ParseError(msg);
}
break;
}
});
return data;
} | javascript | function assertUniTypeObject(attr, data, type) {
data = assertObject(attr, data);
if (data === null) {
return null;
}
Object.keys(data).forEach(key => {
if (type === undefined) {
type = typeof data[key];
}
type = type.toLowerCase();
let msg = `Attribute ${attr} must be of type "object" and have all its properties of type ${type}.`
+ `\nExpected "${attr}.${key}" to be of type "${type}", but go "${typeof data[key]}".`;
switch (type) {
case 'array':
if (!Array.isArray(data[key])) {
throw new ParseError(msg);
}
break;
default:
if (typeof data[key] !== type) {
throw new ParseError(msg);
}
break;
}
});
return data;
} | [
"function",
"assertUniTypeObject",
"(",
"attr",
",",
"data",
",",
"type",
")",
"{",
"data",
"=",
"assertObject",
"(",
"attr",
",",
"data",
")",
";",
"if",
"(",
"data",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Object",
".",
"keys",
"(",
"data",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"if",
"(",
"type",
"===",
"undefined",
")",
"{",
"type",
"=",
"typeof",
"data",
"[",
"key",
"]",
";",
"}",
"type",
"=",
"type",
".",
"toLowerCase",
"(",
")",
";",
"let",
"msg",
"=",
"`",
"${",
"attr",
"}",
"${",
"type",
"}",
"`",
"+",
"`",
"\\n",
"${",
"attr",
"}",
"${",
"key",
"}",
"${",
"type",
"}",
"${",
"typeof",
"data",
"[",
"key",
"]",
"}",
"`",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'array'",
":",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"data",
"[",
"key",
"]",
")",
")",
"{",
"throw",
"new",
"ParseError",
"(",
"msg",
")",
";",
"}",
"break",
";",
"default",
":",
"if",
"(",
"typeof",
"data",
"[",
"key",
"]",
"!==",
"type",
")",
"{",
"throw",
"new",
"ParseError",
"(",
"msg",
")",
";",
"}",
"break",
";",
"}",
"}",
")",
";",
"return",
"data",
";",
"}"
] | Throws if the provided object is not an object or if it contains heterogeaous typed properties.
Returns the unmodified data if validated.
@throws {ParseError}
@param {string} attr - tested attribute name
@param {*} data
@param {string} [type] - expected type for data properties
@returns {object|null} | [
"Throws",
"if",
"the",
"provided",
"object",
"is",
"not",
"an",
"object",
"or",
"if",
"it",
"contains",
"heterogeaous",
"typed",
"properties",
".",
"Returns",
"the",
"unmodified",
"data",
"if",
"validated",
"."
] | 7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2 | https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L70-L102 | train |
kuzzleio/kuzzle-common-objects | lib/utils/assertType.js | assertString | function assertString(attr, data) {
if (data === null || data === undefined) {
return null;
}
if (typeof data !== 'string') {
throw new ParseError(`Attribute ${attr} must be of type "string"`);
}
return data;
} | javascript | function assertString(attr, data) {
if (data === null || data === undefined) {
return null;
}
if (typeof data !== 'string') {
throw new ParseError(`Attribute ${attr} must be of type "string"`);
}
return data;
} | [
"function",
"assertString",
"(",
"attr",
",",
"data",
")",
"{",
"if",
"(",
"data",
"===",
"null",
"||",
"data",
"===",
"undefined",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"typeof",
"data",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"ParseError",
"(",
"`",
"${",
"attr",
"}",
"`",
")",
";",
"}",
"return",
"data",
";",
"}"
] | Throws if the provided data is not a string
Returns the unmodified data if validated
@throws
@param {string} attr - tested attribute name
@param {*} data
@return {null|string} | [
"Throws",
"if",
"the",
"provided",
"data",
"is",
"not",
"a",
"string",
"Returns",
"the",
"unmodified",
"data",
"if",
"validated"
] | 7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2 | https://github.com/kuzzleio/kuzzle-common-objects/blob/7a7bac8245d9a34ea14c8e7326e95a1f13b9acc2/lib/utils/assertType.js#L114-L124 | train |
mia-js/mia-js-core | lib/routesHandler/lib/preconditionsCheck.js | function (values, model, type) {
var deferred = Q.defer();
var modelData = {data: model};
ModelValidator.validate(values, modelData, function (err, data) {
deferred.resolve({data: data, err: err, type: type});
});
return deferred.promise;
} | javascript | function (values, model, type) {
var deferred = Q.defer();
var modelData = {data: model};
ModelValidator.validate(values, modelData, function (err, data) {
deferred.resolve({data: data, err: err, type: type});
});
return deferred.promise;
} | [
"function",
"(",
"values",
",",
"model",
",",
"type",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"var",
"modelData",
"=",
"{",
"data",
":",
"model",
"}",
";",
"ModelValidator",
".",
"validate",
"(",
"values",
",",
"modelData",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"deferred",
".",
"resolve",
"(",
"{",
"data",
":",
"data",
",",
"err",
":",
"err",
",",
"type",
":",
"type",
"}",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Validate given values using given model
@param values
@param model
@param type
@returns {*}
@private | [
"Validate",
"given",
"values",
"using",
"given",
"model"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/preconditionsCheck.js#L82-L90 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/preconditionsCheck.js | function (req, controller) {
var parameters = [];
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.header) {
parameters.push(_checkValues(req.headers, controller.conditions.parameters.header, "header"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.query) {
parameters.push(_checkValues(req.query, controller.conditions.parameters.query, "query"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.body) {
parameters.push(_checkValues(req.body, controller.conditions.parameters.body, "body"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.path) {
parameters.push(_checkValues(req.params, controller.conditions.parameters.path, "path"))
}
return Q.all(parameters).then(function (results) {
var validatedData = [];
var errors = [];
results.forEach(function (result) {
if (result.data) {
if (!validatedData[result.type]) {
validatedData[result.type] = {};
}
validatedData[result.type] = result.data;
}
// Collect validation errors
if (result.err && result.err.err && result.err.name == "ValidationError") {
var resultErrors = result.err.err;
resultErrors.forEach(function (error) {
error.in = result.type;
errors.push(error);
});
}
});
return Q({
validatedData: {
name: controller.name,
version: controller.version,
method: controller.method,
function: controller.function,
data: validatedData
},
errors: errors
});
});
} | javascript | function (req, controller) {
var parameters = [];
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.header) {
parameters.push(_checkValues(req.headers, controller.conditions.parameters.header, "header"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.query) {
parameters.push(_checkValues(req.query, controller.conditions.parameters.query, "query"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.body) {
parameters.push(_checkValues(req.body, controller.conditions.parameters.body, "body"))
}
if (controller.conditions && controller.conditions.parameters && controller.conditions.parameters.path) {
parameters.push(_checkValues(req.params, controller.conditions.parameters.path, "path"))
}
return Q.all(parameters).then(function (results) {
var validatedData = [];
var errors = [];
results.forEach(function (result) {
if (result.data) {
if (!validatedData[result.type]) {
validatedData[result.type] = {};
}
validatedData[result.type] = result.data;
}
// Collect validation errors
if (result.err && result.err.err && result.err.name == "ValidationError") {
var resultErrors = result.err.err;
resultErrors.forEach(function (error) {
error.in = result.type;
errors.push(error);
});
}
});
return Q({
validatedData: {
name: controller.name,
version: controller.version,
method: controller.method,
function: controller.function,
data: validatedData
},
errors: errors
});
});
} | [
"function",
"(",
"req",
",",
"controller",
")",
"{",
"var",
"parameters",
"=",
"[",
"]",
";",
"if",
"(",
"controller",
".",
"conditions",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
".",
"header",
")",
"{",
"parameters",
".",
"push",
"(",
"_checkValues",
"(",
"req",
".",
"headers",
",",
"controller",
".",
"conditions",
".",
"parameters",
".",
"header",
",",
"\"header\"",
")",
")",
"}",
"if",
"(",
"controller",
".",
"conditions",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
".",
"query",
")",
"{",
"parameters",
".",
"push",
"(",
"_checkValues",
"(",
"req",
".",
"query",
",",
"controller",
".",
"conditions",
".",
"parameters",
".",
"query",
",",
"\"query\"",
")",
")",
"}",
"if",
"(",
"controller",
".",
"conditions",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
".",
"body",
")",
"{",
"parameters",
".",
"push",
"(",
"_checkValues",
"(",
"req",
".",
"body",
",",
"controller",
".",
"conditions",
".",
"parameters",
".",
"body",
",",
"\"body\"",
")",
")",
"}",
"if",
"(",
"controller",
".",
"conditions",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
"&&",
"controller",
".",
"conditions",
".",
"parameters",
".",
"path",
")",
"{",
"parameters",
".",
"push",
"(",
"_checkValues",
"(",
"req",
".",
"params",
",",
"controller",
".",
"conditions",
".",
"parameters",
".",
"path",
",",
"\"path\"",
")",
")",
"}",
"return",
"Q",
".",
"all",
"(",
"parameters",
")",
".",
"then",
"(",
"function",
"(",
"results",
")",
"{",
"var",
"validatedData",
"=",
"[",
"]",
";",
"var",
"errors",
"=",
"[",
"]",
";",
"results",
".",
"forEach",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"result",
".",
"data",
")",
"{",
"if",
"(",
"!",
"validatedData",
"[",
"result",
".",
"type",
"]",
")",
"{",
"validatedData",
"[",
"result",
".",
"type",
"]",
"=",
"{",
"}",
";",
"}",
"validatedData",
"[",
"result",
".",
"type",
"]",
"=",
"result",
".",
"data",
";",
"}",
"if",
"(",
"result",
".",
"err",
"&&",
"result",
".",
"err",
".",
"err",
"&&",
"result",
".",
"err",
".",
"name",
"==",
"\"ValidationError\"",
")",
"{",
"var",
"resultErrors",
"=",
"result",
".",
"err",
".",
"err",
";",
"resultErrors",
".",
"forEach",
"(",
"function",
"(",
"error",
")",
"{",
"error",
".",
"in",
"=",
"result",
".",
"type",
";",
"errors",
".",
"push",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"Q",
"(",
"{",
"validatedData",
":",
"{",
"name",
":",
"controller",
".",
"name",
",",
"version",
":",
"controller",
".",
"version",
",",
"method",
":",
"controller",
".",
"method",
",",
"function",
":",
"controller",
".",
"function",
",",
"data",
":",
"validatedData",
"}",
",",
"errors",
":",
"errors",
"}",
")",
";",
"}",
")",
";",
"}"
] | Parse parameter model of controller and validate all request parameters for header,query and body
@param req
@param controller
@returns {*}
@private | [
"Parse",
"parameter",
"model",
"of",
"controller",
"and",
"validate",
"all",
"request",
"parameters",
"for",
"header",
"query",
"and",
"body"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/preconditionsCheck.js#L99-L149 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/preconditionsCheck.js | function (req, res, next) {
var hostId = req.miajs.route.hostId;
var url = req.miajs.route.url;
var prefix = req.miajs.route.prefix;
var method = req.miajs.route.method;
var group = req.miajs.route.group;
var version = req.miajs.route.version;
var registeredServices = Shared.registeredServices();
var errors = [];
var routeFound = false;
req.miajs = req.miajs || {};
//console.log('checkPreconditions: url: ' + url + ', method: ' + method + ', body: ' + JSON.stringify(req.body));
for (var index in registeredServices) {
if (registeredServices[index].group == group
&& registeredServices[index].hostId == hostId
&& registeredServices[index].version == version
&& registeredServices[index].prefix == prefix
&& registeredServices[index].method == method
&& registeredServices[index].url == url
) {
routeFound = true;
if (registeredServices[index].preconditions) {
var service = registeredServices[index];
var preconditionsList = service.preconditions;
var qfunctions = [];
for (var cIndex in preconditionsList) {
qfunctions.push(_checkControllerConditions(req, preconditionsList[cIndex]));
}
Q.all(qfunctions).then(function (results) {
req.miajs.commonValidatedParameters = [];
results.forEach(function (result) {
if (result) {
if (result.validatedData) {
req.miajs.commonValidatedParameters.push(result.validatedData);
}
var controllerErrors = result.errors;
controllerErrors.forEach(function (error) {
var inList = false;
// Check for error duplicates
for (var eIndex in errors) {
if (errors[eIndex].code == error.code && errors[eIndex].id == error.id && errors[eIndex].in == error.in) {
inList = true;
}
}
if (inList == false) {
errors.push(error);
}
});
}
});
}).then(function () {
if (!_.isEmpty(errors)) {
next({'status': 400, err: errors})
return;
}
else {
next();
return;
}
}).catch(function (err) {
next({'status': 400, err: err});
return;
});
}
else {
next();
return;
}
}
}
if (routeFound == false) {
Logger.error('Can not find controller file in preconditionsCheck to perform parameter validation. Request canceled due to security reasons');
next({status: 500});
return;
}
} | javascript | function (req, res, next) {
var hostId = req.miajs.route.hostId;
var url = req.miajs.route.url;
var prefix = req.miajs.route.prefix;
var method = req.miajs.route.method;
var group = req.miajs.route.group;
var version = req.miajs.route.version;
var registeredServices = Shared.registeredServices();
var errors = [];
var routeFound = false;
req.miajs = req.miajs || {};
//console.log('checkPreconditions: url: ' + url + ', method: ' + method + ', body: ' + JSON.stringify(req.body));
for (var index in registeredServices) {
if (registeredServices[index].group == group
&& registeredServices[index].hostId == hostId
&& registeredServices[index].version == version
&& registeredServices[index].prefix == prefix
&& registeredServices[index].method == method
&& registeredServices[index].url == url
) {
routeFound = true;
if (registeredServices[index].preconditions) {
var service = registeredServices[index];
var preconditionsList = service.preconditions;
var qfunctions = [];
for (var cIndex in preconditionsList) {
qfunctions.push(_checkControllerConditions(req, preconditionsList[cIndex]));
}
Q.all(qfunctions).then(function (results) {
req.miajs.commonValidatedParameters = [];
results.forEach(function (result) {
if (result) {
if (result.validatedData) {
req.miajs.commonValidatedParameters.push(result.validatedData);
}
var controllerErrors = result.errors;
controllerErrors.forEach(function (error) {
var inList = false;
// Check for error duplicates
for (var eIndex in errors) {
if (errors[eIndex].code == error.code && errors[eIndex].id == error.id && errors[eIndex].in == error.in) {
inList = true;
}
}
if (inList == false) {
errors.push(error);
}
});
}
});
}).then(function () {
if (!_.isEmpty(errors)) {
next({'status': 400, err: errors})
return;
}
else {
next();
return;
}
}).catch(function (err) {
next({'status': 400, err: err});
return;
});
}
else {
next();
return;
}
}
}
if (routeFound == false) {
Logger.error('Can not find controller file in preconditionsCheck to perform parameter validation. Request canceled due to security reasons');
next({status: 500});
return;
}
} | [
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"hostId",
"=",
"req",
".",
"miajs",
".",
"route",
".",
"hostId",
";",
"var",
"url",
"=",
"req",
".",
"miajs",
".",
"route",
".",
"url",
";",
"var",
"prefix",
"=",
"req",
".",
"miajs",
".",
"route",
".",
"prefix",
";",
"var",
"method",
"=",
"req",
".",
"miajs",
".",
"route",
".",
"method",
";",
"var",
"group",
"=",
"req",
".",
"miajs",
".",
"route",
".",
"group",
";",
"var",
"version",
"=",
"req",
".",
"miajs",
".",
"route",
".",
"version",
";",
"var",
"registeredServices",
"=",
"Shared",
".",
"registeredServices",
"(",
")",
";",
"var",
"errors",
"=",
"[",
"]",
";",
"var",
"routeFound",
"=",
"false",
";",
"req",
".",
"miajs",
"=",
"req",
".",
"miajs",
"||",
"{",
"}",
";",
"for",
"(",
"var",
"index",
"in",
"registeredServices",
")",
"{",
"if",
"(",
"registeredServices",
"[",
"index",
"]",
".",
"group",
"==",
"group",
"&&",
"registeredServices",
"[",
"index",
"]",
".",
"hostId",
"==",
"hostId",
"&&",
"registeredServices",
"[",
"index",
"]",
".",
"version",
"==",
"version",
"&&",
"registeredServices",
"[",
"index",
"]",
".",
"prefix",
"==",
"prefix",
"&&",
"registeredServices",
"[",
"index",
"]",
".",
"method",
"==",
"method",
"&&",
"registeredServices",
"[",
"index",
"]",
".",
"url",
"==",
"url",
")",
"{",
"routeFound",
"=",
"true",
";",
"if",
"(",
"registeredServices",
"[",
"index",
"]",
".",
"preconditions",
")",
"{",
"var",
"service",
"=",
"registeredServices",
"[",
"index",
"]",
";",
"var",
"preconditionsList",
"=",
"service",
".",
"preconditions",
";",
"var",
"qfunctions",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"cIndex",
"in",
"preconditionsList",
")",
"{",
"qfunctions",
".",
"push",
"(",
"_checkControllerConditions",
"(",
"req",
",",
"preconditionsList",
"[",
"cIndex",
"]",
")",
")",
";",
"}",
"Q",
".",
"all",
"(",
"qfunctions",
")",
".",
"then",
"(",
"function",
"(",
"results",
")",
"{",
"req",
".",
"miajs",
".",
"commonValidatedParameters",
"=",
"[",
"]",
";",
"results",
".",
"forEach",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"result",
")",
"{",
"if",
"(",
"result",
".",
"validatedData",
")",
"{",
"req",
".",
"miajs",
".",
"commonValidatedParameters",
".",
"push",
"(",
"result",
".",
"validatedData",
")",
";",
"}",
"var",
"controllerErrors",
"=",
"result",
".",
"errors",
";",
"controllerErrors",
".",
"forEach",
"(",
"function",
"(",
"error",
")",
"{",
"var",
"inList",
"=",
"false",
";",
"for",
"(",
"var",
"eIndex",
"in",
"errors",
")",
"{",
"if",
"(",
"errors",
"[",
"eIndex",
"]",
".",
"code",
"==",
"error",
".",
"code",
"&&",
"errors",
"[",
"eIndex",
"]",
".",
"id",
"==",
"error",
".",
"id",
"&&",
"errors",
"[",
"eIndex",
"]",
".",
"in",
"==",
"error",
".",
"in",
")",
"{",
"inList",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"inList",
"==",
"false",
")",
"{",
"errors",
".",
"push",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"errors",
")",
")",
"{",
"next",
"(",
"{",
"'status'",
":",
"400",
",",
"err",
":",
"errors",
"}",
")",
"return",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"return",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"next",
"(",
"{",
"'status'",
":",
"400",
",",
"err",
":",
"err",
"}",
")",
";",
"return",
";",
"}",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"return",
";",
"}",
"}",
"}",
"if",
"(",
"routeFound",
"==",
"false",
")",
"{",
"Logger",
".",
"error",
"(",
"'Can not find controller file in preconditionsCheck to perform parameter validation. Request canceled due to security reasons'",
")",
";",
"next",
"(",
"{",
"status",
":",
"500",
"}",
")",
";",
"return",
";",
"}",
"}"
] | Apply all preconditions defined in all controllers of this route.
Try to find preconditions in registeredServices matching url, prefix, method, group and version
@param req
@param res
@param next | [
"Apply",
"all",
"preconditions",
"defined",
"in",
"all",
"controllers",
"of",
"this",
"route",
".",
"Try",
"to",
"find",
"preconditions",
"in",
"registeredServices",
"matching",
"url",
"prefix",
"method",
"group",
"and",
"version"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/preconditionsCheck.js#L158-L245 | train |
|
mia-js/mia-js-core | lib/mia-js.js | function () {
Shared.initialize('/config', process.argv[2]);
Shared.setAppHttp(appHttp);
Shared.setAppHttps(appHttps);
Shared.setExpress(express);
// Init memcached
var memcached = Shared.memcached();
// Init redis cache
var redis = Shared.redis(true);
//Enable gzip compression
appHttp.use(compression());
appHttp.disable('x-powered-by');
appHttps.use(compression());
appHttps.disable('x-powered-by');
var env = Shared.config("environment");
var maxLag = env.maxLag;
if (maxLag) {
toobusy.maxLag(maxLag);
}
appHttp.use(function (req, res, next) {
if (maxLag && toobusy()) {
Logger.error("Server is busy, rejected request");
res.status(503).send("I'm busy right now, sorry.");
} else {
next();
}
});
appHttps.use(function (req, res, next) {
if (maxLag && toobusy()) {
Logger.error("Server is busy, rejected request");
res.status(503).send("I'm busy right now, sorry.");
} else {
next();
}
});
return Q();
} | javascript | function () {
Shared.initialize('/config', process.argv[2]);
Shared.setAppHttp(appHttp);
Shared.setAppHttps(appHttps);
Shared.setExpress(express);
// Init memcached
var memcached = Shared.memcached();
// Init redis cache
var redis = Shared.redis(true);
//Enable gzip compression
appHttp.use(compression());
appHttp.disable('x-powered-by');
appHttps.use(compression());
appHttps.disable('x-powered-by');
var env = Shared.config("environment");
var maxLag = env.maxLag;
if (maxLag) {
toobusy.maxLag(maxLag);
}
appHttp.use(function (req, res, next) {
if (maxLag && toobusy()) {
Logger.error("Server is busy, rejected request");
res.status(503).send("I'm busy right now, sorry.");
} else {
next();
}
});
appHttps.use(function (req, res, next) {
if (maxLag && toobusy()) {
Logger.error("Server is busy, rejected request");
res.status(503).send("I'm busy right now, sorry.");
} else {
next();
}
});
return Q();
} | [
"function",
"(",
")",
"{",
"Shared",
".",
"initialize",
"(",
"'/config'",
",",
"process",
".",
"argv",
"[",
"2",
"]",
")",
";",
"Shared",
".",
"setAppHttp",
"(",
"appHttp",
")",
";",
"Shared",
".",
"setAppHttps",
"(",
"appHttps",
")",
";",
"Shared",
".",
"setExpress",
"(",
"express",
")",
";",
"var",
"memcached",
"=",
"Shared",
".",
"memcached",
"(",
")",
";",
"var",
"redis",
"=",
"Shared",
".",
"redis",
"(",
"true",
")",
";",
"appHttp",
".",
"use",
"(",
"compression",
"(",
")",
")",
";",
"appHttp",
".",
"disable",
"(",
"'x-powered-by'",
")",
";",
"appHttps",
".",
"use",
"(",
"compression",
"(",
")",
")",
";",
"appHttps",
".",
"disable",
"(",
"'x-powered-by'",
")",
";",
"var",
"env",
"=",
"Shared",
".",
"config",
"(",
"\"environment\"",
")",
";",
"var",
"maxLag",
"=",
"env",
".",
"maxLag",
";",
"if",
"(",
"maxLag",
")",
"{",
"toobusy",
".",
"maxLag",
"(",
"maxLag",
")",
";",
"}",
"appHttp",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"maxLag",
"&&",
"toobusy",
"(",
")",
")",
"{",
"Logger",
".",
"error",
"(",
"\"Server is busy, rejected request\"",
")",
";",
"res",
".",
"status",
"(",
"503",
")",
".",
"send",
"(",
"\"I'm busy right now, sorry.\"",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"appHttps",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"maxLag",
"&&",
"toobusy",
"(",
")",
")",
"{",
"Logger",
".",
"error",
"(",
"\"Server is busy, rejected request\"",
")",
";",
"res",
".",
"status",
"(",
"503",
")",
".",
"send",
"(",
"\"I'm busy right now, sorry.\"",
")",
";",
"}",
"else",
"{",
"next",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"Q",
"(",
")",
";",
"}"
] | Set initialize functions
@returns {*}
@private | [
"Set",
"initialize",
"functions"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L52-L95 | train |
|
mia-js/mia-js-core | lib/mia-js.js | function (initFunction) {
if (_.isFunction(initFunction)) {
Logger.info("Run init function");
_customInitFuncton = initFunction;
return initFunction(appHttp)
.then(function () {
return initFunction(appHttps);
});
}
return Q();
} | javascript | function (initFunction) {
if (_.isFunction(initFunction)) {
Logger.info("Run init function");
_customInitFuncton = initFunction;
return initFunction(appHttp)
.then(function () {
return initFunction(appHttps);
});
}
return Q();
} | [
"function",
"(",
"initFunction",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"initFunction",
")",
")",
"{",
"Logger",
".",
"info",
"(",
"\"Run init function\"",
")",
";",
"_customInitFuncton",
"=",
"initFunction",
";",
"return",
"initFunction",
"(",
"appHttp",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"initFunction",
"(",
"appHttps",
")",
";",
"}",
")",
";",
"}",
"return",
"Q",
"(",
")",
";",
"}"
] | Call and set custom init function to global
@param initFunction
@returns {*}
@private | [
"Call",
"and",
"set",
"custom",
"init",
"function",
"to",
"global"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L110-L120 | train |
|
mia-js/mia-js-core | lib/mia-js.js | function () {
//set logger
if (!module.parent) {
appHttp.use(morgan({format: 'dev'}));
appHttps.use(morgan({format: 'dev'}));
}
return Q();
} | javascript | function () {
//set logger
if (!module.parent) {
appHttp.use(morgan({format: 'dev'}));
appHttps.use(morgan({format: 'dev'}));
}
return Q();
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"module",
".",
"parent",
")",
"{",
"appHttp",
".",
"use",
"(",
"morgan",
"(",
"{",
"format",
":",
"'dev'",
"}",
")",
")",
";",
"appHttps",
".",
"use",
"(",
"morgan",
"(",
"{",
"format",
":",
"'dev'",
"}",
")",
")",
";",
"}",
"return",
"Q",
"(",
")",
";",
"}"
] | Set morgan logger
@returns {*}
@private | [
"Set",
"morgan",
"logger"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L174-L181 | train |
|
mia-js/mia-js-core | lib/mia-js.js | function (host, reInit) {
if (_.isEmpty(host.id) || !_.isString(host.id)) {
throw new Error("Host configuration is invalid. Host id is missing or not a string");
}
if (_.isEmpty(host.host)) {
throw new Error("Host configuration is invalid. Host is missing");
}
if (_.isString(host.host)) {
host.host = [host.host];
}
if (!_.isArray(host.host)) {
throw new Error("Host configuration is invalid. Host should be array or string");
}
var router = new express.Router();
if (reInit === false) {
// Check if host is already defined. Use same router instance to merge routes
for (var index in _vhosts) {
for (var vh in _vhosts[index]["host"]) {
if (_vhosts[index]["host"][vh] == host.host) {
router = _vhosts[index]["router"];
}
}
}
}
_vhosts[host.id] = {
host: host.host,
router: router,
http: !host.listener ? true : host.listener && host.listener.http || null,
https: !host.listener ? true : host.listener && host.listener.https || null
};
_applyRouterConfig(_vhosts[host.id]["router"]);
_customInitFuncton(_vhosts[host.id]["router"]);
} | javascript | function (host, reInit) {
if (_.isEmpty(host.id) || !_.isString(host.id)) {
throw new Error("Host configuration is invalid. Host id is missing or not a string");
}
if (_.isEmpty(host.host)) {
throw new Error("Host configuration is invalid. Host is missing");
}
if (_.isString(host.host)) {
host.host = [host.host];
}
if (!_.isArray(host.host)) {
throw new Error("Host configuration is invalid. Host should be array or string");
}
var router = new express.Router();
if (reInit === false) {
// Check if host is already defined. Use same router instance to merge routes
for (var index in _vhosts) {
for (var vh in _vhosts[index]["host"]) {
if (_vhosts[index]["host"][vh] == host.host) {
router = _vhosts[index]["router"];
}
}
}
}
_vhosts[host.id] = {
host: host.host,
router: router,
http: !host.listener ? true : host.listener && host.listener.http || null,
https: !host.listener ? true : host.listener && host.listener.https || null
};
_applyRouterConfig(_vhosts[host.id]["router"]);
_customInitFuncton(_vhosts[host.id]["router"]);
} | [
"function",
"(",
"host",
",",
"reInit",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"host",
".",
"id",
")",
"||",
"!",
"_",
".",
"isString",
"(",
"host",
".",
"id",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Host configuration is invalid. Host id is missing or not a string\"",
")",
";",
"}",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"host",
".",
"host",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Host configuration is invalid. Host is missing\"",
")",
";",
"}",
"if",
"(",
"_",
".",
"isString",
"(",
"host",
".",
"host",
")",
")",
"{",
"host",
".",
"host",
"=",
"[",
"host",
".",
"host",
"]",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"host",
".",
"host",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Host configuration is invalid. Host should be array or string\"",
")",
";",
"}",
"var",
"router",
"=",
"new",
"express",
".",
"Router",
"(",
")",
";",
"if",
"(",
"reInit",
"===",
"false",
")",
"{",
"for",
"(",
"var",
"index",
"in",
"_vhosts",
")",
"{",
"for",
"(",
"var",
"vh",
"in",
"_vhosts",
"[",
"index",
"]",
"[",
"\"host\"",
"]",
")",
"{",
"if",
"(",
"_vhosts",
"[",
"index",
"]",
"[",
"\"host\"",
"]",
"[",
"vh",
"]",
"==",
"host",
".",
"host",
")",
"{",
"router",
"=",
"_vhosts",
"[",
"index",
"]",
"[",
"\"router\"",
"]",
";",
"}",
"}",
"}",
"}",
"_vhosts",
"[",
"host",
".",
"id",
"]",
"=",
"{",
"host",
":",
"host",
".",
"host",
",",
"router",
":",
"router",
",",
"http",
":",
"!",
"host",
".",
"listener",
"?",
"true",
":",
"host",
".",
"listener",
"&&",
"host",
".",
"listener",
".",
"http",
"||",
"null",
",",
"https",
":",
"!",
"host",
".",
"listener",
"?",
"true",
":",
"host",
".",
"listener",
"&&",
"host",
".",
"listener",
".",
"https",
"||",
"null",
"}",
";",
"_applyRouterConfig",
"(",
"_vhosts",
"[",
"host",
".",
"id",
"]",
"[",
"\"router\"",
"]",
")",
";",
"_customInitFuncton",
"(",
"_vhosts",
"[",
"host",
".",
"id",
"]",
"[",
"\"router\"",
"]",
")",
";",
"}"
] | Parse virtual host definition from mia.js global environment configuration
@param {Object} host
@param {Boolean} reInit
@private | [
"Parse",
"virtual",
"host",
"definition",
"from",
"mia",
".",
"js",
"global",
"environment",
"configuration"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L189-L227 | train |
|
mia-js/mia-js-core | lib/mia-js.js | function (reInit = false) {
//load routes
var environment = Shared.config("environment");
var hosts = environment.hosts;
if (hosts) {
if (!_.isArray(hosts)) {
hosts = [hosts];
}
for (var host in hosts) {
_parseHosts(hosts[host], reInit);
}
}
_vhosts["*"] = {
host: '*',
router: new express.Router()
};
_applyRouterConfig(_vhosts["*"]["router"]);
_customInitFuncton(_vhosts["*"]["router"]);
return RoutesHandler.initializeRoutes(_vhosts, reInit === false);
} | javascript | function (reInit = false) {
//load routes
var environment = Shared.config("environment");
var hosts = environment.hosts;
if (hosts) {
if (!_.isArray(hosts)) {
hosts = [hosts];
}
for (var host in hosts) {
_parseHosts(hosts[host], reInit);
}
}
_vhosts["*"] = {
host: '*',
router: new express.Router()
};
_applyRouterConfig(_vhosts["*"]["router"]);
_customInitFuncton(_vhosts["*"]["router"]);
return RoutesHandler.initializeRoutes(_vhosts, reInit === false);
} | [
"function",
"(",
"reInit",
"=",
"false",
")",
"{",
"var",
"environment",
"=",
"Shared",
".",
"config",
"(",
"\"environment\"",
")",
";",
"var",
"hosts",
"=",
"environment",
".",
"hosts",
";",
"if",
"(",
"hosts",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"hosts",
")",
")",
"{",
"hosts",
"=",
"[",
"hosts",
"]",
";",
"}",
"for",
"(",
"var",
"host",
"in",
"hosts",
")",
"{",
"_parseHosts",
"(",
"hosts",
"[",
"host",
"]",
",",
"reInit",
")",
";",
"}",
"}",
"_vhosts",
"[",
"\"*\"",
"]",
"=",
"{",
"host",
":",
"'*'",
",",
"router",
":",
"new",
"express",
".",
"Router",
"(",
")",
"}",
";",
"_applyRouterConfig",
"(",
"_vhosts",
"[",
"\"*\"",
"]",
"[",
"\"router\"",
"]",
")",
";",
"_customInitFuncton",
"(",
"_vhosts",
"[",
"\"*\"",
"]",
"[",
"\"router\"",
"]",
")",
";",
"return",
"RoutesHandler",
".",
"initializeRoutes",
"(",
"_vhosts",
",",
"reInit",
"===",
"false",
")",
";",
"}"
] | Register all routes defined in routes definition of projects and apply to virtual hosts
@param {Boolean} reInit
@returns {*}
@private | [
"Register",
"all",
"routes",
"defined",
"in",
"routes",
"definition",
"of",
"projects",
"and",
"apply",
"to",
"virtual",
"hosts"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L245-L266 | train |
|
mia-js/mia-js-core | lib/mia-js.js | function () {
const cronJobsToStart = _getNamesOfCronJobsToStart();
if (!cronJobsToStart && _shouldStartCrons() && Shared.isDbConnectionAvailable() === true) {
return CronJobManagerJob.startListening().then(function () {
Logger.tag('Cron').info('Cron Job Manager is started. Starting all available cron jobs');
return Q();
}, function (err) {
Logger.tag('Cron').error('Error starting Cron Job Manager ');
return Q.reject(err);
});
} else if (cronJobsToStart && _shouldStartCrons()) {
Logger.tag('Cron').info('Starting specific cron jobs "' + cronJobsToStart.join(', ') + '"');
try {
const cronJobs = Shared.cronModules(cronJobsToStart);
let promises = [];
for (let cron of cronJobs) {
// Set force run config
cron.forceRun = true;
promises.push(cron.worker(cron, cron));
}
return Q.all(promises)
.then(() => process.exit())
.catch(() => process.exit(1));
} catch (err) {
process.exit(1);
}
} else {
Logger.tag('Cron').warn('Cron Manager is disabled for this environment.');
return Q();
}
} | javascript | function () {
const cronJobsToStart = _getNamesOfCronJobsToStart();
if (!cronJobsToStart && _shouldStartCrons() && Shared.isDbConnectionAvailable() === true) {
return CronJobManagerJob.startListening().then(function () {
Logger.tag('Cron').info('Cron Job Manager is started. Starting all available cron jobs');
return Q();
}, function (err) {
Logger.tag('Cron').error('Error starting Cron Job Manager ');
return Q.reject(err);
});
} else if (cronJobsToStart && _shouldStartCrons()) {
Logger.tag('Cron').info('Starting specific cron jobs "' + cronJobsToStart.join(', ') + '"');
try {
const cronJobs = Shared.cronModules(cronJobsToStart);
let promises = [];
for (let cron of cronJobs) {
// Set force run config
cron.forceRun = true;
promises.push(cron.worker(cron, cron));
}
return Q.all(promises)
.then(() => process.exit())
.catch(() => process.exit(1));
} catch (err) {
process.exit(1);
}
} else {
Logger.tag('Cron').warn('Cron Manager is disabled for this environment.');
return Q();
}
} | [
"function",
"(",
")",
"{",
"const",
"cronJobsToStart",
"=",
"_getNamesOfCronJobsToStart",
"(",
")",
";",
"if",
"(",
"!",
"cronJobsToStart",
"&&",
"_shouldStartCrons",
"(",
")",
"&&",
"Shared",
".",
"isDbConnectionAvailable",
"(",
")",
"===",
"true",
")",
"{",
"return",
"CronJobManagerJob",
".",
"startListening",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"Logger",
".",
"tag",
"(",
"'Cron'",
")",
".",
"info",
"(",
"'Cron Job Manager is started. Starting all available cron jobs'",
")",
";",
"return",
"Q",
"(",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"Logger",
".",
"tag",
"(",
"'Cron'",
")",
".",
"error",
"(",
"'Error starting Cron Job Manager '",
")",
";",
"return",
"Q",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"cronJobsToStart",
"&&",
"_shouldStartCrons",
"(",
")",
")",
"{",
"Logger",
".",
"tag",
"(",
"'Cron'",
")",
".",
"info",
"(",
"'Starting specific cron jobs \"'",
"+",
"cronJobsToStart",
".",
"join",
"(",
"', '",
")",
"+",
"'\"'",
")",
";",
"try",
"{",
"const",
"cronJobs",
"=",
"Shared",
".",
"cronModules",
"(",
"cronJobsToStart",
")",
";",
"let",
"promises",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"cron",
"of",
"cronJobs",
")",
"{",
"cron",
".",
"forceRun",
"=",
"true",
";",
"promises",
".",
"push",
"(",
"cron",
".",
"worker",
"(",
"cron",
",",
"cron",
")",
")",
";",
"}",
"return",
"Q",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"(",
")",
"=>",
"process",
".",
"exit",
"(",
")",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"process",
".",
"exit",
"(",
"1",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}",
"else",
"{",
"Logger",
".",
"tag",
"(",
"'Cron'",
")",
".",
"warn",
"(",
"'Cron Manager is disabled for this environment.'",
")",
";",
"return",
"Q",
"(",
")",
";",
"}",
"}"
] | Start cron manager
@returns {*}
@private | [
"Start",
"cron",
"manager"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L284-L316 | train |
|
mia-js/mia-js-core | lib/mia-js.js | function () {
const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons');
if (crons) {
const cronTasks = crons.replace(/\s/g, '').split(',');
return cronTasks.length > 0 ? cronTasks : undefined;
}
return undefined;
} | javascript | function () {
const crons = _.get(Shared, 'runtimeArgs.cron') || _.get(Shared, 'runtimeArgs.crons');
if (crons) {
const cronTasks = crons.replace(/\s/g, '').split(',');
return cronTasks.length > 0 ? cronTasks : undefined;
}
return undefined;
} | [
"function",
"(",
")",
"{",
"const",
"crons",
"=",
"_",
".",
"get",
"(",
"Shared",
",",
"'runtimeArgs.cron'",
")",
"||",
"_",
".",
"get",
"(",
"Shared",
",",
"'runtimeArgs.crons'",
")",
";",
"if",
"(",
"crons",
")",
"{",
"const",
"cronTasks",
"=",
"crons",
".",
"replace",
"(",
"/",
"\\s",
"/",
"g",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
";",
"return",
"cronTasks",
".",
"length",
">",
"0",
"?",
"cronTasks",
":",
"undefined",
";",
"}",
"return",
"undefined",
";",
"}"
] | Checks process arguments if specific cron jobs should be started immediately. That's the case if there is a third
argument like "cron=NameOfCronjobToStart,NameOfAnotherCronjobToStart"
@returns {Array} Names of cron jobs to start
@private | [
"Checks",
"process",
"arguments",
"if",
"specific",
"cron",
"jobs",
"should",
"be",
"started",
"immediately",
".",
"That",
"s",
"the",
"case",
"if",
"there",
"is",
"a",
"third",
"argument",
"like",
"cron",
"=",
"NameOfCronjobToStart",
"NameOfAnotherCronjobToStart"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/mia-js.js#L324-L331 | train |
|
rapid7/rism | lib/rism.js | setResponsive | function setResponsive(name) {
if (name) {
setResponsiveComponents.call(this, name);
} else {
_utils2["default"].forEach(Object.keys(this._component), (function (name) {
setResponsiveComponents.call(this, name);
}).bind(this));
}
if (_utils2["default"].isUndefined(name)) {
_utils2["default"].forEach(this._matchMedias._orders, (function (query) {
if (this._matchMedias[query].matches) {
_utils2["default"].forIn(this._responsiveStyles[query], (function (style, key) {
if (!this._styles[key]) {
this._styles[key] = {};
}
this[key] = _utils2["default"].merge(this._styles[key], (0, _reactPrefixer2["default"])(style));
}).bind(this));
}
}).bind(this));
}
} | javascript | function setResponsive(name) {
if (name) {
setResponsiveComponents.call(this, name);
} else {
_utils2["default"].forEach(Object.keys(this._component), (function (name) {
setResponsiveComponents.call(this, name);
}).bind(this));
}
if (_utils2["default"].isUndefined(name)) {
_utils2["default"].forEach(this._matchMedias._orders, (function (query) {
if (this._matchMedias[query].matches) {
_utils2["default"].forIn(this._responsiveStyles[query], (function (style, key) {
if (!this._styles[key]) {
this._styles[key] = {};
}
this[key] = _utils2["default"].merge(this._styles[key], (0, _reactPrefixer2["default"])(style));
}).bind(this));
}
}).bind(this));
}
} | [
"function",
"setResponsive",
"(",
"name",
")",
"{",
"if",
"(",
"name",
")",
"{",
"setResponsiveComponents",
".",
"call",
"(",
"this",
",",
"name",
")",
";",
"}",
"else",
"{",
"_utils2",
"[",
"\"default\"",
"]",
".",
"forEach",
"(",
"Object",
".",
"keys",
"(",
"this",
".",
"_component",
")",
",",
"(",
"function",
"(",
"name",
")",
"{",
"setResponsiveComponents",
".",
"call",
"(",
"this",
",",
"name",
")",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"_utils2",
"[",
"\"default\"",
"]",
".",
"isUndefined",
"(",
"name",
")",
")",
"{",
"_utils2",
"[",
"\"default\"",
"]",
".",
"forEach",
"(",
"this",
".",
"_matchMedias",
".",
"_orders",
",",
"(",
"function",
"(",
"query",
")",
"{",
"if",
"(",
"this",
".",
"_matchMedias",
"[",
"query",
"]",
".",
"matches",
")",
"{",
"_utils2",
"[",
"\"default\"",
"]",
".",
"forIn",
"(",
"this",
".",
"_responsiveStyles",
"[",
"query",
"]",
",",
"(",
"function",
"(",
"style",
",",
"key",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_styles",
"[",
"key",
"]",
")",
"{",
"this",
".",
"_styles",
"[",
"key",
"]",
"=",
"{",
"}",
";",
"}",
"this",
"[",
"key",
"]",
"=",
"_utils2",
"[",
"\"default\"",
"]",
".",
"merge",
"(",
"this",
".",
"_styles",
"[",
"key",
"]",
",",
"(",
"0",
",",
"_reactPrefixer2",
"[",
"\"default\"",
"]",
")",
"(",
"style",
")",
")",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"}"
] | set responsive values | [
"set",
"responsive",
"values"
] | cc1b8dd05175b0df375c0892edc4b1fefdf72b0f | https://github.com/rapid7/rism/blob/cc1b8dd05175b0df375c0892edc4b1fefdf72b0f/lib/rism.js#L154-L176 | train |
playmedia/http-cli | lib/config.js | loadDefault | function loadDefault() {
return {
port: 8000,
host: '127.0.0.1',
root: './',
logFormat: 'combined',
middlewares: [
{
name: 'cors',
cfg: {
origin: true
}
},
{
name: 'morgan',
cfg: {}
},
{
name: 'serveStatic',
cfg: {}
},
{
name: 'serveIndex',
cfg: {
icons: true
}
}
]
}
} | javascript | function loadDefault() {
return {
port: 8000,
host: '127.0.0.1',
root: './',
logFormat: 'combined',
middlewares: [
{
name: 'cors',
cfg: {
origin: true
}
},
{
name: 'morgan',
cfg: {}
},
{
name: 'serveStatic',
cfg: {}
},
{
name: 'serveIndex',
cfg: {
icons: true
}
}
]
}
} | [
"function",
"loadDefault",
"(",
")",
"{",
"return",
"{",
"port",
":",
"8000",
",",
"host",
":",
"'127.0.0.1'",
",",
"root",
":",
"'./'",
",",
"logFormat",
":",
"'combined'",
",",
"middlewares",
":",
"[",
"{",
"name",
":",
"'cors'",
",",
"cfg",
":",
"{",
"origin",
":",
"true",
"}",
"}",
",",
"{",
"name",
":",
"'morgan'",
",",
"cfg",
":",
"{",
"}",
"}",
",",
"{",
"name",
":",
"'serveStatic'",
",",
"cfg",
":",
"{",
"}",
"}",
",",
"{",
"name",
":",
"'serveIndex'",
",",
"cfg",
":",
"{",
"icons",
":",
"true",
"}",
"}",
"]",
"}",
"}"
] | Get default HTTP server configuration.
@return {Object} The HTTP server configuration. | [
"Get",
"default",
"HTTP",
"server",
"configuration",
"."
] | 81862084ef50cf9db6530b0da48cbe721355378f | https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L8-L37 | train |
playmedia/http-cli | lib/config.js | loadFromFile | function loadFromFile(filename) {
var cfg = {}
Object.assign(
cfg,
loadDefault(),
JSON.parse(fs.readFileSync(filename))
)
return cfg
} | javascript | function loadFromFile(filename) {
var cfg = {}
Object.assign(
cfg,
loadDefault(),
JSON.parse(fs.readFileSync(filename))
)
return cfg
} | [
"function",
"loadFromFile",
"(",
"filename",
")",
"{",
"var",
"cfg",
"=",
"{",
"}",
"Object",
".",
"assign",
"(",
"cfg",
",",
"loadDefault",
"(",
")",
",",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"filename",
")",
")",
")",
"return",
"cfg",
"}"
] | Get HTTP server configuration from JSON file.
@param {string} filename - The JSON filename.
@throws Will throw an error if invalid filename or JSON.
@return {Object} The HTTP server configuration. | [
"Get",
"HTTP",
"server",
"configuration",
"from",
"JSON",
"file",
"."
] | 81862084ef50cf9db6530b0da48cbe721355378f | https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L45-L54 | train |
playmedia/http-cli | lib/config.js | saveToFile | function saveToFile(filename, cfg) {
// Use 'wx' flag to fails if filename exists
fs.writeFileSync(filename, JSON.stringify(cfg, null, 2), {flag: 'wx'})
} | javascript | function saveToFile(filename, cfg) {
// Use 'wx' flag to fails if filename exists
fs.writeFileSync(filename, JSON.stringify(cfg, null, 2), {flag: 'wx'})
} | [
"function",
"saveToFile",
"(",
"filename",
",",
"cfg",
")",
"{",
"fs",
".",
"writeFileSync",
"(",
"filename",
",",
"JSON",
".",
"stringify",
"(",
"cfg",
",",
"null",
",",
"2",
")",
",",
"{",
"flag",
":",
"'wx'",
"}",
")",
"}"
] | Save HTTP server configuration to JSON file.
@param {string} filename - The JSON filename.
@param {Object} cfg - The HTTP server configuration.
@throws Will throw an error if filename exists. | [
"Save",
"HTTP",
"server",
"configuration",
"to",
"JSON",
"file",
"."
] | 81862084ef50cf9db6530b0da48cbe721355378f | https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L62-L65 | train |
playmedia/http-cli | lib/config.js | loadFromOptions | function loadFromOptions(opts) {
var defCfg = loadDefault()
var cfg = opts.config ? loadFromFile(opts.config) : loadDefault()
// Command line config override file loaded config
for (var k in opts) {
defCfg.hasOwnProperty(k) && (defCfg[k] !== opts[k] && (cfg[k] = opts[k]))
}
return cfg
} | javascript | function loadFromOptions(opts) {
var defCfg = loadDefault()
var cfg = opts.config ? loadFromFile(opts.config) : loadDefault()
// Command line config override file loaded config
for (var k in opts) {
defCfg.hasOwnProperty(k) && (defCfg[k] !== opts[k] && (cfg[k] = opts[k]))
}
return cfg
} | [
"function",
"loadFromOptions",
"(",
"opts",
")",
"{",
"var",
"defCfg",
"=",
"loadDefault",
"(",
")",
"var",
"cfg",
"=",
"opts",
".",
"config",
"?",
"loadFromFile",
"(",
"opts",
".",
"config",
")",
":",
"loadDefault",
"(",
")",
"for",
"(",
"var",
"k",
"in",
"opts",
")",
"{",
"defCfg",
".",
"hasOwnProperty",
"(",
"k",
")",
"&&",
"(",
"defCfg",
"[",
"k",
"]",
"!==",
"opts",
"[",
"k",
"]",
"&&",
"(",
"cfg",
"[",
"k",
"]",
"=",
"opts",
"[",
"k",
"]",
")",
")",
"}",
"return",
"cfg",
"}"
] | Get HTTP server configuration from command line options.
@param {Object} opts - The command line options.
@return {Object} The HTTP server configuration. | [
"Get",
"HTTP",
"server",
"configuration",
"from",
"command",
"line",
"options",
"."
] | 81862084ef50cf9db6530b0da48cbe721355378f | https://github.com/playmedia/http-cli/blob/81862084ef50cf9db6530b0da48cbe721355378f/lib/config.js#L72-L82 | train |
mia-js/mia-js-core | lib/moduleLoader/lib/requireAll.js | function (options, iterationInfo) {
var files;
var modules = {};
var result = {};
// remember the starting directory
try {
files = fs.readdirSync(iterationInfo.dirName);
} catch (e) {
if (options.optional)
return {};
else
throw new Error('Directory not found: ' + iterationInfo.dirName);
}
// iterate through files in the current directory
files.forEach(function (fileName) {
iterationInfo.dirName = iterationInfo.initialDirName + '/' + fileName + '/' + options.moduleDir;
iterationInfo.projectDir = iterationInfo.initialDirName + '/' + fileName;
result = _.assign(doInterations(options, iterationInfo), result);
});
return result;
} | javascript | function (options, iterationInfo) {
var files;
var modules = {};
var result = {};
// remember the starting directory
try {
files = fs.readdirSync(iterationInfo.dirName);
} catch (e) {
if (options.optional)
return {};
else
throw new Error('Directory not found: ' + iterationInfo.dirName);
}
// iterate through files in the current directory
files.forEach(function (fileName) {
iterationInfo.dirName = iterationInfo.initialDirName + '/' + fileName + '/' + options.moduleDir;
iterationInfo.projectDir = iterationInfo.initialDirName + '/' + fileName;
result = _.assign(doInterations(options, iterationInfo), result);
});
return result;
} | [
"function",
"(",
"options",
",",
"iterationInfo",
")",
"{",
"var",
"files",
";",
"var",
"modules",
"=",
"{",
"}",
";",
"var",
"result",
"=",
"{",
"}",
";",
"try",
"{",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"iterationInfo",
".",
"dirName",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"options",
".",
"optional",
")",
"return",
"{",
"}",
";",
"else",
"throw",
"new",
"Error",
"(",
"'Directory not found: '",
"+",
"iterationInfo",
".",
"dirName",
")",
";",
"}",
"files",
".",
"forEach",
"(",
"function",
"(",
"fileName",
")",
"{",
"iterationInfo",
".",
"dirName",
"=",
"iterationInfo",
".",
"initialDirName",
"+",
"'/'",
"+",
"fileName",
"+",
"'/'",
"+",
"options",
".",
"moduleDir",
";",
"iterationInfo",
".",
"projectDir",
"=",
"iterationInfo",
".",
"initialDirName",
"+",
"'/'",
"+",
"fileName",
";",
"result",
"=",
"_",
".",
"assign",
"(",
"doInterations",
"(",
"options",
",",
"iterationInfo",
")",
",",
"result",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Parses a directory and searches for options.module subdir. If found subdir is searched for required files
@param options
@param iterationInfo
@returns {{}} | [
"Parses",
"a",
"directory",
"and",
"searches",
"for",
"options",
".",
"module",
"subdir",
".",
"If",
"found",
"subdir",
"is",
"searched",
"for",
"required",
"files"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L100-L123 | train |
|
mia-js/mia-js-core | lib/moduleLoader/lib/requireAll.js | function (options, iterationInfo, modules) {
// filename filter
if (options.fileNameFilter) {
var match = iterationInfo.fileName.match(options.fileNameFilter);
if (!match) {
return;
}
}
// Filter spec.js files
var match = iterationInfo.fileName.match(/.spec.js/i);
if (match) {
return;
}
// relative path filter
if (options.relativePathFilter) {
var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter);
if (!pathMatch)
return;
}
//load module
loadModule(modules, options, iterationInfo);
} | javascript | function (options, iterationInfo, modules) {
// filename filter
if (options.fileNameFilter) {
var match = iterationInfo.fileName.match(options.fileNameFilter);
if (!match) {
return;
}
}
// Filter spec.js files
var match = iterationInfo.fileName.match(/.spec.js/i);
if (match) {
return;
}
// relative path filter
if (options.relativePathFilter) {
var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter);
if (!pathMatch)
return;
}
//load module
loadModule(modules, options, iterationInfo);
} | [
"function",
"(",
"options",
",",
"iterationInfo",
",",
"modules",
")",
"{",
"if",
"(",
"options",
".",
"fileNameFilter",
")",
"{",
"var",
"match",
"=",
"iterationInfo",
".",
"fileName",
".",
"match",
"(",
"options",
".",
"fileNameFilter",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
";",
"}",
"}",
"var",
"match",
"=",
"iterationInfo",
".",
"fileName",
".",
"match",
"(",
"/",
".spec.js",
"/",
"i",
")",
";",
"if",
"(",
"match",
")",
"{",
"return",
";",
"}",
"if",
"(",
"options",
".",
"relativePathFilter",
")",
"{",
"var",
"pathMatch",
"=",
"iterationInfo",
".",
"relativeFullPath",
".",
"match",
"(",
"options",
".",
"relativePathFilter",
")",
";",
"if",
"(",
"!",
"pathMatch",
")",
"return",
";",
"}",
"loadModule",
"(",
"modules",
",",
"options",
",",
"iterationInfo",
")",
";",
"}"
] | Process single file to module dictionary
@param options
@param fileName
@param modules | [
"Process",
"single",
"file",
"to",
"module",
"dictionary"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L181-L205 | train |
|
mia-js/mia-js-core | lib/moduleLoader/lib/requireAll.js | function (modules, options, iterationInfo) {
// load module into memory (unless `dontLoad` is true)
var module = true;
//default is options.dontLoad === false
if (options.dontLoad !== true) {
//if module is to be loaded
module = require(iterationInfo.absoluteFullPath);
// If a module is found but was loaded as 'undefined', don't include it (since it's probably unusable)
if (typeof module === 'undefined') {
throw new Error('Invalid module:' + iterationInfo.absoluteFullPath);
}
var identity;
//var name;
var version;
if (options.useVersions === true) {
if (module.version) {
version = module.version;
}
else {
version = '1.0';
}
}
if (module.identity) {
identity = module.identity;
//name = identity;
}
else {
identity = generateIdentity(options, iterationInfo);
//name = identity;
}
//consider default options.injectIdentity === true
if (options.injectIdentity !== false) {
module.fileName = iterationInfo.fileName;
module.projectDir = iterationInfo.projectDir;
module.relativePath = iterationInfo.relativePath;
module.relativeFullPath = iterationInfo.relativeFullPath;
module.absolutePath = iterationInfo.absolutePath;
module.absoluteFullPath = iterationInfo.absoluteFullPath;
module.identity = identity;
//module.name = name;
if (options.useVersions === true) {
module.version = version;
}
}
else {
identity = generateIdentity(options, iterationInfo);
}
//check if identity is unique within the collection and add to dictionary
if (options.useVersions === true) {
if (modules[identity] && modules[identity][version]) {
var anotherModule = modules[identity][version];
throw new Error("Identity '" + identity + "' with version '" + version + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
}
modules[identity] = modules[identity] || {};
modules[identity][version] = module;
}
else {
var anotherModule = modules[identity];
if (anotherModule) {
throw new Error("Identity '" + identity + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
}
modules[identity] = module;
}
}
} | javascript | function (modules, options, iterationInfo) {
// load module into memory (unless `dontLoad` is true)
var module = true;
//default is options.dontLoad === false
if (options.dontLoad !== true) {
//if module is to be loaded
module = require(iterationInfo.absoluteFullPath);
// If a module is found but was loaded as 'undefined', don't include it (since it's probably unusable)
if (typeof module === 'undefined') {
throw new Error('Invalid module:' + iterationInfo.absoluteFullPath);
}
var identity;
//var name;
var version;
if (options.useVersions === true) {
if (module.version) {
version = module.version;
}
else {
version = '1.0';
}
}
if (module.identity) {
identity = module.identity;
//name = identity;
}
else {
identity = generateIdentity(options, iterationInfo);
//name = identity;
}
//consider default options.injectIdentity === true
if (options.injectIdentity !== false) {
module.fileName = iterationInfo.fileName;
module.projectDir = iterationInfo.projectDir;
module.relativePath = iterationInfo.relativePath;
module.relativeFullPath = iterationInfo.relativeFullPath;
module.absolutePath = iterationInfo.absolutePath;
module.absoluteFullPath = iterationInfo.absoluteFullPath;
module.identity = identity;
//module.name = name;
if (options.useVersions === true) {
module.version = version;
}
}
else {
identity = generateIdentity(options, iterationInfo);
}
//check if identity is unique within the collection and add to dictionary
if (options.useVersions === true) {
if (modules[identity] && modules[identity][version]) {
var anotherModule = modules[identity][version];
throw new Error("Identity '" + identity + "' with version '" + version + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
}
modules[identity] = modules[identity] || {};
modules[identity][version] = module;
}
else {
var anotherModule = modules[identity];
if (anotherModule) {
throw new Error("Identity '" + identity + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
}
modules[identity] = module;
}
}
} | [
"function",
"(",
"modules",
",",
"options",
",",
"iterationInfo",
")",
"{",
"var",
"module",
"=",
"true",
";",
"if",
"(",
"options",
".",
"dontLoad",
"!==",
"true",
")",
"{",
"module",
"=",
"require",
"(",
"iterationInfo",
".",
"absoluteFullPath",
")",
";",
"if",
"(",
"typeof",
"module",
"===",
"'undefined'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid module:'",
"+",
"iterationInfo",
".",
"absoluteFullPath",
")",
";",
"}",
"var",
"identity",
";",
"var",
"version",
";",
"if",
"(",
"options",
".",
"useVersions",
"===",
"true",
")",
"{",
"if",
"(",
"module",
".",
"version",
")",
"{",
"version",
"=",
"module",
".",
"version",
";",
"}",
"else",
"{",
"version",
"=",
"'1.0'",
";",
"}",
"}",
"if",
"(",
"module",
".",
"identity",
")",
"{",
"identity",
"=",
"module",
".",
"identity",
";",
"}",
"else",
"{",
"identity",
"=",
"generateIdentity",
"(",
"options",
",",
"iterationInfo",
")",
";",
"}",
"if",
"(",
"options",
".",
"injectIdentity",
"!==",
"false",
")",
"{",
"module",
".",
"fileName",
"=",
"iterationInfo",
".",
"fileName",
";",
"module",
".",
"projectDir",
"=",
"iterationInfo",
".",
"projectDir",
";",
"module",
".",
"relativePath",
"=",
"iterationInfo",
".",
"relativePath",
";",
"module",
".",
"relativeFullPath",
"=",
"iterationInfo",
".",
"relativeFullPath",
";",
"module",
".",
"absolutePath",
"=",
"iterationInfo",
".",
"absolutePath",
";",
"module",
".",
"absoluteFullPath",
"=",
"iterationInfo",
".",
"absoluteFullPath",
";",
"module",
".",
"identity",
"=",
"identity",
";",
"if",
"(",
"options",
".",
"useVersions",
"===",
"true",
")",
"{",
"module",
".",
"version",
"=",
"version",
";",
"}",
"}",
"else",
"{",
"identity",
"=",
"generateIdentity",
"(",
"options",
",",
"iterationInfo",
")",
";",
"}",
"if",
"(",
"options",
".",
"useVersions",
"===",
"true",
")",
"{",
"if",
"(",
"modules",
"[",
"identity",
"]",
"&&",
"modules",
"[",
"identity",
"]",
"[",
"version",
"]",
")",
"{",
"var",
"anotherModule",
"=",
"modules",
"[",
"identity",
"]",
"[",
"version",
"]",
";",
"throw",
"new",
"Error",
"(",
"\"Identity '\"",
"+",
"identity",
"+",
"\"' with version '\"",
"+",
"version",
"+",
"\"' is already registered by module at '\"",
"+",
"anotherModule",
".",
"absoluteFullPath",
"+",
"\"'\"",
")",
";",
"}",
"modules",
"[",
"identity",
"]",
"=",
"modules",
"[",
"identity",
"]",
"||",
"{",
"}",
";",
"modules",
"[",
"identity",
"]",
"[",
"version",
"]",
"=",
"module",
";",
"}",
"else",
"{",
"var",
"anotherModule",
"=",
"modules",
"[",
"identity",
"]",
";",
"if",
"(",
"anotherModule",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Identity '\"",
"+",
"identity",
"+",
"\"' is already registered by module at '\"",
"+",
"anotherModule",
".",
"absoluteFullPath",
"+",
"\"'\"",
")",
";",
"}",
"modules",
"[",
"identity",
"]",
"=",
"module",
";",
"}",
"}",
"}"
] | Load single module
@param modules
@param options
@param iterationInfo | [
"Load",
"single",
"module"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L213-L285 | train |
|
mia-js/mia-js-core | lib/moduleLoader/lib/requireAll.js | function (options, iterationInfo) {
// Use the identity for the key name
var identity;
if (options.mode === 'list') {
identity = iterationInfo.relativeFullPath;
//identity = identity.toLowerCase();
//find and replace all containments of '/', ':' and '\' within the string
identity = identity.replace(/\/|\\|:/g, '');
}
else if (options.mode === 'tree') {
identity = iterationInfo.fileName;
//identity = identity.toLowerCase();
}
else
throw new Error('Unknown mode');
//remove extention
identity = identity.substr(0, identity.lastIndexOf('.')) || identity;
return identity;
} | javascript | function (options, iterationInfo) {
// Use the identity for the key name
var identity;
if (options.mode === 'list') {
identity = iterationInfo.relativeFullPath;
//identity = identity.toLowerCase();
//find and replace all containments of '/', ':' and '\' within the string
identity = identity.replace(/\/|\\|:/g, '');
}
else if (options.mode === 'tree') {
identity = iterationInfo.fileName;
//identity = identity.toLowerCase();
}
else
throw new Error('Unknown mode');
//remove extention
identity = identity.substr(0, identity.lastIndexOf('.')) || identity;
return identity;
} | [
"function",
"(",
"options",
",",
"iterationInfo",
")",
"{",
"var",
"identity",
";",
"if",
"(",
"options",
".",
"mode",
"===",
"'list'",
")",
"{",
"identity",
"=",
"iterationInfo",
".",
"relativeFullPath",
";",
"identity",
"=",
"identity",
".",
"replace",
"(",
"/",
"\\/|\\\\|:",
"/",
"g",
",",
"''",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"mode",
"===",
"'tree'",
")",
"{",
"identity",
"=",
"iterationInfo",
".",
"fileName",
";",
"}",
"else",
"throw",
"new",
"Error",
"(",
"'Unknown mode'",
")",
";",
"identity",
"=",
"identity",
".",
"substr",
"(",
"0",
",",
"identity",
".",
"lastIndexOf",
"(",
"'.'",
")",
")",
"||",
"identity",
";",
"return",
"identity",
";",
"}"
] | Generates identity for a module
@param options
@param iterationInfo
@returns {string} | [
"Generates",
"identity",
"for",
"a",
"module"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L293-L313 | train |
|
mia-js/mia-js-core | lib/moduleLoader/lib/requireAll.js | function (options, iterationInfo, modules) {
// Ignore explicitly excluded directories
if (options.excludeDirs) {
var match = iterationInfo.fileName.match(options.excludeDirs);
if (match)
return;
}
// Recursively call requireAll on each child directory
var subIterationInfo = _.clone(iterationInfo);
++subIterationInfo.depth;
subIterationInfo.dirName = iterationInfo.absoluteFullPath;
//process subtree recursively
var subTreeResult = doInterations(options, subIterationInfo);
//omit empty dirs
if (_.isEmpty(subTreeResult))
return;
//add to the list or to the subtree
if (options.mode === 'list') {
//check uniqueness
_.forEach(subTreeResult, function (value, index) {
if (options.useVersions === true) {
modules[index] = modules[index] || {};
_.forEach(value, function (versionValue, versionIndex) {
if (modules[index][versionIndex])
throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'");
modules[index][versionIndex] = versionValue;
});
}
else {
if (modules[index])
throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'");
modules[index] = value;
}
})
}
else if (options.mode === 'tree') {
if (options.markDirectories !== false) {
subTreeResult.isDirectory = true;
}
var identity = generateIdentity(options, iterationInfo);
modules[identity] = subTreeResult;
}
else
throw new Error('Unknown mode');
} | javascript | function (options, iterationInfo, modules) {
// Ignore explicitly excluded directories
if (options.excludeDirs) {
var match = iterationInfo.fileName.match(options.excludeDirs);
if (match)
return;
}
// Recursively call requireAll on each child directory
var subIterationInfo = _.clone(iterationInfo);
++subIterationInfo.depth;
subIterationInfo.dirName = iterationInfo.absoluteFullPath;
//process subtree recursively
var subTreeResult = doInterations(options, subIterationInfo);
//omit empty dirs
if (_.isEmpty(subTreeResult))
return;
//add to the list or to the subtree
if (options.mode === 'list') {
//check uniqueness
_.forEach(subTreeResult, function (value, index) {
if (options.useVersions === true) {
modules[index] = modules[index] || {};
_.forEach(value, function (versionValue, versionIndex) {
if (modules[index][versionIndex])
throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'");
modules[index][versionIndex] = versionValue;
});
}
else {
if (modules[index])
throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'");
modules[index] = value;
}
})
}
else if (options.mode === 'tree') {
if (options.markDirectories !== false) {
subTreeResult.isDirectory = true;
}
var identity = generateIdentity(options, iterationInfo);
modules[identity] = subTreeResult;
}
else
throw new Error('Unknown mode');
} | [
"function",
"(",
"options",
",",
"iterationInfo",
",",
"modules",
")",
"{",
"if",
"(",
"options",
".",
"excludeDirs",
")",
"{",
"var",
"match",
"=",
"iterationInfo",
".",
"fileName",
".",
"match",
"(",
"options",
".",
"excludeDirs",
")",
";",
"if",
"(",
"match",
")",
"return",
";",
"}",
"var",
"subIterationInfo",
"=",
"_",
".",
"clone",
"(",
"iterationInfo",
")",
";",
"++",
"subIterationInfo",
".",
"depth",
";",
"subIterationInfo",
".",
"dirName",
"=",
"iterationInfo",
".",
"absoluteFullPath",
";",
"var",
"subTreeResult",
"=",
"doInterations",
"(",
"options",
",",
"subIterationInfo",
")",
";",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"subTreeResult",
")",
")",
"return",
";",
"if",
"(",
"options",
".",
"mode",
"===",
"'list'",
")",
"{",
"_",
".",
"forEach",
"(",
"subTreeResult",
",",
"function",
"(",
"value",
",",
"index",
")",
"{",
"if",
"(",
"options",
".",
"useVersions",
"===",
"true",
")",
"{",
"modules",
"[",
"index",
"]",
"=",
"modules",
"[",
"index",
"]",
"||",
"{",
"}",
";",
"_",
".",
"forEach",
"(",
"value",
",",
"function",
"(",
"versionValue",
",",
"versionIndex",
")",
"{",
"if",
"(",
"modules",
"[",
"index",
"]",
"[",
"versionIndex",
"]",
")",
"throw",
"new",
"Error",
"(",
"\"Identity '\"",
"+",
"index",
"+",
"\"' with version '\"",
"+",
"versionIndex",
"+",
"\"' is already registered by module at '\"",
"+",
"modules",
"[",
"index",
"]",
"[",
"versionIndex",
"]",
".",
"absoluteFullPath",
"+",
"\"'\"",
")",
";",
"modules",
"[",
"index",
"]",
"[",
"versionIndex",
"]",
"=",
"versionValue",
";",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"modules",
"[",
"index",
"]",
")",
"throw",
"new",
"Error",
"(",
"\"Identity '\"",
"+",
"index",
"+",
"\"' is already registered by module at '\"",
"+",
"modules",
"[",
"index",
"]",
".",
"absoluteFullPath",
"+",
"\"'\"",
")",
";",
"modules",
"[",
"index",
"]",
"=",
"value",
";",
"}",
"}",
")",
"}",
"else",
"if",
"(",
"options",
".",
"mode",
"===",
"'tree'",
")",
"{",
"if",
"(",
"options",
".",
"markDirectories",
"!==",
"false",
")",
"{",
"subTreeResult",
".",
"isDirectory",
"=",
"true",
";",
"}",
"var",
"identity",
"=",
"generateIdentity",
"(",
"options",
",",
"iterationInfo",
")",
";",
"modules",
"[",
"identity",
"]",
"=",
"subTreeResult",
";",
"}",
"else",
"throw",
"new",
"Error",
"(",
"'Unknown mode'",
")",
";",
"}"
] | Processes one directory level
@param options :: general options
@param iterationInfo :: iteration options
@param modules :: object in which output will be loaded | [
"Processes",
"one",
"directory",
"level"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/moduleLoader/lib/requireAll.js#L321-L371 | train |
|
mia-js/mia-js-core | lib/logger/lib/logger.js | function (level, message, tag, data) {
var env = Shared.config('environment');
var levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];
var logLevelConfig = env.logLevel || "info";
if (logLevelConfig == "none") {
return;
}
var logLevel = levels.indexOf(logLevelConfig) >= 0 ? logLevelConfig : 'info';
// Set default error logging
if (_.isObject(message) && _.isEmpty(data)) {
if (message.message && _.isString(message.message)) {
data = message.stack || "";
message = message.message;
}
else {
data = message;
message = null;
}
}
//Output
if (levels.indexOf(level) <= levels.indexOf(logLevel)) {
var logString = "";
if (env.logFormat === 'json') {
logString = JSON.stringify({
timestamp: new Date().toISOString(),
level,
tag,
message,
data,
hostname: Shared.getCurrentHostId(),
pid: process.pid,
mode: env.mode
});
} else {
if (_.isObject(data)) {
data = Util.inspect(data, {showHidden: false, depth: null});
}
logString += new Date().toISOString() + ' ';
logString += '[' + level + ']';
logString += tag == "default" ? "" : ' [' + tag + ']';
logString += !_.isString(message) ? "" : ': ' + message;
logString += data ? ' --> ' + data : "";
}
if (["error", "fatal"].indexOf(level) >= 0) {
_outputLog("error", logString);
} else if (level == "warn") {
_outputLog("warn", logString);
} else {
_outputLog("info", logString);
}
}
} | javascript | function (level, message, tag, data) {
var env = Shared.config('environment');
var levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];
var logLevelConfig = env.logLevel || "info";
if (logLevelConfig == "none") {
return;
}
var logLevel = levels.indexOf(logLevelConfig) >= 0 ? logLevelConfig : 'info';
// Set default error logging
if (_.isObject(message) && _.isEmpty(data)) {
if (message.message && _.isString(message.message)) {
data = message.stack || "";
message = message.message;
}
else {
data = message;
message = null;
}
}
//Output
if (levels.indexOf(level) <= levels.indexOf(logLevel)) {
var logString = "";
if (env.logFormat === 'json') {
logString = JSON.stringify({
timestamp: new Date().toISOString(),
level,
tag,
message,
data,
hostname: Shared.getCurrentHostId(),
pid: process.pid,
mode: env.mode
});
} else {
if (_.isObject(data)) {
data = Util.inspect(data, {showHidden: false, depth: null});
}
logString += new Date().toISOString() + ' ';
logString += '[' + level + ']';
logString += tag == "default" ? "" : ' [' + tag + ']';
logString += !_.isString(message) ? "" : ': ' + message;
logString += data ? ' --> ' + data : "";
}
if (["error", "fatal"].indexOf(level) >= 0) {
_outputLog("error", logString);
} else if (level == "warn") {
_outputLog("warn", logString);
} else {
_outputLog("info", logString);
}
}
} | [
"function",
"(",
"level",
",",
"message",
",",
"tag",
",",
"data",
")",
"{",
"var",
"env",
"=",
"Shared",
".",
"config",
"(",
"'environment'",
")",
";",
"var",
"levels",
"=",
"[",
"'fatal'",
",",
"'error'",
",",
"'warn'",
",",
"'info'",
",",
"'debug'",
",",
"'trace'",
"]",
";",
"var",
"logLevelConfig",
"=",
"env",
".",
"logLevel",
"||",
"\"info\"",
";",
"if",
"(",
"logLevelConfig",
"==",
"\"none\"",
")",
"{",
"return",
";",
"}",
"var",
"logLevel",
"=",
"levels",
".",
"indexOf",
"(",
"logLevelConfig",
")",
">=",
"0",
"?",
"logLevelConfig",
":",
"'info'",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"message",
")",
"&&",
"_",
".",
"isEmpty",
"(",
"data",
")",
")",
"{",
"if",
"(",
"message",
".",
"message",
"&&",
"_",
".",
"isString",
"(",
"message",
".",
"message",
")",
")",
"{",
"data",
"=",
"message",
".",
"stack",
"||",
"\"\"",
";",
"message",
"=",
"message",
".",
"message",
";",
"}",
"else",
"{",
"data",
"=",
"message",
";",
"message",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"levels",
".",
"indexOf",
"(",
"level",
")",
"<=",
"levels",
".",
"indexOf",
"(",
"logLevel",
")",
")",
"{",
"var",
"logString",
"=",
"\"\"",
";",
"if",
"(",
"env",
".",
"logFormat",
"===",
"'json'",
")",
"{",
"logString",
"=",
"JSON",
".",
"stringify",
"(",
"{",
"timestamp",
":",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
",",
"level",
",",
"tag",
",",
"message",
",",
"data",
",",
"hostname",
":",
"Shared",
".",
"getCurrentHostId",
"(",
")",
",",
"pid",
":",
"process",
".",
"pid",
",",
"mode",
":",
"env",
".",
"mode",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"isObject",
"(",
"data",
")",
")",
"{",
"data",
"=",
"Util",
".",
"inspect",
"(",
"data",
",",
"{",
"showHidden",
":",
"false",
",",
"depth",
":",
"null",
"}",
")",
";",
"}",
"logString",
"+=",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
"+",
"' '",
";",
"logString",
"+=",
"'['",
"+",
"level",
"+",
"']'",
";",
"logString",
"+=",
"tag",
"==",
"\"default\"",
"?",
"\"\"",
":",
"' ['",
"+",
"tag",
"+",
"']'",
";",
"logString",
"+=",
"!",
"_",
".",
"isString",
"(",
"message",
")",
"?",
"\"\"",
":",
"': '",
"+",
"message",
";",
"logString",
"+=",
"data",
"?",
"' ",
"+",
"data",
":",
"\"\"",
";",
"}",
"if",
"(",
"[",
"\"error\"",
",",
"\"fatal\"",
"]",
".",
"indexOf",
"(",
"level",
")",
">=",
"0",
")",
"{",
"_outputLog",
"(",
"\"error\"",
",",
"logString",
")",
";",
"}",
"else",
"if",
"(",
"level",
"==",
"\"warn\"",
")",
"{",
"_outputLog",
"(",
"\"warn\"",
",",
"logString",
")",
";",
"}",
"else",
"{",
"_outputLog",
"(",
"\"info\"",
",",
"logString",
")",
";",
"}",
"}",
"}"
] | Write logging information
@param level => 'none', 'fatal', 'error', 'warn', 'info', 'debug', 'trace'
@param message = >Error message
@param tag => Tags of log info i.e. database, request. Default is 'default' or empty
@param data => Any data object
@private | [
"Write",
"logging",
"information"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/logger/lib/logger.js#L23-L82 | train |
|
mia-js/mia-js-core | lib/logger/lib/logger.js | function (obj, tag) {
tag = _.isArray(tag) ? tag.join(',') : tag;
tag = !_.isEmpty(tag) ? tag.toLowerCase() : 'default';
obj.trace = function (message, data) {
_logEvent("trace", message, tag, data);
};
obj.debug = function (message, data) {
_logEvent("debug", message, tag, data);
};
obj.info = function (message, data) {
_logEvent("info", message, tag, data);
};
obj.warn = function (message, data) {
_logEvent("warn", message, tag, data);
};
obj.error = function (message, data) {
_logEvent("error", message, tag, data);
};
obj.fatal = function (message, data) {
_logEvent("fatal", message, tag, data);
};
return obj;
} | javascript | function (obj, tag) {
tag = _.isArray(tag) ? tag.join(',') : tag;
tag = !_.isEmpty(tag) ? tag.toLowerCase() : 'default';
obj.trace = function (message, data) {
_logEvent("trace", message, tag, data);
};
obj.debug = function (message, data) {
_logEvent("debug", message, tag, data);
};
obj.info = function (message, data) {
_logEvent("info", message, tag, data);
};
obj.warn = function (message, data) {
_logEvent("warn", message, tag, data);
};
obj.error = function (message, data) {
_logEvent("error", message, tag, data);
};
obj.fatal = function (message, data) {
_logEvent("fatal", message, tag, data);
};
return obj;
} | [
"function",
"(",
"obj",
",",
"tag",
")",
"{",
"tag",
"=",
"_",
".",
"isArray",
"(",
"tag",
")",
"?",
"tag",
".",
"join",
"(",
"','",
")",
":",
"tag",
";",
"tag",
"=",
"!",
"_",
".",
"isEmpty",
"(",
"tag",
")",
"?",
"tag",
".",
"toLowerCase",
"(",
")",
":",
"'default'",
";",
"obj",
".",
"trace",
"=",
"function",
"(",
"message",
",",
"data",
")",
"{",
"_logEvent",
"(",
"\"trace\"",
",",
"message",
",",
"tag",
",",
"data",
")",
";",
"}",
";",
"obj",
".",
"debug",
"=",
"function",
"(",
"message",
",",
"data",
")",
"{",
"_logEvent",
"(",
"\"debug\"",
",",
"message",
",",
"tag",
",",
"data",
")",
";",
"}",
";",
"obj",
".",
"info",
"=",
"function",
"(",
"message",
",",
"data",
")",
"{",
"_logEvent",
"(",
"\"info\"",
",",
"message",
",",
"tag",
",",
"data",
")",
";",
"}",
";",
"obj",
".",
"warn",
"=",
"function",
"(",
"message",
",",
"data",
")",
"{",
"_logEvent",
"(",
"\"warn\"",
",",
"message",
",",
"tag",
",",
"data",
")",
";",
"}",
";",
"obj",
".",
"error",
"=",
"function",
"(",
"message",
",",
"data",
")",
"{",
"_logEvent",
"(",
"\"error\"",
",",
"message",
",",
"tag",
",",
"data",
")",
";",
"}",
";",
"obj",
".",
"fatal",
"=",
"function",
"(",
"message",
",",
"data",
")",
"{",
"_logEvent",
"(",
"\"fatal\"",
",",
"message",
",",
"tag",
",",
"data",
")",
";",
"}",
";",
"return",
"obj",
";",
"}"
] | Provide log methods
@param obj
@param tag
@returns {*} | [
"Provide",
"log",
"methods"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/logger/lib/logger.js#L100-L129 | train |
|
AndreasPizsa/grunt-update-json | tasks/lib/update_json.js | expandField | function expandField(input, grunt){
var get = pointer(input);
return function(memo, fin, fout){
if(_.isString(fin)){
var match = fin.match(re.PATH_POINT);
// matched ...with a `$.` ...but not with a `\`
if(match && match[3] === '$.' && !match[1]){
// field name, starts with an unescaped `$`, treat as JSON Path
memo[fout] = jsonPath(input, match[2]);
}else if(match && match[3] === '/' && !match[1]){
// field name, treat as a JSON pointer
memo[fout] = get(match[2]);
}else{
memo[fout] = input[match[2]];
}
}else if(_.isFunction(fin)){
// call a function
memo[fout] = fin(input);
}else if(_.isArray(fin)){
// pick out the values
memo[fout] = _.map(fin, function(value){
return expandField(input)({}, value, "dummy")["dummy"];
});
}else if(_.isObject(fin)){
// build up an object of something else
memo[fout] = _.reduce(fin, expandField(input, grunt), {});
}else if(_.isNull(fin)){
// copy the value
memo[fout] = input[fout];
}else{
grunt.fail.warn('Could not map `' + JSON.stringify(fin) + '` to `' +
JSON.stringify(fout) + '`');
}
return memo;
};
} | javascript | function expandField(input, grunt){
var get = pointer(input);
return function(memo, fin, fout){
if(_.isString(fin)){
var match = fin.match(re.PATH_POINT);
// matched ...with a `$.` ...but not with a `\`
if(match && match[3] === '$.' && !match[1]){
// field name, starts with an unescaped `$`, treat as JSON Path
memo[fout] = jsonPath(input, match[2]);
}else if(match && match[3] === '/' && !match[1]){
// field name, treat as a JSON pointer
memo[fout] = get(match[2]);
}else{
memo[fout] = input[match[2]];
}
}else if(_.isFunction(fin)){
// call a function
memo[fout] = fin(input);
}else if(_.isArray(fin)){
// pick out the values
memo[fout] = _.map(fin, function(value){
return expandField(input)({}, value, "dummy")["dummy"];
});
}else if(_.isObject(fin)){
// build up an object of something else
memo[fout] = _.reduce(fin, expandField(input, grunt), {});
}else if(_.isNull(fin)){
// copy the value
memo[fout] = input[fout];
}else{
grunt.fail.warn('Could not map `' + JSON.stringify(fin) + '` to `' +
JSON.stringify(fout) + '`');
}
return memo;
};
} | [
"function",
"expandField",
"(",
"input",
",",
"grunt",
")",
"{",
"var",
"get",
"=",
"pointer",
"(",
"input",
")",
";",
"return",
"function",
"(",
"memo",
",",
"fin",
",",
"fout",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"fin",
")",
")",
"{",
"var",
"match",
"=",
"fin",
".",
"match",
"(",
"re",
".",
"PATH_POINT",
")",
";",
"if",
"(",
"match",
"&&",
"match",
"[",
"3",
"]",
"===",
"'$.'",
"&&",
"!",
"match",
"[",
"1",
"]",
")",
"{",
"memo",
"[",
"fout",
"]",
"=",
"jsonPath",
"(",
"input",
",",
"match",
"[",
"2",
"]",
")",
";",
"}",
"else",
"if",
"(",
"match",
"&&",
"match",
"[",
"3",
"]",
"===",
"'/'",
"&&",
"!",
"match",
"[",
"1",
"]",
")",
"{",
"memo",
"[",
"fout",
"]",
"=",
"get",
"(",
"match",
"[",
"2",
"]",
")",
";",
"}",
"else",
"{",
"memo",
"[",
"fout",
"]",
"=",
"input",
"[",
"match",
"[",
"2",
"]",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"_",
".",
"isFunction",
"(",
"fin",
")",
")",
"{",
"memo",
"[",
"fout",
"]",
"=",
"fin",
"(",
"input",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isArray",
"(",
"fin",
")",
")",
"{",
"memo",
"[",
"fout",
"]",
"=",
"_",
".",
"map",
"(",
"fin",
",",
"function",
"(",
"value",
")",
"{",
"return",
"expandField",
"(",
"input",
")",
"(",
"{",
"}",
",",
"value",
",",
"\"dummy\"",
")",
"[",
"\"dummy\"",
"]",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"fin",
")",
")",
"{",
"memo",
"[",
"fout",
"]",
"=",
"_",
".",
"reduce",
"(",
"fin",
",",
"expandField",
"(",
"input",
",",
"grunt",
")",
",",
"{",
"}",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isNull",
"(",
"fin",
")",
")",
"{",
"memo",
"[",
"fout",
"]",
"=",
"input",
"[",
"fout",
"]",
";",
"}",
"else",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"'Could not map `'",
"+",
"JSON",
".",
"stringify",
"(",
"fin",
")",
"+",
"'` to `'",
"+",
"JSON",
".",
"stringify",
"(",
"fout",
")",
"+",
"'`'",
")",
";",
"}",
"return",
"memo",
";",
"}",
";",
"}"
] | factory for a reduce function, bound to the input, that can get the value out of the input | [
"factory",
"for",
"a",
"reduce",
"function",
"bound",
"to",
"the",
"input",
"that",
"can",
"get",
"the",
"value",
"out",
"of",
"the",
"input"
] | c85f6575a039c665371ce411f0d47e2a264bb3b6 | https://github.com/AndreasPizsa/grunt-update-json/blob/c85f6575a039c665371ce411f0d47e2a264bb3b6/tasks/lib/update_json.js#L46-L82 | train |
voxgig/seneca-hapi | hapi.js | action_handler | async function action_handler(req, h) {
const data = req.payload
const json = 'string' === typeof data ? tu.parseJSON(data) : data
if (json instanceof Error) {
throw json
}
const seneca = prepare_seneca(req, json)
const msg = tu.internalize_msg(seneca, json)
return await new Promise(resolve => {
var out = null
for (var i = 0; i < modify_action.length; i++) {
out = modify_action[i].call(seneca, msg, req)
if (out) {
return resolve(out)
}
}
seneca.act(msg, function(err, out, meta) {
if (err && !options.debug) {
err.stack = null
}
resolve(tu.externalize_reply(this, err, out, meta))
})
})
} | javascript | async function action_handler(req, h) {
const data = req.payload
const json = 'string' === typeof data ? tu.parseJSON(data) : data
if (json instanceof Error) {
throw json
}
const seneca = prepare_seneca(req, json)
const msg = tu.internalize_msg(seneca, json)
return await new Promise(resolve => {
var out = null
for (var i = 0; i < modify_action.length; i++) {
out = modify_action[i].call(seneca, msg, req)
if (out) {
return resolve(out)
}
}
seneca.act(msg, function(err, out, meta) {
if (err && !options.debug) {
err.stack = null
}
resolve(tu.externalize_reply(this, err, out, meta))
})
})
} | [
"async",
"function",
"action_handler",
"(",
"req",
",",
"h",
")",
"{",
"const",
"data",
"=",
"req",
".",
"payload",
"const",
"json",
"=",
"'string'",
"===",
"typeof",
"data",
"?",
"tu",
".",
"parseJSON",
"(",
"data",
")",
":",
"data",
"if",
"(",
"json",
"instanceof",
"Error",
")",
"{",
"throw",
"json",
"}",
"const",
"seneca",
"=",
"prepare_seneca",
"(",
"req",
",",
"json",
")",
"const",
"msg",
"=",
"tu",
".",
"internalize_msg",
"(",
"seneca",
",",
"json",
")",
"return",
"await",
"new",
"Promise",
"(",
"resolve",
"=>",
"{",
"var",
"out",
"=",
"null",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"modify_action",
".",
"length",
";",
"i",
"++",
")",
"{",
"out",
"=",
"modify_action",
"[",
"i",
"]",
".",
"call",
"(",
"seneca",
",",
"msg",
",",
"req",
")",
"if",
"(",
"out",
")",
"{",
"return",
"resolve",
"(",
"out",
")",
"}",
"}",
"seneca",
".",
"act",
"(",
"msg",
",",
"function",
"(",
"err",
",",
"out",
",",
"meta",
")",
"{",
"if",
"(",
"err",
"&&",
"!",
"options",
".",
"debug",
")",
"{",
"err",
".",
"stack",
"=",
"null",
"}",
"resolve",
"(",
"tu",
".",
"externalize_reply",
"(",
"this",
",",
"err",
",",
"out",
",",
"meta",
")",
")",
"}",
")",
"}",
")",
"}"
] | Convenience handler to call a seneca action directly from inbound POST JSON. | [
"Convenience",
"handler",
"to",
"call",
"a",
"seneca",
"action",
"directly",
"from",
"inbound",
"POST",
"JSON",
"."
] | 377c0e8c38bc2703686fcffa85a5999c93f9ef1c | https://github.com/voxgig/seneca-hapi/blob/377c0e8c38bc2703686fcffa85a5999c93f9ef1c/hapi.js#L64-L91 | train |
mia-js/mia-js-core | lib/cronJobs/lib/jobManagementDbConnector.js | function () {
return ServerHeartbeatModel.find({
status: _statusActive
}).then(function (cursor) {
return Q.ninvoke(cursor, 'toArray').then(function (servers) {
var serverIds = [];
servers.map(function (value) {
serverIds.push(value._id);
});
return _removeAllJobsOfUnknownServer(serverIds);
});
});
} | javascript | function () {
return ServerHeartbeatModel.find({
status: _statusActive
}).then(function (cursor) {
return Q.ninvoke(cursor, 'toArray').then(function (servers) {
var serverIds = [];
servers.map(function (value) {
serverIds.push(value._id);
});
return _removeAllJobsOfUnknownServer(serverIds);
});
});
} | [
"function",
"(",
")",
"{",
"return",
"ServerHeartbeatModel",
".",
"find",
"(",
"{",
"status",
":",
"_statusActive",
"}",
")",
".",
"then",
"(",
"function",
"(",
"cursor",
")",
"{",
"return",
"Q",
".",
"ninvoke",
"(",
"cursor",
",",
"'toArray'",
")",
".",
"then",
"(",
"function",
"(",
"servers",
")",
"{",
"var",
"serverIds",
"=",
"[",
"]",
";",
"servers",
".",
"map",
"(",
"function",
"(",
"value",
")",
"{",
"serverIds",
".",
"push",
"(",
"value",
".",
"_id",
")",
";",
"}",
")",
";",
"return",
"_removeAllJobsOfUnknownServer",
"(",
"serverIds",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Remove unknown serverIds from jobslist, can happen while server restart | [
"Remove",
"unknown",
"serverIds",
"from",
"jobslist",
"can",
"happen",
"while",
"server",
"restart"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/cronJobs/lib/jobManagementDbConnector.js#L301-L313 | train |
|
jbaicoianu/elation | components/utils/scripts/dust.js | function( input, chunk, context ){
// return given input if there is no dust reference to resolve
var output = input;
// dust compiles a string to function, if there are references
if( typeof input === "function"){
if( ( typeof input.isReference !== "undefined" ) && ( input.isReference === true ) ){ // just a plain function, not a dust `body` function
output = input();
} else {
output = '';
chunk.tap(function(data){
output += data;
return '';
}).render(input, context).untap();
if( output === '' ){
output = false;
}
}
}
return output;
} | javascript | function( input, chunk, context ){
// return given input if there is no dust reference to resolve
var output = input;
// dust compiles a string to function, if there are references
if( typeof input === "function"){
if( ( typeof input.isReference !== "undefined" ) && ( input.isReference === true ) ){ // just a plain function, not a dust `body` function
output = input();
} else {
output = '';
chunk.tap(function(data){
output += data;
return '';
}).render(input, context).untap();
if( output === '' ){
output = false;
}
}
}
return output;
} | [
"function",
"(",
"input",
",",
"chunk",
",",
"context",
")",
"{",
"var",
"output",
"=",
"input",
";",
"if",
"(",
"typeof",
"input",
"===",
"\"function\"",
")",
"{",
"if",
"(",
"(",
"typeof",
"input",
".",
"isReference",
"!==",
"\"undefined\"",
")",
"&&",
"(",
"input",
".",
"isReference",
"===",
"true",
")",
")",
"{",
"output",
"=",
"input",
"(",
")",
";",
"}",
"else",
"{",
"output",
"=",
"''",
";",
"chunk",
".",
"tap",
"(",
"function",
"(",
"data",
")",
"{",
"output",
"+=",
"data",
";",
"return",
"''",
";",
"}",
")",
".",
"render",
"(",
"input",
",",
"context",
")",
".",
"untap",
"(",
")",
";",
"if",
"(",
"output",
"===",
"''",
")",
"{",
"output",
"=",
"false",
";",
"}",
"}",
"}",
"return",
"output",
";",
"}"
] | Utility helping to resolve dust references in the given chunk | [
"Utility",
"helping",
"to",
"resolve",
"dust",
"references",
"in",
"the",
"given",
"chunk"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/dust.js#L655-L674 | train |
|
jbaicoianu/elation | components/utils/scripts/dust.js | compactBuffers | function compactBuffers(context, node) {
var out = [node[0]], memo;
for (var i=1, len=node.length; i<len; i++) {
var res = dust.filterNode(context, node[i]);
if (res) {
if (res[0] === 'buffer') {
if (memo) {
memo[1] += res[1];
} else {
memo = res;
out.push(res);
}
} else {
memo = null;
out.push(res);
}
}
}
return out;
} | javascript | function compactBuffers(context, node) {
var out = [node[0]], memo;
for (var i=1, len=node.length; i<len; i++) {
var res = dust.filterNode(context, node[i]);
if (res) {
if (res[0] === 'buffer') {
if (memo) {
memo[1] += res[1];
} else {
memo = res;
out.push(res);
}
} else {
memo = null;
out.push(res);
}
}
}
return out;
} | [
"function",
"compactBuffers",
"(",
"context",
",",
"node",
")",
"{",
"var",
"out",
"=",
"[",
"node",
"[",
"0",
"]",
"]",
",",
"memo",
";",
"for",
"(",
"var",
"i",
"=",
"1",
",",
"len",
"=",
"node",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"res",
"=",
"dust",
".",
"filterNode",
"(",
"context",
",",
"node",
"[",
"i",
"]",
")",
";",
"if",
"(",
"res",
")",
"{",
"if",
"(",
"res",
"[",
"0",
"]",
"===",
"'buffer'",
")",
"{",
"if",
"(",
"memo",
")",
"{",
"memo",
"[",
"1",
"]",
"+=",
"res",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"memo",
"=",
"res",
";",
"out",
".",
"push",
"(",
"res",
")",
";",
"}",
"}",
"else",
"{",
"memo",
"=",
"null",
";",
"out",
".",
"push",
"(",
"res",
")",
";",
"}",
"}",
"}",
"return",
"out",
";",
"}"
] | Compacts consecutive buffer nodes into a single node | [
"Compacts",
"consecutive",
"buffer",
"nodes",
"into",
"a",
"single",
"node"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/dust.js#L838-L857 | train |
mia-js/mia-js-core | lib/utils/lib/ipAddressHelper.js | thisModule | function thisModule() {
var self = this;
/**
* Generate random hash value
* @returns {*}
*/
self.getClientIP = function (req) {
req = req || {};
req.connection = req.connection || {};
req.socket = req.socket || {};
req.client = req.client || {};
var ipString = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.client.remoteAddress || req.ip || "";
var ips = ipString.split(",");
if (ips.length > 0) {
return ips[0];
}
else {
return;
}
};
return self;
} | javascript | function thisModule() {
var self = this;
/**
* Generate random hash value
* @returns {*}
*/
self.getClientIP = function (req) {
req = req || {};
req.connection = req.connection || {};
req.socket = req.socket || {};
req.client = req.client || {};
var ipString = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.client.remoteAddress || req.ip || "";
var ips = ipString.split(",");
if (ips.length > 0) {
return ips[0];
}
else {
return;
}
};
return self;
} | [
"function",
"thisModule",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"getClientIP",
"=",
"function",
"(",
"req",
")",
"{",
"req",
"=",
"req",
"||",
"{",
"}",
";",
"req",
".",
"connection",
"=",
"req",
".",
"connection",
"||",
"{",
"}",
";",
"req",
".",
"socket",
"=",
"req",
".",
"socket",
"||",
"{",
"}",
";",
"req",
".",
"client",
"=",
"req",
".",
"client",
"||",
"{",
"}",
";",
"var",
"ipString",
"=",
"req",
".",
"headers",
"[",
"'x-forwarded-for'",
"]",
"||",
"req",
".",
"connection",
".",
"remoteAddress",
"||",
"req",
".",
"socket",
".",
"remoteAddress",
"||",
"req",
".",
"client",
".",
"remoteAddress",
"||",
"req",
".",
"ip",
"||",
"\"\"",
";",
"var",
"ips",
"=",
"ipString",
".",
"split",
"(",
"\",\"",
")",
";",
"if",
"(",
"ips",
".",
"length",
">",
"0",
")",
"{",
"return",
"ips",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
";",
"return",
"self",
";",
"}"
] | Determine Clients IP Address
@param err
@returns {*} | [
"Determine",
"Clients",
"IP",
"Address"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/utils/lib/ipAddressHelper.js#L7-L31 | train |
AmpersandJS/ampersand-dom | ampersand-dom.js | function (el, cls) {
cls = getString(cls);
if (!cls) return;
if (Array.isArray(cls)) {
cls.forEach(function(c) {
dom.addClass(el, c);
});
} else if (el.classList) {
el.classList.add(cls);
} else {
if (!hasClass(el, cls)) {
if (el.classList) {
el.classList.add(cls);
} else {
el.className += ' ' + cls;
}
}
}
} | javascript | function (el, cls) {
cls = getString(cls);
if (!cls) return;
if (Array.isArray(cls)) {
cls.forEach(function(c) {
dom.addClass(el, c);
});
} else if (el.classList) {
el.classList.add(cls);
} else {
if (!hasClass(el, cls)) {
if (el.classList) {
el.classList.add(cls);
} else {
el.className += ' ' + cls;
}
}
}
} | [
"function",
"(",
"el",
",",
"cls",
")",
"{",
"cls",
"=",
"getString",
"(",
"cls",
")",
";",
"if",
"(",
"!",
"cls",
")",
"return",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"cls",
")",
")",
"{",
"cls",
".",
"forEach",
"(",
"function",
"(",
"c",
")",
"{",
"dom",
".",
"addClass",
"(",
"el",
",",
"c",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"el",
".",
"classList",
")",
"{",
"el",
".",
"classList",
".",
"add",
"(",
"cls",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"hasClass",
"(",
"el",
",",
"cls",
")",
")",
"{",
"if",
"(",
"el",
".",
"classList",
")",
"{",
"el",
".",
"classList",
".",
"add",
"(",
"cls",
")",
";",
"}",
"else",
"{",
"el",
".",
"className",
"+=",
"' '",
"+",
"cls",
";",
"}",
"}",
"}",
"}"
] | optimize if we have classList | [
"optimize",
"if",
"we",
"have",
"classList"
] | 7a79f8a2a6c0bba16eb6d9f5e81295c0286aafa9 | https://github.com/AmpersandJS/ampersand-dom/blob/7a79f8a2a6c0bba16eb6d9f5e81295c0286aafa9/ampersand-dom.js#L7-L25 | train |
|
jbaicoianu/elation | components/utils/scripts/elation.js | function(name, container, args, events) {
/* handling for any default values if args are not specified */
var mergeDefaults = function(args, defaults) {
var args = args || {};
if (typeof defaults == 'object') {
for (var key in defaults) {
if (elation.utils.isNull(args[key])) {
args[key] = defaults[key];
}
}
}
return args;
};
var realname = name;
if (elation.utils.isObject(name)) {
// Simple syntax just takes an object with all arguments
args = name;
realname = elation.utils.any(args.id, args.name, null);
container = (!elation.utils.isNull(args.container) ? args.container : null);
events = (!elation.utils.isNull(args.events) ? args.events : null);
}
// If no args were passed in, we're probably being used as the base for another
// component's prototype, so there's no need to go through full init
if (elation.utils.isNull(realname) && !container && !args) {
var obj = new component.base(type);
// apply default args
obj.args = mergeDefaults(obj.args, elation.utils.clone(obj.defaults));
return obj;
}
// If no name was passed, use the current object count as a name instead ("anonymous" components)
if (elation.utils.isNull(realname) || realname === "") {
realname = component.objcount;
}
if (!component.obj[realname] && !elation.utils.isEmpty(args)) {
component.obj[realname] = obj = new component.base(type);
component.objcount++;
//}
// TODO - I think combining this logic would let us use components without needing HTML elements for the container
//if (component.obj[realname] && container !== undefined) {
component.obj[realname].componentinit(type, realname, container, args, events);
/*
if (component.extendclass) {
component.obj[realname].initSuperClass(component.extendclass);
}
*/
// fix handling for append component infinite recursion issue
if (args.append instanceof elation.component.base)
args.append = args.append.container;
if (args.before instanceof elation.component.base)
args.before = args.before.container;
// apply default args
try {
if (typeof obj.defaults == 'object')
args = mergeDefaults(args, elation.utils.clone(obj.defaults));
var parentclass = component.extendclass;
// recursively apply inherited defaults
while (parentclass) {
if (typeof parentclass.defaults == 'object')
elation.utils.merge(mergeDefaults(args, elation.utils.clone(parentclass.defaults)),args);
parentclass = parentclass.extendclass;
}
} catch (e) {
console.log('-!- Error merging component args', e.msg);
}
if (typeof obj.init == 'function') {
obj.init(realname, container, args, events);
}
}
return component.obj[realname];
} | javascript | function(name, container, args, events) {
/* handling for any default values if args are not specified */
var mergeDefaults = function(args, defaults) {
var args = args || {};
if (typeof defaults == 'object') {
for (var key in defaults) {
if (elation.utils.isNull(args[key])) {
args[key] = defaults[key];
}
}
}
return args;
};
var realname = name;
if (elation.utils.isObject(name)) {
// Simple syntax just takes an object with all arguments
args = name;
realname = elation.utils.any(args.id, args.name, null);
container = (!elation.utils.isNull(args.container) ? args.container : null);
events = (!elation.utils.isNull(args.events) ? args.events : null);
}
// If no args were passed in, we're probably being used as the base for another
// component's prototype, so there's no need to go through full init
if (elation.utils.isNull(realname) && !container && !args) {
var obj = new component.base(type);
// apply default args
obj.args = mergeDefaults(obj.args, elation.utils.clone(obj.defaults));
return obj;
}
// If no name was passed, use the current object count as a name instead ("anonymous" components)
if (elation.utils.isNull(realname) || realname === "") {
realname = component.objcount;
}
if (!component.obj[realname] && !elation.utils.isEmpty(args)) {
component.obj[realname] = obj = new component.base(type);
component.objcount++;
//}
// TODO - I think combining this logic would let us use components without needing HTML elements for the container
//if (component.obj[realname] && container !== undefined) {
component.obj[realname].componentinit(type, realname, container, args, events);
/*
if (component.extendclass) {
component.obj[realname].initSuperClass(component.extendclass);
}
*/
// fix handling for append component infinite recursion issue
if (args.append instanceof elation.component.base)
args.append = args.append.container;
if (args.before instanceof elation.component.base)
args.before = args.before.container;
// apply default args
try {
if (typeof obj.defaults == 'object')
args = mergeDefaults(args, elation.utils.clone(obj.defaults));
var parentclass = component.extendclass;
// recursively apply inherited defaults
while (parentclass) {
if (typeof parentclass.defaults == 'object')
elation.utils.merge(mergeDefaults(args, elation.utils.clone(parentclass.defaults)),args);
parentclass = parentclass.extendclass;
}
} catch (e) {
console.log('-!- Error merging component args', e.msg);
}
if (typeof obj.init == 'function') {
obj.init(realname, container, args, events);
}
}
return component.obj[realname];
} | [
"function",
"(",
"name",
",",
"container",
",",
"args",
",",
"events",
")",
"{",
"var",
"mergeDefaults",
"=",
"function",
"(",
"args",
",",
"defaults",
")",
"{",
"var",
"args",
"=",
"args",
"||",
"{",
"}",
";",
"if",
"(",
"typeof",
"defaults",
"==",
"'object'",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"defaults",
")",
"{",
"if",
"(",
"elation",
".",
"utils",
".",
"isNull",
"(",
"args",
"[",
"key",
"]",
")",
")",
"{",
"args",
"[",
"key",
"]",
"=",
"defaults",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"return",
"args",
";",
"}",
";",
"var",
"realname",
"=",
"name",
";",
"if",
"(",
"elation",
".",
"utils",
".",
"isObject",
"(",
"name",
")",
")",
"{",
"args",
"=",
"name",
";",
"realname",
"=",
"elation",
".",
"utils",
".",
"any",
"(",
"args",
".",
"id",
",",
"args",
".",
"name",
",",
"null",
")",
";",
"container",
"=",
"(",
"!",
"elation",
".",
"utils",
".",
"isNull",
"(",
"args",
".",
"container",
")",
"?",
"args",
".",
"container",
":",
"null",
")",
";",
"events",
"=",
"(",
"!",
"elation",
".",
"utils",
".",
"isNull",
"(",
"args",
".",
"events",
")",
"?",
"args",
".",
"events",
":",
"null",
")",
";",
"}",
"if",
"(",
"elation",
".",
"utils",
".",
"isNull",
"(",
"realname",
")",
"&&",
"!",
"container",
"&&",
"!",
"args",
")",
"{",
"var",
"obj",
"=",
"new",
"component",
".",
"base",
"(",
"type",
")",
";",
"obj",
".",
"args",
"=",
"mergeDefaults",
"(",
"obj",
".",
"args",
",",
"elation",
".",
"utils",
".",
"clone",
"(",
"obj",
".",
"defaults",
")",
")",
";",
"return",
"obj",
";",
"}",
"if",
"(",
"elation",
".",
"utils",
".",
"isNull",
"(",
"realname",
")",
"||",
"realname",
"===",
"\"\"",
")",
"{",
"realname",
"=",
"component",
".",
"objcount",
";",
"}",
"if",
"(",
"!",
"component",
".",
"obj",
"[",
"realname",
"]",
"&&",
"!",
"elation",
".",
"utils",
".",
"isEmpty",
"(",
"args",
")",
")",
"{",
"component",
".",
"obj",
"[",
"realname",
"]",
"=",
"obj",
"=",
"new",
"component",
".",
"base",
"(",
"type",
")",
";",
"component",
".",
"objcount",
"++",
";",
"component",
".",
"obj",
"[",
"realname",
"]",
".",
"componentinit",
"(",
"type",
",",
"realname",
",",
"container",
",",
"args",
",",
"events",
")",
";",
"if",
"(",
"args",
".",
"append",
"instanceof",
"elation",
".",
"component",
".",
"base",
")",
"args",
".",
"append",
"=",
"args",
".",
"append",
".",
"container",
";",
"if",
"(",
"args",
".",
"before",
"instanceof",
"elation",
".",
"component",
".",
"base",
")",
"args",
".",
"before",
"=",
"args",
".",
"before",
".",
"container",
";",
"try",
"{",
"if",
"(",
"typeof",
"obj",
".",
"defaults",
"==",
"'object'",
")",
"args",
"=",
"mergeDefaults",
"(",
"args",
",",
"elation",
".",
"utils",
".",
"clone",
"(",
"obj",
".",
"defaults",
")",
")",
";",
"var",
"parentclass",
"=",
"component",
".",
"extendclass",
";",
"while",
"(",
"parentclass",
")",
"{",
"if",
"(",
"typeof",
"parentclass",
".",
"defaults",
"==",
"'object'",
")",
"elation",
".",
"utils",
".",
"merge",
"(",
"mergeDefaults",
"(",
"args",
",",
"elation",
".",
"utils",
".",
"clone",
"(",
"parentclass",
".",
"defaults",
")",
")",
",",
"args",
")",
";",
"parentclass",
"=",
"parentclass",
".",
"extendclass",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"'-!- Error merging component args'",
",",
"e",
".",
"msg",
")",
";",
"}",
"if",
"(",
"typeof",
"obj",
".",
"init",
"==",
"'function'",
")",
"{",
"obj",
".",
"init",
"(",
"realname",
",",
"container",
",",
"args",
",",
"events",
")",
";",
"}",
"}",
"return",
"component",
".",
"obj",
"[",
"realname",
"]",
";",
"}"
] | At the top level, a component is just a function which checks to see if an instance with the given name exists already. If it doesn't we create it, and then we return a reference to the specified instance. | [
"At",
"the",
"top",
"level",
"a",
"component",
"is",
"just",
"a",
"function",
"which",
"checks",
"to",
"see",
"if",
"an",
"instance",
"with",
"the",
"given",
"name",
"exists",
"already",
".",
"If",
"it",
"doesn",
"t",
"we",
"create",
"it",
"and",
"then",
"we",
"return",
"a",
"reference",
"to",
"the",
"specified",
"instance",
"."
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/elation.js#L238-L322 | train |
|
healthsparq/ember-fountainhead | lib/parse-markdown.js | function(description) {
// Look for triple backtick code blocks flagged as `glimmer`;
// define end of block as triple backticks followed by a newline
let matches = description.match(/(```glimmer)(.|\n)*?```/gi);
if (matches && matches.length) {
matches.map(codeBlock => {
let blockEnd = codeBlock.length + description.indexOf(codeBlock);
let plainCode = codeBlock.replace(/(```glimmer|```)/gi, '');
description = `${description.slice(0, (blockEnd))}${plainCode}${ description.slice(blockEnd)}`;
});
}
return description;
} | javascript | function(description) {
// Look for triple backtick code blocks flagged as `glimmer`;
// define end of block as triple backticks followed by a newline
let matches = description.match(/(```glimmer)(.|\n)*?```/gi);
if (matches && matches.length) {
matches.map(codeBlock => {
let blockEnd = codeBlock.length + description.indexOf(codeBlock);
let plainCode = codeBlock.replace(/(```glimmer|```)/gi, '');
description = `${description.slice(0, (blockEnd))}${plainCode}${ description.slice(blockEnd)}`;
});
}
return description;
} | [
"function",
"(",
"description",
")",
"{",
"let",
"matches",
"=",
"description",
".",
"match",
"(",
"/",
"(```glimmer)(.|\\n)*?```",
"/",
"gi",
")",
";",
"if",
"(",
"matches",
"&&",
"matches",
".",
"length",
")",
"{",
"matches",
".",
"map",
"(",
"codeBlock",
"=>",
"{",
"let",
"blockEnd",
"=",
"codeBlock",
".",
"length",
"+",
"description",
".",
"indexOf",
"(",
"codeBlock",
")",
";",
"let",
"plainCode",
"=",
"codeBlock",
".",
"replace",
"(",
"/",
"(```glimmer|```)",
"/",
"gi",
",",
"''",
")",
";",
"description",
"=",
"`",
"${",
"description",
".",
"slice",
"(",
"0",
",",
"(",
"blockEnd",
")",
")",
"}",
"${",
"plainCode",
"}",
"${",
"description",
".",
"slice",
"(",
"blockEnd",
")",
"}",
"`",
";",
"}",
")",
";",
"}",
"return",
"description",
";",
"}"
] | Scans the description text for instances of markdown code blocks flagged
as `"glimmer"` syntax. If any such instances are found, they are copied,
stripped of their triple backticks and re-inserted into the
`templateString` immediately after the original declaration. This allows
for functional copies of your code examples to be automatically rendered
into the description, without having to duplicate the code block itself.
If your functional code needs to have different setup to work correctly in
the Fountainhead context (for example, if you need to use `core-state` to
set up sandboxed state and controls), simply use `"handlebars"` or no
syntax flag, and manually add the code block you want Fountainhead to
render after your example. Neato!
@method _renderCodeBlocks
@param {String} description The description text to scan for code blocks
@return {String} | [
"Scans",
"the",
"description",
"text",
"for",
"instances",
"of",
"markdown",
"code",
"blocks",
"flagged",
"as",
"glimmer",
"syntax",
".",
"If",
"any",
"such",
"instances",
"are",
"found",
"they",
"are",
"copied",
"stripped",
"of",
"their",
"triple",
"backticks",
"and",
"re",
"-",
"inserted",
"into",
"the",
"templateString",
"immediately",
"after",
"the",
"original",
"declaration",
".",
"This",
"allows",
"for",
"functional",
"copies",
"of",
"your",
"code",
"examples",
"to",
"be",
"automatically",
"rendered",
"into",
"the",
"description",
"without",
"having",
"to",
"duplicate",
"the",
"code",
"block",
"itself",
"."
] | 3577546719b251385ca1093f812889590459205a | https://github.com/healthsparq/ember-fountainhead/blob/3577546719b251385ca1093f812889590459205a/lib/parse-markdown.js#L101-L115 | train |
|
jbaicoianu/elation | components/utils/htdocs/scripts/jsmart.js | obMerge | function obMerge(prefix, ob1, ob2 /*, ...*/)
{
for (var i=2; i<arguments.length; ++i)
{
for (var nm in arguments[i])
{
if (arguments[i].hasOwnProperty(nm) || typeof arguments[i][nm] == 'function')
{
if (typeof(arguments[i][nm]) == 'object' && arguments[i][nm] != null)
{
ob1[prefix+nm] = (arguments[i][nm] instanceof Array) ? new Array : new Object;
obMerge('', ob1[prefix+nm], arguments[i][nm]);
}
else
{
ob1[prefix+nm] = arguments[i][nm];
}
}
}
}
return ob1;
} | javascript | function obMerge(prefix, ob1, ob2 /*, ...*/)
{
for (var i=2; i<arguments.length; ++i)
{
for (var nm in arguments[i])
{
if (arguments[i].hasOwnProperty(nm) || typeof arguments[i][nm] == 'function')
{
if (typeof(arguments[i][nm]) == 'object' && arguments[i][nm] != null)
{
ob1[prefix+nm] = (arguments[i][nm] instanceof Array) ? new Array : new Object;
obMerge('', ob1[prefix+nm], arguments[i][nm]);
}
else
{
ob1[prefix+nm] = arguments[i][nm];
}
}
}
}
return ob1;
} | [
"function",
"obMerge",
"(",
"prefix",
",",
"ob1",
",",
"ob2",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"2",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"++",
"i",
")",
"{",
"for",
"(",
"var",
"nm",
"in",
"arguments",
"[",
"i",
"]",
")",
"{",
"if",
"(",
"arguments",
"[",
"i",
"]",
".",
"hasOwnProperty",
"(",
"nm",
")",
"||",
"typeof",
"arguments",
"[",
"i",
"]",
"[",
"nm",
"]",
"==",
"'function'",
")",
"{",
"if",
"(",
"typeof",
"(",
"arguments",
"[",
"i",
"]",
"[",
"nm",
"]",
")",
"==",
"'object'",
"&&",
"arguments",
"[",
"i",
"]",
"[",
"nm",
"]",
"!=",
"null",
")",
"{",
"ob1",
"[",
"prefix",
"+",
"nm",
"]",
"=",
"(",
"arguments",
"[",
"i",
"]",
"[",
"nm",
"]",
"instanceof",
"Array",
")",
"?",
"new",
"Array",
":",
"new",
"Object",
";",
"obMerge",
"(",
"''",
",",
"ob1",
"[",
"prefix",
"+",
"nm",
"]",
",",
"arguments",
"[",
"i",
"]",
"[",
"nm",
"]",
")",
";",
"}",
"else",
"{",
"ob1",
"[",
"prefix",
"+",
"nm",
"]",
"=",
"arguments",
"[",
"i",
"]",
"[",
"nm",
"]",
";",
"}",
"}",
"}",
"}",
"return",
"ob1",
";",
"}"
] | merges two or more objects into one and add prefix at the beginning of every property name at the top level
objects type is lost, only own properties copied | [
"merges",
"two",
"or",
"more",
"objects",
"into",
"one",
"and",
"add",
"prefix",
"at",
"the",
"beginning",
"of",
"every",
"property",
"name",
"at",
"the",
"top",
"level",
"objects",
"type",
"is",
"lost",
"only",
"own",
"properties",
"copied"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/htdocs/scripts/jsmart.js#L17-L38 | train |
jbaicoianu/elation | components/utils/htdocs/scripts/jsmart.js | function(e, s)
{
var parens = [];
e.tree.push(parens);
parens.parent = e.tree;
e.tree = parens;
} | javascript | function(e, s)
{
var parens = [];
e.tree.push(parens);
parens.parent = e.tree;
e.tree = parens;
} | [
"function",
"(",
"e",
",",
"s",
")",
"{",
"var",
"parens",
"=",
"[",
"]",
";",
"e",
".",
"tree",
".",
"push",
"(",
"parens",
")",
";",
"parens",
".",
"parent",
"=",
"e",
".",
"tree",
";",
"e",
".",
"tree",
"=",
"parens",
";",
"}"
] | expression in parentheses | [
"expression",
"in",
"parentheses"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/htdocs/scripts/jsmart.js#L1093-L1099 | train |
|
mongodb-js/storage-mixin | lib/backends/errback.js | function(done) {
return {
success: function(res) {
done(null, res);
},
error: function(res, err) {
done(err);
}
};
} | javascript | function(done) {
return {
success: function(res) {
done(null, res);
},
error: function(res, err) {
done(err);
}
};
} | [
"function",
"(",
"done",
")",
"{",
"return",
"{",
"success",
":",
"function",
"(",
"res",
")",
"{",
"done",
"(",
"null",
",",
"res",
")",
";",
"}",
",",
"error",
":",
"function",
"(",
"res",
",",
"err",
")",
"{",
"done",
"(",
"err",
")",
";",
"}",
"}",
";",
"}"
] | The opposite of wrapOptions, this helper wraps an errback
and returns an options object that calls the errback appropriately.
@param {Function} done
@return {Object} | [
"The",
"opposite",
"of",
"wrapOptions",
"this",
"helper",
"wraps",
"an",
"errback",
"and",
"returns",
"an",
"options",
"object",
"that",
"calls",
"the",
"errback",
"appropriately",
"."
] | 1f8c26e6db4738f6f502a9a3286d114364fe9ed8 | https://github.com/mongodb-js/storage-mixin/blob/1f8c26e6db4738f6f502a9a3286d114364fe9ed8/lib/backends/errback.js#L34-L43 | train |
|
knownasilya/interval | lib/interval.js | add | function add(base, addend) {
if (util.isDate(base)) {
return new Date(base.getTime() + interval(addend));
}
return interval(base) + interval(addend);
} | javascript | function add(base, addend) {
if (util.isDate(base)) {
return new Date(base.getTime() + interval(addend));
}
return interval(base) + interval(addend);
} | [
"function",
"add",
"(",
"base",
",",
"addend",
")",
"{",
"if",
"(",
"util",
".",
"isDate",
"(",
"base",
")",
")",
"{",
"return",
"new",
"Date",
"(",
"base",
".",
"getTime",
"(",
")",
"+",
"interval",
"(",
"addend",
")",
")",
";",
"}",
"return",
"interval",
"(",
"base",
")",
"+",
"interval",
"(",
"addend",
")",
";",
"}"
] | first parmater can be a date or an interval, second parameter has to be an interval returns the same type as the first parameter | [
"first",
"parmater",
"can",
"be",
"a",
"date",
"or",
"an",
"interval",
"second",
"parameter",
"has",
"to",
"be",
"an",
"interval",
"returns",
"the",
"same",
"type",
"as",
"the",
"first",
"parameter"
] | d8dd395944dc202f79031adeb3defe9296c5a7f8 | https://github.com/knownasilya/interval/blob/d8dd395944dc202f79031adeb3defe9296c5a7f8/lib/interval.js#L95-L100 | train |
faucet-pipeline/faucet-pipeline-sass | lib/make-sass-renderer.js | renderSass | function renderSass(options) {
return new Promise((resolve, reject) => {
try {
// using synchronous rendering because it is faster
let result = sass.renderSync(options);
result.css = fixEOF(result.css);
resolve(result);
} catch(err) {
reject(err);
}
});
} | javascript | function renderSass(options) {
return new Promise((resolve, reject) => {
try {
// using synchronous rendering because it is faster
let result = sass.renderSync(options);
result.css = fixEOF(result.css);
resolve(result);
} catch(err) {
reject(err);
}
});
} | [
"function",
"renderSass",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"try",
"{",
"let",
"result",
"=",
"sass",
".",
"renderSync",
"(",
"options",
")",
";",
"result",
".",
"css",
"=",
"fixEOF",
"(",
"result",
".",
"css",
")",
";",
"resolve",
"(",
"result",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | promisified version of sass.render | [
"promisified",
"version",
"of",
"sass",
".",
"render"
] | a9c1e40671237abdef4939dfb07e8717bb187622 | https://github.com/faucet-pipeline/faucet-pipeline-sass/blob/a9c1e40671237abdef4939dfb07e8717bb187622/lib/make-sass-renderer.js#L29-L40 | train |
jbaicoianu/elation | components/utils/scripts/sylvester.js | function(obj) {
if (obj.anchor) {
// obj is a plane or line
var P = this.elements.slice();
var C = obj.pointClosestTo(P).elements;
return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]);
} else {
// obj is a point
var Q = obj.elements || obj;
if (this.elements.length != Q.length) { return null; }
return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); });
}
} | javascript | function(obj) {
if (obj.anchor) {
// obj is a plane or line
var P = this.elements.slice();
var C = obj.pointClosestTo(P).elements;
return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]);
} else {
// obj is a point
var Q = obj.elements || obj;
if (this.elements.length != Q.length) { return null; }
return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); });
}
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"anchor",
")",
"{",
"var",
"P",
"=",
"this",
".",
"elements",
".",
"slice",
"(",
")",
";",
"var",
"C",
"=",
"obj",
".",
"pointClosestTo",
"(",
"P",
")",
".",
"elements",
";",
"return",
"Vector",
".",
"create",
"(",
"[",
"C",
"[",
"0",
"]",
"+",
"(",
"C",
"[",
"0",
"]",
"-",
"P",
"[",
"0",
"]",
")",
",",
"C",
"[",
"1",
"]",
"+",
"(",
"C",
"[",
"1",
"]",
"-",
"P",
"[",
"1",
"]",
")",
",",
"C",
"[",
"2",
"]",
"+",
"(",
"C",
"[",
"2",
"]",
"-",
"(",
"P",
"[",
"2",
"]",
"||",
"0",
")",
")",
"]",
")",
";",
"}",
"else",
"{",
"var",
"Q",
"=",
"obj",
".",
"elements",
"||",
"obj",
";",
"if",
"(",
"this",
".",
"elements",
".",
"length",
"!=",
"Q",
".",
"length",
")",
"{",
"return",
"null",
";",
"}",
"return",
"this",
".",
"map",
"(",
"function",
"(",
"x",
",",
"i",
")",
"{",
"return",
"Q",
"[",
"i",
"-",
"1",
"]",
"+",
"(",
"Q",
"[",
"i",
"-",
"1",
"]",
"-",
"x",
")",
";",
"}",
")",
";",
"}",
"}"
] | Returns the result of reflecting the point in the given point, line or plane | [
"Returns",
"the",
"result",
"of",
"reflecting",
"the",
"point",
"in",
"the",
"given",
"point",
"line",
"or",
"plane"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/sylvester.js#L264-L276 | train |
|
jbaicoianu/elation | components/utils/scripts/sylvester.js | function(obj) {
if (obj.normal) {
// obj is a plane
var A = this.anchor.elements, D = this.direction.elements;
var A1 = A[0], A2 = A[1], A3 = A[2], D1 = D[0], D2 = D[1], D3 = D[2];
var newA = this.anchor.reflectionIn(obj).elements;
// Add the line's direction vector to its anchor, then mirror that in the plane
var AD1 = A1 + D1, AD2 = A2 + D2, AD3 = A3 + D3;
var Q = obj.pointClosestTo([AD1, AD2, AD3]).elements;
var newD = [Q[0] + (Q[0] - AD1) - newA[0], Q[1] + (Q[1] - AD2) - newA[1], Q[2] + (Q[2] - AD3) - newA[2]];
return Line.create(newA, newD);
} else if (obj.direction) {
// obj is a line - reflection obtained by rotating PI radians about obj
return this.rotate(Math.PI, obj);
} else {
// obj is a point - just reflect the line's anchor in it
var P = obj.elements || obj;
return Line.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.direction);
}
} | javascript | function(obj) {
if (obj.normal) {
// obj is a plane
var A = this.anchor.elements, D = this.direction.elements;
var A1 = A[0], A2 = A[1], A3 = A[2], D1 = D[0], D2 = D[1], D3 = D[2];
var newA = this.anchor.reflectionIn(obj).elements;
// Add the line's direction vector to its anchor, then mirror that in the plane
var AD1 = A1 + D1, AD2 = A2 + D2, AD3 = A3 + D3;
var Q = obj.pointClosestTo([AD1, AD2, AD3]).elements;
var newD = [Q[0] + (Q[0] - AD1) - newA[0], Q[1] + (Q[1] - AD2) - newA[1], Q[2] + (Q[2] - AD3) - newA[2]];
return Line.create(newA, newD);
} else if (obj.direction) {
// obj is a line - reflection obtained by rotating PI radians about obj
return this.rotate(Math.PI, obj);
} else {
// obj is a point - just reflect the line's anchor in it
var P = obj.elements || obj;
return Line.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.direction);
}
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"normal",
")",
"{",
"var",
"A",
"=",
"this",
".",
"anchor",
".",
"elements",
",",
"D",
"=",
"this",
".",
"direction",
".",
"elements",
";",
"var",
"A1",
"=",
"A",
"[",
"0",
"]",
",",
"A2",
"=",
"A",
"[",
"1",
"]",
",",
"A3",
"=",
"A",
"[",
"2",
"]",
",",
"D1",
"=",
"D",
"[",
"0",
"]",
",",
"D2",
"=",
"D",
"[",
"1",
"]",
",",
"D3",
"=",
"D",
"[",
"2",
"]",
";",
"var",
"newA",
"=",
"this",
".",
"anchor",
".",
"reflectionIn",
"(",
"obj",
")",
".",
"elements",
";",
"var",
"AD1",
"=",
"A1",
"+",
"D1",
",",
"AD2",
"=",
"A2",
"+",
"D2",
",",
"AD3",
"=",
"A3",
"+",
"D3",
";",
"var",
"Q",
"=",
"obj",
".",
"pointClosestTo",
"(",
"[",
"AD1",
",",
"AD2",
",",
"AD3",
"]",
")",
".",
"elements",
";",
"var",
"newD",
"=",
"[",
"Q",
"[",
"0",
"]",
"+",
"(",
"Q",
"[",
"0",
"]",
"-",
"AD1",
")",
"-",
"newA",
"[",
"0",
"]",
",",
"Q",
"[",
"1",
"]",
"+",
"(",
"Q",
"[",
"1",
"]",
"-",
"AD2",
")",
"-",
"newA",
"[",
"1",
"]",
",",
"Q",
"[",
"2",
"]",
"+",
"(",
"Q",
"[",
"2",
"]",
"-",
"AD3",
")",
"-",
"newA",
"[",
"2",
"]",
"]",
";",
"return",
"Line",
".",
"create",
"(",
"newA",
",",
"newD",
")",
";",
"}",
"else",
"if",
"(",
"obj",
".",
"direction",
")",
"{",
"return",
"this",
".",
"rotate",
"(",
"Math",
".",
"PI",
",",
"obj",
")",
";",
"}",
"else",
"{",
"var",
"P",
"=",
"obj",
".",
"elements",
"||",
"obj",
";",
"return",
"Line",
".",
"create",
"(",
"this",
".",
"anchor",
".",
"reflectionIn",
"(",
"[",
"P",
"[",
"0",
"]",
",",
"P",
"[",
"1",
"]",
",",
"(",
"P",
"[",
"2",
"]",
"||",
"0",
")",
"]",
")",
",",
"this",
".",
"direction",
")",
";",
"}",
"}"
] | Returns the line's reflection in the given point or line | [
"Returns",
"the",
"line",
"s",
"reflection",
"in",
"the",
"given",
"point",
"or",
"line"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/sylvester.js#L973-L992 | train |
|
ericmatthys/grunt-changelog | tasks/changelog.js | getChanges | function getChanges(log, regex) {
var changes = [];
var match;
while ((match = regex.exec(log))) {
var change = '';
for (var i = 1, len = match.length; i < len; i++) {
change += match[i];
}
changes.push(change.trim());
}
return changes;
} | javascript | function getChanges(log, regex) {
var changes = [];
var match;
while ((match = regex.exec(log))) {
var change = '';
for (var i = 1, len = match.length; i < len; i++) {
change += match[i];
}
changes.push(change.trim());
}
return changes;
} | [
"function",
"getChanges",
"(",
"log",
",",
"regex",
")",
"{",
"var",
"changes",
"=",
"[",
"]",
";",
"var",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"regex",
".",
"exec",
"(",
"log",
")",
")",
")",
"{",
"var",
"change",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"1",
",",
"len",
"=",
"match",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"change",
"+=",
"match",
"[",
"i",
"]",
";",
"}",
"changes",
".",
"push",
"(",
"change",
".",
"trim",
"(",
")",
")",
";",
"}",
"return",
"changes",
";",
"}"
] | Loop through each match and build the array of changes that will be passed to the template. | [
"Loop",
"through",
"each",
"match",
"and",
"build",
"the",
"array",
"of",
"changes",
"that",
"will",
"be",
"passed",
"to",
"the",
"template",
"."
] | 24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6 | https://github.com/ericmatthys/grunt-changelog/blob/24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6/tasks/changelog.js#L76-L91 | train |
ericmatthys/grunt-changelog | tasks/changelog.js | getChangelog | function getChangelog(log) {
var data = {
date: moment().format('YYYY-MM-DD'),
features: getChanges(log, options.featureRegex),
fixes: getChanges(log, options.fixRegex)
};
return template(data);
} | javascript | function getChangelog(log) {
var data = {
date: moment().format('YYYY-MM-DD'),
features: getChanges(log, options.featureRegex),
fixes: getChanges(log, options.fixRegex)
};
return template(data);
} | [
"function",
"getChangelog",
"(",
"log",
")",
"{",
"var",
"data",
"=",
"{",
"date",
":",
"moment",
"(",
")",
".",
"format",
"(",
"'YYYY-MM-DD'",
")",
",",
"features",
":",
"getChanges",
"(",
"log",
",",
"options",
".",
"featureRegex",
")",
",",
"fixes",
":",
"getChanges",
"(",
"log",
",",
"options",
".",
"fixRegex",
")",
"}",
";",
"return",
"template",
"(",
"data",
")",
";",
"}"
] | Generate the changelog using the templates defined in options. | [
"Generate",
"the",
"changelog",
"using",
"the",
"templates",
"defined",
"in",
"options",
"."
] | 24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6 | https://github.com/ericmatthys/grunt-changelog/blob/24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6/tasks/changelog.js#L94-L102 | train |
ericmatthys/grunt-changelog | tasks/changelog.js | writeChangelog | function writeChangelog(changelog) {
var fileContents = null;
var firstLineFile = null;
var firstLineFileHeader = null;
var regex = null;
if (options.insertType && grunt.file.exists(options.dest)) {
fileContents = grunt.file.read(options.dest);
firstLineFile = fileContents.split('\n')[0];
grunt.log.debug('firstLineFile = ' + firstLineFile);
switch (options.insertType) {
case 'prepend':
changelog = changelog + '\n' + fileContents;
break;
case 'append':
changelog = fileContents + '\n' + changelog;
break;
default:
grunt.fatal('"' + options.insertType + '" is not a valid insertType. Please use "append" or "prepend".');
return false;
}
}
if (options.fileHeader) {
firstLineFileHeader = options.fileHeader.split('\n')[0];
grunt.log.debug('firstLineFileHeader = ' + firstLineFileHeader);
if (options.insertType === 'prepend') {
if (firstLineFile !== firstLineFileHeader) {
changelog = options.fileHeader + '\n\n' + changelog;
} else {
regex = new RegExp(options.fileHeader+'\n\n','m');
changelog = options.fileHeader + '\n\n' + changelog.replace(regex, '');
}
// insertType === 'append' || undefined
} else {
if (firstLineFile !== firstLineFileHeader) {
changelog = options.fileHeader + '\n\n' + changelog;
}
}
}
grunt.file.write(options.dest, changelog);
// Log the results.
grunt.log.ok(changelog);
grunt.log.writeln();
grunt.log.writeln('Changelog created at '+ options.dest.toString().cyan + '.');
} | javascript | function writeChangelog(changelog) {
var fileContents = null;
var firstLineFile = null;
var firstLineFileHeader = null;
var regex = null;
if (options.insertType && grunt.file.exists(options.dest)) {
fileContents = grunt.file.read(options.dest);
firstLineFile = fileContents.split('\n')[0];
grunt.log.debug('firstLineFile = ' + firstLineFile);
switch (options.insertType) {
case 'prepend':
changelog = changelog + '\n' + fileContents;
break;
case 'append':
changelog = fileContents + '\n' + changelog;
break;
default:
grunt.fatal('"' + options.insertType + '" is not a valid insertType. Please use "append" or "prepend".');
return false;
}
}
if (options.fileHeader) {
firstLineFileHeader = options.fileHeader.split('\n')[0];
grunt.log.debug('firstLineFileHeader = ' + firstLineFileHeader);
if (options.insertType === 'prepend') {
if (firstLineFile !== firstLineFileHeader) {
changelog = options.fileHeader + '\n\n' + changelog;
} else {
regex = new RegExp(options.fileHeader+'\n\n','m');
changelog = options.fileHeader + '\n\n' + changelog.replace(regex, '');
}
// insertType === 'append' || undefined
} else {
if (firstLineFile !== firstLineFileHeader) {
changelog = options.fileHeader + '\n\n' + changelog;
}
}
}
grunt.file.write(options.dest, changelog);
// Log the results.
grunt.log.ok(changelog);
grunt.log.writeln();
grunt.log.writeln('Changelog created at '+ options.dest.toString().cyan + '.');
} | [
"function",
"writeChangelog",
"(",
"changelog",
")",
"{",
"var",
"fileContents",
"=",
"null",
";",
"var",
"firstLineFile",
"=",
"null",
";",
"var",
"firstLineFileHeader",
"=",
"null",
";",
"var",
"regex",
"=",
"null",
";",
"if",
"(",
"options",
".",
"insertType",
"&&",
"grunt",
".",
"file",
".",
"exists",
"(",
"options",
".",
"dest",
")",
")",
"{",
"fileContents",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"options",
".",
"dest",
")",
";",
"firstLineFile",
"=",
"fileContents",
".",
"split",
"(",
"'\\n'",
")",
"[",
"\\n",
"]",
";",
"0",
"grunt",
".",
"log",
".",
"debug",
"(",
"'firstLineFile = '",
"+",
"firstLineFile",
")",
";",
"}",
"switch",
"(",
"options",
".",
"insertType",
")",
"{",
"case",
"'prepend'",
":",
"changelog",
"=",
"changelog",
"+",
"'\\n'",
"+",
"\\n",
";",
"fileContents",
"break",
";",
"case",
"'append'",
":",
"changelog",
"=",
"fileContents",
"+",
"'\\n'",
"+",
"\\n",
";",
"changelog",
"}",
"break",
";",
"default",
":",
"grunt",
".",
"fatal",
"(",
"'\"'",
"+",
"options",
".",
"insertType",
"+",
"'\" is not a valid insertType. Please use \"append\" or \"prepend\".'",
")",
";",
"return",
"false",
";",
"if",
"(",
"options",
".",
"fileHeader",
")",
"{",
"firstLineFileHeader",
"=",
"options",
".",
"fileHeader",
".",
"split",
"(",
"'\\n'",
")",
"[",
"\\n",
"]",
";",
"0",
"grunt",
".",
"log",
".",
"debug",
"(",
"'firstLineFileHeader = '",
"+",
"firstLineFileHeader",
")",
";",
"}",
"if",
"(",
"options",
".",
"insertType",
"===",
"'prepend'",
")",
"{",
"if",
"(",
"firstLineFile",
"!==",
"firstLineFileHeader",
")",
"{",
"changelog",
"=",
"options",
".",
"fileHeader",
"+",
"'\\n\\n'",
"+",
"\\n",
";",
"}",
"else",
"\\n",
"}",
"else",
"changelog",
"}"
] | Write the changelog to the destination file. | [
"Write",
"the",
"changelog",
"to",
"the",
"destination",
"file",
"."
] | 24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6 | https://github.com/ericmatthys/grunt-changelog/blob/24bc2a0a5ba0bdfb3d46d4fbb10763181eab25e6/tasks/changelog.js#L105-L157 | train |
mia-js/mia-js-core | lib/routesHandler/lib/initializeRoutes.js | function (preconditions) {
var errorCodesList = {
"500": ["InternalServerError"],
"400": [
"UnexpectedDefaultValue",
"UnexpectedType",
"MinLengthUnderachieved",
"MaxLengthExceeded",
"MinValueUnderachived",
"MaxValueExceeded",
"ValueNotAllowed",
"PatternMismatch",
"MissingRequiredParameter"],
"429": ["RateLimitExceeded"],
};
for (var index in preconditions) {
if (preconditions[index].conditions && preconditions[index].conditions.responses) {
for (var code in preconditions[index].conditions.responses) {
if (errorCodesList[code]) {
if (_.isArray(preconditions[index].conditions.responses[code])) {
for (var ecode in preconditions[index].conditions.responses[code]) {
if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code][ecode]) == -1) {
errorCodesList[code].push(preconditions[index].conditions.responses[code][ecode]);
}
}
}
else {
if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code]) == -1) {
errorCodesList[code].push(preconditions[index].conditions.responses[code]);
}
}
}
else {
if (_.isArray(preconditions[index].conditions.responses[code])) {
errorCodesList[code] = _.clone(preconditions[index].conditions.responses[code]);
}
else {
errorCodesList[code] = [_.clone(preconditions[index].conditions.responses[code])];
}
}
}
}
}
return errorCodesList;
} | javascript | function (preconditions) {
var errorCodesList = {
"500": ["InternalServerError"],
"400": [
"UnexpectedDefaultValue",
"UnexpectedType",
"MinLengthUnderachieved",
"MaxLengthExceeded",
"MinValueUnderachived",
"MaxValueExceeded",
"ValueNotAllowed",
"PatternMismatch",
"MissingRequiredParameter"],
"429": ["RateLimitExceeded"],
};
for (var index in preconditions) {
if (preconditions[index].conditions && preconditions[index].conditions.responses) {
for (var code in preconditions[index].conditions.responses) {
if (errorCodesList[code]) {
if (_.isArray(preconditions[index].conditions.responses[code])) {
for (var ecode in preconditions[index].conditions.responses[code]) {
if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code][ecode]) == -1) {
errorCodesList[code].push(preconditions[index].conditions.responses[code][ecode]);
}
}
}
else {
if (_.indexOf(errorCodesList[code], preconditions[index].conditions.responses[code]) == -1) {
errorCodesList[code].push(preconditions[index].conditions.responses[code]);
}
}
}
else {
if (_.isArray(preconditions[index].conditions.responses[code])) {
errorCodesList[code] = _.clone(preconditions[index].conditions.responses[code]);
}
else {
errorCodesList[code] = [_.clone(preconditions[index].conditions.responses[code])];
}
}
}
}
}
return errorCodesList;
} | [
"function",
"(",
"preconditions",
")",
"{",
"var",
"errorCodesList",
"=",
"{",
"\"500\"",
":",
"[",
"\"InternalServerError\"",
"]",
",",
"\"400\"",
":",
"[",
"\"UnexpectedDefaultValue\"",
",",
"\"UnexpectedType\"",
",",
"\"MinLengthUnderachieved\"",
",",
"\"MaxLengthExceeded\"",
",",
"\"MinValueUnderachived\"",
",",
"\"MaxValueExceeded\"",
",",
"\"ValueNotAllowed\"",
",",
"\"PatternMismatch\"",
",",
"\"MissingRequiredParameter\"",
"]",
",",
"\"429\"",
":",
"[",
"\"RateLimitExceeded\"",
"]",
",",
"}",
";",
"for",
"(",
"var",
"index",
"in",
"preconditions",
")",
"{",
"if",
"(",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
"&&",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
")",
"{",
"for",
"(",
"var",
"code",
"in",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
")",
"{",
"if",
"(",
"errorCodesList",
"[",
"code",
"]",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
")",
")",
"{",
"for",
"(",
"var",
"ecode",
"in",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
")",
"{",
"if",
"(",
"_",
".",
"indexOf",
"(",
"errorCodesList",
"[",
"code",
"]",
",",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
"[",
"ecode",
"]",
")",
"==",
"-",
"1",
")",
"{",
"errorCodesList",
"[",
"code",
"]",
".",
"push",
"(",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
"[",
"ecode",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"indexOf",
"(",
"errorCodesList",
"[",
"code",
"]",
",",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
")",
"==",
"-",
"1",
")",
"{",
"errorCodesList",
"[",
"code",
"]",
".",
"push",
"(",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
")",
")",
"{",
"errorCodesList",
"[",
"code",
"]",
"=",
"_",
".",
"clone",
"(",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
")",
";",
"}",
"else",
"{",
"errorCodesList",
"[",
"code",
"]",
"=",
"[",
"_",
".",
"clone",
"(",
"preconditions",
"[",
"index",
"]",
".",
"conditions",
".",
"responses",
"[",
"code",
"]",
")",
"]",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"errorCodesList",
";",
"}"
] | Returns a list of http codes defined in preconditions section in controller | [
"Returns",
"a",
"list",
"of",
"http",
"codes",
"defined",
"in",
"preconditions",
"section",
"in",
"controller"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L88-L132 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/initializeRoutes.js | function (attr, attrName) {
if (_.isObject(attr) && !_.isDate(attr) && !_.isBoolean(attr) && !_.isString(attr) && !_.isNumber(attr) && !_.isFunction(attr) && !_.isRegExp(attr) && !_.isArray(attr)) {
//attr = _removeAttributes();
for (var aIndex in attr) {
attr[aIndex] = _removeAttributes(attr[aIndex], aIndex);
}
return attr;
}
else {
if (_.indexOf(allowedAttributes, attrName) != -1) {
if (_.isFunction(attr)) {
attr = _functionName(attr);
}
return attr;
}
else {
return;
}
}
} | javascript | function (attr, attrName) {
if (_.isObject(attr) && !_.isDate(attr) && !_.isBoolean(attr) && !_.isString(attr) && !_.isNumber(attr) && !_.isFunction(attr) && !_.isRegExp(attr) && !_.isArray(attr)) {
//attr = _removeAttributes();
for (var aIndex in attr) {
attr[aIndex] = _removeAttributes(attr[aIndex], aIndex);
}
return attr;
}
else {
if (_.indexOf(allowedAttributes, attrName) != -1) {
if (_.isFunction(attr)) {
attr = _functionName(attr);
}
return attr;
}
else {
return;
}
}
} | [
"function",
"(",
"attr",
",",
"attrName",
")",
"{",
"if",
"(",
"_",
".",
"isObject",
"(",
"attr",
")",
"&&",
"!",
"_",
".",
"isDate",
"(",
"attr",
")",
"&&",
"!",
"_",
".",
"isBoolean",
"(",
"attr",
")",
"&&",
"!",
"_",
".",
"isString",
"(",
"attr",
")",
"&&",
"!",
"_",
".",
"isNumber",
"(",
"attr",
")",
"&&",
"!",
"_",
".",
"isFunction",
"(",
"attr",
")",
"&&",
"!",
"_",
".",
"isRegExp",
"(",
"attr",
")",
"&&",
"!",
"_",
".",
"isArray",
"(",
"attr",
")",
")",
"{",
"for",
"(",
"var",
"aIndex",
"in",
"attr",
")",
"{",
"attr",
"[",
"aIndex",
"]",
"=",
"_removeAttributes",
"(",
"attr",
"[",
"aIndex",
"]",
",",
"aIndex",
")",
";",
"}",
"return",
"attr",
";",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"indexOf",
"(",
"allowedAttributes",
",",
"attrName",
")",
"!=",
"-",
"1",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"attr",
")",
")",
"{",
"attr",
"=",
"_functionName",
"(",
"attr",
")",
";",
"}",
"return",
"attr",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"}"
] | Remove attributes recursively | [
"Remove",
"attributes",
"recursively"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L148-L168 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/initializeRoutes.js | function (parametersList, parameters, section) {
if (parameters[section]) {
for (var name in parameters[section]) {
var addCondition = parameters[section][name];
if (parametersList[section] && parametersList[section][name]) {
// Merge parameters attributes
for (var attr in addCondition) {
if (_.has(parametersList, [section, name, attr]) === false) {
// Attribute does not exists -> add to list
parametersList[section][name][attr] = addCondition[attr];
} else {
// Attribute already exists compare values
if (_.isFunction(addCondition[attr])) {
addCondition[attr] = _functionName(addCondition[attr]);
}
if (JSON.stringify(parametersList[section][name][attr]) != JSON.stringify(addCondition[attr])) {
throw new Error("Precondition conflict: " + preconditions[index].name + ' -> ' + preconditions[index].version + ' -> ' + preconditions[index].method + ' -> ' + attr + ':' + addCondition[attr] + ' -> already defined in previous controller and value is mismatching');
}
else {
parametersList[section][name][attr] = addCondition[attr];
}
}
}
} else {
parametersList[section] = parametersList[section] ? parametersList[section] : {};
parametersList[section][name] = addCondition;
}
// Filter parameter attributes by allowedAttributes
var validatedParameterAttributes = {};
if (_.has(parametersList, [section, name])) {
for (var attr in parametersList[section][name]) {
validatedParameterAttributes[attr] = _removeAttributes(parametersList[section][name][attr], attr);
}
}
if (!_.isEmpty(validatedParameterAttributes)) {
parametersList[section][name] = validatedParameterAttributes;
}
}
}
return parametersList;
} | javascript | function (parametersList, parameters, section) {
if (parameters[section]) {
for (var name in parameters[section]) {
var addCondition = parameters[section][name];
if (parametersList[section] && parametersList[section][name]) {
// Merge parameters attributes
for (var attr in addCondition) {
if (_.has(parametersList, [section, name, attr]) === false) {
// Attribute does not exists -> add to list
parametersList[section][name][attr] = addCondition[attr];
} else {
// Attribute already exists compare values
if (_.isFunction(addCondition[attr])) {
addCondition[attr] = _functionName(addCondition[attr]);
}
if (JSON.stringify(parametersList[section][name][attr]) != JSON.stringify(addCondition[attr])) {
throw new Error("Precondition conflict: " + preconditions[index].name + ' -> ' + preconditions[index].version + ' -> ' + preconditions[index].method + ' -> ' + attr + ':' + addCondition[attr] + ' -> already defined in previous controller and value is mismatching');
}
else {
parametersList[section][name][attr] = addCondition[attr];
}
}
}
} else {
parametersList[section] = parametersList[section] ? parametersList[section] : {};
parametersList[section][name] = addCondition;
}
// Filter parameter attributes by allowedAttributes
var validatedParameterAttributes = {};
if (_.has(parametersList, [section, name])) {
for (var attr in parametersList[section][name]) {
validatedParameterAttributes[attr] = _removeAttributes(parametersList[section][name][attr], attr);
}
}
if (!_.isEmpty(validatedParameterAttributes)) {
parametersList[section][name] = validatedParameterAttributes;
}
}
}
return parametersList;
} | [
"function",
"(",
"parametersList",
",",
"parameters",
",",
"section",
")",
"{",
"if",
"(",
"parameters",
"[",
"section",
"]",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"parameters",
"[",
"section",
"]",
")",
"{",
"var",
"addCondition",
"=",
"parameters",
"[",
"section",
"]",
"[",
"name",
"]",
";",
"if",
"(",
"parametersList",
"[",
"section",
"]",
"&&",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
")",
"{",
"for",
"(",
"var",
"attr",
"in",
"addCondition",
")",
"{",
"if",
"(",
"_",
".",
"has",
"(",
"parametersList",
",",
"[",
"section",
",",
"name",
",",
"attr",
"]",
")",
"===",
"false",
")",
"{",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
"[",
"attr",
"]",
"=",
"addCondition",
"[",
"attr",
"]",
";",
"}",
"else",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"addCondition",
"[",
"attr",
"]",
")",
")",
"{",
"addCondition",
"[",
"attr",
"]",
"=",
"_functionName",
"(",
"addCondition",
"[",
"attr",
"]",
")",
";",
"}",
"if",
"(",
"JSON",
".",
"stringify",
"(",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
"[",
"attr",
"]",
")",
"!=",
"JSON",
".",
"stringify",
"(",
"addCondition",
"[",
"attr",
"]",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Precondition conflict: \"",
"+",
"preconditions",
"[",
"index",
"]",
".",
"name",
"+",
"' -> '",
"+",
"preconditions",
"[",
"index",
"]",
".",
"version",
"+",
"' -> '",
"+",
"preconditions",
"[",
"index",
"]",
".",
"method",
"+",
"' -> '",
"+",
"attr",
"+",
"':'",
"+",
"addCondition",
"[",
"attr",
"]",
"+",
"' -> already defined in previous controller and value is mismatching'",
")",
";",
"}",
"else",
"{",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
"[",
"attr",
"]",
"=",
"addCondition",
"[",
"attr",
"]",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"parametersList",
"[",
"section",
"]",
"=",
"parametersList",
"[",
"section",
"]",
"?",
"parametersList",
"[",
"section",
"]",
":",
"{",
"}",
";",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
"=",
"addCondition",
";",
"}",
"var",
"validatedParameterAttributes",
"=",
"{",
"}",
";",
"if",
"(",
"_",
".",
"has",
"(",
"parametersList",
",",
"[",
"section",
",",
"name",
"]",
")",
")",
"{",
"for",
"(",
"var",
"attr",
"in",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
")",
"{",
"validatedParameterAttributes",
"[",
"attr",
"]",
"=",
"_removeAttributes",
"(",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
"[",
"attr",
"]",
",",
"attr",
")",
";",
"}",
"}",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"validatedParameterAttributes",
")",
")",
"{",
"parametersList",
"[",
"section",
"]",
"[",
"name",
"]",
"=",
"validatedParameterAttributes",
";",
"}",
"}",
"}",
"return",
"parametersList",
";",
"}"
] | Parse preconditions parameters in section header, query, body | [
"Parse",
"preconditions",
"parameters",
"in",
"section",
"header",
"query",
"body"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L171-L215 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/initializeRoutes.js | function (req, res, next) {
if (!req.miajs.controllerDebugInfo) {
req.miajs.controllerDebugInfo = {};
}
if (controller.name && controller.version) {
req.miajs.controllerDebugInfo[controller.name + '_' + controller.version] = {'runtime': Date.now() - req.miajs.controllerStart};
}
next();
} | javascript | function (req, res, next) {
if (!req.miajs.controllerDebugInfo) {
req.miajs.controllerDebugInfo = {};
}
if (controller.name && controller.version) {
req.miajs.controllerDebugInfo[controller.name + '_' + controller.version] = {'runtime': Date.now() - req.miajs.controllerStart};
}
next();
} | [
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"!",
"req",
".",
"miajs",
".",
"controllerDebugInfo",
")",
"{",
"req",
".",
"miajs",
".",
"controllerDebugInfo",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"controller",
".",
"name",
"&&",
"controller",
".",
"version",
")",
"{",
"req",
".",
"miajs",
".",
"controllerDebugInfo",
"[",
"controller",
".",
"name",
"+",
"'_'",
"+",
"controller",
".",
"version",
"]",
"=",
"{",
"'runtime'",
":",
"Date",
".",
"now",
"(",
")",
"-",
"req",
".",
"miajs",
".",
"controllerStart",
"}",
";",
"}",
"next",
"(",
")",
";",
"}"
] | Measure runtime of controller | [
"Measure",
"runtime",
"of",
"controller"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L381-L389 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/initializeRoutes.js | function (routeConfig, methodValue) {
var rateLimits = [];
var environment = Shared.config("environment");
var globalRateLimit = environment.rateLimit;
if (globalRateLimit) {
if (globalRateLimit.interval && _.isNumber(globalRateLimit.interval) && parseInt(globalRateLimit.interval) > 0 && globalRateLimit.maxRequests && _.isNumber(globalRateLimit.maxRequests) && parseInt(globalRateLimit.maxRequests) > 0) {
rateLimits.push(globalRateLimit);
}
else {
throw new Error('Global rate limit config invalid' + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (routeConfig && routeConfig.rateLimit) {
if (routeConfig.rateLimit.interval && _.isNumber(routeConfig.rateLimit.interval) && parseInt(routeConfig.rateLimit.interval) > 0 && routeConfig.rateLimit.maxRequests && _.isNumber(routeConfig.rateLimit.maxRequests) && parseInt(routeConfig.rateLimit.maxRequests) > 0) {
rateLimits.push(routeConfig.rateLimit);
}
else {
throw new Error('Rate limit config invalid for route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (methodValue && methodValue.rateLimit) {
if (methodValue.rateLimit.interval && _.isNumber(methodValue.rateLimit.interval) && parseInt(methodValue.rateLimit.interval) > 0 && methodValue.rateLimit.maxRequests && _.isNumber(methodValue.rateLimit.maxRequests) && parseInt(methodValue.rateLimit.maxRequests) > 0) {
rateLimits.push(methodValue.rateLimit);
}
else {
throw new Error('Rate limit config invalid for route ' + methodValue.identity + ' in route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (!_.isEmpty(rateLimits) && !Shared.memcached()) {
throw new Error("Rate limits set but memcached not configured. Provide settings for memcached in environment config file");
}
return rateLimits;
} | javascript | function (routeConfig, methodValue) {
var rateLimits = [];
var environment = Shared.config("environment");
var globalRateLimit = environment.rateLimit;
if (globalRateLimit) {
if (globalRateLimit.interval && _.isNumber(globalRateLimit.interval) && parseInt(globalRateLimit.interval) > 0 && globalRateLimit.maxRequests && _.isNumber(globalRateLimit.maxRequests) && parseInt(globalRateLimit.maxRequests) > 0) {
rateLimits.push(globalRateLimit);
}
else {
throw new Error('Global rate limit config invalid' + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (routeConfig && routeConfig.rateLimit) {
if (routeConfig.rateLimit.interval && _.isNumber(routeConfig.rateLimit.interval) && parseInt(routeConfig.rateLimit.interval) > 0 && routeConfig.rateLimit.maxRequests && _.isNumber(routeConfig.rateLimit.maxRequests) && parseInt(routeConfig.rateLimit.maxRequests) > 0) {
rateLimits.push(routeConfig.rateLimit);
}
else {
throw new Error('Rate limit config invalid for route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (methodValue && methodValue.rateLimit) {
if (methodValue.rateLimit.interval && _.isNumber(methodValue.rateLimit.interval) && parseInt(methodValue.rateLimit.interval) > 0 && methodValue.rateLimit.maxRequests && _.isNumber(methodValue.rateLimit.maxRequests) && parseInt(methodValue.rateLimit.maxRequests) > 0) {
rateLimits.push(methodValue.rateLimit);
}
else {
throw new Error('Rate limit config invalid for route ' + methodValue.identity + ' in route file ' + routeConfig.prefix + ". Provide parameters 'interval' and 'maxRequests' with Int value");
}
}
if (!_.isEmpty(rateLimits) && !Shared.memcached()) {
throw new Error("Rate limits set but memcached not configured. Provide settings for memcached in environment config file");
}
return rateLimits;
} | [
"function",
"(",
"routeConfig",
",",
"methodValue",
")",
"{",
"var",
"rateLimits",
"=",
"[",
"]",
";",
"var",
"environment",
"=",
"Shared",
".",
"config",
"(",
"\"environment\"",
")",
";",
"var",
"globalRateLimit",
"=",
"environment",
".",
"rateLimit",
";",
"if",
"(",
"globalRateLimit",
")",
"{",
"if",
"(",
"globalRateLimit",
".",
"interval",
"&&",
"_",
".",
"isNumber",
"(",
"globalRateLimit",
".",
"interval",
")",
"&&",
"parseInt",
"(",
"globalRateLimit",
".",
"interval",
")",
">",
"0",
"&&",
"globalRateLimit",
".",
"maxRequests",
"&&",
"_",
".",
"isNumber",
"(",
"globalRateLimit",
".",
"maxRequests",
")",
"&&",
"parseInt",
"(",
"globalRateLimit",
".",
"maxRequests",
")",
">",
"0",
")",
"{",
"rateLimits",
".",
"push",
"(",
"globalRateLimit",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Global rate limit config invalid'",
"+",
"\". Provide parameters 'interval' and 'maxRequests' with Int value\"",
")",
";",
"}",
"}",
"if",
"(",
"routeConfig",
"&&",
"routeConfig",
".",
"rateLimit",
")",
"{",
"if",
"(",
"routeConfig",
".",
"rateLimit",
".",
"interval",
"&&",
"_",
".",
"isNumber",
"(",
"routeConfig",
".",
"rateLimit",
".",
"interval",
")",
"&&",
"parseInt",
"(",
"routeConfig",
".",
"rateLimit",
".",
"interval",
")",
">",
"0",
"&&",
"routeConfig",
".",
"rateLimit",
".",
"maxRequests",
"&&",
"_",
".",
"isNumber",
"(",
"routeConfig",
".",
"rateLimit",
".",
"maxRequests",
")",
"&&",
"parseInt",
"(",
"routeConfig",
".",
"rateLimit",
".",
"maxRequests",
")",
">",
"0",
")",
"{",
"rateLimits",
".",
"push",
"(",
"routeConfig",
".",
"rateLimit",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Rate limit config invalid for route file '",
"+",
"routeConfig",
".",
"prefix",
"+",
"\". Provide parameters 'interval' and 'maxRequests' with Int value\"",
")",
";",
"}",
"}",
"if",
"(",
"methodValue",
"&&",
"methodValue",
".",
"rateLimit",
")",
"{",
"if",
"(",
"methodValue",
".",
"rateLimit",
".",
"interval",
"&&",
"_",
".",
"isNumber",
"(",
"methodValue",
".",
"rateLimit",
".",
"interval",
")",
"&&",
"parseInt",
"(",
"methodValue",
".",
"rateLimit",
".",
"interval",
")",
">",
"0",
"&&",
"methodValue",
".",
"rateLimit",
".",
"maxRequests",
"&&",
"_",
".",
"isNumber",
"(",
"methodValue",
".",
"rateLimit",
".",
"maxRequests",
")",
"&&",
"parseInt",
"(",
"methodValue",
".",
"rateLimit",
".",
"maxRequests",
")",
">",
"0",
")",
"{",
"rateLimits",
".",
"push",
"(",
"methodValue",
".",
"rateLimit",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Rate limit config invalid for route '",
"+",
"methodValue",
".",
"identity",
"+",
"' in route file '",
"+",
"routeConfig",
".",
"prefix",
"+",
"\". Provide parameters 'interval' and 'maxRequests' with Int value\"",
")",
";",
"}",
"}",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"rateLimits",
")",
"&&",
"!",
"Shared",
".",
"memcached",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Rate limits set but memcached not configured. Provide settings for memcached in environment config file\"",
")",
";",
"}",
"return",
"rateLimits",
";",
"}"
] | Validate rate limits settings | [
"Validate",
"rate",
"limits",
"settings"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L459-L493 | train |
|
mia-js/mia-js-core | lib/routesHandler/lib/initializeRoutes.js | function (req, res, next) {
var ip = IPAddressHelper.getClientIP(req)
, route = req.miajs.route
, key = ip + route.path + route.method;
if (_.isEmpty(route.rateLimits)) {
next();
return;
}
RateLimiter.checkRateLimitsByKey(key, route.rateLimits).then(function (rateLimiterResult) {
if (rateLimiterResult.remaining == -1) {
_logInfo("Rate limit of " + rateLimiterResult.limit + "req/" + rateLimiterResult.timeInterval + "min requests exceeded " + route.requestmethod.toUpperCase() + " " + route.url + " for " + ip);
res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
res.header("X-Rate-Limit-Remaining", 0);
res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
next(new MiaError({
status: 429,
err: {
'code': 'RateLimitExceeded',
'msg': Translator('system', 'RateLimitExceeded')
}
}));
}
else {
res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
res.header("X-Rate-Limit-Remaining", rateLimiterResult.remaining);
res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
next();
}
}).catch(function () {
next();
});
} | javascript | function (req, res, next) {
var ip = IPAddressHelper.getClientIP(req)
, route = req.miajs.route
, key = ip + route.path + route.method;
if (_.isEmpty(route.rateLimits)) {
next();
return;
}
RateLimiter.checkRateLimitsByKey(key, route.rateLimits).then(function (rateLimiterResult) {
if (rateLimiterResult.remaining == -1) {
_logInfo("Rate limit of " + rateLimiterResult.limit + "req/" + rateLimiterResult.timeInterval + "min requests exceeded " + route.requestmethod.toUpperCase() + " " + route.url + " for " + ip);
res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
res.header("X-Rate-Limit-Remaining", 0);
res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
next(new MiaError({
status: 429,
err: {
'code': 'RateLimitExceeded',
'msg': Translator('system', 'RateLimitExceeded')
}
}));
}
else {
res.header("X-Rate-Limit-Limit", rateLimiterResult.limit);
res.header("X-Rate-Limit-Remaining", rateLimiterResult.remaining);
res.header("X-Rate-Limit-Reset", rateLimiterResult.timeTillReset);
next();
}
}).catch(function () {
next();
});
} | [
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"ip",
"=",
"IPAddressHelper",
".",
"getClientIP",
"(",
"req",
")",
",",
"route",
"=",
"req",
".",
"miajs",
".",
"route",
",",
"key",
"=",
"ip",
"+",
"route",
".",
"path",
"+",
"route",
".",
"method",
";",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"route",
".",
"rateLimits",
")",
")",
"{",
"next",
"(",
")",
";",
"return",
";",
"}",
"RateLimiter",
".",
"checkRateLimitsByKey",
"(",
"key",
",",
"route",
".",
"rateLimits",
")",
".",
"then",
"(",
"function",
"(",
"rateLimiterResult",
")",
"{",
"if",
"(",
"rateLimiterResult",
".",
"remaining",
"==",
"-",
"1",
")",
"{",
"_logInfo",
"(",
"\"Rate limit of \"",
"+",
"rateLimiterResult",
".",
"limit",
"+",
"\"req/\"",
"+",
"rateLimiterResult",
".",
"timeInterval",
"+",
"\"min requests exceeded \"",
"+",
"route",
".",
"requestmethod",
".",
"toUpperCase",
"(",
")",
"+",
"\" \"",
"+",
"route",
".",
"url",
"+",
"\" for \"",
"+",
"ip",
")",
";",
"res",
".",
"header",
"(",
"\"X-Rate-Limit-Limit\"",
",",
"rateLimiterResult",
".",
"limit",
")",
";",
"res",
".",
"header",
"(",
"\"X-Rate-Limit-Remaining\"",
",",
"0",
")",
";",
"res",
".",
"header",
"(",
"\"X-Rate-Limit-Reset\"",
",",
"rateLimiterResult",
".",
"timeTillReset",
")",
";",
"next",
"(",
"new",
"MiaError",
"(",
"{",
"status",
":",
"429",
",",
"err",
":",
"{",
"'code'",
":",
"'RateLimitExceeded'",
",",
"'msg'",
":",
"Translator",
"(",
"'system'",
",",
"'RateLimitExceeded'",
")",
"}",
"}",
")",
")",
";",
"}",
"else",
"{",
"res",
".",
"header",
"(",
"\"X-Rate-Limit-Limit\"",
",",
"rateLimiterResult",
".",
"limit",
")",
";",
"res",
".",
"header",
"(",
"\"X-Rate-Limit-Remaining\"",
",",
"rateLimiterResult",
".",
"remaining",
")",
";",
"res",
".",
"header",
"(",
"\"X-Rate-Limit-Reset\"",
",",
"rateLimiterResult",
".",
"timeTillReset",
")",
";",
"next",
"(",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"next",
"(",
")",
";",
"}",
")",
";",
"}"
] | Route for rate limits check | [
"Route",
"for",
"rate",
"limits",
"check"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/routesHandler/lib/initializeRoutes.js#L497-L530 | train |
|
mia-js/mia-js-core | lib/rateLimiter/lib/rateLimiter.js | function (range) {
var coeff = 1000 * 60 * range;
return new Date(Math.ceil(new Date(Date.now()).getTime() / coeff) * coeff).getTime() / 1000;
} | javascript | function (range) {
var coeff = 1000 * 60 * range;
return new Date(Math.ceil(new Date(Date.now()).getTime() / coeff) * coeff).getTime() / 1000;
} | [
"function",
"(",
"range",
")",
"{",
"var",
"coeff",
"=",
"1000",
"*",
"60",
"*",
"range",
";",
"return",
"new",
"Date",
"(",
"Math",
".",
"ceil",
"(",
"new",
"Date",
"(",
"Date",
".",
"now",
"(",
")",
")",
".",
"getTime",
"(",
")",
"/",
"coeff",
")",
"*",
"coeff",
")",
".",
"getTime",
"(",
")",
"/",
"1000",
";",
"}"
] | Calculate current time interval slot | [
"Calculate",
"current",
"time",
"interval",
"slot"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/rateLimiter/lib/rateLimiter.js#L21-L24 | train |
|
mia-js/mia-js-core | lib/rateLimiter/lib/rateLimiter.js | function (key, timeInterval, limit) {
//Validate rate limiter settings
if (!_.isNumber(timeInterval) || parseInt(timeInterval) <= 0 || !_.isNumber(limit) || parseInt(limit) <= 0) {
return Q.reject();
}
var cacheKey = Encryption.md5("MiaJSRateLimit" + key + _calculateCurrentTimeInterval(timeInterval));
return _validateRateLimit(cacheKey, timeInterval, limit).then(function (value) {
return Q({
limit: limit,
remaining: limit - value,
timeInterval: timeInterval,
timeTillReset: _getTimeLeftTillReset(timeInterval)
});
});
} | javascript | function (key, timeInterval, limit) {
//Validate rate limiter settings
if (!_.isNumber(timeInterval) || parseInt(timeInterval) <= 0 || !_.isNumber(limit) || parseInt(limit) <= 0) {
return Q.reject();
}
var cacheKey = Encryption.md5("MiaJSRateLimit" + key + _calculateCurrentTimeInterval(timeInterval));
return _validateRateLimit(cacheKey, timeInterval, limit).then(function (value) {
return Q({
limit: limit,
remaining: limit - value,
timeInterval: timeInterval,
timeTillReset: _getTimeLeftTillReset(timeInterval)
});
});
} | [
"function",
"(",
"key",
",",
"timeInterval",
",",
"limit",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isNumber",
"(",
"timeInterval",
")",
"||",
"parseInt",
"(",
"timeInterval",
")",
"<=",
"0",
"||",
"!",
"_",
".",
"isNumber",
"(",
"limit",
")",
"||",
"parseInt",
"(",
"limit",
")",
"<=",
"0",
")",
"{",
"return",
"Q",
".",
"reject",
"(",
")",
";",
"}",
"var",
"cacheKey",
"=",
"Encryption",
".",
"md5",
"(",
"\"MiaJSRateLimit\"",
"+",
"key",
"+",
"_calculateCurrentTimeInterval",
"(",
"timeInterval",
")",
")",
";",
"return",
"_validateRateLimit",
"(",
"cacheKey",
",",
"timeInterval",
",",
"limit",
")",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"return",
"Q",
"(",
"{",
"limit",
":",
"limit",
",",
"remaining",
":",
"limit",
"-",
"value",
",",
"timeInterval",
":",
"timeInterval",
",",
"timeTillReset",
":",
"_getTimeLeftTillReset",
"(",
"timeInterval",
")",
"}",
")",
";",
"}",
")",
";",
"}"
] | Check global rate limits per ip | [
"Check",
"global",
"rate",
"limits",
"per",
"ip"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/rateLimiter/lib/rateLimiter.js#L27-L41 | train |
|
mia-js/mia-js-core | lib/rateLimiter/lib/rateLimiter.js | function (key, intervalSize, limit) {
var deferred = Q.defer()
, memcached = Shared.memcached();
if (!memcached) {
deferred.reject();
}
else {
//Get current rate for ip
memcached.get(key, function (err, value) {
if (err) {
//Allow access as failover
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
deferred.reject();
}
else if (_.isUndefined(value)) {
memcached.set(key, 1, 60 * intervalSize, function (err) {
if (err) {
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
}
});
deferred.resolve(1);
}
else {
//Do not increase rate counter if exceeded anyway
if (value < limit) {
// Increase rate counter by 1
memcached.incr(key, 1, function (err) {
if (err) {
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
}
});
}
deferred.resolve(value + 1);
}
});
}
return deferred.promise;
} | javascript | function (key, intervalSize, limit) {
var deferred = Q.defer()
, memcached = Shared.memcached();
if (!memcached) {
deferred.reject();
}
else {
//Get current rate for ip
memcached.get(key, function (err, value) {
if (err) {
//Allow access as failover
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
deferred.reject();
}
else if (_.isUndefined(value)) {
memcached.set(key, 1, 60 * intervalSize, function (err) {
if (err) {
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
}
});
deferred.resolve(1);
}
else {
//Do not increase rate counter if exceeded anyway
if (value < limit) {
// Increase rate counter by 1
memcached.incr(key, 1, function (err) {
if (err) {
Logger.warn("Rate limit set but memcached error, allow access without limit", err);
}
});
}
deferred.resolve(value + 1);
}
});
}
return deferred.promise;
} | [
"function",
"(",
"key",
",",
"intervalSize",
",",
"limit",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
",",
"memcached",
"=",
"Shared",
".",
"memcached",
"(",
")",
";",
"if",
"(",
"!",
"memcached",
")",
"{",
"deferred",
".",
"reject",
"(",
")",
";",
"}",
"else",
"{",
"memcached",
".",
"get",
"(",
"key",
",",
"function",
"(",
"err",
",",
"value",
")",
"{",
"if",
"(",
"err",
")",
"{",
"Logger",
".",
"warn",
"(",
"\"Rate limit set but memcached error, allow access without limit\"",
",",
"err",
")",
";",
"deferred",
".",
"reject",
"(",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isUndefined",
"(",
"value",
")",
")",
"{",
"memcached",
".",
"set",
"(",
"key",
",",
"1",
",",
"60",
"*",
"intervalSize",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"Logger",
".",
"warn",
"(",
"\"Rate limit set but memcached error, allow access without limit\"",
",",
"err",
")",
";",
"}",
"}",
")",
";",
"deferred",
".",
"resolve",
"(",
"1",
")",
";",
"}",
"else",
"{",
"if",
"(",
"value",
"<",
"limit",
")",
"{",
"memcached",
".",
"incr",
"(",
"key",
",",
"1",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"Logger",
".",
"warn",
"(",
"\"Rate limit set but memcached error, allow access without limit\"",
",",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"deferred",
".",
"resolve",
"(",
"value",
"+",
"1",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"deferred",
".",
"promise",
";",
"}"
] | Validate and increase current rate limit in memcache | [
"Validate",
"and",
"increase",
"current",
"rate",
"limit",
"in",
"memcache"
] | 77c976a72382fd0edef1144f9bea47d8c175c26b | https://github.com/mia-js/mia-js-core/blob/77c976a72382fd0edef1144f9bea47d8c175c26b/lib/rateLimiter/lib/rateLimiter.js#L44-L81 | train |
|
jbaicoianu/elation | components/utils/scripts/jit.js | function(e, win) {
var event = $.event.get(e, win);
var wheel = $.event.getWheel(event);
that.handleEvent('MouseWheel', e, win, wheel);
} | javascript | function(e, win) {
var event = $.event.get(e, win);
var wheel = $.event.getWheel(event);
that.handleEvent('MouseWheel', e, win, wheel);
} | [
"function",
"(",
"e",
",",
"win",
")",
"{",
"var",
"event",
"=",
"$",
".",
"event",
".",
"get",
"(",
"e",
",",
"win",
")",
";",
"var",
"wheel",
"=",
"$",
".",
"event",
".",
"getWheel",
"(",
"event",
")",
";",
"that",
".",
"handleEvent",
"(",
"'MouseWheel'",
",",
"e",
",",
"win",
",",
"wheel",
")",
";",
"}"
] | attach mousewheel event | [
"attach",
"mousewheel",
"event"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L2037-L2041 | train |
|
jbaicoianu/elation | components/utils/scripts/jit.js | $E | function $E(tag, props) {
var elem = document.createElement(tag);
for(var p in props) {
if(typeof props[p] == "object") {
$.extend(elem[p], props[p]);
} else {
elem[p] = props[p];
}
}
if (tag == "canvas" && !supportsCanvas && G_vmlCanvasManager) {
elem = G_vmlCanvasManager.initElement(document.body.appendChild(elem));
}
return elem;
} | javascript | function $E(tag, props) {
var elem = document.createElement(tag);
for(var p in props) {
if(typeof props[p] == "object") {
$.extend(elem[p], props[p]);
} else {
elem[p] = props[p];
}
}
if (tag == "canvas" && !supportsCanvas && G_vmlCanvasManager) {
elem = G_vmlCanvasManager.initElement(document.body.appendChild(elem));
}
return elem;
} | [
"function",
"$E",
"(",
"tag",
",",
"props",
")",
"{",
"var",
"elem",
"=",
"document",
".",
"createElement",
"(",
"tag",
")",
";",
"for",
"(",
"var",
"p",
"in",
"props",
")",
"{",
"if",
"(",
"typeof",
"props",
"[",
"p",
"]",
"==",
"\"object\"",
")",
"{",
"$",
".",
"extend",
"(",
"elem",
"[",
"p",
"]",
",",
"props",
"[",
"p",
"]",
")",
";",
"}",
"else",
"{",
"elem",
"[",
"p",
"]",
"=",
"props",
"[",
"p",
"]",
";",
"}",
"}",
"if",
"(",
"tag",
"==",
"\"canvas\"",
"&&",
"!",
"supportsCanvas",
"&&",
"G_vmlCanvasManager",
")",
"{",
"elem",
"=",
"G_vmlCanvasManager",
".",
"initElement",
"(",
"document",
".",
"body",
".",
"appendChild",
"(",
"elem",
")",
")",
";",
"}",
"return",
"elem",
";",
"}"
] | create element function | [
"create",
"element",
"function"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L2719-L2732 | train |
jbaicoianu/elation | components/utils/scripts/jit.js | getNodesToHide | function getNodesToHide(node) {
node = node || this.clickedNode;
if(!this.config.constrained) {
return [];
}
var Geom = this.geom;
var graph = this.graph;
var canvas = this.canvas;
var level = node._depth, nodeArray = [];
graph.eachNode(function(n) {
if(n.exist && !n.selected) {
if(n.isDescendantOf(node.id)) {
if(n._depth <= level) nodeArray.push(n);
} else {
nodeArray.push(n);
}
}
});
var leafLevel = Geom.getRightLevelToShow(node, canvas);
node.eachLevel(leafLevel, leafLevel, function(n) {
if(n.exist && !n.selected) nodeArray.push(n);
});
for (var i = 0; i < nodesInPath.length; i++) {
var n = this.graph.getNode(nodesInPath[i]);
if(!n.isDescendantOf(node.id)) {
nodeArray.push(n);
}
}
return nodeArray;
} | javascript | function getNodesToHide(node) {
node = node || this.clickedNode;
if(!this.config.constrained) {
return [];
}
var Geom = this.geom;
var graph = this.graph;
var canvas = this.canvas;
var level = node._depth, nodeArray = [];
graph.eachNode(function(n) {
if(n.exist && !n.selected) {
if(n.isDescendantOf(node.id)) {
if(n._depth <= level) nodeArray.push(n);
} else {
nodeArray.push(n);
}
}
});
var leafLevel = Geom.getRightLevelToShow(node, canvas);
node.eachLevel(leafLevel, leafLevel, function(n) {
if(n.exist && !n.selected) nodeArray.push(n);
});
for (var i = 0; i < nodesInPath.length; i++) {
var n = this.graph.getNode(nodesInPath[i]);
if(!n.isDescendantOf(node.id)) {
nodeArray.push(n);
}
}
return nodeArray;
} | [
"function",
"getNodesToHide",
"(",
"node",
")",
"{",
"node",
"=",
"node",
"||",
"this",
".",
"clickedNode",
";",
"if",
"(",
"!",
"this",
".",
"config",
".",
"constrained",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"Geom",
"=",
"this",
".",
"geom",
";",
"var",
"graph",
"=",
"this",
".",
"graph",
";",
"var",
"canvas",
"=",
"this",
".",
"canvas",
";",
"var",
"level",
"=",
"node",
".",
"_depth",
",",
"nodeArray",
"=",
"[",
"]",
";",
"graph",
".",
"eachNode",
"(",
"function",
"(",
"n",
")",
"{",
"if",
"(",
"n",
".",
"exist",
"&&",
"!",
"n",
".",
"selected",
")",
"{",
"if",
"(",
"n",
".",
"isDescendantOf",
"(",
"node",
".",
"id",
")",
")",
"{",
"if",
"(",
"n",
".",
"_depth",
"<=",
"level",
")",
"nodeArray",
".",
"push",
"(",
"n",
")",
";",
"}",
"else",
"{",
"nodeArray",
".",
"push",
"(",
"n",
")",
";",
"}",
"}",
"}",
")",
";",
"var",
"leafLevel",
"=",
"Geom",
".",
"getRightLevelToShow",
"(",
"node",
",",
"canvas",
")",
";",
"node",
".",
"eachLevel",
"(",
"leafLevel",
",",
"leafLevel",
",",
"function",
"(",
"n",
")",
"{",
"if",
"(",
"n",
".",
"exist",
"&&",
"!",
"n",
".",
"selected",
")",
"nodeArray",
".",
"push",
"(",
"n",
")",
";",
"}",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nodesInPath",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"n",
"=",
"this",
".",
"graph",
".",
"getNode",
"(",
"nodesInPath",
"[",
"i",
"]",
")",
";",
"if",
"(",
"!",
"n",
".",
"isDescendantOf",
"(",
"node",
".",
"id",
")",
")",
"{",
"nodeArray",
".",
"push",
"(",
"n",
")",
";",
"}",
"}",
"return",
"nodeArray",
";",
"}"
] | Nodes to contract | [
"Nodes",
"to",
"contract"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L8113-L8143 | train |
jbaicoianu/elation | components/utils/scripts/jit.js | getNodesToShow | function getNodesToShow(node) {
var nodeArray = [], config = this.config;
node = node || this.clickedNode;
this.clickedNode.eachLevel(0, config.levelsToShow, function(n) {
if(config.multitree && !('$orn' in n.data)
&& n.anySubnode(function(ch){ return ch.exist && !ch.drawn; })) {
nodeArray.push(n);
} else if(n.drawn && !n.anySubnode("drawn")) {
nodeArray.push(n);
}
});
return nodeArray;
} | javascript | function getNodesToShow(node) {
var nodeArray = [], config = this.config;
node = node || this.clickedNode;
this.clickedNode.eachLevel(0, config.levelsToShow, function(n) {
if(config.multitree && !('$orn' in n.data)
&& n.anySubnode(function(ch){ return ch.exist && !ch.drawn; })) {
nodeArray.push(n);
} else if(n.drawn && !n.anySubnode("drawn")) {
nodeArray.push(n);
}
});
return nodeArray;
} | [
"function",
"getNodesToShow",
"(",
"node",
")",
"{",
"var",
"nodeArray",
"=",
"[",
"]",
",",
"config",
"=",
"this",
".",
"config",
";",
"node",
"=",
"node",
"||",
"this",
".",
"clickedNode",
";",
"this",
".",
"clickedNode",
".",
"eachLevel",
"(",
"0",
",",
"config",
".",
"levelsToShow",
",",
"function",
"(",
"n",
")",
"{",
"if",
"(",
"config",
".",
"multitree",
"&&",
"!",
"(",
"'$orn'",
"in",
"n",
".",
"data",
")",
"&&",
"n",
".",
"anySubnode",
"(",
"function",
"(",
"ch",
")",
"{",
"return",
"ch",
".",
"exist",
"&&",
"!",
"ch",
".",
"drawn",
";",
"}",
")",
")",
"{",
"nodeArray",
".",
"push",
"(",
"n",
")",
";",
"}",
"else",
"if",
"(",
"n",
".",
"drawn",
"&&",
"!",
"n",
".",
"anySubnode",
"(",
"\"drawn\"",
")",
")",
"{",
"nodeArray",
".",
"push",
"(",
"n",
")",
";",
"}",
"}",
")",
";",
"return",
"nodeArray",
";",
"}"
] | Nodes to expand | [
"Nodes",
"to",
"expand"
] | 5fb8824d8b7150c463daf2fe99c31716c6e8812f | https://github.com/jbaicoianu/elation/blob/5fb8824d8b7150c463daf2fe99c31716c6e8812f/components/utils/scripts/jit.js#L8145-L8157 | train |
primus/substream | substream.js | SubStream | function SubStream(stream, name, options) {
if (!(this instanceof SubStream)) return new SubStream(stream, name, options);
options = options || {};
this.readyState = stream.readyState; // Copy the current readyState.
this.stream = stream; // The underlaying stream.
this.name = name; // The stream namespace/name.
this.primus = options.primus; // Primus reference.
//
// Register the SubStream on the socket.
//
if (!stream.streams) stream.streams = {};
if (!stream.streams[name]) stream.streams[name] = this;
Stream.call(this);
//
// No need to continue with the execution if we don't have any events that
// need to be proxied.
//
if (!options.proxy) return;
for (var i = 0, l = options.proxy.length, event; i < l; i++) {
event = options.proxy[i];
this.stream.on(event, this.emits(event));
}
} | javascript | function SubStream(stream, name, options) {
if (!(this instanceof SubStream)) return new SubStream(stream, name, options);
options = options || {};
this.readyState = stream.readyState; // Copy the current readyState.
this.stream = stream; // The underlaying stream.
this.name = name; // The stream namespace/name.
this.primus = options.primus; // Primus reference.
//
// Register the SubStream on the socket.
//
if (!stream.streams) stream.streams = {};
if (!stream.streams[name]) stream.streams[name] = this;
Stream.call(this);
//
// No need to continue with the execution if we don't have any events that
// need to be proxied.
//
if (!options.proxy) return;
for (var i = 0, l = options.proxy.length, event; i < l; i++) {
event = options.proxy[i];
this.stream.on(event, this.emits(event));
}
} | [
"function",
"SubStream",
"(",
"stream",
",",
"name",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"SubStream",
")",
")",
"return",
"new",
"SubStream",
"(",
"stream",
",",
"name",
",",
"options",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"readyState",
"=",
"stream",
".",
"readyState",
";",
"this",
".",
"stream",
"=",
"stream",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"primus",
"=",
"options",
".",
"primus",
";",
"if",
"(",
"!",
"stream",
".",
"streams",
")",
"stream",
".",
"streams",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"stream",
".",
"streams",
"[",
"name",
"]",
")",
"stream",
".",
"streams",
"[",
"name",
"]",
"=",
"this",
";",
"Stream",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"!",
"options",
".",
"proxy",
")",
"return",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"options",
".",
"proxy",
".",
"length",
",",
"event",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"event",
"=",
"options",
".",
"proxy",
"[",
"i",
"]",
";",
"this",
".",
"stream",
".",
"on",
"(",
"event",
",",
"this",
".",
"emits",
"(",
"event",
")",
")",
";",
"}",
"}"
] | Streams provides a streaming, namespaced interface on top of a regular
stream.
Options:
- proxy: Array of addition events that need to be re-emitted.
@constructor
@param {Stream} stream The stream that needs we're streaming over.
@param {String} name The name of our stream.
@param {object} options SubStream configuration.
@api public | [
"Streams",
"provides",
"a",
"streaming",
"namespaced",
"interface",
"on",
"top",
"of",
"a",
"regular",
"stream",
"."
] | 626792b746e1dc90b67a81045f442ee1f584c0ec | https://github.com/primus/substream/blob/626792b746e1dc90b67a81045f442ee1f584c0ec/substream.js#L25-L53 | train |
mozilla-jetpack/node-fx-runner | lib/utils.js | fallBack | function fallBack () {
var programFilesVar = "ProgramFiles";
if (arch === "(64)") {
console.warn("You are using 32-bit version of Firefox on 64-bit versions of the Windows.\nSome features may not work correctly in this version. You should upgrade Firefox to the latest 64-bit version now!")
programFilesVar = "ProgramFiles(x86)";
}
resolve(path.join(process.env[programFilesVar], appName, "firefox.exe"));
} | javascript | function fallBack () {
var programFilesVar = "ProgramFiles";
if (arch === "(64)") {
console.warn("You are using 32-bit version of Firefox on 64-bit versions of the Windows.\nSome features may not work correctly in this version. You should upgrade Firefox to the latest 64-bit version now!")
programFilesVar = "ProgramFiles(x86)";
}
resolve(path.join(process.env[programFilesVar], appName, "firefox.exe"));
} | [
"function",
"fallBack",
"(",
")",
"{",
"var",
"programFilesVar",
"=",
"\"ProgramFiles\"",
";",
"if",
"(",
"arch",
"===",
"\"(64)\"",
")",
"{",
"console",
".",
"warn",
"(",
"\"You are using 32-bit version of Firefox on 64-bit versions of the Windows.\\nSome features may not work correctly in this version. You should upgrade Firefox to the latest 64-bit version now!\"",
")",
"\\n",
"}",
"programFilesVar",
"=",
"\"ProgramFiles(x86)\"",
";",
"}"
] | this is used when reading the registry goes wrong. | [
"this",
"is",
"used",
"when",
"reading",
"the",
"registry",
"goes",
"wrong",
"."
] | 71e3848b6adac1054829391c826fd88cfb28f621 | https://github.com/mozilla-jetpack/node-fx-runner/blob/71e3848b6adac1054829391c826fd88cfb28f621/lib/utils.js#L74-L81 | train |
primus/substream | index.js | listen | function listen(event, spark) {
if ('end' === event) return function end() {
if (!spark.streams) return;
for (var stream in spark.streams) {
stream = spark.streams[stream];
if (stream.end) stream.end();
}
};
if ('readyStateChange' === event) return function change(reason) {
if (!spark.streams) return;
for (var stream in spark.streams) {
stream = spark.streams[stream];
stream.readyState = spark.readyState;
if (stream.emit) emit.call(stream, event, reason);
}
};
return function proxy() {
if (!spark.streams) return;
var args = Array.prototype.slice.call(arguments, 0);
for (var stream in spark.streams) {
if (stream.emit) emit.call(stream, [event].concat(args));
}
};
} | javascript | function listen(event, spark) {
if ('end' === event) return function end() {
if (!spark.streams) return;
for (var stream in spark.streams) {
stream = spark.streams[stream];
if (stream.end) stream.end();
}
};
if ('readyStateChange' === event) return function change(reason) {
if (!spark.streams) return;
for (var stream in spark.streams) {
stream = spark.streams[stream];
stream.readyState = spark.readyState;
if (stream.emit) emit.call(stream, event, reason);
}
};
return function proxy() {
if (!spark.streams) return;
var args = Array.prototype.slice.call(arguments, 0);
for (var stream in spark.streams) {
if (stream.emit) emit.call(stream, [event].concat(args));
}
};
} | [
"function",
"listen",
"(",
"event",
",",
"spark",
")",
"{",
"if",
"(",
"'end'",
"===",
"event",
")",
"return",
"function",
"end",
"(",
")",
"{",
"if",
"(",
"!",
"spark",
".",
"streams",
")",
"return",
";",
"for",
"(",
"var",
"stream",
"in",
"spark",
".",
"streams",
")",
"{",
"stream",
"=",
"spark",
".",
"streams",
"[",
"stream",
"]",
";",
"if",
"(",
"stream",
".",
"end",
")",
"stream",
".",
"end",
"(",
")",
";",
"}",
"}",
";",
"if",
"(",
"'readyStateChange'",
"===",
"event",
")",
"return",
"function",
"change",
"(",
"reason",
")",
"{",
"if",
"(",
"!",
"spark",
".",
"streams",
")",
"return",
";",
"for",
"(",
"var",
"stream",
"in",
"spark",
".",
"streams",
")",
"{",
"stream",
"=",
"spark",
".",
"streams",
"[",
"stream",
"]",
";",
"stream",
".",
"readyState",
"=",
"spark",
".",
"readyState",
";",
"if",
"(",
"stream",
".",
"emit",
")",
"emit",
".",
"call",
"(",
"stream",
",",
"event",
",",
"reason",
")",
";",
"}",
"}",
";",
"return",
"function",
"proxy",
"(",
")",
"{",
"if",
"(",
"!",
"spark",
".",
"streams",
")",
"return",
";",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"for",
"(",
"var",
"stream",
"in",
"spark",
".",
"streams",
")",
"{",
"if",
"(",
"stream",
".",
"emit",
")",
"emit",
".",
"call",
"(",
"stream",
",",
"[",
"event",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"}",
"}",
";",
"}"
] | Return a preconfigured listener.
@param {String} event Name of the event.
@returns {Function} listener
@api private | [
"Return",
"a",
"preconfigured",
"listener",
"."
] | 626792b746e1dc90b67a81045f442ee1f584c0ec | https://github.com/primus/substream/blob/626792b746e1dc90b67a81045f442ee1f584c0ec/index.js#L25-L54 | train |
globality-corp/nodule-logging | src/logger.js | createLoggerStream | function createLoggerStream(name, level, logglyConfig) {
const streams = [process.stdout];
if (logglyConfig.enabled) {
const logglyStream = new LogglyStream({
token: logglyConfig.token,
subdomain: logglyConfig.subdomain,
name,
environment: logglyConfig.environment,
});
streams.push(logglyStream);
}
return new UnionStream({ streams });
} | javascript | function createLoggerStream(name, level, logglyConfig) {
const streams = [process.stdout];
if (logglyConfig.enabled) {
const logglyStream = new LogglyStream({
token: logglyConfig.token,
subdomain: logglyConfig.subdomain,
name,
environment: logglyConfig.environment,
});
streams.push(logglyStream);
}
return new UnionStream({ streams });
} | [
"function",
"createLoggerStream",
"(",
"name",
",",
"level",
",",
"logglyConfig",
")",
"{",
"const",
"streams",
"=",
"[",
"process",
".",
"stdout",
"]",
";",
"if",
"(",
"logglyConfig",
".",
"enabled",
")",
"{",
"const",
"logglyStream",
"=",
"new",
"LogglyStream",
"(",
"{",
"token",
":",
"logglyConfig",
".",
"token",
",",
"subdomain",
":",
"logglyConfig",
".",
"subdomain",
",",
"name",
",",
"environment",
":",
"logglyConfig",
".",
"environment",
",",
"}",
")",
";",
"streams",
".",
"push",
"(",
"logglyStream",
")",
";",
"}",
"return",
"new",
"UnionStream",
"(",
"{",
"streams",
"}",
")",
";",
"}"
] | singleton to create a logging instance based on config | [
"singleton",
"to",
"create",
"a",
"logging",
"instance",
"based",
"on",
"config"
] | 5283de6c8bf8a2866f377aa82eca80bc3b30a5c3 | https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/logger.js#L16-L28 | train |
wikimedia/restbase-mod-table-cassandra | lib/schemaMigration.js | confChanged | function confChanged(current, proposed) {
if (stringify(current.conf) !== stringify(proposed.conf)) {
if (current.version >= proposed.version) {
const e = new Error('Schema change, but no version increment.');
e.current = current;
e.proposed = proposed;
throw e;
}
return true;
} else {
return false;
}
} | javascript | function confChanged(current, proposed) {
if (stringify(current.conf) !== stringify(proposed.conf)) {
if (current.version >= proposed.version) {
const e = new Error('Schema change, but no version increment.');
e.current = current;
e.proposed = proposed;
throw e;
}
return true;
} else {
return false;
}
} | [
"function",
"confChanged",
"(",
"current",
",",
"proposed",
")",
"{",
"if",
"(",
"stringify",
"(",
"current",
".",
"conf",
")",
"!==",
"stringify",
"(",
"proposed",
".",
"conf",
")",
")",
"{",
"if",
"(",
"current",
".",
"version",
">=",
"proposed",
".",
"version",
")",
"{",
"const",
"e",
"=",
"new",
"Error",
"(",
"'Schema change, but no version increment.'",
")",
";",
"e",
".",
"current",
"=",
"current",
";",
"e",
".",
"proposed",
"=",
"proposed",
";",
"throw",
"e",
";",
"}",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Check if a schema part differs, and if it does, if the version was
incremented.
@param {Object} current { conf: {object}, version: {number} }
@param {Object} proposed { conf: {object}, version: {number} }
@return {boolean} Whether the attribute has changed.
@throws {Error} If the schema fragment changed, but the version was not
incremented. | [
"Check",
"if",
"a",
"schema",
"part",
"differs",
"and",
"if",
"it",
"does",
"if",
"the",
"version",
"was",
"incremented",
"."
] | f226a4bd1c75a31243a895d1106bf8ccd643113a | https://github.com/wikimedia/restbase-mod-table-cassandra/blob/f226a4bd1c75a31243a895d1106bf8ccd643113a/lib/schemaMigration.js#L16-L28 | train |
globality-corp/nodule-logging | src/logFormatting.js | validatePropertyType | function validatePropertyType(property, type, recursive) {
return type && (
(recursive && typeof property === 'object') ||
(type === 'string' && typeof property === 'string') ||
(type === 'number' && typeof property === 'number') ||
(type === 'uuid' && isUuid(property)) ||
(type === 'uuidList' && isUuidList(property))
);
} | javascript | function validatePropertyType(property, type, recursive) {
return type && (
(recursive && typeof property === 'object') ||
(type === 'string' && typeof property === 'string') ||
(type === 'number' && typeof property === 'number') ||
(type === 'uuid' && isUuid(property)) ||
(type === 'uuidList' && isUuidList(property))
);
} | [
"function",
"validatePropertyType",
"(",
"property",
",",
"type",
",",
"recursive",
")",
"{",
"return",
"type",
"&&",
"(",
"(",
"recursive",
"&&",
"typeof",
"property",
"===",
"'object'",
")",
"||",
"(",
"type",
"===",
"'string'",
"&&",
"typeof",
"property",
"===",
"'string'",
")",
"||",
"(",
"type",
"===",
"'number'",
"&&",
"typeof",
"property",
"===",
"'number'",
")",
"||",
"(",
"type",
"===",
"'uuid'",
"&&",
"isUuid",
"(",
"property",
")",
")",
"||",
"(",
"type",
"===",
"'uuidList'",
"&&",
"isUuidList",
"(",
"property",
")",
")",
")",
";",
"}"
] | Helper function to parseObject | [
"Helper",
"function",
"to",
"parseObject"
] | 5283de6c8bf8a2866f377aa82eca80bc3b30a5c3 | https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/logFormatting.js#L44-L52 | train |
globality-corp/nodule-logging | src/logFormatting.js | parseObject | function parseObject(obj, { name, path, subPaths, type, recursive = true, ...args }) {
let property = get(obj, path);
if (property === null || !validatePropertyType(property, type, recursive)) {
return [];
}
if (type === 'uuidList' && isUuidList(property)) {
return [{ [name]: property.split(',') }];
}
if (recursive && typeof property === 'object') {
const propertyName = isNil(name) ? '' : name;
const nextPaths = subPaths || Object.keys(property);
return flatten(nextPaths
.map(subPath => parseObject(obj, {
name: `${propertyName}${subPath}`,
path: `${path}.${subPath}`,
recursive: false,
type,
...args,
})));
}
if (args.filterPattern) {
property = typeof property === 'string' ? get(property.match(args.filterPattern), '[1]') : null;
}
if (args.hideUUID) {
property = typeof property === 'string' ? property.replace(
RegExp('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}', 'g'),
'{uuid}',
) : null;
}
return property === null ? [] : [{ [name]: property }];
} | javascript | function parseObject(obj, { name, path, subPaths, type, recursive = true, ...args }) {
let property = get(obj, path);
if (property === null || !validatePropertyType(property, type, recursive)) {
return [];
}
if (type === 'uuidList' && isUuidList(property)) {
return [{ [name]: property.split(',') }];
}
if (recursive && typeof property === 'object') {
const propertyName = isNil(name) ? '' : name;
const nextPaths = subPaths || Object.keys(property);
return flatten(nextPaths
.map(subPath => parseObject(obj, {
name: `${propertyName}${subPath}`,
path: `${path}.${subPath}`,
recursive: false,
type,
...args,
})));
}
if (args.filterPattern) {
property = typeof property === 'string' ? get(property.match(args.filterPattern), '[1]') : null;
}
if (args.hideUUID) {
property = typeof property === 'string' ? property.replace(
RegExp('[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}', 'g'),
'{uuid}',
) : null;
}
return property === null ? [] : [{ [name]: property }];
} | [
"function",
"parseObject",
"(",
"obj",
",",
"{",
"name",
",",
"path",
",",
"subPaths",
",",
"type",
",",
"recursive",
"=",
"true",
",",
"...",
"args",
"}",
")",
"{",
"let",
"property",
"=",
"get",
"(",
"obj",
",",
"path",
")",
";",
"if",
"(",
"property",
"===",
"null",
"||",
"!",
"validatePropertyType",
"(",
"property",
",",
"type",
",",
"recursive",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"type",
"===",
"'uuidList'",
"&&",
"isUuidList",
"(",
"property",
")",
")",
"{",
"return",
"[",
"{",
"[",
"name",
"]",
":",
"property",
".",
"split",
"(",
"','",
")",
"}",
"]",
";",
"}",
"if",
"(",
"recursive",
"&&",
"typeof",
"property",
"===",
"'object'",
")",
"{",
"const",
"propertyName",
"=",
"isNil",
"(",
"name",
")",
"?",
"''",
":",
"name",
";",
"const",
"nextPaths",
"=",
"subPaths",
"||",
"Object",
".",
"keys",
"(",
"property",
")",
";",
"return",
"flatten",
"(",
"nextPaths",
".",
"map",
"(",
"subPath",
"=>",
"parseObject",
"(",
"obj",
",",
"{",
"name",
":",
"`",
"${",
"propertyName",
"}",
"${",
"subPath",
"}",
"`",
",",
"path",
":",
"`",
"${",
"path",
"}",
"${",
"subPath",
"}",
"`",
",",
"recursive",
":",
"false",
",",
"type",
",",
"...",
"args",
",",
"}",
")",
")",
")",
";",
"}",
"if",
"(",
"args",
".",
"filterPattern",
")",
"{",
"property",
"=",
"typeof",
"property",
"===",
"'string'",
"?",
"get",
"(",
"property",
".",
"match",
"(",
"args",
".",
"filterPattern",
")",
",",
"'[1]'",
")",
":",
"null",
";",
"}",
"if",
"(",
"args",
".",
"hideUUID",
")",
"{",
"property",
"=",
"typeof",
"property",
"===",
"'string'",
"?",
"property",
".",
"replace",
"(",
"RegExp",
"(",
"'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'",
",",
"'g'",
")",
",",
"'{uuid}'",
",",
")",
":",
"null",
";",
"}",
"return",
"property",
"===",
"null",
"?",
"[",
"]",
":",
"[",
"{",
"[",
"name",
"]",
":",
"property",
"}",
"]",
";",
"}"
] | Helper function to extractLoggingProperties Parse rules and return an array of properties to log | [
"Helper",
"function",
"to",
"extractLoggingProperties",
"Parse",
"rules",
"and",
"return",
"an",
"array",
"of",
"properties",
"to",
"log"
] | 5283de6c8bf8a2866f377aa82eca80bc3b30a5c3 | https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/logFormatting.js#L57-L87 | train |
maurelian/eth-registrar-ens | src/index.js | Entry | function Entry(name, hash, status, mode, deed, registrationDate, value, highestBid) {
// TODO: improve Entry constructor so that unknown names can be handled via getEntry
this.name = name;
this.hash = hash;
this.status = status;
this.mode = mode;
this.deed = deed;
this.registrationDate = registrationDate;
this.value = value;
this.highestBid = highestBid;
} | javascript | function Entry(name, hash, status, mode, deed, registrationDate, value, highestBid) {
// TODO: improve Entry constructor so that unknown names can be handled via getEntry
this.name = name;
this.hash = hash;
this.status = status;
this.mode = mode;
this.deed = deed;
this.registrationDate = registrationDate;
this.value = value;
this.highestBid = highestBid;
} | [
"function",
"Entry",
"(",
"name",
",",
"hash",
",",
"status",
",",
"mode",
",",
"deed",
",",
"registrationDate",
",",
"value",
",",
"highestBid",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"hash",
"=",
"hash",
";",
"this",
".",
"status",
"=",
"status",
";",
"this",
".",
"mode",
"=",
"mode",
";",
"this",
".",
"deed",
"=",
"deed",
";",
"this",
".",
"registrationDate",
"=",
"registrationDate",
";",
"this",
".",
"value",
"=",
"value",
";",
"this",
".",
"highestBid",
"=",
"highestBid",
";",
"}"
] | Constructs a new Entry object corresponding to a name.
@ignore
@param {string} name The unhashed name
@param {string} hash
@param {number} status
@param {address} deed
@param {number} registrationDate
@param {number} value
@param {number} highestBid | [
"Constructs",
"a",
"new",
"Entry",
"object",
"corresponding",
"to",
"a",
"name",
"."
] | a70baba4de1bcbdb8479f84e1ac694bd670349d5 | https://github.com/maurelian/eth-registrar-ens/blob/a70baba4de1bcbdb8479f84e1ac694bd670349d5/src/index.js#L131-L141 | train |
globality-corp/nodule-logging | src/middleware.js | skip | function skip(ignoreRouteUrls) {
return function ignoreUrl(req) {
const url = req.originalUrl || req.url;
return ignoreRouteUrls.includes(url);
};
} | javascript | function skip(ignoreRouteUrls) {
return function ignoreUrl(req) {
const url = req.originalUrl || req.url;
return ignoreRouteUrls.includes(url);
};
} | [
"function",
"skip",
"(",
"ignoreRouteUrls",
")",
"{",
"return",
"function",
"ignoreUrl",
"(",
"req",
")",
"{",
"const",
"url",
"=",
"req",
".",
"originalUrl",
"||",
"req",
".",
"url",
";",
"return",
"ignoreRouteUrls",
".",
"includes",
"(",
"url",
")",
";",
"}",
";",
"}"
] | exclude any health or other ignorable urls | [
"exclude",
"any",
"health",
"or",
"other",
"ignorable",
"urls"
] | 5283de6c8bf8a2866f377aa82eca80bc3b30a5c3 | https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/middleware.js#L9-L14 | train |
globality-corp/nodule-logging | src/middleware.js | omit | function omit(req, blacklist) {
return omitBy(req, (value, key) => blacklist.includes(key));
} | javascript | function omit(req, blacklist) {
return omitBy(req, (value, key) => blacklist.includes(key));
} | [
"function",
"omit",
"(",
"req",
",",
"blacklist",
")",
"{",
"return",
"omitBy",
"(",
"req",
",",
"(",
"value",
",",
"key",
")",
"=>",
"blacklist",
".",
"includes",
"(",
"key",
")",
")",
";",
"}"
] | filter out named properties from req object | [
"filter",
"out",
"named",
"properties",
"from",
"req",
"object"
] | 5283de6c8bf8a2866f377aa82eca80bc3b30a5c3 | https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/middleware.js#L28-L30 | train |
globality-corp/nodule-logging | src/middleware.js | morganMiddleware | function morganMiddleware(req, res, next) {
const { ignoreRouteUrls, includeReqHeaders, omitReqProperties } = getConfig('logger');
const { format } = getConfig('logger.morgan');
// define custom tokens
morgan.token('operation-hash', request => get(request, 'body.extensions.persistentQuery.sha256Hash'));
morgan.token('operation-name', request => get(request, 'body.operationName'));
morgan.token('user-id', request => get(request, 'locals.user.id'));
morgan.token('company-id', request => get(request, 'locals.user.companyId'));
morgan.token('message', request => request.name || '-');
morgan.token('request-id', request => request.id);
morgan.token('request-headers', (request) => {
const headers = includeReqHeaders === true
? omit(request.headers, omitReqProperties) : {};
return JSON.stringify(headers);
});
const logger = getContainer('logger');
const formatFormat = json(format);
const options = {
stream: asStream(logger),
skip: skip(ignoreRouteUrls),
};
return morgan(formatFormat, options)(req, res, next);
} | javascript | function morganMiddleware(req, res, next) {
const { ignoreRouteUrls, includeReqHeaders, omitReqProperties } = getConfig('logger');
const { format } = getConfig('logger.morgan');
// define custom tokens
morgan.token('operation-hash', request => get(request, 'body.extensions.persistentQuery.sha256Hash'));
morgan.token('operation-name', request => get(request, 'body.operationName'));
morgan.token('user-id', request => get(request, 'locals.user.id'));
morgan.token('company-id', request => get(request, 'locals.user.companyId'));
morgan.token('message', request => request.name || '-');
morgan.token('request-id', request => request.id);
morgan.token('request-headers', (request) => {
const headers = includeReqHeaders === true
? omit(request.headers, omitReqProperties) : {};
return JSON.stringify(headers);
});
const logger = getContainer('logger');
const formatFormat = json(format);
const options = {
stream: asStream(logger),
skip: skip(ignoreRouteUrls),
};
return morgan(formatFormat, options)(req, res, next);
} | [
"function",
"morganMiddleware",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"const",
"{",
"ignoreRouteUrls",
",",
"includeReqHeaders",
",",
"omitReqProperties",
"}",
"=",
"getConfig",
"(",
"'logger'",
")",
";",
"const",
"{",
"format",
"}",
"=",
"getConfig",
"(",
"'logger.morgan'",
")",
";",
"morgan",
".",
"token",
"(",
"'operation-hash'",
",",
"request",
"=>",
"get",
"(",
"request",
",",
"'body.extensions.persistentQuery.sha256Hash'",
")",
")",
";",
"morgan",
".",
"token",
"(",
"'operation-name'",
",",
"request",
"=>",
"get",
"(",
"request",
",",
"'body.operationName'",
")",
")",
";",
"morgan",
".",
"token",
"(",
"'user-id'",
",",
"request",
"=>",
"get",
"(",
"request",
",",
"'locals.user.id'",
")",
")",
";",
"morgan",
".",
"token",
"(",
"'company-id'",
",",
"request",
"=>",
"get",
"(",
"request",
",",
"'locals.user.companyId'",
")",
")",
";",
"morgan",
".",
"token",
"(",
"'message'",
",",
"request",
"=>",
"request",
".",
"name",
"||",
"'-'",
")",
";",
"morgan",
".",
"token",
"(",
"'request-id'",
",",
"request",
"=>",
"request",
".",
"id",
")",
";",
"morgan",
".",
"token",
"(",
"'request-headers'",
",",
"(",
"request",
")",
"=>",
"{",
"const",
"headers",
"=",
"includeReqHeaders",
"===",
"true",
"?",
"omit",
"(",
"request",
".",
"headers",
",",
"omitReqProperties",
")",
":",
"{",
"}",
";",
"return",
"JSON",
".",
"stringify",
"(",
"headers",
")",
";",
"}",
")",
";",
"const",
"logger",
"=",
"getContainer",
"(",
"'logger'",
")",
";",
"const",
"formatFormat",
"=",
"json",
"(",
"format",
")",
";",
"const",
"options",
"=",
"{",
"stream",
":",
"asStream",
"(",
"logger",
")",
",",
"skip",
":",
"skip",
"(",
"ignoreRouteUrls",
")",
",",
"}",
";",
"return",
"morgan",
"(",
"formatFormat",
",",
"options",
")",
"(",
"req",
",",
"res",
",",
"next",
")",
";",
"}"
] | Use morgan library to log every HTTP response Also set req._startAt - that is used by the logger | [
"Use",
"morgan",
"library",
"to",
"log",
"every",
"HTTP",
"response",
"Also",
"set",
"req",
".",
"_startAt",
"-",
"that",
"is",
"used",
"by",
"the",
"logger"
] | 5283de6c8bf8a2866f377aa82eca80bc3b30a5c3 | https://github.com/globality-corp/nodule-logging/blob/5283de6c8bf8a2866f377aa82eca80bc3b30a5c3/src/middleware.js#L40-L63 | train |
wikimedia/restbase-mod-table-cassandra | maintenance/lib/index.js | getConfig | function getConfig(config) {
// Read a RESTBase configuration from a (optional) path argument, an (optional) CONFIG
// env var, or from /etc/restbase/config.yaml
var conf;
if (config) {
conf = config;
} else if (process.env.CONFIG) {
conf = process.env.CONFIG;
} else {
conf = '/etc/restbase/config.yaml';
}
var confObj = yaml.safeLoad(fs.readFileSync(conf));
return confObj.default_project['x-modules'][0].options.table;
} | javascript | function getConfig(config) {
// Read a RESTBase configuration from a (optional) path argument, an (optional) CONFIG
// env var, or from /etc/restbase/config.yaml
var conf;
if (config) {
conf = config;
} else if (process.env.CONFIG) {
conf = process.env.CONFIG;
} else {
conf = '/etc/restbase/config.yaml';
}
var confObj = yaml.safeLoad(fs.readFileSync(conf));
return confObj.default_project['x-modules'][0].options.table;
} | [
"function",
"getConfig",
"(",
"config",
")",
"{",
"var",
"conf",
";",
"if",
"(",
"config",
")",
"{",
"conf",
"=",
"config",
";",
"}",
"else",
"if",
"(",
"process",
".",
"env",
".",
"CONFIG",
")",
"{",
"conf",
"=",
"process",
".",
"env",
".",
"CONFIG",
";",
"}",
"else",
"{",
"conf",
"=",
"'/etc/restbase/config.yaml'",
";",
"}",
"var",
"confObj",
"=",
"yaml",
".",
"safeLoad",
"(",
"fs",
".",
"readFileSync",
"(",
"conf",
")",
")",
";",
"return",
"confObj",
".",
"default_project",
"[",
"'x-modules'",
"]",
"[",
"0",
"]",
".",
"options",
".",
"table",
";",
"}"
] | Return the table section of a RESTBase config.
@param {string} config - Path to a RESTBase YAML configuration file.
@return {Object} table section of configuration. | [
"Return",
"the",
"table",
"section",
"of",
"a",
"RESTBase",
"config",
"."
] | f226a4bd1c75a31243a895d1106bf8ccd643113a | https://github.com/wikimedia/restbase-mod-table-cassandra/blob/f226a4bd1c75a31243a895d1106bf8ccd643113a/maintenance/lib/index.js#L12-L27 | train |
jsrmath/sharp11 | lib/note.js | function (name) {
var octave = null;
name = prepareNoteName(name);
// Extract octave number if given
if (/\d$/.test(name)) {
octave = parseInt(name.slice(-1));
name = name.slice(0, -1);
}
// Throw an error for an invalid note name
if (!(/^[A-Ga-g](bb|##|[b#n])?$/).test(name)) {
throw new Error('Invalid note name: ' + name);
}
return {
letter: name[0].toUpperCase(),
acc: name.slice(1) || 'n',
octave: octave
};
} | javascript | function (name) {
var octave = null;
name = prepareNoteName(name);
// Extract octave number if given
if (/\d$/.test(name)) {
octave = parseInt(name.slice(-1));
name = name.slice(0, -1);
}
// Throw an error for an invalid note name
if (!(/^[A-Ga-g](bb|##|[b#n])?$/).test(name)) {
throw new Error('Invalid note name: ' + name);
}
return {
letter: name[0].toUpperCase(),
acc: name.slice(1) || 'n',
octave: octave
};
} | [
"function",
"(",
"name",
")",
"{",
"var",
"octave",
"=",
"null",
";",
"name",
"=",
"prepareNoteName",
"(",
"name",
")",
";",
"if",
"(",
"/",
"\\d$",
"/",
".",
"test",
"(",
"name",
")",
")",
"{",
"octave",
"=",
"parseInt",
"(",
"name",
".",
"slice",
"(",
"-",
"1",
")",
")",
";",
"name",
"=",
"name",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"}",
"if",
"(",
"!",
"(",
"/",
"^[A-Ga-g](bb|##|[b#n])?$",
"/",
")",
".",
"test",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid note name: '",
"+",
"name",
")",
";",
"}",
"return",
"{",
"letter",
":",
"name",
"[",
"0",
"]",
".",
"toUpperCase",
"(",
")",
",",
"acc",
":",
"name",
".",
"slice",
"(",
"1",
")",
"||",
"'n'",
",",
"octave",
":",
"octave",
"}",
";",
"}"
] | Parse a note name and return object with letter, accidental | [
"Parse",
"a",
"note",
"name",
"and",
"return",
"object",
"with",
"letter",
"accidental"
] | 4f5857c40535b1bccc102ffdcc42a086e213016a | https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L37-L58 | train |
|
jsrmath/sharp11 | lib/note.js | function (note, number) {
var letter = note.letter;
var index = scale.indexOf(note.letter);
var newIndex = mod(index + number - 1, scale.length);
assert(index > -1);
assert(newIndex > -1 && newIndex < scale.length);
return scale[newIndex];
} | javascript | function (note, number) {
var letter = note.letter;
var index = scale.indexOf(note.letter);
var newIndex = mod(index + number - 1, scale.length);
assert(index > -1);
assert(newIndex > -1 && newIndex < scale.length);
return scale[newIndex];
} | [
"function",
"(",
"note",
",",
"number",
")",
"{",
"var",
"letter",
"=",
"note",
".",
"letter",
";",
"var",
"index",
"=",
"scale",
".",
"indexOf",
"(",
"note",
".",
"letter",
")",
";",
"var",
"newIndex",
"=",
"mod",
"(",
"index",
"+",
"number",
"-",
"1",
",",
"scale",
".",
"length",
")",
";",
"assert",
"(",
"index",
">",
"-",
"1",
")",
";",
"assert",
"(",
"newIndex",
">",
"-",
"1",
"&&",
"newIndex",
"<",
"scale",
".",
"length",
")",
";",
"return",
"scale",
"[",
"newIndex",
"]",
";",
"}"
] | Increase the letter of a note by a given interval | [
"Increase",
"the",
"letter",
"of",
"a",
"note",
"by",
"a",
"given",
"interval"
] | 4f5857c40535b1bccc102ffdcc42a086e213016a | https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L61-L70 | train |
|
jsrmath/sharp11 | lib/note.js | function (letter1, letter2) {
var index1 = scale.indexOf(letter1);
var index2 = scale.indexOf(letter2);
var distance = mod(index2 - index1, scale.length) + 1;
assert(index1 > -1);
assert(index2 > -1);
assert(distance > 0 && distance <= scale.length);
return distance;
} | javascript | function (letter1, letter2) {
var index1 = scale.indexOf(letter1);
var index2 = scale.indexOf(letter2);
var distance = mod(index2 - index1, scale.length) + 1;
assert(index1 > -1);
assert(index2 > -1);
assert(distance > 0 && distance <= scale.length);
return distance;
} | [
"function",
"(",
"letter1",
",",
"letter2",
")",
"{",
"var",
"index1",
"=",
"scale",
".",
"indexOf",
"(",
"letter1",
")",
";",
"var",
"index2",
"=",
"scale",
".",
"indexOf",
"(",
"letter2",
")",
";",
"var",
"distance",
"=",
"mod",
"(",
"index2",
"-",
"index1",
",",
"scale",
".",
"length",
")",
"+",
"1",
";",
"assert",
"(",
"index1",
">",
"-",
"1",
")",
";",
"assert",
"(",
"index2",
">",
"-",
"1",
")",
";",
"assert",
"(",
"distance",
">",
"0",
"&&",
"distance",
"<=",
"scale",
".",
"length",
")",
";",
"return",
"distance",
";",
"}"
] | Find the interval number between two notes given their letters | [
"Find",
"the",
"interval",
"number",
"between",
"two",
"notes",
"given",
"their",
"letters"
] | 4f5857c40535b1bccc102ffdcc42a086e213016a | https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L73-L83 | train |
|
jsrmath/sharp11 | lib/note.js | function (int) {
var map = interval.isPerfect(int.number) ? perfectOffsets : majorOffsets;
var key = _.invert(map)[int.quality];
return parseInt(key, 10);
} | javascript | function (int) {
var map = interval.isPerfect(int.number) ? perfectOffsets : majorOffsets;
var key = _.invert(map)[int.quality];
return parseInt(key, 10);
} | [
"function",
"(",
"int",
")",
"{",
"var",
"map",
"=",
"interval",
".",
"isPerfect",
"(",
"int",
".",
"number",
")",
"?",
"perfectOffsets",
":",
"majorOffsets",
";",
"var",
"key",
"=",
"_",
".",
"invert",
"(",
"map",
")",
"[",
"int",
".",
"quality",
"]",
";",
"return",
"parseInt",
"(",
"key",
",",
"10",
")",
";",
"}"
] | Find the number of half steps between interval and corresponding diatonic interval | [
"Find",
"the",
"number",
"of",
"half",
"steps",
"between",
"interval",
"and",
"corresponding",
"diatonic",
"interval"
] | 4f5857c40535b1bccc102ffdcc42a086e213016a | https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L97-L102 | train |
|
jsrmath/sharp11 | lib/note.js | function (number, halfSteps) {
var diatonicHalfSteps = getDiatonicHalfSteps(number);
var halfStepOffset = halfSteps - diatonicHalfSteps;
// Handle various abnormalities
if (halfStepOffset === 11) halfStepOffset = -1;
if (halfStepOffset === -11) halfStepOffset = 1;
return halfStepOffset;
} | javascript | function (number, halfSteps) {
var diatonicHalfSteps = getDiatonicHalfSteps(number);
var halfStepOffset = halfSteps - diatonicHalfSteps;
// Handle various abnormalities
if (halfStepOffset === 11) halfStepOffset = -1;
if (halfStepOffset === -11) halfStepOffset = 1;
return halfStepOffset;
} | [
"function",
"(",
"number",
",",
"halfSteps",
")",
"{",
"var",
"diatonicHalfSteps",
"=",
"getDiatonicHalfSteps",
"(",
"number",
")",
";",
"var",
"halfStepOffset",
"=",
"halfSteps",
"-",
"diatonicHalfSteps",
";",
"if",
"(",
"halfStepOffset",
"===",
"11",
")",
"halfStepOffset",
"=",
"-",
"1",
";",
"if",
"(",
"halfStepOffset",
"===",
"-",
"11",
")",
"halfStepOffset",
"=",
"1",
";",
"return",
"halfStepOffset",
";",
"}"
] | Find the offset between | [
"Find",
"the",
"offset",
"between"
] | 4f5857c40535b1bccc102ffdcc42a086e213016a | https://github.com/jsrmath/sharp11/blob/4f5857c40535b1bccc102ffdcc42a086e213016a/lib/note.js#L105-L114 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.