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 |
---|---|---|---|---|---|---|---|---|---|---|---|
myrmex-org/myrmex | packages/lambda/src/index.js | loadIntegrationsHook | function loadIntegrationsHook(region, context, endpoints, integrationResults) {
return require('./hooks/load-integration').hook(region, context, endpoints, integrationResults);
} | javascript | function loadIntegrationsHook(region, context, endpoints, integrationResults) {
return require('./hooks/load-integration').hook(region, context, endpoints, integrationResults);
} | [
"function",
"loadIntegrationsHook",
"(",
"region",
",",
"context",
",",
"endpoints",
",",
"integrationResults",
")",
"{",
"return",
"require",
"(",
"'./hooks/load-integration'",
")",
".",
"hook",
"(",
"region",
",",
"context",
",",
"endpoints",
",",
"integrationResults",
")",
";",
"}"
] | This hook perform the deployment of lambdas in AWS and return integration data
that will be used to configure the related endpoints
@param {string} region - the AWS region where we doing the deployment
@param {Object} endpoints - the list of endpoints that will be deployed
@param {Array} context - a object containing the stage and the environment
@param {Array} integrationResults - the collection of integration results
we will add our own integrations results
to this array
@returns {Promise<Array>} | [
"This",
"hook",
"perform",
"the",
"deployment",
"of",
"lambdas",
"in",
"AWS",
"and",
"return",
"integration",
"data",
"that",
"will",
"be",
"used",
"to",
"configure",
"the",
"related",
"endpoints"
] | 9dba3b8686d87bd603779b00c0545cd12ccad43c | https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/lambda/src/index.js#L234-L236 | train |
glayzzle/grafine | src/graph.js | function (hash, capacity) {
if (!hash) hash = 255;
if (!capacity) capacity = hash * 4;
this._hash = hash;
this._capacity = capacity;
this._nextId = 0;
this._shards = [];
this._indexes = [];
} | javascript | function (hash, capacity) {
if (!hash) hash = 255;
if (!capacity) capacity = hash * 4;
this._hash = hash;
this._capacity = capacity;
this._nextId = 0;
this._shards = [];
this._indexes = [];
} | [
"function",
"(",
"hash",
",",
"capacity",
")",
"{",
"if",
"(",
"!",
"hash",
")",
"hash",
"=",
"255",
";",
"if",
"(",
"!",
"capacity",
")",
"capacity",
"=",
"hash",
"*",
"4",
";",
"this",
".",
"_hash",
"=",
"hash",
";",
"this",
".",
"_capacity",
"=",
"capacity",
";",
"this",
".",
"_nextId",
"=",
"0",
";",
"this",
".",
"_shards",
"=",
"[",
"]",
";",
"this",
".",
"_indexes",
"=",
"[",
"]",
";",
"}"
] | Initialize a storage
@constructor Graph | [
"Initialize",
"a",
"storage"
] | 616ff0a57806d6b809b69e81f3e5ff77919fc3cd | https://github.com/glayzzle/grafine/blob/616ff0a57806d6b809b69e81f3e5ff77919fc3cd/src/graph.js#L14-L22 | train |
|
jefersondaniel/dom-form-serializer | lib/InputWriters.js | setSelectValue | function setSelectValue (elem, value) {
var optionSet, option
var options = elem.options
var values = makeArray(value)
var i = options.length
while (i--) {
option = options[ i ]
/* eslint-disable no-cond-assign */
if (values.indexOf(option.value) > -1) {
option.setAttribute('selected', true)
optionSet = true
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if (!optionSet) {
elem.selectedIndex = -1
}
} | javascript | function setSelectValue (elem, value) {
var optionSet, option
var options = elem.options
var values = makeArray(value)
var i = options.length
while (i--) {
option = options[ i ]
/* eslint-disable no-cond-assign */
if (values.indexOf(option.value) > -1) {
option.setAttribute('selected', true)
optionSet = true
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if (!optionSet) {
elem.selectedIndex = -1
}
} | [
"function",
"setSelectValue",
"(",
"elem",
",",
"value",
")",
"{",
"var",
"optionSet",
",",
"option",
"var",
"options",
"=",
"elem",
".",
"options",
"var",
"values",
"=",
"makeArray",
"(",
"value",
")",
"var",
"i",
"=",
"options",
".",
"length",
"while",
"(",
"i",
"--",
")",
"{",
"option",
"=",
"options",
"[",
"i",
"]",
"if",
"(",
"values",
".",
"indexOf",
"(",
"option",
".",
"value",
")",
">",
"-",
"1",
")",
"{",
"option",
".",
"setAttribute",
"(",
"'selected'",
",",
"true",
")",
"optionSet",
"=",
"true",
"}",
"}",
"if",
"(",
"!",
"optionSet",
")",
"{",
"elem",
".",
"selectedIndex",
"=",
"-",
"1",
"}",
"}"
] | Write select values
@see {@link https://github.com/jquery/jquery/blob/master/src/attributes/val.js|Github}
@param {object} Select element
@param {string|array} Select value | [
"Write",
"select",
"values"
] | 97e0ebf0431b87e4a9b98d87b1d2d037d27c8af2 | https://github.com/jefersondaniel/dom-form-serializer/blob/97e0ebf0431b87e4a9b98d87b1d2d037d27c8af2/lib/InputWriters.js#L42-L62 | train |
tcr/rem | lib/rem.js | disambiguateInvocation | function disambiguateInvocation() {
if (req.body && !req._explicitMime) {
req.setHeader('Content-Type', req.body);
req.removeHeader('Content-Length');
req.body = null;
}
} | javascript | function disambiguateInvocation() {
if (req.body && !req._explicitMime) {
req.setHeader('Content-Type', req.body);
req.removeHeader('Content-Length');
req.body = null;
}
} | [
"function",
"disambiguateInvocation",
"(",
")",
"{",
"if",
"(",
"req",
".",
"body",
"&&",
"!",
"req",
".",
"_explicitMime",
")",
"{",
"req",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"req",
".",
"body",
")",
";",
"req",
".",
"removeHeader",
"(",
"'Content-Length'",
")",
";",
"req",
".",
"body",
"=",
"null",
";",
"}",
"}"
] | Disambiguate between MIME type and string body in route invocation. | [
"Disambiguate",
"between",
"MIME",
"type",
"and",
"string",
"body",
"in",
"route",
"invocation",
"."
] | 992775542608f2de148f6560c248a65a217d6422 | https://github.com/tcr/rem/blob/992775542608f2de148f6560c248a65a217d6422/lib/rem.js#L1695-L1701 | train |
greedbell/gulp-require-modules | path.js | realRequirPath | function realRequirPath(filePath) {
// console.log('realRequirPath:filePath: ' + filePath);
var jsFilePath = filePath + '.js';
if (fs.existsSync(filePath)) {
if (fs.statSync(filePath).isDirectory()) {
jsFilePath = filePath + '.js';
if (fs.existsSync(jsFilePath)) {
return jsFilePath;
} else {
jsFilePath = path.join(filePath, 'index.js');
}
// console.log('realRequirPath:jsFilePath: ' + jsFilePath);
} else if (fs.statSync(filePath).isFile()) {
return filePath;
} else {
return null;
}
} else {
jsFilePath = filePath + '.js';
// console.log('realRequirPath:filePath: ' + filePath);
}
if (fs.existsSync(jsFilePath)) {
// console.log('realRequirPath:filePath: ' + filePath);
return jsFilePath;
} else {
return null;
}
} | javascript | function realRequirPath(filePath) {
// console.log('realRequirPath:filePath: ' + filePath);
var jsFilePath = filePath + '.js';
if (fs.existsSync(filePath)) {
if (fs.statSync(filePath).isDirectory()) {
jsFilePath = filePath + '.js';
if (fs.existsSync(jsFilePath)) {
return jsFilePath;
} else {
jsFilePath = path.join(filePath, 'index.js');
}
// console.log('realRequirPath:jsFilePath: ' + jsFilePath);
} else if (fs.statSync(filePath).isFile()) {
return filePath;
} else {
return null;
}
} else {
jsFilePath = filePath + '.js';
// console.log('realRequirPath:filePath: ' + filePath);
}
if (fs.existsSync(jsFilePath)) {
// console.log('realRequirPath:filePath: ' + filePath);
return jsFilePath;
} else {
return null;
}
} | [
"function",
"realRequirPath",
"(",
"filePath",
")",
"{",
"var",
"jsFilePath",
"=",
"filePath",
"+",
"'.js'",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"if",
"(",
"fs",
".",
"statSync",
"(",
"filePath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"jsFilePath",
"=",
"filePath",
"+",
"'.js'",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"jsFilePath",
")",
")",
"{",
"return",
"jsFilePath",
";",
"}",
"else",
"{",
"jsFilePath",
"=",
"path",
".",
"join",
"(",
"filePath",
",",
"'index.js'",
")",
";",
"}",
"}",
"else",
"if",
"(",
"fs",
".",
"statSync",
"(",
"filePath",
")",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"filePath",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"jsFilePath",
"=",
"filePath",
"+",
"'.js'",
";",
"}",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"jsFilePath",
")",
")",
"{",
"return",
"jsFilePath",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | get real required file path
module to module.js or module/index.js
@param filePath
@returns {*} | [
"get",
"real",
"required",
"file",
"path"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L12-L40 | train |
greedbell/gulp-require-modules | path.js | subModulePath | function subModulePath(subModule, node_modules) {
var index = subModule.indexOf("/");
var length = subModule.length;
if (index <= 0 || index + 1 == length) {
return null;
}
var module = subModule.substring(0, index);
var relative = subModule.substring(index + 1, length);
var moduleDirectory = path.join(node_modules, module);
var filePath = path.join(moduleDirectory, relative);
return realRequirPath(filePath);
} | javascript | function subModulePath(subModule, node_modules) {
var index = subModule.indexOf("/");
var length = subModule.length;
if (index <= 0 || index + 1 == length) {
return null;
}
var module = subModule.substring(0, index);
var relative = subModule.substring(index + 1, length);
var moduleDirectory = path.join(node_modules, module);
var filePath = path.join(moduleDirectory, relative);
return realRequirPath(filePath);
} | [
"function",
"subModulePath",
"(",
"subModule",
",",
"node_modules",
")",
"{",
"var",
"index",
"=",
"subModule",
".",
"indexOf",
"(",
"\"/\"",
")",
";",
"var",
"length",
"=",
"subModule",
".",
"length",
";",
"if",
"(",
"index",
"<=",
"0",
"||",
"index",
"+",
"1",
"==",
"length",
")",
"{",
"return",
"null",
";",
"}",
"var",
"module",
"=",
"subModule",
".",
"substring",
"(",
"0",
",",
"index",
")",
";",
"var",
"relative",
"=",
"subModule",
".",
"substring",
"(",
"index",
"+",
"1",
",",
"length",
")",
";",
"var",
"moduleDirectory",
"=",
"path",
".",
"join",
"(",
"node_modules",
",",
"module",
")",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"moduleDirectory",
",",
"relative",
")",
";",
"return",
"realRequirPath",
"(",
"filePath",
")",
";",
"}"
] | get the full path of subModule
@param subModule subModule
@returns {*} /User/XXXX/node_modules/module/relative.js | [
"get",
"the",
"full",
"path",
"of",
"subModule"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L48-L60 | train |
greedbell/gulp-require-modules | path.js | modulePath | function modulePath(module, node_modules) {
var pkgFile = path.join(node_modules, module, 'package.json');
if (!fs.existsSync(pkgFile)) {
return null;
}
var data = fs.readFileSync(pkgFile, 'utf8');
var pkg = JSON.parse(data);
var fileName = pkg.main || 'index.js';
var filePath = path.join(node_modules, module, fileName);
return realRequirPath(filePath);
} | javascript | function modulePath(module, node_modules) {
var pkgFile = path.join(node_modules, module, 'package.json');
if (!fs.existsSync(pkgFile)) {
return null;
}
var data = fs.readFileSync(pkgFile, 'utf8');
var pkg = JSON.parse(data);
var fileName = pkg.main || 'index.js';
var filePath = path.join(node_modules, module, fileName);
return realRequirPath(filePath);
} | [
"function",
"modulePath",
"(",
"module",
",",
"node_modules",
")",
"{",
"var",
"pkgFile",
"=",
"path",
".",
"join",
"(",
"node_modules",
",",
"module",
",",
"'package.json'",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"pkgFile",
")",
")",
"{",
"return",
"null",
";",
"}",
"var",
"data",
"=",
"fs",
".",
"readFileSync",
"(",
"pkgFile",
",",
"'utf8'",
")",
";",
"var",
"pkg",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"var",
"fileName",
"=",
"pkg",
".",
"main",
"||",
"'index.js'",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"node_modules",
",",
"module",
",",
"fileName",
")",
";",
"return",
"realRequirPath",
"(",
"filePath",
")",
";",
"}"
] | get required module full path
@param module module
@returns {*} /User/XXXX/node_modules/module/index.js | [
"get",
"required",
"module",
"full",
"path"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L68-L78 | train |
greedbell/gulp-require-modules | path.js | requirePath | function requirePath(fromPath, require) {
// console.log('requirePath:fromPath: ' + fromPath);
// console.log('requirePath:require: ' + require);
if (fromPath === null || fromPath === undefined
|| require === null || require === undefined) {
return null;
}
var filePath = path.resolve(path.dirname(fromPath), require);
return realRequirPath(filePath);
} | javascript | function requirePath(fromPath, require) {
// console.log('requirePath:fromPath: ' + fromPath);
// console.log('requirePath:require: ' + require);
if (fromPath === null || fromPath === undefined
|| require === null || require === undefined) {
return null;
}
var filePath = path.resolve(path.dirname(fromPath), require);
return realRequirPath(filePath);
} | [
"function",
"requirePath",
"(",
"fromPath",
",",
"require",
")",
"{",
"if",
"(",
"fromPath",
"===",
"null",
"||",
"fromPath",
"===",
"undefined",
"||",
"require",
"===",
"null",
"||",
"require",
"===",
"undefined",
")",
"{",
"return",
"null",
";",
"}",
"var",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"dirname",
"(",
"fromPath",
")",
",",
"require",
")",
";",
"return",
"realRequirPath",
"(",
"filePath",
")",
";",
"}"
] | get required file full path
@param fromPath /User/XXXX/node_modules/module/index.js
@param require ./require
@returns {*} /User/XXXX/node_modules/module/require/index.js | [
"get",
"required",
"file",
"full",
"path"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L87-L96 | train |
greedbell/gulp-require-modules | path.js | targetPath | function targetPath(fromPath, basePath, targetDirectory) {
// console.log('targetPath:fromPath: ' + fromPath);
// console.log('targetPath:basePath: ' + basePath);
// console.log('targetPath:targetDirectory: ' + targetDirectory);
var relativePath = path.relative(basePath, fromPath);
// console.log('targetPath:relativePath: ' + relativePath);
// console.log('targetPath: ' + path.resolve(targetDirectory, relativePath));
return path.resolve(targetDirectory, relativePath);
} | javascript | function targetPath(fromPath, basePath, targetDirectory) {
// console.log('targetPath:fromPath: ' + fromPath);
// console.log('targetPath:basePath: ' + basePath);
// console.log('targetPath:targetDirectory: ' + targetDirectory);
var relativePath = path.relative(basePath, fromPath);
// console.log('targetPath:relativePath: ' + relativePath);
// console.log('targetPath: ' + path.resolve(targetDirectory, relativePath));
return path.resolve(targetDirectory, relativePath);
} | [
"function",
"targetPath",
"(",
"fromPath",
",",
"basePath",
",",
"targetDirectory",
")",
"{",
"var",
"relativePath",
"=",
"path",
".",
"relative",
"(",
"basePath",
",",
"fromPath",
")",
";",
"return",
"path",
".",
"resolve",
"(",
"targetDirectory",
",",
"relativePath",
")",
";",
"}"
] | full path in targetDirectory
@param fromPath /User/XXXX/node_modules/module/index.js
@param basePath /User/XXXX/node_modules/
@param targetDirectory /User/XXXX/dist/npm/
@returns {*} /User/XXXX/dist/npm/module/index.js | [
"full",
"path",
"in",
"targetDirectory"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L105-L113 | train |
greedbell/gulp-require-modules | path.js | relativePath | function relativePath(from, to) {
// console.log('relativePath:from: ' + from);
// console.log('relativePath:to: ' + to);
var relative = path.relative(from, to);
if (!relative || relative.length < 1) {
return relative;
}
var first = relative.substr(0, 1);
if (first !== '.' && first !== '/') {
relative = './' + relative;
}
// especially used for windows
relative = relative.split(path.sep).join('/');
return relative;
} | javascript | function relativePath(from, to) {
// console.log('relativePath:from: ' + from);
// console.log('relativePath:to: ' + to);
var relative = path.relative(from, to);
if (!relative || relative.length < 1) {
return relative;
}
var first = relative.substr(0, 1);
if (first !== '.' && first !== '/') {
relative = './' + relative;
}
// especially used for windows
relative = relative.split(path.sep).join('/');
return relative;
} | [
"function",
"relativePath",
"(",
"from",
",",
"to",
")",
"{",
"var",
"relative",
"=",
"path",
".",
"relative",
"(",
"from",
",",
"to",
")",
";",
"if",
"(",
"!",
"relative",
"||",
"relative",
".",
"length",
"<",
"1",
")",
"{",
"return",
"relative",
";",
"}",
"var",
"first",
"=",
"relative",
".",
"substr",
"(",
"0",
",",
"1",
")",
";",
"if",
"(",
"first",
"!==",
"'.'",
"&&",
"first",
"!==",
"'/'",
")",
"{",
"relative",
"=",
"'./'",
"+",
"relative",
";",
"}",
"relative",
"=",
"relative",
".",
"split",
"(",
"path",
".",
"sep",
")",
".",
"join",
"(",
"'/'",
")",
";",
"return",
"relative",
";",
"}"
] | get relative path
@param from
@param to
@returns {*} | [
"get",
"relative",
"path"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/path.js#L122-L138 | train |
andrey-p/remarkable-classy | index.js | replaceRenderer | function replaceRenderer(md, renderer) {
var openMethodName = renderer.fullName + "_open";
replacedMethods[openMethodName] = md.renderer.rules[openMethodName];
md.renderer.rules[openMethodName] = function (tokens, idx) {
var classy, result;
// first get the result as per the original method we replaced
result = replacedMethods[openMethodName].apply(null, arguments).trim();
if (renderer.inline) {
classy = getClassyFromInlineElement(tokens, idx, renderer.fullName);
} else {
classy = getClassyFromBlockElement(tokens, idx, renderer.fullName);
}
if (classy) {
result = result.replace(new RegExp("<" + renderer.pattern), "$& class=\"" + classy.content + "\"");
}
return result;
};
} | javascript | function replaceRenderer(md, renderer) {
var openMethodName = renderer.fullName + "_open";
replacedMethods[openMethodName] = md.renderer.rules[openMethodName];
md.renderer.rules[openMethodName] = function (tokens, idx) {
var classy, result;
// first get the result as per the original method we replaced
result = replacedMethods[openMethodName].apply(null, arguments).trim();
if (renderer.inline) {
classy = getClassyFromInlineElement(tokens, idx, renderer.fullName);
} else {
classy = getClassyFromBlockElement(tokens, idx, renderer.fullName);
}
if (classy) {
result = result.replace(new RegExp("<" + renderer.pattern), "$& class=\"" + classy.content + "\"");
}
return result;
};
} | [
"function",
"replaceRenderer",
"(",
"md",
",",
"renderer",
")",
"{",
"var",
"openMethodName",
"=",
"renderer",
".",
"fullName",
"+",
"\"_open\"",
";",
"replacedMethods",
"[",
"openMethodName",
"]",
"=",
"md",
".",
"renderer",
".",
"rules",
"[",
"openMethodName",
"]",
";",
"md",
".",
"renderer",
".",
"rules",
"[",
"openMethodName",
"]",
"=",
"function",
"(",
"tokens",
",",
"idx",
")",
"{",
"var",
"classy",
",",
"result",
";",
"result",
"=",
"replacedMethods",
"[",
"openMethodName",
"]",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"renderer",
".",
"inline",
")",
"{",
"classy",
"=",
"getClassyFromInlineElement",
"(",
"tokens",
",",
"idx",
",",
"renderer",
".",
"fullName",
")",
";",
"}",
"else",
"{",
"classy",
"=",
"getClassyFromBlockElement",
"(",
"tokens",
",",
"idx",
",",
"renderer",
".",
"fullName",
")",
";",
"}",
"if",
"(",
"classy",
")",
"{",
"result",
"=",
"result",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"\"<\"",
"+",
"renderer",
".",
"pattern",
")",
",",
"\"$& class=\\\"\"",
"+",
"\\\"",
"+",
"classy",
".",
"content",
")",
";",
"}",
"\"\\\"\"",
"}",
";",
"}"
] | replace all rules that we want to enable classy on | [
"replace",
"all",
"rules",
"that",
"we",
"want",
"to",
"enable",
"classy",
"on"
] | f4517df3d9d8a270c7e1d1d0ca1c13cd4a88bb4a | https://github.com/andrey-p/remarkable-classy/blob/f4517df3d9d8a270c7e1d1d0ca1c13cd4a88bb4a/index.js#L138-L160 | train |
segmentio/ecs-logs-js | lib/index.js | Logger | function Logger(options) {
if (!options) {
options = { };
}
if (typeof options.level === 'undefined') {
options.level = 'debug';
}
if (!options.transports) {
options.transports = [new Transport(options)];
delete options.name;
delete options.hostname;
delete options.timestamp;
delete options.formatter;
}
Logger.super_.call(this, options);
this.setLevels(options.levels || Levels);
} | javascript | function Logger(options) {
if (!options) {
options = { };
}
if (typeof options.level === 'undefined') {
options.level = 'debug';
}
if (!options.transports) {
options.transports = [new Transport(options)];
delete options.name;
delete options.hostname;
delete options.timestamp;
delete options.formatter;
}
Logger.super_.call(this, options);
this.setLevels(options.levels || Levels);
} | [
"function",
"Logger",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"options",
".",
"level",
"===",
"'undefined'",
")",
"{",
"options",
".",
"level",
"=",
"'debug'",
";",
"}",
"if",
"(",
"!",
"options",
".",
"transports",
")",
"{",
"options",
".",
"transports",
"=",
"[",
"new",
"Transport",
"(",
"options",
")",
"]",
";",
"delete",
"options",
".",
"name",
";",
"delete",
"options",
".",
"hostname",
";",
"delete",
"options",
".",
"timestamp",
";",
"delete",
"options",
".",
"formatter",
";",
"}",
"Logger",
".",
"super_",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"this",
".",
"setLevels",
"(",
"options",
".",
"levels",
"||",
"Levels",
")",
";",
"}"
] | The Logger type is a winston logger with preconfigured defaults to output
log messages compatible with ecs-logs.
@example
var ecslogs = require('ecs-logs-js');
var log = new ecslogs.Logger({
level: 'info'
});
log.info('Hi there!');
@param {Object} [options] The configuration object for the new logger,
besides the properties documented here the options object can also carry all
properties that the Transport and Formatter constructors accept, they will be
passed to the default transport and formatter instantiated if none was given.
@param {string} [level] The minimum level for log messages this logger will
pass to its transports, defaults to 'debug'
@param {transports} [Object[]] An array of winston transports that the logger
will be passing log messages to, defaults to a single instance of Transport. | [
"The",
"Logger",
"type",
"is",
"a",
"winston",
"logger",
"with",
"preconfigured",
"defaults",
"to",
"output",
"log",
"messages",
"compatible",
"with",
"ecs",
"-",
"logs",
"."
] | 0e089554ac6ff77b9cbebbaae45a40a3a14d7336 | https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L55-L74 | train |
segmentio/ecs-logs-js | lib/index.js | Transport | function Transport(options) {
if (!options) {
options = { };
}
this.name = options.name || 'ecs-logs';
this.level = options.level || 'debug';
this.output = options.output || function(s) {
process.stdout.write(s + '\n');
};
this.timestamp = options.timestamp || Date.now;
this.formatter = options.formatter || new Formatter({
hostname: options.hostname
});
} | javascript | function Transport(options) {
if (!options) {
options = { };
}
this.name = options.name || 'ecs-logs';
this.level = options.level || 'debug';
this.output = options.output || function(s) {
process.stdout.write(s + '\n');
};
this.timestamp = options.timestamp || Date.now;
this.formatter = options.formatter || new Formatter({
hostname: options.hostname
});
} | [
"function",
"Transport",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"this",
".",
"name",
"=",
"options",
".",
"name",
"||",
"'ecs-logs'",
";",
"this",
".",
"level",
"=",
"options",
".",
"level",
"||",
"'debug'",
";",
"this",
".",
"output",
"=",
"options",
".",
"output",
"||",
"function",
"(",
"s",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"s",
"+",
"'\\n'",
")",
";",
"}",
";",
"\\n",
"this",
".",
"timestamp",
"=",
"options",
".",
"timestamp",
"||",
"Date",
".",
"now",
";",
"}"
] | The Transport type implements a winston log transport preconfigured to
output log messages compatible with ecs-logs.
@example
var ecslogs = require('ecs-logs-js');
var winston = require('winston');
// Instantiate an ecs-logs compatible winston logger with ecslogs.Transport
var logger = new winston.Logger({
transports: [
new ecslogs.Transport()
]
});
@param {Object} [options] The configuration object for the new transport,
besides the properties documented here the options object can also carry all
properties that the Formatter constructor accepts, they will be passed to the
default formatter instantiated if none was given.
@param {string} [options.name] The transport name, defaults to 'ecs-logs'
@param {string} [options.level] The transport level, defaults to 'debug'
messages, this is passed to the default formatter if none was provided
@param {function} [options.output] A function called when the transport has
a log message to send, defaults to writing to stdout.
@param {function} [options.timestamp] A function returning timestamps,
defaults to Date.now
@param {Object} [options.formatter] A winston formatter, defaults to an
instance of Formatter | [
"The",
"Transport",
"type",
"implements",
"a",
"winston",
"log",
"transport",
"preconfigured",
"to",
"output",
"log",
"messages",
"compatible",
"with",
"ecs",
"-",
"logs",
"."
] | 0e089554ac6ff77b9cbebbaae45a40a3a14d7336 | https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L112-L126 | train |
segmentio/ecs-logs-js | lib/index.js | Formatter | function Formatter(options) {
function format(entry) { // eslint-disable-line
return stringify(makeEvent(entry, format.hostname));
}
if (!options) {
options = { };
}
Object.setPrototypeOf(format, Formatter.prototype);
format.hostname = options.hostname || os.hostname();
return format;
} | javascript | function Formatter(options) {
function format(entry) { // eslint-disable-line
return stringify(makeEvent(entry, format.hostname));
}
if (!options) {
options = { };
}
Object.setPrototypeOf(format, Formatter.prototype);
format.hostname = options.hostname || os.hostname();
return format;
} | [
"function",
"Formatter",
"(",
"options",
")",
"{",
"function",
"format",
"(",
"entry",
")",
"{",
"return",
"stringify",
"(",
"makeEvent",
"(",
"entry",
",",
"format",
".",
"hostname",
")",
")",
";",
"}",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"Object",
".",
"setPrototypeOf",
"(",
"format",
",",
"Formatter",
".",
"prototype",
")",
";",
"format",
".",
"hostname",
"=",
"options",
".",
"hostname",
"||",
"os",
".",
"hostname",
"(",
")",
";",
"return",
"format",
";",
"}"
] | The Formatter type implements a winston log formatter that produces messages
compatible with ecs-logs.
The object returned when instantiating the Formatter type is callable. When
called, it expects a log entry object.
@example
var ecslogs = require('ecs-logs-js');
var winston = require('winston');
// Instantiate an ecs-logs compatible winston logger with ecslogs.Formatter
var logger = new winston.Logger({
transports: [
new winston.transports.Console({
timestamp: Date.now,
formatter: new ecslogs.Formatter()
})
]
});
@example
var ecslogs = require('ecs-logs-js');
var formatter = new ecslogs.Formatter();
// Returns a serialized log message compatible with ecs-logs.
var s = formatter({
message: 'the log message',
level: 'info',
meta: {
'User-Agent': 'node'
}
});
@param {Object} [options] The configuration object for the new formatter
@param {string} [options.hostname] The hostname to report in the log
messages, defaults to the value returned by os.hostname()
@return {string} When a formatter instance is called it accepts a log entry
as argument and returns a JSON representation of the entry in a format
compatible with ecs-logs | [
"The",
"Formatter",
"type",
"implements",
"a",
"winston",
"log",
"formatter",
"that",
"produces",
"messages",
"compatible",
"with",
"ecs",
"-",
"logs",
"."
] | 0e089554ac6ff77b9cbebbaae45a40a3a14d7336 | https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L184-L196 | train |
segmentio/ecs-logs-js | lib/index.js | makeEvent | function makeEvent(entry, hostname) {
var errors = extractErrors(entry.meta);
var event = {
level: entry.level ? entry.level.toUpperCase() : 'NONE',
time: new Date(
entry.timestamp ? entry.timestamp() : Date.now()
).toISOString(),
info: { },
data: entry.meta || { },
message: entry.message || ''
};
if (hostname) {
event.info.host = hostname;
}
if (errors.length) {
errors.forEach(function(e, i) {
errors[i] = makeEventError(e);
});
event.info.errors = errors;
}
return event;
} | javascript | function makeEvent(entry, hostname) {
var errors = extractErrors(entry.meta);
var event = {
level: entry.level ? entry.level.toUpperCase() : 'NONE',
time: new Date(
entry.timestamp ? entry.timestamp() : Date.now()
).toISOString(),
info: { },
data: entry.meta || { },
message: entry.message || ''
};
if (hostname) {
event.info.host = hostname;
}
if (errors.length) {
errors.forEach(function(e, i) {
errors[i] = makeEventError(e);
});
event.info.errors = errors;
}
return event;
} | [
"function",
"makeEvent",
"(",
"entry",
",",
"hostname",
")",
"{",
"var",
"errors",
"=",
"extractErrors",
"(",
"entry",
".",
"meta",
")",
";",
"var",
"event",
"=",
"{",
"level",
":",
"entry",
".",
"level",
"?",
"entry",
".",
"level",
".",
"toUpperCase",
"(",
")",
":",
"'NONE'",
",",
"time",
":",
"new",
"Date",
"(",
"entry",
".",
"timestamp",
"?",
"entry",
".",
"timestamp",
"(",
")",
":",
"Date",
".",
"now",
"(",
")",
")",
".",
"toISOString",
"(",
")",
",",
"info",
":",
"{",
"}",
",",
"data",
":",
"entry",
".",
"meta",
"||",
"{",
"}",
",",
"message",
":",
"entry",
".",
"message",
"||",
"''",
"}",
";",
"if",
"(",
"hostname",
")",
"{",
"event",
".",
"info",
".",
"host",
"=",
"hostname",
";",
"}",
"if",
"(",
"errors",
".",
"length",
")",
"{",
"errors",
".",
"forEach",
"(",
"function",
"(",
"e",
",",
"i",
")",
"{",
"errors",
"[",
"i",
"]",
"=",
"makeEventError",
"(",
"e",
")",
";",
"}",
")",
";",
"event",
".",
"info",
".",
"errors",
"=",
"errors",
";",
"}",
"return",
"event",
";",
"}"
] | Given a log entry and an optional hostname the function generates and returns
an ecs-logs event.
@param {Object} entry A log entry, this is the type of objects received by
formatters.
@param {string} [hostname] An optional hostname to set on the event.
@return {Object} An ecs-logs event generated from the arguments. | [
"Given",
"a",
"log",
"entry",
"and",
"an",
"optional",
"hostname",
"the",
"function",
"generates",
"and",
"returns",
"an",
"ecs",
"-",
"logs",
"event",
"."
] | 0e089554ac6ff77b9cbebbaae45a40a3a14d7336 | https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L211-L235 | train |
segmentio/ecs-logs-js | lib/index.js | makeEventError | function makeEventError(error) {
var stack = error.stack.split('\n');
stack.splice(0, 1);
stack.forEach(function(s, i) {
stack[i] = s.trim();
});
return {
type: typeName(error),
error: error.message,
stack: stack.filter(function(s) {
return s;
})
};
} | javascript | function makeEventError(error) {
var stack = error.stack.split('\n');
stack.splice(0, 1);
stack.forEach(function(s, i) {
stack[i] = s.trim();
});
return {
type: typeName(error),
error: error.message,
stack: stack.filter(function(s) {
return s;
})
};
} | [
"function",
"makeEventError",
"(",
"error",
")",
"{",
"var",
"stack",
"=",
"error",
".",
"stack",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"stack",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"stack",
".",
"forEach",
"(",
"function",
"(",
"s",
",",
"i",
")",
"{",
"stack",
"[",
"i",
"]",
"=",
"s",
".",
"trim",
"(",
")",
";",
"}",
")",
";",
"}"
] | Given an error object, returns an event error as expected in the `info` field
of ecs-logs messages.
@param {Object} error The error object to convert.
@return {Object} An event error object generated from the argument. | [
"Given",
"an",
"error",
"object",
"returns",
"an",
"event",
"error",
"as",
"expected",
"in",
"the",
"info",
"field",
"of",
"ecs",
"-",
"logs",
"messages",
"."
] | 0e089554ac6ff77b9cbebbaae45a40a3a14d7336 | https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L245-L260 | train |
segmentio/ecs-logs-js | lib/index.js | extractErrors | function extractErrors(obj) {
if (obj instanceof Error) {
return [obj];
}
var errors = [];
if (obj) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
if (val instanceof Error) {
errors.push(val);
delete obj[key];
}
});
}
return errors;
} | javascript | function extractErrors(obj) {
if (obj instanceof Error) {
return [obj];
}
var errors = [];
if (obj) {
Object.keys(obj).forEach(function(key) {
var val = obj[key];
if (val instanceof Error) {
errors.push(val);
delete obj[key];
}
});
}
return errors;
} | [
"function",
"extractErrors",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
"instanceof",
"Error",
")",
"{",
"return",
"[",
"obj",
"]",
";",
"}",
"var",
"errors",
"=",
"[",
"]",
";",
"if",
"(",
"obj",
")",
"{",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"var",
"val",
"=",
"obj",
"[",
"key",
"]",
";",
"if",
"(",
"val",
"instanceof",
"Error",
")",
"{",
"errors",
".",
"push",
"(",
"val",
")",
";",
"delete",
"obj",
"[",
"key",
"]",
";",
"}",
"}",
")",
";",
"}",
"return",
"errors",
";",
"}"
] | Scans the object passed as argument looking for Error values. The values that
matched are removed from the object and placed in the array returned by the
function.
Only the top-level properties of the object are checked, the function doesn't
search the object recursively.
@param {Object} obj The object to extract errors from.
@return {Array} The list of errors extracted from the object. | [
"Scans",
"the",
"object",
"passed",
"as",
"argument",
"looking",
"for",
"Error",
"values",
".",
"The",
"values",
"that",
"matched",
"are",
"removed",
"from",
"the",
"object",
"and",
"placed",
"in",
"the",
"array",
"returned",
"by",
"the",
"function",
"."
] | 0e089554ac6ff77b9cbebbaae45a40a3a14d7336 | https://github.com/segmentio/ecs-logs-js/blob/0e089554ac6ff77b9cbebbaae45a40a3a14d7336/lib/index.js#L274-L292 | train |
jamonserrano/jamon | jamon.js | addRemoveToggleClass | function addRemoveToggleClass (context, className, method) {
// Split by spaces, then remove empty elements caused by extra whitespace
const classNames = trimAndSplit(className);
if (classNames.length) {
context.forEach(element => {
if (method !== "toggle") {
// 'add' and 'remove' accept multiple parameters…
element.classList[method](...classNames);
} else {
// while 'toggle' accepts only one
classNames.forEach(className => element.classList.toggle(className))
}
});
}
return context;
} | javascript | function addRemoveToggleClass (context, className, method) {
// Split by spaces, then remove empty elements caused by extra whitespace
const classNames = trimAndSplit(className);
if (classNames.length) {
context.forEach(element => {
if (method !== "toggle") {
// 'add' and 'remove' accept multiple parameters…
element.classList[method](...classNames);
} else {
// while 'toggle' accepts only one
classNames.forEach(className => element.classList.toggle(className))
}
});
}
return context;
} | [
"function",
"addRemoveToggleClass",
"(",
"context",
",",
"className",
",",
"method",
")",
"{",
"const",
"classNames",
"=",
"trimAndSplit",
"(",
"className",
")",
";",
"if",
"(",
"classNames",
".",
"length",
")",
"{",
"context",
".",
"forEach",
"(",
"element",
"=>",
"{",
"if",
"(",
"method",
"!==",
"\"toggle\"",
")",
"{",
"element",
".",
"classList",
"[",
"method",
"]",
"(",
"...",
"classNames",
")",
";",
"}",
"else",
"{",
"classNames",
".",
"forEach",
"(",
"className",
"=>",
"element",
".",
"classList",
".",
"toggle",
"(",
"className",
")",
")",
"}",
"}",
")",
";",
"}",
"return",
"context",
";",
"}"
] | Add, remove, or toggle class names
@private
@param {Jamon} context - The Jamón instance
@param {string} className - Space-separated class names
@param {string} method - Method to use on the class name(s)
@return {Jamon} | [
"Add",
"remove",
"or",
"toggle",
"class",
"names"
] | 3640aba49009938a35763d0ed2170d3b63f9f6c2 | https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L111-L128 | train |
jamonserrano/jamon | jamon.js | getSetRemoveProperty | function getSetRemoveProperty (collection, property, value) {
if (isUndefined(value)) {
// get property of first element if there is one
return collection[0] ? collection[0][property] : undefined;
} else if (value !== null) {
collection.forEach(element => element[property] = value)
} else {
collection.forEach(element => delete element[property])
}
return collection;
} | javascript | function getSetRemoveProperty (collection, property, value) {
if (isUndefined(value)) {
// get property of first element if there is one
return collection[0] ? collection[0][property] : undefined;
} else if (value !== null) {
collection.forEach(element => element[property] = value)
} else {
collection.forEach(element => delete element[property])
}
return collection;
} | [
"function",
"getSetRemoveProperty",
"(",
"collection",
",",
"property",
",",
"value",
")",
"{",
"if",
"(",
"isUndefined",
"(",
"value",
")",
")",
"{",
"return",
"collection",
"[",
"0",
"]",
"?",
"collection",
"[",
"0",
"]",
"[",
"property",
"]",
":",
"undefined",
";",
"}",
"else",
"if",
"(",
"value",
"!==",
"null",
")",
"{",
"collection",
".",
"forEach",
"(",
"element",
"=>",
"element",
"[",
"property",
"]",
"=",
"value",
")",
"}",
"else",
"{",
"collection",
".",
"forEach",
"(",
"element",
"=>",
"delete",
"element",
"[",
"property",
"]",
")",
"}",
"return",
"collection",
";",
"}"
] | Get, set or remove element properties
@private
@param {Jamon} collection - The Jamón instance
@param {string} property - Property name
@param {string|null|undefined} value - Property value (null to remove property)
@return {Jamon} | [
"Get",
"set",
"or",
"remove",
"element",
"properties"
] | 3640aba49009938a35763d0ed2170d3b63f9f6c2 | https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L138-L149 | train |
jamonserrano/jamon | jamon.js | getDimension | function getDimension (collection, dimension) {
const first = collection[0];
if (first && typeof first.getBoundingClientRect === "function") {
return first.getBoundingClientRect()[dimension];
}
} | javascript | function getDimension (collection, dimension) {
const first = collection[0];
if (first && typeof first.getBoundingClientRect === "function") {
return first.getBoundingClientRect()[dimension];
}
} | [
"function",
"getDimension",
"(",
"collection",
",",
"dimension",
")",
"{",
"const",
"first",
"=",
"collection",
"[",
"0",
"]",
";",
"if",
"(",
"first",
"&&",
"typeof",
"first",
".",
"getBoundingClientRect",
"===",
"\"function\"",
")",
"{",
"return",
"first",
".",
"getBoundingClientRect",
"(",
")",
"[",
"dimension",
"]",
";",
"}",
"}"
] | Get the width or height of the first element in the collection
@private
@param {Jamon} collection - The Jamón instance
@param {string} dimension - The dimension to get
@return {(number|undefined)} - The result | [
"Get",
"the",
"width",
"or",
"height",
"of",
"the",
"first",
"element",
"in",
"the",
"collection"
] | 3640aba49009938a35763d0ed2170d3b63f9f6c2 | https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L158-L163 | train |
jamonserrano/jamon | jamon.js | callNodeMethod | function callNodeMethod(targets, subjects, method, returnTargets) {
targets.forEach(target => {
const subject = targets.indexOf(target) ? clone(subjects, true) : subjects;
if (isIterable(subjects)) {
target[method](...subject);
} else {
target[method](subject);
}
normalize(target);
});
return returnTargets ? targets : subjects;
} | javascript | function callNodeMethod(targets, subjects, method, returnTargets) {
targets.forEach(target => {
const subject = targets.indexOf(target) ? clone(subjects, true) : subjects;
if (isIterable(subjects)) {
target[method](...subject);
} else {
target[method](subject);
}
normalize(target);
});
return returnTargets ? targets : subjects;
} | [
"function",
"callNodeMethod",
"(",
"targets",
",",
"subjects",
",",
"method",
",",
"returnTargets",
")",
"{",
"targets",
".",
"forEach",
"(",
"target",
"=>",
"{",
"const",
"subject",
"=",
"targets",
".",
"indexOf",
"(",
"target",
")",
"?",
"clone",
"(",
"subjects",
",",
"true",
")",
":",
"subjects",
";",
"if",
"(",
"isIterable",
"(",
"subjects",
")",
")",
"{",
"target",
"[",
"method",
"]",
"(",
"...",
"subject",
")",
";",
"}",
"else",
"{",
"target",
"[",
"method",
"]",
"(",
"subject",
")",
";",
"}",
"normalize",
"(",
"target",
")",
";",
"}",
")",
";",
"return",
"returnTargets",
"?",
"targets",
":",
"subjects",
";",
"}"
] | Call node methods on multiple targets and with multiple subjects
@private
@param {Jamon} targets
@param {Jamon} subjects
@param {string} method - node method to call
@param {boolean} returnTargets - return the targets?
@return {Jamon}
@todo jamonize both targets and subjects if needed | [
"Call",
"node",
"methods",
"on",
"multiple",
"targets",
"and",
"with",
"multiple",
"subjects"
] | 3640aba49009938a35763d0ed2170d3b63f9f6c2 | https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L175-L189 | train |
jamonserrano/jamon | jamon.js | normalize | function normalize(node, method) {
if (method === "prepend" || method === "append") {
node.normalize();
} else if (node.parentNode) {
node.parentNode.normalize();
}
} | javascript | function normalize(node, method) {
if (method === "prepend" || method === "append") {
node.normalize();
} else if (node.parentNode) {
node.parentNode.normalize();
}
} | [
"function",
"normalize",
"(",
"node",
",",
"method",
")",
"{",
"if",
"(",
"method",
"===",
"\"prepend\"",
"||",
"method",
"===",
"\"append\"",
")",
"{",
"node",
".",
"normalize",
"(",
")",
";",
"}",
"else",
"if",
"(",
"node",
".",
"parentNode",
")",
"{",
"node",
".",
"parentNode",
".",
"normalize",
"(",
")",
";",
"}",
"}"
] | Normalize text nodes
@private
@param {Node} node
@param {string} method - node method that needs normalization | [
"Normalize",
"text",
"nodes"
] | 3640aba49009938a35763d0ed2170d3b63f9f6c2 | https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L197-L203 | train |
jamonserrano/jamon | jamon.js | clone | function clone(collection, deep = true) {
const clones = new Jamon();
collection.forEach(element => clones.push(element.cloneNode(deep)));
return clones;
} | javascript | function clone(collection, deep = true) {
const clones = new Jamon();
collection.forEach(element => clones.push(element.cloneNode(deep)));
return clones;
} | [
"function",
"clone",
"(",
"collection",
",",
"deep",
"=",
"true",
")",
"{",
"const",
"clones",
"=",
"new",
"Jamon",
"(",
")",
";",
"collection",
".",
"forEach",
"(",
"element",
"=>",
"clones",
".",
"push",
"(",
"element",
".",
"cloneNode",
"(",
"deep",
")",
")",
")",
";",
"return",
"clones",
";",
"}"
] | Clone each element in a collection
@private
@param {Jamon} collection
@param {boolean} [deep=true] - deep clone?
@return {Jamon} the cloned collection | [
"Clone",
"each",
"element",
"in",
"a",
"collection"
] | 3640aba49009938a35763d0ed2170d3b63f9f6c2 | https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L212-L218 | train |
jamonserrano/jamon | jamon.js | getProxiedListener | function getProxiedListener (listener, selector) {
// get existing proxy storage of the listener
let proxies = listener[proxyKey];
// the proxy to return
let proxy;
// or create the storage
if (isUndefined(proxies)) {
proxies = new Map();
listener[proxyKey] = proxies;
}
if (proxies.has(selector)) {
// a proxy for this selector already exists - get it
proxy = proxies.get(selector);
} else {
// create a new proxy for this selector
proxy = function (e) {
const target = e.target;
// only call the listener if the target matches the selector
if (target.matches(selector)) {
listener.call(target, e);
}
}
// store proxy
proxies.set(selector, proxy);
}
return proxy;
} | javascript | function getProxiedListener (listener, selector) {
// get existing proxy storage of the listener
let proxies = listener[proxyKey];
// the proxy to return
let proxy;
// or create the storage
if (isUndefined(proxies)) {
proxies = new Map();
listener[proxyKey] = proxies;
}
if (proxies.has(selector)) {
// a proxy for this selector already exists - get it
proxy = proxies.get(selector);
} else {
// create a new proxy for this selector
proxy = function (e) {
const target = e.target;
// only call the listener if the target matches the selector
if (target.matches(selector)) {
listener.call(target, e);
}
}
// store proxy
proxies.set(selector, proxy);
}
return proxy;
} | [
"function",
"getProxiedListener",
"(",
"listener",
",",
"selector",
")",
"{",
"let",
"proxies",
"=",
"listener",
"[",
"proxyKey",
"]",
";",
"let",
"proxy",
";",
"if",
"(",
"isUndefined",
"(",
"proxies",
")",
")",
"{",
"proxies",
"=",
"new",
"Map",
"(",
")",
";",
"listener",
"[",
"proxyKey",
"]",
"=",
"proxies",
";",
"}",
"if",
"(",
"proxies",
".",
"has",
"(",
"selector",
")",
")",
"{",
"proxy",
"=",
"proxies",
".",
"get",
"(",
"selector",
")",
";",
"}",
"else",
"{",
"proxy",
"=",
"function",
"(",
"e",
")",
"{",
"const",
"target",
"=",
"e",
".",
"target",
";",
"if",
"(",
"target",
".",
"matches",
"(",
"selector",
")",
")",
"{",
"listener",
".",
"call",
"(",
"target",
",",
"e",
")",
";",
"}",
"}",
"proxies",
".",
"set",
"(",
"selector",
",",
"proxy",
")",
";",
"}",
"return",
"proxy",
";",
"}"
] | Generate a proxy for the given listener-selector combination
@private
@param {Function} listener - the listener function
@param {string} selector - the selector
@return {Function} - the listener or the proxy | [
"Generate",
"a",
"proxy",
"for",
"the",
"given",
"listener",
"-",
"selector",
"combination"
] | 3640aba49009938a35763d0ed2170d3b63f9f6c2 | https://github.com/jamonserrano/jamon/blob/3640aba49009938a35763d0ed2170d3b63f9f6c2/jamon.js#L227-L256 | train |
vorpaljs/vorpal-grep | dist/grep.js | walkDirRecursive | function walkDirRecursive(arr, currentDirPath) {
fs.readdirSync(currentDirPath).forEach(function (name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
arr = walkDirRecursive(arr, filePath);
} else {
arr.push(filePath);
}
});
return arr;
} | javascript | function walkDirRecursive(arr, currentDirPath) {
fs.readdirSync(currentDirPath).forEach(function (name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
arr = walkDirRecursive(arr, filePath);
} else {
arr.push(filePath);
}
});
return arr;
} | [
"function",
"walkDirRecursive",
"(",
"arr",
",",
"currentDirPath",
")",
"{",
"fs",
".",
"readdirSync",
"(",
"currentDirPath",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"currentDirPath",
",",
"name",
")",
";",
"var",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"filePath",
")",
";",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"arr",
"=",
"walkDirRecursive",
"(",
"arr",
",",
"filePath",
")",
";",
"}",
"else",
"{",
"arr",
".",
"push",
"(",
"filePath",
")",
";",
"}",
"}",
")",
";",
"return",
"arr",
";",
"}"
] | Recursively walks through and executes
a callback function for each directory found.
@param {String} currentDirPath
@param {Function} callback
@api private | [
"Recursively",
"walks",
"through",
"and",
"executes",
"a",
"callback",
"function",
"for",
"each",
"directory",
"found",
"."
] | a9f19ceca6099702134f59618e6809d9d6fb4e59 | https://github.com/vorpaljs/vorpal-grep/blob/a9f19ceca6099702134f59618e6809d9d6fb4e59/dist/grep.js#L226-L237 | train |
shakyShane/svg-sprite-data | lib/svg-sprite.js | SVGSprite | function SVGSprite(options) {
options = _.extend({}, options);
// Validate & prepare the options
this._options = _.extend(defaultOptions, options);
this._options.prefix = (new String(this._options.prefix || '').trim()) || null;
this._options.common = (new String(this._options.common || '').trim()) || null;
this._options.maxwidth = Math.abs(parseInt(this._options.maxwidth || 1000, 10));
this._options.maxheight = Math.abs(parseInt(this._options.maxheight || 1000, 10));
this._options.padding = Math.abs(parseInt(this._options.padding, 10));
this._options.pseudo = (new String(this._options.pseudo).trim()) || '~';
this._options.dims = !!this._options.dims;
this._options.verbose = Math.min(Math.max(0, parseInt(this._options.verbose, 10)), 3);
this._options.render = _.extend({css: true}, this._options.render);
this._options.cleanwith = (new String(this._options.cleanwith || '').trim()) || null;
this._options.cleanconfig = _.extend({}, this._options.cleanconfig || {});
this.namespacePow = [];
// Reset all internal stacks
this._reset();
var SVGO = require('svgo');
this._options.cleanconfig.plugins = svgoDefaults.concat(this._options.cleanconfig.plugins || []);
this._cleaner = new SVGO(this._options.cleanconfig);
this._clean = this._cleanSVGO;
} | javascript | function SVGSprite(options) {
options = _.extend({}, options);
// Validate & prepare the options
this._options = _.extend(defaultOptions, options);
this._options.prefix = (new String(this._options.prefix || '').trim()) || null;
this._options.common = (new String(this._options.common || '').trim()) || null;
this._options.maxwidth = Math.abs(parseInt(this._options.maxwidth || 1000, 10));
this._options.maxheight = Math.abs(parseInt(this._options.maxheight || 1000, 10));
this._options.padding = Math.abs(parseInt(this._options.padding, 10));
this._options.pseudo = (new String(this._options.pseudo).trim()) || '~';
this._options.dims = !!this._options.dims;
this._options.verbose = Math.min(Math.max(0, parseInt(this._options.verbose, 10)), 3);
this._options.render = _.extend({css: true}, this._options.render);
this._options.cleanwith = (new String(this._options.cleanwith || '').trim()) || null;
this._options.cleanconfig = _.extend({}, this._options.cleanconfig || {});
this.namespacePow = [];
// Reset all internal stacks
this._reset();
var SVGO = require('svgo');
this._options.cleanconfig.plugins = svgoDefaults.concat(this._options.cleanconfig.plugins || []);
this._cleaner = new SVGO(this._options.cleanconfig);
this._clean = this._cleanSVGO;
} | [
"function",
"SVGSprite",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"options",
")",
";",
"this",
".",
"_options",
"=",
"_",
".",
"extend",
"(",
"defaultOptions",
",",
"options",
")",
";",
"this",
".",
"_options",
".",
"prefix",
"=",
"(",
"new",
"String",
"(",
"this",
".",
"_options",
".",
"prefix",
"||",
"''",
")",
".",
"trim",
"(",
")",
")",
"||",
"null",
";",
"this",
".",
"_options",
".",
"common",
"=",
"(",
"new",
"String",
"(",
"this",
".",
"_options",
".",
"common",
"||",
"''",
")",
".",
"trim",
"(",
")",
")",
"||",
"null",
";",
"this",
".",
"_options",
".",
"maxwidth",
"=",
"Math",
".",
"abs",
"(",
"parseInt",
"(",
"this",
".",
"_options",
".",
"maxwidth",
"||",
"1000",
",",
"10",
")",
")",
";",
"this",
".",
"_options",
".",
"maxheight",
"=",
"Math",
".",
"abs",
"(",
"parseInt",
"(",
"this",
".",
"_options",
".",
"maxheight",
"||",
"1000",
",",
"10",
")",
")",
";",
"this",
".",
"_options",
".",
"padding",
"=",
"Math",
".",
"abs",
"(",
"parseInt",
"(",
"this",
".",
"_options",
".",
"padding",
",",
"10",
")",
")",
";",
"this",
".",
"_options",
".",
"pseudo",
"=",
"(",
"new",
"String",
"(",
"this",
".",
"_options",
".",
"pseudo",
")",
".",
"trim",
"(",
")",
")",
"||",
"'~'",
";",
"this",
".",
"_options",
".",
"dims",
"=",
"!",
"!",
"this",
".",
"_options",
".",
"dims",
";",
"this",
".",
"_options",
".",
"verbose",
"=",
"Math",
".",
"min",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"parseInt",
"(",
"this",
".",
"_options",
".",
"verbose",
",",
"10",
")",
")",
",",
"3",
")",
";",
"this",
".",
"_options",
".",
"render",
"=",
"_",
".",
"extend",
"(",
"{",
"css",
":",
"true",
"}",
",",
"this",
".",
"_options",
".",
"render",
")",
";",
"this",
".",
"_options",
".",
"cleanwith",
"=",
"(",
"new",
"String",
"(",
"this",
".",
"_options",
".",
"cleanwith",
"||",
"''",
")",
".",
"trim",
"(",
")",
")",
"||",
"null",
";",
"this",
".",
"_options",
".",
"cleanconfig",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"_options",
".",
"cleanconfig",
"||",
"{",
"}",
")",
";",
"this",
".",
"namespacePow",
"=",
"[",
"]",
";",
"this",
".",
"_reset",
"(",
")",
";",
"var",
"SVGO",
"=",
"require",
"(",
"'svgo'",
")",
";",
"this",
".",
"_options",
".",
"cleanconfig",
".",
"plugins",
"=",
"svgoDefaults",
".",
"concat",
"(",
"this",
".",
"_options",
".",
"cleanconfig",
".",
"plugins",
"||",
"[",
"]",
")",
";",
"this",
".",
"_cleaner",
"=",
"new",
"SVGO",
"(",
"this",
".",
"_options",
".",
"cleanconfig",
")",
";",
"this",
".",
"_clean",
"=",
"this",
".",
"_cleanSVGO",
";",
"}"
] | SVG Sprite generator
@param {Object} options Options
@return {SVGSprite} SVG sprite generator instance
@throws {Error} | [
"SVG",
"Sprite",
"generator"
] | fa2bd9e68df3dd5906153333245aa06a5ac4b2b3 | https://github.com/shakyShane/svg-sprite-data/blob/fa2bd9e68df3dd5906153333245aa06a5ac4b2b3/lib/svg-sprite.js#L76-L102 | train |
myrmex-org/myrmex | packages/api-gateway/src/cli/inspect-api.js | executeCommand | function executeCommand(parameters) {
if (parameters.colors === undefined) {
parameters.colors = plugin.myrmex.getConfig('colors');
}
return plugin.findApi(parameters.apiIdentifier)
.then(api => {
return api.generateSpec(parameters.specVersion);
})
.then(jsonSpec => {
let spec = JSON.stringify(jsonSpec, null, 2);
if (parameters.colors) {
spec = icli.highlight(spec, { json: true });
}
icli.print(spec);
return Promise.resolve(jsonSpec);
});
} | javascript | function executeCommand(parameters) {
if (parameters.colors === undefined) {
parameters.colors = plugin.myrmex.getConfig('colors');
}
return plugin.findApi(parameters.apiIdentifier)
.then(api => {
return api.generateSpec(parameters.specVersion);
})
.then(jsonSpec => {
let spec = JSON.stringify(jsonSpec, null, 2);
if (parameters.colors) {
spec = icli.highlight(spec, { json: true });
}
icli.print(spec);
return Promise.resolve(jsonSpec);
});
} | [
"function",
"executeCommand",
"(",
"parameters",
")",
"{",
"if",
"(",
"parameters",
".",
"colors",
"===",
"undefined",
")",
"{",
"parameters",
".",
"colors",
"=",
"plugin",
".",
"myrmex",
".",
"getConfig",
"(",
"'colors'",
")",
";",
"}",
"return",
"plugin",
".",
"findApi",
"(",
"parameters",
".",
"apiIdentifier",
")",
".",
"then",
"(",
"api",
"=>",
"{",
"return",
"api",
".",
"generateSpec",
"(",
"parameters",
".",
"specVersion",
")",
";",
"}",
")",
".",
"then",
"(",
"jsonSpec",
"=>",
"{",
"let",
"spec",
"=",
"JSON",
".",
"stringify",
"(",
"jsonSpec",
",",
"null",
",",
"2",
")",
";",
"if",
"(",
"parameters",
".",
"colors",
")",
"{",
"spec",
"=",
"icli",
".",
"highlight",
"(",
"spec",
",",
"{",
"json",
":",
"true",
"}",
")",
";",
"}",
"icli",
".",
"print",
"(",
"spec",
")",
";",
"return",
"Promise",
".",
"resolve",
"(",
"jsonSpec",
")",
";",
"}",
")",
";",
"}"
] | Output API specification
@param {Object} parameters - the parameters provided in the command and in the prompt
@returns {Promise<null>} - The execution stops here | [
"Output",
"API",
"specification"
] | 9dba3b8686d87bd603779b00c0545cd12ccad43c | https://github.com/myrmex-org/myrmex/blob/9dba3b8686d87bd603779b00c0545cd12ccad43c/packages/api-gateway/src/cli/inspect-api.js#L91-L107 | train |
helion3/lodash-addons | src/check.js | check | function check(value, ...validators) {
let valid = false;
_.each(validators, (validator) => {
return !(valid = validator(value));
});
if (!valid) {
throw new TypeError('Argument is not any of the accepted types.');
}
} | javascript | function check(value, ...validators) {
let valid = false;
_.each(validators, (validator) => {
return !(valid = validator(value));
});
if (!valid) {
throw new TypeError('Argument is not any of the accepted types.');
}
} | [
"function",
"check",
"(",
"value",
",",
"...",
"validators",
")",
"{",
"let",
"valid",
"=",
"false",
";",
"_",
".",
"each",
"(",
"validators",
",",
"(",
"validator",
")",
"=>",
"{",
"return",
"!",
"(",
"valid",
"=",
"validator",
"(",
"value",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"valid",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument is not any of the accepted types.'",
")",
";",
"}",
"}"
] | Throw a TypeError if value doesn't match one of any provided validation methods.
@static
@memberOf _
@category Preconditions
@param {mixed} value Value
@return {void} | [
"Throw",
"a",
"TypeError",
"if",
"value",
"doesn",
"t",
"match",
"one",
"of",
"any",
"provided",
"validation",
"methods",
"."
] | 83b5bf14258241e7ae35eef346151a332fdb6f50 | https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/check.js#L12-L21 | train |
jonschlinkert/engine-lodash | index.js | delimsObject | function delimsObject(delims) {
var a = delims[0], b = delims[1];
var res = {};
res.interpolate = lazy.delimiters(a + '=', b);
res.evaluate = lazy.delimiters(a, b);
res.escape = lazy.delimiters(a + '-', b);
return res;
} | javascript | function delimsObject(delims) {
var a = delims[0], b = delims[1];
var res = {};
res.interpolate = lazy.delimiters(a + '=', b);
res.evaluate = lazy.delimiters(a, b);
res.escape = lazy.delimiters(a + '-', b);
return res;
} | [
"function",
"delimsObject",
"(",
"delims",
")",
"{",
"var",
"a",
"=",
"delims",
"[",
"0",
"]",
",",
"b",
"=",
"delims",
"[",
"1",
"]",
";",
"var",
"res",
"=",
"{",
"}",
";",
"res",
".",
"interpolate",
"=",
"lazy",
".",
"delimiters",
"(",
"a",
"+",
"'='",
",",
"b",
")",
";",
"res",
".",
"evaluate",
"=",
"lazy",
".",
"delimiters",
"(",
"a",
",",
"b",
")",
";",
"res",
".",
"escape",
"=",
"lazy",
".",
"delimiters",
"(",
"a",
"+",
"'-'",
",",
"b",
")",
";",
"return",
"res",
";",
"}"
] | Handle custom delimiters | [
"Handle",
"custom",
"delimiters"
] | 2fce0ea5e773345d98cd71867580af348ed50bc0 | https://github.com/jonschlinkert/engine-lodash/blob/2fce0ea5e773345d98cd71867580af348ed50bc0/index.js#L187-L194 | train |
jonschlinkert/engine-lodash | index.js | inspectHelpers | function inspectHelpers(settings, opts) {
var helpers = Object.keys(settings.imports);
for (var key in opts) {
if (helpers.indexOf(key) !== -1) {
conflictMessage(settings, opts, key);
}
}
} | javascript | function inspectHelpers(settings, opts) {
var helpers = Object.keys(settings.imports);
for (var key in opts) {
if (helpers.indexOf(key) !== -1) {
conflictMessage(settings, opts, key);
}
}
} | [
"function",
"inspectHelpers",
"(",
"settings",
",",
"opts",
")",
"{",
"var",
"helpers",
"=",
"Object",
".",
"keys",
"(",
"settings",
".",
"imports",
")",
";",
"for",
"(",
"var",
"key",
"in",
"opts",
")",
"{",
"if",
"(",
"helpers",
".",
"indexOf",
"(",
"key",
")",
"!==",
"-",
"1",
")",
"{",
"conflictMessage",
"(",
"settings",
",",
"opts",
",",
"key",
")",
";",
"}",
"}",
"}"
] | Inspect helpers if `debugEngine` is enabled | [
"Inspect",
"helpers",
"if",
"debugEngine",
"is",
"enabled"
] | 2fce0ea5e773345d98cd71867580af348ed50bc0 | https://github.com/jonschlinkert/engine-lodash/blob/2fce0ea5e773345d98cd71867580af348ed50bc0/index.js#L200-L207 | train |
helion3/lodash-addons | src/hasOfType.js | hasOfType | function hasOfType(value, path, validator) {
return _.has(value, path) ? validator(_.get(value, path)) : false;
} | javascript | function hasOfType(value, path, validator) {
return _.has(value, path) ? validator(_.get(value, path)) : false;
} | [
"function",
"hasOfType",
"(",
"value",
",",
"path",
",",
"validator",
")",
"{",
"return",
"_",
".",
"has",
"(",
"value",
",",
"path",
")",
"?",
"validator",
"(",
"_",
".",
"get",
"(",
"value",
",",
"path",
")",
")",
":",
"false",
";",
"}"
] | If _.has returns true, run a validator on value.
@static
@memberOf _
@category Object
@param {mixed} value Collection for _.has
@param {string} path Path
@param {function} validator Function to validate value.
@return {boolean} Whether collection has prop, and it passes validation
@example
_.hasOfType({ test: '' }, 'test', _.isString);
// => true | [
"If",
"_",
".",
"has",
"returns",
"true",
"run",
"a",
"validator",
"on",
"value",
"."
] | 83b5bf14258241e7ae35eef346151a332fdb6f50 | https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/hasOfType.js#L18-L20 | train |
anseki/htmlclean-cli | htmlclean-cli.js | mkdirParents | function mkdirParents(dirPath) {
dirPath.split(/\/|\\/).reduce(function(parents, dir) {
var path = pathUtil.resolve((parents += dir + pathUtil.sep)); // normalize
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
} else if (!fs.statSync(path).isDirectory()) {
throw new Error('Non directory already exists: ' + path);
}
return parents;
}, '');
} | javascript | function mkdirParents(dirPath) {
dirPath.split(/\/|\\/).reduce(function(parents, dir) {
var path = pathUtil.resolve((parents += dir + pathUtil.sep)); // normalize
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
} else if (!fs.statSync(path).isDirectory()) {
throw new Error('Non directory already exists: ' + path);
}
return parents;
}, '');
} | [
"function",
"mkdirParents",
"(",
"dirPath",
")",
"{",
"dirPath",
".",
"split",
"(",
"/",
"\\/|\\\\",
"/",
")",
".",
"reduce",
"(",
"function",
"(",
"parents",
",",
"dir",
")",
"{",
"var",
"path",
"=",
"pathUtil",
".",
"resolve",
"(",
"(",
"parents",
"+=",
"dir",
"+",
"pathUtil",
".",
"sep",
")",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"path",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"path",
")",
";",
"}",
"else",
"if",
"(",
"!",
"fs",
".",
"statSync",
"(",
"path",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Non directory already exists: '",
"+",
"path",
")",
";",
"}",
"return",
"parents",
";",
"}",
",",
"''",
")",
";",
"}"
] | mkdir -p | [
"mkdir",
"-",
"p"
] | f468a97a70bc870a5cfcbd644b3735053f4d83c6 | https://github.com/anseki/htmlclean-cli/blob/f468a97a70bc870a5cfcbd644b3735053f4d83c6/htmlclean-cli.js#L29-L39 | train |
anseki/htmlclean-cli | htmlclean-cli.js | readStdin | function readStdin() {
var stdin = process.stdin,
fd = stdin.isTTY && process.platform !== 'win32' ?
fs.openSync('/dev/tty', 'rs') : stdin.fd,
bufSize = stdin.isTTY ? DEFAULT_BUF_SIZE :
(fs.fstatSync(fd).size || DEFAULT_BUF_SIZE),
buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(bufSize) : new Buffer(bufSize),
rsize, input = '';
while (true) {
rsize = 0;
try {
rsize = fs.readSync(fd, buffer, 0, bufSize);
} catch (e) {
if (e.code === 'EOF') { break; }
throw e;
}
if (rsize === 0) { break; }
input += buffer.toString(program.encoding, 0, rsize);
}
return input;
} | javascript | function readStdin() {
var stdin = process.stdin,
fd = stdin.isTTY && process.platform !== 'win32' ?
fs.openSync('/dev/tty', 'rs') : stdin.fd,
bufSize = stdin.isTTY ? DEFAULT_BUF_SIZE :
(fs.fstatSync(fd).size || DEFAULT_BUF_SIZE),
buffer = Buffer.allocUnsafe && Buffer.alloc ? Buffer.alloc(bufSize) : new Buffer(bufSize),
rsize, input = '';
while (true) {
rsize = 0;
try {
rsize = fs.readSync(fd, buffer, 0, bufSize);
} catch (e) {
if (e.code === 'EOF') { break; }
throw e;
}
if (rsize === 0) { break; }
input += buffer.toString(program.encoding, 0, rsize);
}
return input;
} | [
"function",
"readStdin",
"(",
")",
"{",
"var",
"stdin",
"=",
"process",
".",
"stdin",
",",
"fd",
"=",
"stdin",
".",
"isTTY",
"&&",
"process",
".",
"platform",
"!==",
"'win32'",
"?",
"fs",
".",
"openSync",
"(",
"'/dev/tty'",
",",
"'rs'",
")",
":",
"stdin",
".",
"fd",
",",
"bufSize",
"=",
"stdin",
".",
"isTTY",
"?",
"DEFAULT_BUF_SIZE",
":",
"(",
"fs",
".",
"fstatSync",
"(",
"fd",
")",
".",
"size",
"||",
"DEFAULT_BUF_SIZE",
")",
",",
"buffer",
"=",
"Buffer",
".",
"allocUnsafe",
"&&",
"Buffer",
".",
"alloc",
"?",
"Buffer",
".",
"alloc",
"(",
"bufSize",
")",
":",
"new",
"Buffer",
"(",
"bufSize",
")",
",",
"rsize",
",",
"input",
"=",
"''",
";",
"while",
"(",
"true",
")",
"{",
"rsize",
"=",
"0",
";",
"try",
"{",
"rsize",
"=",
"fs",
".",
"readSync",
"(",
"fd",
",",
"buffer",
",",
"0",
",",
"bufSize",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"code",
"===",
"'EOF'",
")",
"{",
"break",
";",
"}",
"throw",
"e",
";",
"}",
"if",
"(",
"rsize",
"===",
"0",
")",
"{",
"break",
";",
"}",
"input",
"+=",
"buffer",
".",
"toString",
"(",
"program",
".",
"encoding",
",",
"0",
",",
"rsize",
")",
";",
"}",
"return",
"input",
";",
"}"
] | path was normalized | [
"path",
"was",
"normalized"
] | f468a97a70bc870a5cfcbd644b3735053f4d83c6 | https://github.com/anseki/htmlclean-cli/blob/f468a97a70bc870a5cfcbd644b3735053f4d83c6/htmlclean-cli.js#L54-L74 | train |
dbartholomae/create-readme | docs/javascript/application.js | dispatch | function dispatch(event, scope){
var key, handler, k, i, modifiersMatch;
key = event.keyCode;
// if a modifier key, set the key.<modifierkeyname> property to true and return
if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
if(key in _mods) {
_mods[key] = true;
// 'assignKey' from inside this closure is exported to window.key
for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
return;
}
// see if we need to ignore the keypress (ftiler() can can be overridden)
// by default ignore key presses if a select, textarea, or input is focused
if(!assignKey.filter.call(this, event)) return;
// abort if no potentially matching shortcuts found
if (!(key in _handlers)) return;
// for each potential shortcut
for (i = 0; i < _handlers[key].length; i++) {
handler = _handlers[key][i];
// see if it's in the current scope
if(handler.scope == scope || handler.scope == 'all'){
// check if modifiers match if any
modifiersMatch = handler.mods.length > 0;
for(k in _mods)
if((!_mods[k] && index(handler.mods, +k) > -1) ||
(_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
// call the handler and stop the event if neccessary
if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
if(handler.method(event, handler)===false){
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(event.stopPropagation) event.stopPropagation();
if(event.cancelBubble) event.cancelBubble = true;
}
}
}
}
} | javascript | function dispatch(event, scope){
var key, handler, k, i, modifiersMatch;
key = event.keyCode;
// if a modifier key, set the key.<modifierkeyname> property to true and return
if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
if(key in _mods) {
_mods[key] = true;
// 'assignKey' from inside this closure is exported to window.key
for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
return;
}
// see if we need to ignore the keypress (ftiler() can can be overridden)
// by default ignore key presses if a select, textarea, or input is focused
if(!assignKey.filter.call(this, event)) return;
// abort if no potentially matching shortcuts found
if (!(key in _handlers)) return;
// for each potential shortcut
for (i = 0; i < _handlers[key].length; i++) {
handler = _handlers[key][i];
// see if it's in the current scope
if(handler.scope == scope || handler.scope == 'all'){
// check if modifiers match if any
modifiersMatch = handler.mods.length > 0;
for(k in _mods)
if((!_mods[k] && index(handler.mods, +k) > -1) ||
(_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
// call the handler and stop the event if neccessary
if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
if(handler.method(event, handler)===false){
if(event.preventDefault) event.preventDefault();
else event.returnValue = false;
if(event.stopPropagation) event.stopPropagation();
if(event.cancelBubble) event.cancelBubble = true;
}
}
}
}
} | [
"function",
"dispatch",
"(",
"event",
",",
"scope",
")",
"{",
"var",
"key",
",",
"handler",
",",
"k",
",",
"i",
",",
"modifiersMatch",
";",
"key",
"=",
"event",
".",
"keyCode",
";",
"if",
"(",
"key",
"==",
"93",
"||",
"key",
"==",
"224",
")",
"key",
"=",
"91",
";",
"if",
"(",
"key",
"in",
"_mods",
")",
"{",
"_mods",
"[",
"key",
"]",
"=",
"true",
";",
"for",
"(",
"k",
"in",
"_MODIFIERS",
")",
"if",
"(",
"_MODIFIERS",
"[",
"k",
"]",
"==",
"key",
")",
"assignKey",
"[",
"k",
"]",
"=",
"true",
";",
"return",
";",
"}",
"if",
"(",
"!",
"assignKey",
".",
"filter",
".",
"call",
"(",
"this",
",",
"event",
")",
")",
"return",
";",
"if",
"(",
"!",
"(",
"key",
"in",
"_handlers",
")",
")",
"return",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"_handlers",
"[",
"key",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"handler",
"=",
"_handlers",
"[",
"key",
"]",
"[",
"i",
"]",
";",
"if",
"(",
"handler",
".",
"scope",
"==",
"scope",
"||",
"handler",
".",
"scope",
"==",
"'all'",
")",
"{",
"modifiersMatch",
"=",
"handler",
".",
"mods",
".",
"length",
">",
"0",
";",
"for",
"(",
"k",
"in",
"_mods",
")",
"if",
"(",
"(",
"!",
"_mods",
"[",
"k",
"]",
"&&",
"index",
"(",
"handler",
".",
"mods",
",",
"+",
"k",
")",
">",
"-",
"1",
")",
"||",
"(",
"_mods",
"[",
"k",
"]",
"&&",
"index",
"(",
"handler",
".",
"mods",
",",
"+",
"k",
")",
"==",
"-",
"1",
")",
")",
"modifiersMatch",
"=",
"false",
";",
"if",
"(",
"(",
"handler",
".",
"mods",
".",
"length",
"==",
"0",
"&&",
"!",
"_mods",
"[",
"16",
"]",
"&&",
"!",
"_mods",
"[",
"18",
"]",
"&&",
"!",
"_mods",
"[",
"17",
"]",
"&&",
"!",
"_mods",
"[",
"91",
"]",
")",
"||",
"modifiersMatch",
")",
"{",
"if",
"(",
"handler",
".",
"method",
"(",
"event",
",",
"handler",
")",
"===",
"false",
")",
"{",
"if",
"(",
"event",
".",
"preventDefault",
")",
"event",
".",
"preventDefault",
"(",
")",
";",
"else",
"event",
".",
"returnValue",
"=",
"false",
";",
"if",
"(",
"event",
".",
"stopPropagation",
")",
"event",
".",
"stopPropagation",
"(",
")",
";",
"if",
"(",
"event",
".",
"cancelBubble",
")",
"event",
".",
"cancelBubble",
"=",
"true",
";",
"}",
"}",
"}",
"}",
"}"
] | handle keydown event | [
"handle",
"keydown",
"event"
] | 7c1a49aaa38897fa686a1f358e9229db37f2604b | https://github.com/dbartholomae/create-readme/blob/7c1a49aaa38897fa686a1f358e9229db37f2604b/docs/javascript/application.js#L10245-L10287 | train |
greedbell/gulp-require-modules | index.js | getMatches | function getMatches(str, re) {
if (str == null) {
return null;
}
if (re == null) {
return null;
}
var results = [];
var match;
while ((match = re.exec(str)) !== null) {
results.push(match[1]);
}
return results;
} | javascript | function getMatches(str, re) {
if (str == null) {
return null;
}
if (re == null) {
return null;
}
var results = [];
var match;
while ((match = re.exec(str)) !== null) {
results.push(match[1]);
}
return results;
} | [
"function",
"getMatches",
"(",
"str",
",",
"re",
")",
"{",
"if",
"(",
"str",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"re",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"var",
"results",
"=",
"[",
"]",
";",
"var",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"re",
".",
"exec",
"(",
"str",
")",
")",
"!==",
"null",
")",
"{",
"results",
".",
"push",
"(",
"match",
"[",
"1",
"]",
")",
";",
"}",
"return",
"results",
";",
"}"
] | get mateched string
@param str
@param re
@returns {*} | [
"get",
"mateched",
"string"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/index.js#L60-L73 | train |
greedbell/gulp-require-modules | index.js | transformFile | function transformFile(from, to, modulesDirectory) {
var contents = fs.readFileSync(from, 'utf8');
// modules
var modules = getModules(contents);
for (var index in modules) {
var module = modules[index];
if (modulesManifest.hasOwnProperty(module)) {
continue;
}
var modulePath = path_util.modulePath(module, node_modules);
if (modulePath === null) {
continue;
}
var targetPath = path_util.targetPath(modulePath, node_modules, modulesDirectory);
modulesManifest[module] = path.relative(process.cwd(), targetPath);
if (!fs.existsSync(targetPath)) {
transformFile(modulePath, targetPath, modulesDirectory);
}
var relativePath = path_util.relativePath(to, targetPath);
var re = eval('\/require\\\(\[\'\"\]' + module + '\[\'\"\]\\\)\/ig');
contents = contents.replace(re, 'require(\'' + relativePath + '\')');
}
// requires
var requires = getRequires(contents);
for (var index in requires) {
var require = requires[index];
var requirePath = path_util.requirePath(from, require);
if (requirePath === null) {
continue;
}
if (requiresManifest.hasOwnProperty(requirePath)) {
continue;
} else {
requiresManifest[requirePath] = true;
}
var targetPath = path_util.targetPath(requirePath, node_modules, modulesDirectory);
if (!fs.existsSync(targetPath)) {
transformFile(requirePath, targetPath, modulesDirectory);
}
}
var dirname = path.dirname(to);
fs.mkdirsSync(dirname);
fs.writeFileSync(to, contents, 'utf8');
} | javascript | function transformFile(from, to, modulesDirectory) {
var contents = fs.readFileSync(from, 'utf8');
// modules
var modules = getModules(contents);
for (var index in modules) {
var module = modules[index];
if (modulesManifest.hasOwnProperty(module)) {
continue;
}
var modulePath = path_util.modulePath(module, node_modules);
if (modulePath === null) {
continue;
}
var targetPath = path_util.targetPath(modulePath, node_modules, modulesDirectory);
modulesManifest[module] = path.relative(process.cwd(), targetPath);
if (!fs.existsSync(targetPath)) {
transformFile(modulePath, targetPath, modulesDirectory);
}
var relativePath = path_util.relativePath(to, targetPath);
var re = eval('\/require\\\(\[\'\"\]' + module + '\[\'\"\]\\\)\/ig');
contents = contents.replace(re, 'require(\'' + relativePath + '\')');
}
// requires
var requires = getRequires(contents);
for (var index in requires) {
var require = requires[index];
var requirePath = path_util.requirePath(from, require);
if (requirePath === null) {
continue;
}
if (requiresManifest.hasOwnProperty(requirePath)) {
continue;
} else {
requiresManifest[requirePath] = true;
}
var targetPath = path_util.targetPath(requirePath, node_modules, modulesDirectory);
if (!fs.existsSync(targetPath)) {
transformFile(requirePath, targetPath, modulesDirectory);
}
}
var dirname = path.dirname(to);
fs.mkdirsSync(dirname);
fs.writeFileSync(to, contents, 'utf8');
} | [
"function",
"transformFile",
"(",
"from",
",",
"to",
",",
"modulesDirectory",
")",
"{",
"var",
"contents",
"=",
"fs",
".",
"readFileSync",
"(",
"from",
",",
"'utf8'",
")",
";",
"var",
"modules",
"=",
"getModules",
"(",
"contents",
")",
";",
"for",
"(",
"var",
"index",
"in",
"modules",
")",
"{",
"var",
"module",
"=",
"modules",
"[",
"index",
"]",
";",
"if",
"(",
"modulesManifest",
".",
"hasOwnProperty",
"(",
"module",
")",
")",
"{",
"continue",
";",
"}",
"var",
"modulePath",
"=",
"path_util",
".",
"modulePath",
"(",
"module",
",",
"node_modules",
")",
";",
"if",
"(",
"modulePath",
"===",
"null",
")",
"{",
"continue",
";",
"}",
"var",
"targetPath",
"=",
"path_util",
".",
"targetPath",
"(",
"modulePath",
",",
"node_modules",
",",
"modulesDirectory",
")",
";",
"modulesManifest",
"[",
"module",
"]",
"=",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"targetPath",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"targetPath",
")",
")",
"{",
"transformFile",
"(",
"modulePath",
",",
"targetPath",
",",
"modulesDirectory",
")",
";",
"}",
"var",
"relativePath",
"=",
"path_util",
".",
"relativePath",
"(",
"to",
",",
"targetPath",
")",
";",
"var",
"re",
"=",
"eval",
"(",
"'\\/require\\\\\\(\\[\\'\\\"\\]'",
"+",
"\\/",
"+",
"\\\\",
")",
";",
"\\(",
"}",
"\\[",
"\\'",
"\\\"",
"\\]",
"module",
"}"
] | copy file from node_module to modulesDirectory
@param from file full path
@param to file full path
@param modulesDirectory | [
"copy",
"file",
"from",
"node_module",
"to",
"modulesDirectory"
] | a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc | https://github.com/greedbell/gulp-require-modules/blob/a4ff07bcf3ddb0138269fbe5a68fa251a971cdbc/index.js#L82-L128 | train |
borela-tech/js-toolbox | entries/react/spa/ErrorBoundary.js | parseMappedStack | function parseMappedStack(stack) {
let result = []
for (let line of stack) {
// at ... (file:///namespace/path:line:column)
const MATCHED = line.match(/\(.*?:\/{3}(.*?)\/(.*):(.*?):(.*?)\)$/)
// The line couldn’t be parsed.
if (!MATCHED){
result.push({stackLine: line})
continue
}
result.push({
column: MATCHED[4],
line: MATCHED[3],
namespace: MATCHED[1],
path: MATCHED[2],
stackLine: line,
})
}
return result
} | javascript | function parseMappedStack(stack) {
let result = []
for (let line of stack) {
// at ... (file:///namespace/path:line:column)
const MATCHED = line.match(/\(.*?:\/{3}(.*?)\/(.*):(.*?):(.*?)\)$/)
// The line couldn’t be parsed.
if (!MATCHED){
result.push({stackLine: line})
continue
}
result.push({
column: MATCHED[4],
line: MATCHED[3],
namespace: MATCHED[1],
path: MATCHED[2],
stackLine: line,
})
}
return result
} | [
"function",
"parseMappedStack",
"(",
"stack",
")",
"{",
"let",
"result",
"=",
"[",
"]",
"for",
"(",
"let",
"line",
"of",
"stack",
")",
"{",
"const",
"MATCHED",
"=",
"line",
".",
"match",
"(",
"/",
"\\(.*?:\\/{3}(.*?)\\/(.*):(.*?):(.*?)\\)$",
"/",
")",
"if",
"(",
"!",
"MATCHED",
")",
"{",
"result",
".",
"push",
"(",
"{",
"stackLine",
":",
"line",
"}",
")",
"continue",
"}",
"result",
".",
"push",
"(",
"{",
"column",
":",
"MATCHED",
"[",
"4",
"]",
",",
"line",
":",
"MATCHED",
"[",
"3",
"]",
",",
"namespace",
":",
"MATCHED",
"[",
"1",
"]",
",",
"path",
":",
"MATCHED",
"[",
"2",
"]",
",",
"stackLine",
":",
"line",
",",
"}",
")",
"}",
"return",
"result",
"}"
] | Return the a new mapped stack where each item is an object with properties
for line, column, namespace and file path. | [
"Return",
"the",
"a",
"new",
"mapped",
"stack",
"where",
"each",
"item",
"is",
"an",
"object",
"with",
"properties",
"for",
"line",
"column",
"namespace",
"and",
"file",
"path",
"."
] | 0ed75d373fa1573d64a3d715ee8e6e24852824e4 | https://github.com/borela-tech/js-toolbox/blob/0ed75d373fa1573d64a3d715ee8e6e24852824e4/entries/react/spa/ErrorBoundary.js#L21-L42 | train |
helion3/lodash-addons | src/sign.js | sign | function sign(value) {
let sign = NaN;
if (_.isNumber(value)) {
if (value === 0) {
sign = value;
}
else if (value >= 1) {
sign = 1;
}
else if (value <= -1) {
sign = -1;
}
}
return sign;
} | javascript | function sign(value) {
let sign = NaN;
if (_.isNumber(value)) {
if (value === 0) {
sign = value;
}
else if (value >= 1) {
sign = 1;
}
else if (value <= -1) {
sign = -1;
}
}
return sign;
} | [
"function",
"sign",
"(",
"value",
")",
"{",
"let",
"sign",
"=",
"NaN",
";",
"if",
"(",
"_",
".",
"isNumber",
"(",
"value",
")",
")",
"{",
"if",
"(",
"value",
"===",
"0",
")",
"{",
"sign",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"value",
">=",
"1",
")",
"{",
"sign",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"value",
"<=",
"-",
"1",
")",
"{",
"sign",
"=",
"-",
"1",
";",
"}",
"}",
"return",
"sign",
";",
"}"
] | Returns a number representing the sign of `value`.
If `value` is a positive number, negative number, positive zero or negative zero,
the function will return 1, -1, 0 or -0 respectively. Otherwise, NaN is returned.
@static
@memberOf _
@category Math
@param {number} value A number
@returns {number} A number representing the sign
@example
_.sign(10);
// => 1
_.sign(-10);
// => -1 | [
"Returns",
"a",
"number",
"representing",
"the",
"sign",
"of",
"value",
"."
] | 83b5bf14258241e7ae35eef346151a332fdb6f50 | https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/sign.js#L22-L38 | train |
helion3/lodash-addons | src/internal/baseGetType.js | baseGetType | function baseGetType(validator, baseDefault, value, replacement) {
let result;
if (validator(value)) {
result = value;
}
else if (validator(replacement)) {
result = replacement;
}
else {
result = baseDefault;
}
return result;
} | javascript | function baseGetType(validator, baseDefault, value, replacement) {
let result;
if (validator(value)) {
result = value;
}
else if (validator(replacement)) {
result = replacement;
}
else {
result = baseDefault;
}
return result;
} | [
"function",
"baseGetType",
"(",
"validator",
",",
"baseDefault",
",",
"value",
",",
"replacement",
")",
"{",
"let",
"result",
";",
"if",
"(",
"validator",
"(",
"value",
")",
")",
"{",
"result",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"validator",
"(",
"replacement",
")",
")",
"{",
"result",
"=",
"replacement",
";",
"}",
"else",
"{",
"result",
"=",
"baseDefault",
";",
"}",
"return",
"result",
";",
"}"
] | Base function for returning a default when the given value fails validation.
@private
@param {function} validator Validation function.
@param {*} baseDefault Base default value.
@param {*} value Given value.
@param {*} replacement Custom replacement.
@return {*} Final value. | [
"Base",
"function",
"for",
"returning",
"a",
"default",
"when",
"the",
"given",
"value",
"fails",
"validation",
"."
] | 83b5bf14258241e7ae35eef346151a332fdb6f50 | https://github.com/helion3/lodash-addons/blob/83b5bf14258241e7ae35eef346151a332fdb6f50/src/internal/baseGetType.js#L11-L25 | train |
Frijol/PulseSensor | index.js | use | function use (hardware, callback) {
if (!hardware) {
// Set default configuration
hardware = require('tessel').port['GPIO'].pin['A1'];
}
return new PulseSensor(hardware, callback);
} | javascript | function use (hardware, callback) {
if (!hardware) {
// Set default configuration
hardware = require('tessel').port['GPIO'].pin['A1'];
}
return new PulseSensor(hardware, callback);
} | [
"function",
"use",
"(",
"hardware",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"hardware",
")",
"{",
"hardware",
"=",
"require",
"(",
"'tessel'",
")",
".",
"port",
"[",
"'GPIO'",
"]",
".",
"pin",
"[",
"'A1'",
"]",
";",
"}",
"return",
"new",
"PulseSensor",
"(",
"hardware",
",",
"callback",
")",
";",
"}"
] | Standard Tessel use function | [
"Standard",
"Tessel",
"use",
"function"
] | a28b0687ca2f287ba6ed58fc38149b25a7e0c949 | https://github.com/Frijol/PulseSensor/blob/a28b0687ca2f287ba6ed58fc38149b25a7e0c949/index.js#L80-L86 | train |
karlkfi/ngindox | lib/nginx.js | parse | function parse(fileString, callback) {
return NginxConf.parse(fileString, function(err, _config) {
if (err) {
return callback(err);
}
return parseNginxConf(_config, callback);
});
} | javascript | function parse(fileString, callback) {
return NginxConf.parse(fileString, function(err, _config) {
if (err) {
return callback(err);
}
return parseNginxConf(_config, callback);
});
} | [
"function",
"parse",
"(",
"fileString",
",",
"callback",
")",
"{",
"return",
"NginxConf",
".",
"parse",
"(",
"fileString",
",",
"function",
"(",
"err",
",",
"_config",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"return",
"parseNginxConf",
"(",
"_config",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Parses a file string into an Nginx Config object. Does not expand file includes. | [
"Parses",
"a",
"file",
"string",
"into",
"an",
"Nginx",
"Config",
"object",
".",
"Does",
"not",
"expand",
"file",
"includes",
"."
] | 2c0e8a682d7bde9e5d73a853f45bf1460f4664e9 | https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/nginx.js#L10-L18 | train |
karlkfi/ngindox | lib/nginx.js | parseFile | function parseFile(filePath, encoding, callback) {
return fs.readFile(filePath, encoding, function(err, fileString) {
if (err) {
return callback(err);
}
fileString = expandIncludes(fileString, path.dirname(filePath));
return parse(fileString, callback);
});
} | javascript | function parseFile(filePath, encoding, callback) {
return fs.readFile(filePath, encoding, function(err, fileString) {
if (err) {
return callback(err);
}
fileString = expandIncludes(fileString, path.dirname(filePath));
return parse(fileString, callback);
});
} | [
"function",
"parseFile",
"(",
"filePath",
",",
"encoding",
",",
"callback",
")",
"{",
"return",
"fs",
".",
"readFile",
"(",
"filePath",
",",
"encoding",
",",
"function",
"(",
"err",
",",
"fileString",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"fileString",
"=",
"expandIncludes",
"(",
"fileString",
",",
"path",
".",
"dirname",
"(",
"filePath",
")",
")",
";",
"return",
"parse",
"(",
"fileString",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Reads and parses a file into an Nginx Config object Expands file includes. | [
"Reads",
"and",
"parses",
"a",
"file",
"into",
"an",
"Nginx",
"Config",
"object",
"Expands",
"file",
"includes",
"."
] | 2c0e8a682d7bde9e5d73a853f45bf1460f4664e9 | https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/nginx.js#L22-L32 | train |
Bitclimb/coinjs-lib | src/script.js | isOPInt | function isOPInt (value) {
return types.Number(value) &&
((value === OPS.OP_0) ||
(value >= OPS.OP_1 && value <= OPS.OP_16) ||
(value === OPS.OP_1NEGATE));
} | javascript | function isOPInt (value) {
return types.Number(value) &&
((value === OPS.OP_0) ||
(value >= OPS.OP_1 && value <= OPS.OP_16) ||
(value === OPS.OP_1NEGATE));
} | [
"function",
"isOPInt",
"(",
"value",
")",
"{",
"return",
"types",
".",
"Number",
"(",
"value",
")",
"&&",
"(",
"(",
"value",
"===",
"OPS",
".",
"OP_0",
")",
"||",
"(",
"value",
">=",
"OPS",
".",
"OP_1",
"&&",
"value",
"<=",
"OPS",
".",
"OP_16",
")",
"||",
"(",
"value",
"===",
"OPS",
".",
"OP_1NEGATE",
")",
")",
";",
"}"
] | OP_1 - 1 | [
"OP_1",
"-",
"1"
] | df40d37a63b3f77eda590c7aa46555c6faee3c6d | https://github.com/Bitclimb/coinjs-lib/blob/df40d37a63b3f77eda590c7aa46555c6faee3c6d/src/script.js#L11-L16 | train |
toymachiner62/mongo-factory | index.js | getConnection | function getConnection(connectionString) {
return new Promise(function(resolve, reject) {
// If connectionString is null or undefined, return an error.
if (_.isEmpty(connectionString)) {
return reject('getConnection must be called with a mongo connection string');
}
// Check if a connection already exists for the provided connectionString.
var pool = _.findWhere(connections, { connectionString: connectionString });
// If a connection pool was found, resolve the promise with it.
if (pool) {
return resolve(pool.db);
}
// If the connection pool has not been instantiated,
// instantiate it and return the connection.
MongoClient.connect(connectionString, function(err, database) {
if (err) {
return reject(err);
}
// Store the connection in the connections array.
connections.push({
connectionString: connectionString,
db: database
});
return resolve(database);
});
});
} | javascript | function getConnection(connectionString) {
return new Promise(function(resolve, reject) {
// If connectionString is null or undefined, return an error.
if (_.isEmpty(connectionString)) {
return reject('getConnection must be called with a mongo connection string');
}
// Check if a connection already exists for the provided connectionString.
var pool = _.findWhere(connections, { connectionString: connectionString });
// If a connection pool was found, resolve the promise with it.
if (pool) {
return resolve(pool.db);
}
// If the connection pool has not been instantiated,
// instantiate it and return the connection.
MongoClient.connect(connectionString, function(err, database) {
if (err) {
return reject(err);
}
// Store the connection in the connections array.
connections.push({
connectionString: connectionString,
db: database
});
return resolve(database);
});
});
} | [
"function",
"getConnection",
"(",
"connectionString",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"connectionString",
")",
")",
"{",
"return",
"reject",
"(",
"'getConnection must be called with a mongo connection string'",
")",
";",
"}",
"var",
"pool",
"=",
"_",
".",
"findWhere",
"(",
"connections",
",",
"{",
"connectionString",
":",
"connectionString",
"}",
")",
";",
"if",
"(",
"pool",
")",
"{",
"return",
"resolve",
"(",
"pool",
".",
"db",
")",
";",
"}",
"MongoClient",
".",
"connect",
"(",
"connectionString",
",",
"function",
"(",
"err",
",",
"database",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"connections",
".",
"push",
"(",
"{",
"connectionString",
":",
"connectionString",
",",
"db",
":",
"database",
"}",
")",
";",
"return",
"resolve",
"(",
"database",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Gets a Mongo connection from the pool.
If the connection pool has not been instantiated yet, it is first
instantiated and a connection is returned.
@returns {Promise|Db} - A promise object that resolves to a Mongo db object. | [
"Gets",
"a",
"Mongo",
"connection",
"from",
"the",
"pool",
"."
] | a080b957cdda8e6969ea600e89afe74a09248419 | https://github.com/toymachiner62/mongo-factory/blob/a080b957cdda8e6969ea600e89afe74a09248419/index.js#L26-L57 | train |
pmorjan/couchdb-promises | examples/attachment-stream2.js | initDB | function initDB () {
return db.listDatabases()
.then(response => {
if (response.data.indexOf(dbName) !== -1) {
// database already exists
return Promise.resolve('ok')
} else {
// create new database
return db.createDatabase(dbName).then(() => 'ok')
}
})
} | javascript | function initDB () {
return db.listDatabases()
.then(response => {
if (response.data.indexOf(dbName) !== -1) {
// database already exists
return Promise.resolve('ok')
} else {
// create new database
return db.createDatabase(dbName).then(() => 'ok')
}
})
} | [
"function",
"initDB",
"(",
")",
"{",
"return",
"db",
".",
"listDatabases",
"(",
")",
".",
"then",
"(",
"response",
"=>",
"{",
"if",
"(",
"response",
".",
"data",
".",
"indexOf",
"(",
"dbName",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"'ok'",
")",
"}",
"else",
"{",
"return",
"db",
".",
"createDatabase",
"(",
"dbName",
")",
".",
"then",
"(",
"(",
")",
"=>",
"'ok'",
")",
"}",
"}",
")",
"}"
] | create db if it does not already exist
@return {Promise} | [
"create",
"db",
"if",
"it",
"does",
"not",
"already",
"exist"
] | 7472ea272e417970ab2b036739909e227aefd296 | https://github.com/pmorjan/couchdb-promises/blob/7472ea272e417970ab2b036739909e227aefd296/examples/attachment-stream2.js#L13-L24 | train |
pmorjan/couchdb-promises | examples/attachment-stream2.js | initDocument | function initDocument (docName) {
return db.getDocument(dbName, docName)
.then(response => response.data._rev) // document already exists
.catch(response => {
if (response.status === 404) {
// create new document
return db.createDocument(dbName, {foo: 'bar'}, docName)
.then(response => response.data.rev)
} else {
// real error
return Promise.reject(response)
}
})
} | javascript | function initDocument (docName) {
return db.getDocument(dbName, docName)
.then(response => response.data._rev) // document already exists
.catch(response => {
if (response.status === 404) {
// create new document
return db.createDocument(dbName, {foo: 'bar'}, docName)
.then(response => response.data.rev)
} else {
// real error
return Promise.reject(response)
}
})
} | [
"function",
"initDocument",
"(",
"docName",
")",
"{",
"return",
"db",
".",
"getDocument",
"(",
"dbName",
",",
"docName",
")",
".",
"then",
"(",
"response",
"=>",
"response",
".",
"data",
".",
"_rev",
")",
".",
"catch",
"(",
"response",
"=>",
"{",
"if",
"(",
"response",
".",
"status",
"===",
"404",
")",
"{",
"return",
"db",
".",
"createDocument",
"(",
"dbName",
",",
"{",
"foo",
":",
"'bar'",
"}",
",",
"docName",
")",
".",
"then",
"(",
"response",
"=>",
"response",
".",
"data",
".",
"rev",
")",
"}",
"else",
"{",
"return",
"Promise",
".",
"reject",
"(",
"response",
")",
"}",
"}",
")",
"}"
] | get existing document or create new
@param {String} docName
@return {Promise} - fulfilled with document revision | [
"get",
"existing",
"document",
"or",
"create",
"new"
] | 7472ea272e417970ab2b036739909e227aefd296 | https://github.com/pmorjan/couchdb-promises/blob/7472ea272e417970ab2b036739909e227aefd296/examples/attachment-stream2.js#L31-L44 | train |
pmorjan/couchdb-promises | examples/attachment-stream2.js | addAttachment | function addAttachment (docName, docRev) {
const args = os.type() === 'Darwin' ? ['-l', '1'] : ['-b', '-n', '1']
const stream = spawn('top', args).stdout
const attName = `top-${Date.now()}.txt`
const attContentType = 'text/plain'
return db.addAttachment(dbName, docName, attName, docRev, attContentType, stream)
.then(response => response.data.rev)
} | javascript | function addAttachment (docName, docRev) {
const args = os.type() === 'Darwin' ? ['-l', '1'] : ['-b', '-n', '1']
const stream = spawn('top', args).stdout
const attName = `top-${Date.now()}.txt`
const attContentType = 'text/plain'
return db.addAttachment(dbName, docName, attName, docRev, attContentType, stream)
.then(response => response.data.rev)
} | [
"function",
"addAttachment",
"(",
"docName",
",",
"docRev",
")",
"{",
"const",
"args",
"=",
"os",
".",
"type",
"(",
")",
"===",
"'Darwin'",
"?",
"[",
"'-l'",
",",
"'1'",
"]",
":",
"[",
"'-b'",
",",
"'-n'",
",",
"'1'",
"]",
"const",
"stream",
"=",
"spawn",
"(",
"'top'",
",",
"args",
")",
".",
"stdout",
"const",
"attName",
"=",
"`",
"${",
"Date",
".",
"now",
"(",
")",
"}",
"`",
"const",
"attContentType",
"=",
"'text/plain'",
"return",
"db",
".",
"addAttachment",
"(",
"dbName",
",",
"docName",
",",
"attName",
",",
"docRev",
",",
"attContentType",
",",
"stream",
")",
".",
"then",
"(",
"response",
"=>",
"response",
".",
"data",
".",
"rev",
")",
"}"
] | attach the output of 'top' to the document
@param {String} docName
@param {String} docRev
@return {Promise} - fulfilled with new document revision | [
"attach",
"the",
"output",
"of",
"top",
"to",
"the",
"document"
] | 7472ea272e417970ab2b036739909e227aefd296 | https://github.com/pmorjan/couchdb-promises/blob/7472ea272e417970ab2b036739909e227aefd296/examples/attachment-stream2.js#L52-L59 | train |
DesTincT/bemlint | lib/formatters/tap.js | outputDiagnostics | function outputDiagnostics(diagnostic) {
var prefix = " ";
var output = prefix + "---\n";
output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix);
output += "...\n";
return output;
} | javascript | function outputDiagnostics(diagnostic) {
var prefix = " ";
var output = prefix + "---\n";
output += prefix + yaml.safeDump(diagnostic).split("\n").join("\n" + prefix);
output += "...\n";
return output;
} | [
"function",
"outputDiagnostics",
"(",
"diagnostic",
")",
"{",
"var",
"prefix",
"=",
"\" \"",
";",
"var",
"output",
"=",
"prefix",
"+",
"\"---\\n\"",
";",
"\\n",
"output",
"+=",
"prefix",
"+",
"yaml",
".",
"safeDump",
"(",
"diagnostic",
")",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"\\n",
"join",
";",
"(",
"\"\\n\"",
"+",
"\\n",
")",
"}"
] | Takes in a JavaScript object and outputs a TAP diagnostics string
@param {object} diagnostic JavaScript object to be embedded as YAML into output.
@returns {string} diagnostics string with YAML embedded - TAP version 13 compliant | [
"Takes",
"in",
"a",
"JavaScript",
"object",
"and",
"outputs",
"a",
"TAP",
"diagnostics",
"string"
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/formatters/tap.js#L31-L37 | train |
thumbsup/theme-classic | theme/public/lightgallery/js/lightgallery-all.js | function(element) {
this.core = $(element).data('lightGallery');
this.$el = $(element);
// Execute only if items are above 1
if (this.core.$items.length < 2) {
return false;
}
this.core.s = $.extend({}, defaults, this.core.s);
this.interval = false;
// Identify if slide happened from autoplay
this.fromAuto = true;
// Identify if autoplay canceled from touch/drag
this.canceledOnTouch = false;
// save fourceautoplay value
this.fourceAutoplayTemp = this.core.s.fourceAutoplay;
// do not allow progress bar if browser does not support css3 transitions
if (!this.core.doCss()) {
this.core.s.progressBar = false;
}
this.init();
return this;
} | javascript | function(element) {
this.core = $(element).data('lightGallery');
this.$el = $(element);
// Execute only if items are above 1
if (this.core.$items.length < 2) {
return false;
}
this.core.s = $.extend({}, defaults, this.core.s);
this.interval = false;
// Identify if slide happened from autoplay
this.fromAuto = true;
// Identify if autoplay canceled from touch/drag
this.canceledOnTouch = false;
// save fourceautoplay value
this.fourceAutoplayTemp = this.core.s.fourceAutoplay;
// do not allow progress bar if browser does not support css3 transitions
if (!this.core.doCss()) {
this.core.s.progressBar = false;
}
this.init();
return this;
} | [
"function",
"(",
"element",
")",
"{",
"this",
".",
"core",
"=",
"$",
"(",
"element",
")",
".",
"data",
"(",
"'lightGallery'",
")",
";",
"this",
".",
"$el",
"=",
"$",
"(",
"element",
")",
";",
"if",
"(",
"this",
".",
"core",
".",
"$items",
".",
"length",
"<",
"2",
")",
"{",
"return",
"false",
";",
"}",
"this",
".",
"core",
".",
"s",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"defaults",
",",
"this",
".",
"core",
".",
"s",
")",
";",
"this",
".",
"interval",
"=",
"false",
";",
"this",
".",
"fromAuto",
"=",
"true",
";",
"this",
".",
"canceledOnTouch",
"=",
"false",
";",
"this",
".",
"fourceAutoplayTemp",
"=",
"this",
".",
"core",
".",
"s",
".",
"fourceAutoplay",
";",
"if",
"(",
"!",
"this",
".",
"core",
".",
"doCss",
"(",
")",
")",
"{",
"this",
".",
"core",
".",
"s",
".",
"progressBar",
"=",
"false",
";",
"}",
"this",
".",
"init",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Creates the autoplay plugin.
@param {object} element - lightGallery element | [
"Creates",
"the",
"autoplay",
"plugin",
"."
] | 9fe4545a0e8552969ff7daf34f95fc5c05e7c22c | https://github.com/thumbsup/theme-classic/blob/9fe4545a0e8552969ff7daf34f95fc5c05e7c22c/theme/public/lightgallery/js/lightgallery-all.js#L1327-L1358 | train |
|
Mike96Angelo/Generate-JS | generate.js | getFunctionName | function getFunctionName(func) {
if (func.name !== void(0)) {
return func.name;
}
// Else use IE Shim
var funcNameMatch = func.toString()
.match(/function\s*([^\s]*)\s*\(/);
func.name = (funcNameMatch && funcNameMatch[1]) || '';
return func.name;
} | javascript | function getFunctionName(func) {
if (func.name !== void(0)) {
return func.name;
}
// Else use IE Shim
var funcNameMatch = func.toString()
.match(/function\s*([^\s]*)\s*\(/);
func.name = (funcNameMatch && funcNameMatch[1]) || '';
return func.name;
} | [
"function",
"getFunctionName",
"(",
"func",
")",
"{",
"if",
"(",
"func",
".",
"name",
"!==",
"void",
"(",
"0",
")",
")",
"{",
"return",
"func",
".",
"name",
";",
"}",
"var",
"funcNameMatch",
"=",
"func",
".",
"toString",
"(",
")",
".",
"match",
"(",
"/",
"function\\s*([^\\s]*)\\s*\\(",
"/",
")",
";",
"func",
".",
"name",
"=",
"(",
"funcNameMatch",
"&&",
"funcNameMatch",
"[",
"1",
"]",
")",
"||",
"''",
";",
"return",
"func",
".",
"name",
";",
"}"
] | Returns the name of function 'func'.
@param {Function} func Any function.
@return {String} Name of 'func'. | [
"Returns",
"the",
"name",
"of",
"function",
"func",
"."
] | f207fa08dad991f6cd54e47d4a775f2c70a7aee5 | https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L36-L45 | train |
Mike96Angelo/Generate-JS | generate.js | isGetSet | function isGetSet(obj) {
var keys, length;
if (obj && typeof obj === 'object') {
keys = Object.getOwnPropertyNames(obj)
.sort();
length = keys.length;
if ((length === 1 && (keys[0] === 'get' && typeof obj.get ===
'function' ||
keys[0] === 'set' && typeof obj.set === 'function'
)) ||
(length === 2 && (keys[0] === 'get' && typeof obj.get ===
'function' &&
keys[1] === 'set' && typeof obj.set === 'function'
))) {
return true;
}
}
return false;
} | javascript | function isGetSet(obj) {
var keys, length;
if (obj && typeof obj === 'object') {
keys = Object.getOwnPropertyNames(obj)
.sort();
length = keys.length;
if ((length === 1 && (keys[0] === 'get' && typeof obj.get ===
'function' ||
keys[0] === 'set' && typeof obj.set === 'function'
)) ||
(length === 2 && (keys[0] === 'get' && typeof obj.get ===
'function' &&
keys[1] === 'set' && typeof obj.set === 'function'
))) {
return true;
}
}
return false;
} | [
"function",
"isGetSet",
"(",
"obj",
")",
"{",
"var",
"keys",
",",
"length",
";",
"if",
"(",
"obj",
"&&",
"typeof",
"obj",
"===",
"'object'",
")",
"{",
"keys",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"obj",
")",
".",
"sort",
"(",
")",
";",
"length",
"=",
"keys",
".",
"length",
";",
"if",
"(",
"(",
"length",
"===",
"1",
"&&",
"(",
"keys",
"[",
"0",
"]",
"===",
"'get'",
"&&",
"typeof",
"obj",
".",
"get",
"===",
"'function'",
"||",
"keys",
"[",
"0",
"]",
"===",
"'set'",
"&&",
"typeof",
"obj",
".",
"set",
"===",
"'function'",
")",
")",
"||",
"(",
"length",
"===",
"2",
"&&",
"(",
"keys",
"[",
"0",
"]",
"===",
"'get'",
"&&",
"typeof",
"obj",
".",
"get",
"===",
"'function'",
"&&",
"keys",
"[",
"1",
"]",
"===",
"'set'",
"&&",
"typeof",
"obj",
".",
"set",
"===",
"'function'",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Returns true if 'obj' is an object containing only get and set functions, false otherwise.
@param {Any} obj Value to be tested.
@return {Boolean} true or false. | [
"Returns",
"true",
"if",
"obj",
"is",
"an",
"object",
"containing",
"only",
"get",
"and",
"set",
"functions",
"false",
"otherwise",
"."
] | f207fa08dad991f6cd54e47d4a775f2c70a7aee5 | https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L52-L71 | train |
Mike96Angelo/Generate-JS | generate.js | defineObjectProperties | function defineObjectProperties(obj, descriptor, properties) {
var setProperties = {},
i,
keys,
length,
p = properties || descriptor,
d = properties && descriptor;
properties = (p && typeof p === 'object') ? p : {};
descriptor = (d && typeof d === 'object') ? d : {};
keys = Object.getOwnPropertyNames(properties);
length = keys.length;
for (i = 0; i < length; i++) {
if (isGetSet(properties[keys[i]])) {
setProperties[keys[i]] = {
configurable: !!descriptor.configurable,
enumerable: !!descriptor.enumerable,
get: properties[keys[i]].get,
set: properties[keys[i]].set
};
} else {
setProperties[keys[i]] = {
configurable: !!descriptor.configurable,
enumerable: !!descriptor.enumerable,
writable: !!descriptor.writable,
value: properties[keys[i]]
};
}
}
Object.defineProperties(obj, setProperties);
return obj;
} | javascript | function defineObjectProperties(obj, descriptor, properties) {
var setProperties = {},
i,
keys,
length,
p = properties || descriptor,
d = properties && descriptor;
properties = (p && typeof p === 'object') ? p : {};
descriptor = (d && typeof d === 'object') ? d : {};
keys = Object.getOwnPropertyNames(properties);
length = keys.length;
for (i = 0; i < length; i++) {
if (isGetSet(properties[keys[i]])) {
setProperties[keys[i]] = {
configurable: !!descriptor.configurable,
enumerable: !!descriptor.enumerable,
get: properties[keys[i]].get,
set: properties[keys[i]].set
};
} else {
setProperties[keys[i]] = {
configurable: !!descriptor.configurable,
enumerable: !!descriptor.enumerable,
writable: !!descriptor.writable,
value: properties[keys[i]]
};
}
}
Object.defineProperties(obj, setProperties);
return obj;
} | [
"function",
"defineObjectProperties",
"(",
"obj",
",",
"descriptor",
",",
"properties",
")",
"{",
"var",
"setProperties",
"=",
"{",
"}",
",",
"i",
",",
"keys",
",",
"length",
",",
"p",
"=",
"properties",
"||",
"descriptor",
",",
"d",
"=",
"properties",
"&&",
"descriptor",
";",
"properties",
"=",
"(",
"p",
"&&",
"typeof",
"p",
"===",
"'object'",
")",
"?",
"p",
":",
"{",
"}",
";",
"descriptor",
"=",
"(",
"d",
"&&",
"typeof",
"d",
"===",
"'object'",
")",
"?",
"d",
":",
"{",
"}",
";",
"keys",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"properties",
")",
";",
"length",
"=",
"keys",
".",
"length",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isGetSet",
"(",
"properties",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
")",
"{",
"setProperties",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"{",
"configurable",
":",
"!",
"!",
"descriptor",
".",
"configurable",
",",
"enumerable",
":",
"!",
"!",
"descriptor",
".",
"enumerable",
",",
"get",
":",
"properties",
"[",
"keys",
"[",
"i",
"]",
"]",
".",
"get",
",",
"set",
":",
"properties",
"[",
"keys",
"[",
"i",
"]",
"]",
".",
"set",
"}",
";",
"}",
"else",
"{",
"setProperties",
"[",
"keys",
"[",
"i",
"]",
"]",
"=",
"{",
"configurable",
":",
"!",
"!",
"descriptor",
".",
"configurable",
",",
"enumerable",
":",
"!",
"!",
"descriptor",
".",
"enumerable",
",",
"writable",
":",
"!",
"!",
"descriptor",
".",
"writable",
",",
"value",
":",
"properties",
"[",
"keys",
"[",
"i",
"]",
"]",
"}",
";",
"}",
"}",
"Object",
".",
"defineProperties",
"(",
"obj",
",",
"setProperties",
")",
";",
"return",
"obj",
";",
"}"
] | Defines properties on 'obj'.
@param {Object} obj An object that 'properties' will be attached to.
@param {Object} descriptor Optional object descriptor that will be applied to all attaching properties on 'properties'.
@param {Object} properties An object who's properties will be attached to 'obj'.
@return {Generator} 'obj'. | [
"Defines",
"properties",
"on",
"obj",
"."
] | f207fa08dad991f6cd54e47d4a775f2c70a7aee5 | https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L80-L114 | train |
Mike96Angelo/Generate-JS | generate.js | isGeneration | function isGeneration(generator) {
assertTypeError(generator, 'function');
var _ = this;
return _.prototype.isPrototypeOf(generator.prototype);
} | javascript | function isGeneration(generator) {
assertTypeError(generator, 'function');
var _ = this;
return _.prototype.isPrototypeOf(generator.prototype);
} | [
"function",
"isGeneration",
"(",
"generator",
")",
"{",
"assertTypeError",
"(",
"generator",
",",
"'function'",
")",
";",
"var",
"_",
"=",
"this",
";",
"return",
"_",
".",
"prototype",
".",
"isPrototypeOf",
"(",
"generator",
".",
"prototype",
")",
";",
"}"
] | Returns true if 'generator' was generated by this Generator.
@param {Generator} generator A Generator.
@return {Boolean} true or false. | [
"Returns",
"true",
"if",
"generator",
"was",
"generated",
"by",
"this",
"Generator",
"."
] | f207fa08dad991f6cd54e47d4a775f2c70a7aee5 | https://github.com/Mike96Angelo/Generate-JS/blob/f207fa08dad991f6cd54e47d4a775f2c70a7aee5/generate.js#L155-L161 | train |
vesln/b | lib/child-bench/index.js | ChildBench | function ChildBench(name, file, opts){
opts || (opts = {})
var args = [file]
var options = {}
// extra process arguments
if (opts.args) args.push.apply(args, opts.args)
// bench subject
if (opts.subject) options.env = { subject: opts.subject }
var reqs = this.requests = {}
this.child = fork(runner, args, options)
.on('message', function(msg){
var result = reqs[msg.id]
msg.value.name = name
switch (msg.type) {
case 'result': result.write(msg.value); break
case 'error':
var err = new Error(msg.value.message)
err.stack = msg.value.stack
result.error(err)
break
default:
throw new Error('unknown message ' + JSON.stringify(msg))
}
})
// clean up
.on('exit', function(code){
if (code > 0) process.exit(code)
})
} | javascript | function ChildBench(name, file, opts){
opts || (opts = {})
var args = [file]
var options = {}
// extra process arguments
if (opts.args) args.push.apply(args, opts.args)
// bench subject
if (opts.subject) options.env = { subject: opts.subject }
var reqs = this.requests = {}
this.child = fork(runner, args, options)
.on('message', function(msg){
var result = reqs[msg.id]
msg.value.name = name
switch (msg.type) {
case 'result': result.write(msg.value); break
case 'error':
var err = new Error(msg.value.message)
err.stack = msg.value.stack
result.error(err)
break
default:
throw new Error('unknown message ' + JSON.stringify(msg))
}
})
// clean up
.on('exit', function(code){
if (code > 0) process.exit(code)
})
} | [
"function",
"ChildBench",
"(",
"name",
",",
"file",
",",
"opts",
")",
"{",
"opts",
"||",
"(",
"opts",
"=",
"{",
"}",
")",
"var",
"args",
"=",
"[",
"file",
"]",
"var",
"options",
"=",
"{",
"}",
"if",
"(",
"opts",
".",
"args",
")",
"args",
".",
"push",
".",
"apply",
"(",
"args",
",",
"opts",
".",
"args",
")",
"if",
"(",
"opts",
".",
"subject",
")",
"options",
".",
"env",
"=",
"{",
"subject",
":",
"opts",
".",
"subject",
"}",
"var",
"reqs",
"=",
"this",
".",
"requests",
"=",
"{",
"}",
"this",
".",
"child",
"=",
"fork",
"(",
"runner",
",",
"args",
",",
"options",
")",
".",
"on",
"(",
"'message'",
",",
"function",
"(",
"msg",
")",
"{",
"var",
"result",
"=",
"reqs",
"[",
"msg",
".",
"id",
"]",
"msg",
".",
"value",
".",
"name",
"=",
"name",
"switch",
"(",
"msg",
".",
"type",
")",
"{",
"case",
"'result'",
":",
"result",
".",
"write",
"(",
"msg",
".",
"value",
")",
";",
"break",
"case",
"'error'",
":",
"var",
"err",
"=",
"new",
"Error",
"(",
"msg",
".",
"value",
".",
"message",
")",
"err",
".",
"stack",
"=",
"msg",
".",
"value",
".",
"stack",
"result",
".",
"error",
"(",
"err",
")",
"break",
"default",
":",
"throw",
"new",
"Error",
"(",
"'unknown message '",
"+",
"JSON",
".",
"stringify",
"(",
"msg",
")",
")",
"}",
"}",
")",
".",
"on",
"(",
"'exit'",
",",
"function",
"(",
"code",
")",
"{",
"if",
"(",
"code",
">",
"0",
")",
"process",
".",
"exit",
"(",
"code",
")",
"}",
")",
"}"
] | create benchmark that runs in a separate process
implements a similar API to benchmark.js
@param {String} name
@param {String} file absolute path
@param {Object} [opts] | [
"create",
"benchmark",
"that",
"runs",
"in",
"a",
"separate",
"process",
"implements",
"a",
"similar",
"API",
"to",
"benchmark",
".",
"js"
] | 9bddf3032885ae51095946a2f153e5b03cbec332 | https://github.com/vesln/b/blob/9bddf3032885ae51095946a2f153e5b03cbec332/lib/child-bench/index.js#L17-L46 | train |
perezpaya/irelia | lib/main.js | function(settings) {
this.key = settings.key;
this.endpoint = settings.endpoint;
if (this.endpoint) {
console.log(
'Irelia has been updated to version 0.2 where we are using a new url system. You will have to update your config for using it. Check documentation at: '
.cyan +
'https://github.com/alexperezpaya/irelia'.underline.blue);
}
if (settings.debug === true) {
this.debug = true;
}
this.secure = (settings.secure) ? settings.secure : false;
this.host = settings.host;
this.path = settings.path;
return this;
} | javascript | function(settings) {
this.key = settings.key;
this.endpoint = settings.endpoint;
if (this.endpoint) {
console.log(
'Irelia has been updated to version 0.2 where we are using a new url system. You will have to update your config for using it. Check documentation at: '
.cyan +
'https://github.com/alexperezpaya/irelia'.underline.blue);
}
if (settings.debug === true) {
this.debug = true;
}
this.secure = (settings.secure) ? settings.secure : false;
this.host = settings.host;
this.path = settings.path;
return this;
} | [
"function",
"(",
"settings",
")",
"{",
"this",
".",
"key",
"=",
"settings",
".",
"key",
";",
"this",
".",
"endpoint",
"=",
"settings",
".",
"endpoint",
";",
"if",
"(",
"this",
".",
"endpoint",
")",
"{",
"console",
".",
"log",
"(",
"'Irelia has been updated to version 0.2 where we are using a new url system. You will have to update your config for using it. Check documentation at: '",
".",
"cyan",
"+",
"'https://github.com/alexperezpaya/irelia'",
".",
"underline",
".",
"blue",
")",
";",
"}",
"if",
"(",
"settings",
".",
"debug",
"===",
"true",
")",
"{",
"this",
".",
"debug",
"=",
"true",
";",
"}",
"this",
".",
"secure",
"=",
"(",
"settings",
".",
"secure",
")",
"?",
"settings",
".",
"secure",
":",
"false",
";",
"this",
".",
"host",
"=",
"settings",
".",
"host",
";",
"this",
".",
"path",
"=",
"settings",
".",
"path",
";",
"return",
"this",
";",
"}"
] | Inits class and saves settings in it | [
"Inits",
"class",
"and",
"saves",
"settings",
"in",
"it"
] | 6c1237fe7f7ed0483fdfeda414dcb69222d4b567 | https://github.com/perezpaya/irelia/blob/6c1237fe7f7ed0483fdfeda414dcb69222d4b567/lib/main.js#L12-L34 | train |
|
rewgt/shadow-widget | src/react_widget.js | getLineInfo | function getLineInfo(bRet,bNum,code) {
var numCount = 0, hintCount = 0;
var bLn = code.split(ln_re_), len = bLn.length;
var iLastLn = -1, sLastNum = '0';
for (var i=0; i < len; i++) {
var item = bLn[i], hasHint = false;
var sNew = item.replace(hint_re_, function(sMatch) {
hasHint = true; hintCount += 1;
var iTmp = sMatch.length;
if (iLastLn + 1 == i) {
iLastLn = i; sLastNum = (parseInt(sLastNum) + 1) + '';
iTmp -= 1;
sLastNum = sLastNum.slice(-iTmp); // trim to same width: ~~
if (sLastNum.length < iTmp) sLastNum = (new Array(iTmp-sLastNum.length+1)).join('0') + sLastNum;
bRet[i] = sLastNum + '!';
}
else bRet[i] = (new Array(iTmp)).join(' ') + '!';
return '';
});
if (hasHint)
bLn[i] = sNew;
else {
var hasNum = false;
var sNew2 = item.replace(num_re_, function(sMatch) {
hasNum = true; numCount += 1;
sLastNum = bRet[i] = sMatch.slice(0,-1);
iLastLn = i;
return '';
});
if (hasNum) bLn[i] = sNew2;
}
}
if (!bRet.length) // no changing
return code;
else {
if (!hintCount && numCount <= 1) { // avoid accident preceed-number
bRet.splice(0);
return code; // no changing
}
else {
if (numCount) bNum.push(numCount);
return bLn.join('\n');
}
}
} | javascript | function getLineInfo(bRet,bNum,code) {
var numCount = 0, hintCount = 0;
var bLn = code.split(ln_re_), len = bLn.length;
var iLastLn = -1, sLastNum = '0';
for (var i=0; i < len; i++) {
var item = bLn[i], hasHint = false;
var sNew = item.replace(hint_re_, function(sMatch) {
hasHint = true; hintCount += 1;
var iTmp = sMatch.length;
if (iLastLn + 1 == i) {
iLastLn = i; sLastNum = (parseInt(sLastNum) + 1) + '';
iTmp -= 1;
sLastNum = sLastNum.slice(-iTmp); // trim to same width: ~~
if (sLastNum.length < iTmp) sLastNum = (new Array(iTmp-sLastNum.length+1)).join('0') + sLastNum;
bRet[i] = sLastNum + '!';
}
else bRet[i] = (new Array(iTmp)).join(' ') + '!';
return '';
});
if (hasHint)
bLn[i] = sNew;
else {
var hasNum = false;
var sNew2 = item.replace(num_re_, function(sMatch) {
hasNum = true; numCount += 1;
sLastNum = bRet[i] = sMatch.slice(0,-1);
iLastLn = i;
return '';
});
if (hasNum) bLn[i] = sNew2;
}
}
if (!bRet.length) // no changing
return code;
else {
if (!hintCount && numCount <= 1) { // avoid accident preceed-number
bRet.splice(0);
return code; // no changing
}
else {
if (numCount) bNum.push(numCount);
return bLn.join('\n');
}
}
} | [
"function",
"getLineInfo",
"(",
"bRet",
",",
"bNum",
",",
"code",
")",
"{",
"var",
"numCount",
"=",
"0",
",",
"hintCount",
"=",
"0",
";",
"var",
"bLn",
"=",
"code",
".",
"split",
"(",
"ln_re_",
")",
",",
"len",
"=",
"bLn",
".",
"length",
";",
"var",
"iLastLn",
"=",
"-",
"1",
",",
"sLastNum",
"=",
"'0'",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"item",
"=",
"bLn",
"[",
"i",
"]",
",",
"hasHint",
"=",
"false",
";",
"var",
"sNew",
"=",
"item",
".",
"replace",
"(",
"hint_re_",
",",
"function",
"(",
"sMatch",
")",
"{",
"hasHint",
"=",
"true",
";",
"hintCount",
"+=",
"1",
";",
"var",
"iTmp",
"=",
"sMatch",
".",
"length",
";",
"if",
"(",
"iLastLn",
"+",
"1",
"==",
"i",
")",
"{",
"iLastLn",
"=",
"i",
";",
"sLastNum",
"=",
"(",
"parseInt",
"(",
"sLastNum",
")",
"+",
"1",
")",
"+",
"''",
";",
"iTmp",
"-=",
"1",
";",
"sLastNum",
"=",
"sLastNum",
".",
"slice",
"(",
"-",
"iTmp",
")",
";",
"if",
"(",
"sLastNum",
".",
"length",
"<",
"iTmp",
")",
"sLastNum",
"=",
"(",
"new",
"Array",
"(",
"iTmp",
"-",
"sLastNum",
".",
"length",
"+",
"1",
")",
")",
".",
"join",
"(",
"'0'",
")",
"+",
"sLastNum",
";",
"bRet",
"[",
"i",
"]",
"=",
"sLastNum",
"+",
"'!'",
";",
"}",
"else",
"bRet",
"[",
"i",
"]",
"=",
"(",
"new",
"Array",
"(",
"iTmp",
")",
")",
".",
"join",
"(",
"' '",
")",
"+",
"'!'",
";",
"return",
"''",
";",
"}",
")",
";",
"if",
"(",
"hasHint",
")",
"bLn",
"[",
"i",
"]",
"=",
"sNew",
";",
"else",
"{",
"var",
"hasNum",
"=",
"false",
";",
"var",
"sNew2",
"=",
"item",
".",
"replace",
"(",
"num_re_",
",",
"function",
"(",
"sMatch",
")",
"{",
"hasNum",
"=",
"true",
";",
"numCount",
"+=",
"1",
";",
"sLastNum",
"=",
"bRet",
"[",
"i",
"]",
"=",
"sMatch",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
";",
"iLastLn",
"=",
"i",
";",
"return",
"''",
";",
"}",
")",
";",
"if",
"(",
"hasNum",
")",
"bLn",
"[",
"i",
"]",
"=",
"sNew2",
";",
"}",
"}",
"if",
"(",
"!",
"bRet",
".",
"length",
")",
"return",
"code",
";",
"else",
"{",
"if",
"(",
"!",
"hintCount",
"&&",
"numCount",
"<=",
"1",
")",
"{",
"bRet",
".",
"splice",
"(",
"0",
")",
";",
"return",
"code",
";",
"}",
"else",
"{",
"if",
"(",
"numCount",
")",
"bNum",
".",
"push",
"(",
"numCount",
")",
";",
"return",
"bLn",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
"}",
"}"
] | start with '~~' means highlight this line | [
"start",
"with",
"~~",
"means",
"highlight",
"this",
"line"
] | 5baa1f563d647b6d1ecb6c108bc5bcef150ea683 | https://github.com/rewgt/shadow-widget/blob/5baa1f563d647b6d1ecb6c108bc5bcef150ea683/src/react_widget.js#L1922-L1968 | train |
pfmooney/node-ldap-filter | lib/helpers.js | getAttrValue | function getAttrValue(obj, attr, strictCase) {
assert.object(obj);
assert.string(attr);
// Check for exact case match first
if (obj.hasOwnProperty(attr)) {
return obj[attr];
} else if (strictCase) {
return undefined;
}
// Perform case-insensitive enumeration after that
var lower = attr.toLowerCase();
var result;
Object.getOwnPropertyNames(obj).some(function (name) {
if (name.toLowerCase() === lower) {
result = obj[name];
return true;
}
return false;
});
return result;
} | javascript | function getAttrValue(obj, attr, strictCase) {
assert.object(obj);
assert.string(attr);
// Check for exact case match first
if (obj.hasOwnProperty(attr)) {
return obj[attr];
} else if (strictCase) {
return undefined;
}
// Perform case-insensitive enumeration after that
var lower = attr.toLowerCase();
var result;
Object.getOwnPropertyNames(obj).some(function (name) {
if (name.toLowerCase() === lower) {
result = obj[name];
return true;
}
return false;
});
return result;
} | [
"function",
"getAttrValue",
"(",
"obj",
",",
"attr",
",",
"strictCase",
")",
"{",
"assert",
".",
"object",
"(",
"obj",
")",
";",
"assert",
".",
"string",
"(",
"attr",
")",
";",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"attr",
")",
")",
"{",
"return",
"obj",
"[",
"attr",
"]",
";",
"}",
"else",
"if",
"(",
"strictCase",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"lower",
"=",
"attr",
".",
"toLowerCase",
"(",
")",
";",
"var",
"result",
";",
"Object",
".",
"getOwnPropertyNames",
"(",
"obj",
")",
".",
"some",
"(",
"function",
"(",
"name",
")",
"{",
"if",
"(",
"name",
".",
"toLowerCase",
"(",
")",
"===",
"lower",
")",
"{",
"result",
"=",
"obj",
"[",
"name",
"]",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Fetch value for named object attribute.
@param {Object} obj object to fetch value from
@param {String} attr name of attribute to fetch
@param {Boolean} strictCase attribute name is case-sensitive. default: false | [
"Fetch",
"value",
"for",
"named",
"object",
"attribute",
"."
] | daa5a5d5d11c73582275cc75aa9f3ff839b1ab06 | https://github.com/pfmooney/node-ldap-filter/blob/daa5a5d5d11c73582275cc75aa9f3ff839b1ab06/lib/helpers.js#L103-L124 | train |
exsilium/xmodem.js | lib/index.js | function(callback, delay, repetitions) {
var x = 0;
var intervalID = setInterval(function () {
if (++x === repetitions) {
clearInterval(intervalID);
receive_interval_timer = false;
}
callback();
}, delay);
return intervalID;
} | javascript | function(callback, delay, repetitions) {
var x = 0;
var intervalID = setInterval(function () {
if (++x === repetitions) {
clearInterval(intervalID);
receive_interval_timer = false;
}
callback();
}, delay);
return intervalID;
} | [
"function",
"(",
"callback",
",",
"delay",
",",
"repetitions",
")",
"{",
"var",
"x",
"=",
"0",
";",
"var",
"intervalID",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"++",
"x",
"===",
"repetitions",
")",
"{",
"clearInterval",
"(",
"intervalID",
")",
";",
"receive_interval_timer",
"=",
"false",
";",
"}",
"callback",
"(",
")",
";",
"}",
",",
"delay",
")",
";",
"return",
"intervalID",
";",
"}"
] | Internal helper function for scoped intervals
@private | [
"Internal",
"helper",
"function",
"for",
"scoped",
"intervals"
] | 045ea33cbe62f0820891000daf89a46e186fd1a0 | https://github.com/exsilium/xmodem.js/blob/045ea33cbe62f0820891000daf89a46e186fd1a0/lib/index.js#L352-L362 | train |
|
DesTincT/bemlint | lib/ignored-paths.js | removePrefixFromFilepath | function removePrefixFromFilepath(filepath, prefix) {
prefix += "/";
if (filepath.indexOf(prefix) === 0) {
filepath = filepath.substr(prefix.length);
}
return filepath;
} | javascript | function removePrefixFromFilepath(filepath, prefix) {
prefix += "/";
if (filepath.indexOf(prefix) === 0) {
filepath = filepath.substr(prefix.length);
}
return filepath;
} | [
"function",
"removePrefixFromFilepath",
"(",
"filepath",
",",
"prefix",
")",
"{",
"prefix",
"+=",
"\"/\"",
";",
"if",
"(",
"filepath",
".",
"indexOf",
"(",
"prefix",
")",
"===",
"0",
")",
"{",
"filepath",
"=",
"filepath",
".",
"substr",
"(",
"prefix",
".",
"length",
")",
";",
"}",
"return",
"filepath",
";",
"}"
] | Remove a prefix from a filepath
@param {string} filepath Path to remove the prefix from
@param {string} prefix Prefix to remove from filepath
@returns {string} Normalized filepath | [
"Remove",
"a",
"prefix",
"from",
"a",
"filepath"
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/ignored-paths.js#L69-L75 | train |
DesTincT/bemlint | lib/ignored-paths.js | resolveFilepath | function resolveFilepath(filepath, baseDir) {
if (baseDir) {
var base = normalizeFilepath(path.resolve(baseDir));
filepath = removePrefixFromFilepath(filepath, base);
filepath = removePrefixFromFilepath(filepath, fs.realpathSync(base));
}
filepath.replace(/^\//, "");
return filepath;
} | javascript | function resolveFilepath(filepath, baseDir) {
if (baseDir) {
var base = normalizeFilepath(path.resolve(baseDir));
filepath = removePrefixFromFilepath(filepath, base);
filepath = removePrefixFromFilepath(filepath, fs.realpathSync(base));
}
filepath.replace(/^\//, "");
return filepath;
} | [
"function",
"resolveFilepath",
"(",
"filepath",
",",
"baseDir",
")",
"{",
"if",
"(",
"baseDir",
")",
"{",
"var",
"base",
"=",
"normalizeFilepath",
"(",
"path",
".",
"resolve",
"(",
"baseDir",
")",
")",
";",
"filepath",
"=",
"removePrefixFromFilepath",
"(",
"filepath",
",",
"base",
")",
";",
"filepath",
"=",
"removePrefixFromFilepath",
"(",
"filepath",
",",
"fs",
".",
"realpathSync",
"(",
"base",
")",
")",
";",
"}",
"filepath",
".",
"replace",
"(",
"/",
"^\\/",
"/",
",",
"\"\"",
")",
";",
"return",
"filepath",
";",
"}"
] | Resolves a filepath
@param {string} filepath Path resolve
@param {string} baseDir Base directory to resolve the filepath from
@returns {string} Resolved filepath | [
"Resolves",
"a",
"filepath"
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/ignored-paths.js#L83-L91 | train |
DesTincT/bemlint | lib/ignored-paths.js | addIgnoreFile | function addIgnoreFile(ig, filepath) {
if (fs.existsSync(filepath)) {
ig.add(fs.readFileSync(filepath).toString());
}
return ig;
} | javascript | function addIgnoreFile(ig, filepath) {
if (fs.existsSync(filepath)) {
ig.add(fs.readFileSync(filepath).toString());
}
return ig;
} | [
"function",
"addIgnoreFile",
"(",
"ig",
",",
"filepath",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"filepath",
")",
")",
"{",
"ig",
".",
"add",
"(",
"fs",
".",
"readFileSync",
"(",
"filepath",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"ig",
";",
"}"
] | add ignore file to node-ignore instance
@param {object} ig, instance of node-ignore
@param {string} filepath, file to add to ig
@returns {array} raw ignore rules | [
"add",
"ignore",
"file",
"to",
"node",
"-",
"ignore",
"instance"
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/ignored-paths.js#L144-L149 | train |
eGavr/toc-md | lib/toc.js | function (header, prevToken) {
var options = this.options;
if (header.depth > options.maxDepth) return;
var headerText = utils.getHeader(header.text, prevToken);
if (!headerText) return;
var anchor = this._getAnchor(header.text, prevToken),
indent = utils.getIndent(this._usedHeaders, header.depth);
this._usedHeaders.unshift({
depth: header.depth,
indent: indent
});
this.data += indent + options.bullet + ' [' + headerText.replace(/\\/g, '\\\\') + '](#' + anchor + ')' + EOL;
} | javascript | function (header, prevToken) {
var options = this.options;
if (header.depth > options.maxDepth) return;
var headerText = utils.getHeader(header.text, prevToken);
if (!headerText) return;
var anchor = this._getAnchor(header.text, prevToken),
indent = utils.getIndent(this._usedHeaders, header.depth);
this._usedHeaders.unshift({
depth: header.depth,
indent: indent
});
this.data += indent + options.bullet + ' [' + headerText.replace(/\\/g, '\\\\') + '](#' + anchor + ')' + EOL;
} | [
"function",
"(",
"header",
",",
"prevToken",
")",
"{",
"var",
"options",
"=",
"this",
".",
"options",
";",
"if",
"(",
"header",
".",
"depth",
">",
"options",
".",
"maxDepth",
")",
"return",
";",
"var",
"headerText",
"=",
"utils",
".",
"getHeader",
"(",
"header",
".",
"text",
",",
"prevToken",
")",
";",
"if",
"(",
"!",
"headerText",
")",
"return",
";",
"var",
"anchor",
"=",
"this",
".",
"_getAnchor",
"(",
"header",
".",
"text",
",",
"prevToken",
")",
",",
"indent",
"=",
"utils",
".",
"getIndent",
"(",
"this",
".",
"_usedHeaders",
",",
"header",
".",
"depth",
")",
";",
"this",
".",
"_usedHeaders",
".",
"unshift",
"(",
"{",
"depth",
":",
"header",
".",
"depth",
",",
"indent",
":",
"indent",
"}",
")",
";",
"this",
".",
"data",
"+=",
"indent",
"+",
"options",
".",
"bullet",
"+",
"' ['",
"+",
"headerText",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'\\\\\\\\'",
")",
"+",
"\\\\",
"+",
"\\\\",
"+",
"'](#'",
"+",
"anchor",
";",
"}"
] | Adds a TOC elemet
@param {Object} [header]
@param {Number} [header.depth]
@param {String} [header.text]
@returns {undefined}
@public | [
"Adds",
"a",
"TOC",
"elemet"
] | debdf98d7c1035eeec2a25350c5ab2263c2cd89e | https://github.com/eGavr/toc-md/blob/debdf98d7c1035eeec2a25350c5ab2263c2cd89e/lib/toc.js#L34-L52 | train |
|
eGavr/toc-md | lib/toc.js | function (headerText, prevToken) {
if (prevToken && prevToken.type === 'paragraph' && utils.isHtml(prevToken.text)) {
var anchorFromHtml = utils.getAnchorFromHtml(prevToken.text);
if (anchorFromHtml) {
return anchorFromHtml;
}
}
var anchor = utils.getAnchorFromHeader(headerText, prevToken);
if (this._cache.hasOwnProperty(anchor)) {
anchor += '-' + this._cache[anchor]++;
} else {
this._cache[anchor] = 1;
}
return anchor;
} | javascript | function (headerText, prevToken) {
if (prevToken && prevToken.type === 'paragraph' && utils.isHtml(prevToken.text)) {
var anchorFromHtml = utils.getAnchorFromHtml(prevToken.text);
if (anchorFromHtml) {
return anchorFromHtml;
}
}
var anchor = utils.getAnchorFromHeader(headerText, prevToken);
if (this._cache.hasOwnProperty(anchor)) {
anchor += '-' + this._cache[anchor]++;
} else {
this._cache[anchor] = 1;
}
return anchor;
} | [
"function",
"(",
"headerText",
",",
"prevToken",
")",
"{",
"if",
"(",
"prevToken",
"&&",
"prevToken",
".",
"type",
"===",
"'paragraph'",
"&&",
"utils",
".",
"isHtml",
"(",
"prevToken",
".",
"text",
")",
")",
"{",
"var",
"anchorFromHtml",
"=",
"utils",
".",
"getAnchorFromHtml",
"(",
"prevToken",
".",
"text",
")",
";",
"if",
"(",
"anchorFromHtml",
")",
"{",
"return",
"anchorFromHtml",
";",
"}",
"}",
"var",
"anchor",
"=",
"utils",
".",
"getAnchorFromHeader",
"(",
"headerText",
",",
"prevToken",
")",
";",
"if",
"(",
"this",
".",
"_cache",
".",
"hasOwnProperty",
"(",
"anchor",
")",
")",
"{",
"anchor",
"+=",
"'-'",
"+",
"this",
".",
"_cache",
"[",
"anchor",
"]",
"++",
";",
"}",
"else",
"{",
"this",
".",
"_cache",
"[",
"anchor",
"]",
"=",
"1",
";",
"}",
"return",
"anchor",
";",
"}"
] | Returns an anchor for a given header
@param {String} headerText
@returns {String} | [
"Returns",
"an",
"anchor",
"for",
"a",
"given",
"header"
] | debdf98d7c1035eeec2a25350c5ab2263c2cd89e | https://github.com/eGavr/toc-md/blob/debdf98d7c1035eeec2a25350c5ab2263c2cd89e/lib/toc.js#L89-L106 | train |
|
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper | index.js | parseGoogleNewsRSSData | function parseGoogleNewsRSSData(fileData) {
// sanity check that this is valid google news RSS
if (fileData.indexOf('[email protected]') != -1) {
// set an empty array of news story objects
var allGoogleNewsData = [ ];
var params = {normalizeWhitespace: true, xmlMode: true};
// load the html into the cheerio doc
var cheerio = require("cheerio");
var fullDoc = cheerio.load(fileData, params);
// iterate through movies and strip useful parts, add each to return object
fullDoc('item').each(function(i, elem) {
// load current item
var itemDoc = cheerio.load(fullDoc(this).html(), params);
// break out parts of interest
// some sections need cleaning so do that as well
var fullTitleLine = itemDoc('title').text().trim();
var fullTitleSplitIndex = fullTitleLine.lastIndexOf(' - ');
var titlePart = fullTitleLine.substring(0, fullTitleSplitIndex);
var sourcePart = fullTitleLine.substring(fullTitleSplitIndex + 3, fullTitleSplitIndex.length);
var fullURLPart = itemDoc('link').html().trim();
var cleanURLPart = fullURLPart.split(';url=')[1];
var categoryPart = itemDoc('category').html();
if (categoryPart != null)
categoryPart = categoryPart.trim();
var pubDatePart = itemDoc('pubDate').html().trim();
var fullDescriptionPart = itemDoc('description').text().trim();
var descriptionStart = fullDescriptionPart.indexOf('</font><br><font size="-1">');
var descriptionEnd = fullDescriptionPart.indexOf('</font>', descriptionStart + 1);
var cleanDescriptionPart = fullDescriptionPart.substring(descriptionStart, descriptionEnd);
var cleanDescriptionPart = cleanDescriptionPart.replace('</font><br><font size="-1">', '');
var cleanDescriptionPart = cleanDescriptionPart.replace('<b>...</b>', '...');
// build final object for the current news story
var fullObject = { title: titlePart
, source: sourcePart
, category: categoryPart
, pubDate: pubDatePart
, fullURL: fullURLPart
, cleanURL: cleanURLPart
, fullDescription: fullDescriptionPart
, cleanDescription: cleanDescriptionPart
};
// add thew news story obejct to the array
allGoogleNewsData.push(fullObject);
});
// return no error state and the collected news story objects
return {error: false, data: allGoogleNewsData};
}
// if sanity check failed, return true error state and an error message
return {error: errorFlag, errorMessage: 'Fetched RSS data does not contain expected content.', data: null};
} | javascript | function parseGoogleNewsRSSData(fileData) {
// sanity check that this is valid google news RSS
if (fileData.indexOf('[email protected]') != -1) {
// set an empty array of news story objects
var allGoogleNewsData = [ ];
var params = {normalizeWhitespace: true, xmlMode: true};
// load the html into the cheerio doc
var cheerio = require("cheerio");
var fullDoc = cheerio.load(fileData, params);
// iterate through movies and strip useful parts, add each to return object
fullDoc('item').each(function(i, elem) {
// load current item
var itemDoc = cheerio.load(fullDoc(this).html(), params);
// break out parts of interest
// some sections need cleaning so do that as well
var fullTitleLine = itemDoc('title').text().trim();
var fullTitleSplitIndex = fullTitleLine.lastIndexOf(' - ');
var titlePart = fullTitleLine.substring(0, fullTitleSplitIndex);
var sourcePart = fullTitleLine.substring(fullTitleSplitIndex + 3, fullTitleSplitIndex.length);
var fullURLPart = itemDoc('link').html().trim();
var cleanURLPart = fullURLPart.split(';url=')[1];
var categoryPart = itemDoc('category').html();
if (categoryPart != null)
categoryPart = categoryPart.trim();
var pubDatePart = itemDoc('pubDate').html().trim();
var fullDescriptionPart = itemDoc('description').text().trim();
var descriptionStart = fullDescriptionPart.indexOf('</font><br><font size="-1">');
var descriptionEnd = fullDescriptionPart.indexOf('</font>', descriptionStart + 1);
var cleanDescriptionPart = fullDescriptionPart.substring(descriptionStart, descriptionEnd);
var cleanDescriptionPart = cleanDescriptionPart.replace('</font><br><font size="-1">', '');
var cleanDescriptionPart = cleanDescriptionPart.replace('<b>...</b>', '...');
// build final object for the current news story
var fullObject = { title: titlePart
, source: sourcePart
, category: categoryPart
, pubDate: pubDatePart
, fullURL: fullURLPart
, cleanURL: cleanURLPart
, fullDescription: fullDescriptionPart
, cleanDescription: cleanDescriptionPart
};
// add thew news story obejct to the array
allGoogleNewsData.push(fullObject);
});
// return no error state and the collected news story objects
return {error: false, data: allGoogleNewsData};
}
// if sanity check failed, return true error state and an error message
return {error: errorFlag, errorMessage: 'Fetched RSS data does not contain expected content.', data: null};
} | [
"function",
"parseGoogleNewsRSSData",
"(",
"fileData",
")",
"{",
"if",
"(",
"fileData",
".",
"indexOf",
"(",
"'[email protected]'",
")",
"!=",
"-",
"1",
")",
"{",
"var",
"allGoogleNewsData",
"=",
"[",
"]",
";",
"var",
"params",
"=",
"{",
"normalizeWhitespace",
":",
"true",
",",
"xmlMode",
":",
"true",
"}",
";",
"var",
"cheerio",
"=",
"require",
"(",
"\"cheerio\"",
")",
";",
"var",
"fullDoc",
"=",
"cheerio",
".",
"load",
"(",
"fileData",
",",
"params",
")",
";",
"fullDoc",
"(",
"'item'",
")",
".",
"each",
"(",
"function",
"(",
"i",
",",
"elem",
")",
"{",
"var",
"itemDoc",
"=",
"cheerio",
".",
"load",
"(",
"fullDoc",
"(",
"this",
")",
".",
"html",
"(",
")",
",",
"params",
")",
";",
"var",
"fullTitleLine",
"=",
"itemDoc",
"(",
"'title'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
";",
"var",
"fullTitleSplitIndex",
"=",
"fullTitleLine",
".",
"lastIndexOf",
"(",
"' - '",
")",
";",
"var",
"titlePart",
"=",
"fullTitleLine",
".",
"substring",
"(",
"0",
",",
"fullTitleSplitIndex",
")",
";",
"var",
"sourcePart",
"=",
"fullTitleLine",
".",
"substring",
"(",
"fullTitleSplitIndex",
"+",
"3",
",",
"fullTitleSplitIndex",
".",
"length",
")",
";",
"var",
"fullURLPart",
"=",
"itemDoc",
"(",
"'link'",
")",
".",
"html",
"(",
")",
".",
"trim",
"(",
")",
";",
"var",
"cleanURLPart",
"=",
"fullURLPart",
".",
"split",
"(",
"';url='",
")",
"[",
"1",
"]",
";",
"var",
"categoryPart",
"=",
"itemDoc",
"(",
"'category'",
")",
".",
"html",
"(",
")",
";",
"if",
"(",
"categoryPart",
"!=",
"null",
")",
"categoryPart",
"=",
"categoryPart",
".",
"trim",
"(",
")",
";",
"var",
"pubDatePart",
"=",
"itemDoc",
"(",
"'pubDate'",
")",
".",
"html",
"(",
")",
".",
"trim",
"(",
")",
";",
"var",
"fullDescriptionPart",
"=",
"itemDoc",
"(",
"'description'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
";",
"var",
"descriptionStart",
"=",
"fullDescriptionPart",
".",
"indexOf",
"(",
"'</font><br><font size=\"-1\">'",
")",
";",
"var",
"descriptionEnd",
"=",
"fullDescriptionPart",
".",
"indexOf",
"(",
"'</font>'",
",",
"descriptionStart",
"+",
"1",
")",
";",
"var",
"cleanDescriptionPart",
"=",
"fullDescriptionPart",
".",
"substring",
"(",
"descriptionStart",
",",
"descriptionEnd",
")",
";",
"var",
"cleanDescriptionPart",
"=",
"cleanDescriptionPart",
".",
"replace",
"(",
"'</font><br><font size=\"-1\">'",
",",
"''",
")",
";",
"var",
"cleanDescriptionPart",
"=",
"cleanDescriptionPart",
".",
"replace",
"(",
"'<b>...</b>'",
",",
"'...'",
")",
";",
"var",
"fullObject",
"=",
"{",
"title",
":",
"titlePart",
",",
"source",
":",
"sourcePart",
",",
"category",
":",
"categoryPart",
",",
"pubDate",
":",
"pubDatePart",
",",
"fullURL",
":",
"fullURLPart",
",",
"cleanURL",
":",
"cleanURLPart",
",",
"fullDescription",
":",
"fullDescriptionPart",
",",
"cleanDescription",
":",
"cleanDescriptionPart",
"}",
";",
"allGoogleNewsData",
".",
"push",
"(",
"fullObject",
")",
";",
"}",
")",
";",
"return",
"{",
"error",
":",
"false",
",",
"data",
":",
"allGoogleNewsData",
"}",
";",
"}",
"return",
"{",
"error",
":",
"errorFlag",
",",
"errorMessage",
":",
"'Fetched RSS data does not contain expected content.'",
",",
"data",
":",
"null",
"}",
";",
"}"
] | parses the data returned from the RSS request returns the data object sent back via the callback | [
"parses",
"the",
"data",
"returned",
"from",
"the",
"RSS",
"request",
"returns",
"the",
"data",
"object",
"sent",
"back",
"via",
"the",
"callback"
] | df62b2d1af2d6154e3a075f30ed152282dd9e2f3 | https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L27-L76 | train |
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper | index.js | parseGoogleNewsRSSParamsErrorHelper | function parseGoogleNewsRSSParamsErrorHelper(errorMessage) {
return {error: true
, errorMessage: errorMessage
, type: null
, terms: null
, url: null
};
} | javascript | function parseGoogleNewsRSSParamsErrorHelper(errorMessage) {
return {error: true
, errorMessage: errorMessage
, type: null
, terms: null
, url: null
};
} | [
"function",
"parseGoogleNewsRSSParamsErrorHelper",
"(",
"errorMessage",
")",
"{",
"return",
"{",
"error",
":",
"true",
",",
"errorMessage",
":",
"errorMessage",
",",
"type",
":",
"null",
",",
"terms",
":",
"null",
",",
"url",
":",
"null",
"}",
";",
"}"
] | returns a proper return object with error and message set as specfied | [
"returns",
"a",
"proper",
"return",
"object",
"with",
"error",
"and",
"message",
"set",
"as",
"specfied"
] | df62b2d1af2d6154e3a075f30ed152282dd9e2f3 | https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L79-L86 | train |
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper | index.js | parseGoogleNewsRSSParams | function parseGoogleNewsRSSParams(params) {
// get params of interest
var newsType = params.newsType;
var newsTypeTerms = params.newsTypeTerms;
// if missing just one parameter flag error as such
if ((newsType == undefined) && (newsTypeTerms != undefined))
return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms set with no newsType set.');
if ((newsType != undefined) && (newsTypeTerms == undefined))
return parseGoogleNewsRSSParamsErrorHelper('Parameter newsType set with no newsTypeTerms set.');
// if missing both parameters, set to default
if ((newsType == undefined) && (newsTypeTerms == undefined)) {
newsType = 'TOPIC';
newsTypeTerms = 'HEADLINES';
}
// fix case parameters
newsType = newsType.toUpperCase();
newsTypeTerms = newsTypeTerms.toUpperCase();
// expand newsType name if needed
if (newsType == 'T')
newsType = 'TOPIC';
if (newsType == 'Q')
newsType = 'QUERY';
// if an invalid newsType set flag error as such
if ((newsType != 'TOPIC') && (newsType != 'QUERY'))
return parseGoogleNewsRSSParamsErrorHelper('Invalid newsType parameter specified.');
// if type is topic
if (newsType == 'TOPIC') {
// init the short and long term names of the topic type
var newsTypeTermTopicShort = null;
var newsTypeTermTopicLong = null;
// check the term for either short or long name and then set names accordingly
if ((newsTypeTerms == 'H') || (newsTypeTerms == 'HEADLINES')) {
newsTypeTermTopicShort = 'H';
newsTypeTermTopicLong = 'HEADLINES';
}
if ((newsTypeTerms == 'N') || (newsTypeTerms == 'NATIONAL')) {
newsTypeTermTopicShort = 'N';
newsTypeTermTopicLong = 'NATIONAL';
}
if ((newsTypeTerms == 'W') || (newsTypeTerms == 'WORLD')) {
newsTypeTermTopicShort = 'W';
newsTypeTermTopicLong = 'WORLD';
}
if ((newsTypeTerms == 'E') || (newsTypeTerms == 'ENTERTAINMENT')) {
newsTypeTermTopicShort = 'E';
newsTypeTermTopicLong = 'ENTERTAINMENT';
}
if ((newsTypeTerms == 'B') || (newsTypeTerms == 'BUSINESS')) {
newsTypeTermTopicShort = 'B';
newsTypeTermTopicLong = 'BUSINESS';
}
if ((newsTypeTerms == 'S') || (newsTypeTerms == 'SPORTS')) {
newsTypeTermTopicShort = 'S';
newsTypeTermTopicLong = 'SPORTS';
}
if ((newsTypeTerms == 'T') || (newsTypeTerms == 'SCI/TECH')) {
newsTypeTermTopicShort = 'T';
newsTypeTermTopicLong = 'SCI/TECH';
}
if ((newsTypeTerms == 'TC') || (newsTypeTerms == 'TECHNOLOGY')) {
newsTypeTermTopicShort = 'TC';
newsTypeTermTopicLong = 'TECHNOLOGY';
}
// if nothing was set it was a bad topic type flag error as such
if (newsTypeTermTopicShort == null)
return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms is unknown for newsType TOPIC.');
// build the request URL
var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&topic='
+ newsTypeTermTopicShort.toLowerCase()
+ '&output=rss';
// build the return object
return {error: false, errorMessage: null,
type: 'TOPIC', terms: newsTypeTermTopicLong, url: newsURL};
}
// if type is query
if (newsType == 'QUERY') {
var newsTypeTermsQuery = newsTypeTerms.toLowerCase().replace(',', '+OR+').replace(' ', '+');
var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&q='
+ newsTypeTermsQuery
+ '&output=rss';
// build the return object
return {error: false, errorMessage: null,
type: 'QUERY', terms: newsTypeTerms, url: newsURL};
}
// otherwise return generic error state
return parseGoogleNewsRSSParamsErrorHelper('Unknown parameter error occured.');
} | javascript | function parseGoogleNewsRSSParams(params) {
// get params of interest
var newsType = params.newsType;
var newsTypeTerms = params.newsTypeTerms;
// if missing just one parameter flag error as such
if ((newsType == undefined) && (newsTypeTerms != undefined))
return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms set with no newsType set.');
if ((newsType != undefined) && (newsTypeTerms == undefined))
return parseGoogleNewsRSSParamsErrorHelper('Parameter newsType set with no newsTypeTerms set.');
// if missing both parameters, set to default
if ((newsType == undefined) && (newsTypeTerms == undefined)) {
newsType = 'TOPIC';
newsTypeTerms = 'HEADLINES';
}
// fix case parameters
newsType = newsType.toUpperCase();
newsTypeTerms = newsTypeTerms.toUpperCase();
// expand newsType name if needed
if (newsType == 'T')
newsType = 'TOPIC';
if (newsType == 'Q')
newsType = 'QUERY';
// if an invalid newsType set flag error as such
if ((newsType != 'TOPIC') && (newsType != 'QUERY'))
return parseGoogleNewsRSSParamsErrorHelper('Invalid newsType parameter specified.');
// if type is topic
if (newsType == 'TOPIC') {
// init the short and long term names of the topic type
var newsTypeTermTopicShort = null;
var newsTypeTermTopicLong = null;
// check the term for either short or long name and then set names accordingly
if ((newsTypeTerms == 'H') || (newsTypeTerms == 'HEADLINES')) {
newsTypeTermTopicShort = 'H';
newsTypeTermTopicLong = 'HEADLINES';
}
if ((newsTypeTerms == 'N') || (newsTypeTerms == 'NATIONAL')) {
newsTypeTermTopicShort = 'N';
newsTypeTermTopicLong = 'NATIONAL';
}
if ((newsTypeTerms == 'W') || (newsTypeTerms == 'WORLD')) {
newsTypeTermTopicShort = 'W';
newsTypeTermTopicLong = 'WORLD';
}
if ((newsTypeTerms == 'E') || (newsTypeTerms == 'ENTERTAINMENT')) {
newsTypeTermTopicShort = 'E';
newsTypeTermTopicLong = 'ENTERTAINMENT';
}
if ((newsTypeTerms == 'B') || (newsTypeTerms == 'BUSINESS')) {
newsTypeTermTopicShort = 'B';
newsTypeTermTopicLong = 'BUSINESS';
}
if ((newsTypeTerms == 'S') || (newsTypeTerms == 'SPORTS')) {
newsTypeTermTopicShort = 'S';
newsTypeTermTopicLong = 'SPORTS';
}
if ((newsTypeTerms == 'T') || (newsTypeTerms == 'SCI/TECH')) {
newsTypeTermTopicShort = 'T';
newsTypeTermTopicLong = 'SCI/TECH';
}
if ((newsTypeTerms == 'TC') || (newsTypeTerms == 'TECHNOLOGY')) {
newsTypeTermTopicShort = 'TC';
newsTypeTermTopicLong = 'TECHNOLOGY';
}
// if nothing was set it was a bad topic type flag error as such
if (newsTypeTermTopicShort == null)
return parseGoogleNewsRSSParamsErrorHelper('Parameter newsTypeTerms is unknown for newsType TOPIC.');
// build the request URL
var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&topic='
+ newsTypeTermTopicShort.toLowerCase()
+ '&output=rss';
// build the return object
return {error: false, errorMessage: null,
type: 'TOPIC', terms: newsTypeTermTopicLong, url: newsURL};
}
// if type is query
if (newsType == 'QUERY') {
var newsTypeTermsQuery = newsTypeTerms.toLowerCase().replace(',', '+OR+').replace(' ', '+');
var newsURL = 'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&q='
+ newsTypeTermsQuery
+ '&output=rss';
// build the return object
return {error: false, errorMessage: null,
type: 'QUERY', terms: newsTypeTerms, url: newsURL};
}
// otherwise return generic error state
return parseGoogleNewsRSSParamsErrorHelper('Unknown parameter error occured.');
} | [
"function",
"parseGoogleNewsRSSParams",
"(",
"params",
")",
"{",
"var",
"newsType",
"=",
"params",
".",
"newsType",
";",
"var",
"newsTypeTerms",
"=",
"params",
".",
"newsTypeTerms",
";",
"if",
"(",
"(",
"newsType",
"==",
"undefined",
")",
"&&",
"(",
"newsTypeTerms",
"!=",
"undefined",
")",
")",
"return",
"parseGoogleNewsRSSParamsErrorHelper",
"(",
"'Parameter newsTypeTerms set with no newsType set.'",
")",
";",
"if",
"(",
"(",
"newsType",
"!=",
"undefined",
")",
"&&",
"(",
"newsTypeTerms",
"==",
"undefined",
")",
")",
"return",
"parseGoogleNewsRSSParamsErrorHelper",
"(",
"'Parameter newsType set with no newsTypeTerms set.'",
")",
";",
"if",
"(",
"(",
"newsType",
"==",
"undefined",
")",
"&&",
"(",
"newsTypeTerms",
"==",
"undefined",
")",
")",
"{",
"newsType",
"=",
"'TOPIC'",
";",
"newsTypeTerms",
"=",
"'HEADLINES'",
";",
"}",
"newsType",
"=",
"newsType",
".",
"toUpperCase",
"(",
")",
";",
"newsTypeTerms",
"=",
"newsTypeTerms",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"newsType",
"==",
"'T'",
")",
"newsType",
"=",
"'TOPIC'",
";",
"if",
"(",
"newsType",
"==",
"'Q'",
")",
"newsType",
"=",
"'QUERY'",
";",
"if",
"(",
"(",
"newsType",
"!=",
"'TOPIC'",
")",
"&&",
"(",
"newsType",
"!=",
"'QUERY'",
")",
")",
"return",
"parseGoogleNewsRSSParamsErrorHelper",
"(",
"'Invalid newsType parameter specified.'",
")",
";",
"if",
"(",
"newsType",
"==",
"'TOPIC'",
")",
"{",
"var",
"newsTypeTermTopicShort",
"=",
"null",
";",
"var",
"newsTypeTermTopicLong",
"=",
"null",
";",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'H'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'HEADLINES'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'H'",
";",
"newsTypeTermTopicLong",
"=",
"'HEADLINES'",
";",
"}",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'N'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'NATIONAL'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'N'",
";",
"newsTypeTermTopicLong",
"=",
"'NATIONAL'",
";",
"}",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'W'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'WORLD'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'W'",
";",
"newsTypeTermTopicLong",
"=",
"'WORLD'",
";",
"}",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'E'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'ENTERTAINMENT'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'E'",
";",
"newsTypeTermTopicLong",
"=",
"'ENTERTAINMENT'",
";",
"}",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'B'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'BUSINESS'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'B'",
";",
"newsTypeTermTopicLong",
"=",
"'BUSINESS'",
";",
"}",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'S'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'SPORTS'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'S'",
";",
"newsTypeTermTopicLong",
"=",
"'SPORTS'",
";",
"}",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'T'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'SCI/TECH'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'T'",
";",
"newsTypeTermTopicLong",
"=",
"'SCI/TECH'",
";",
"}",
"if",
"(",
"(",
"newsTypeTerms",
"==",
"'TC'",
")",
"||",
"(",
"newsTypeTerms",
"==",
"'TECHNOLOGY'",
")",
")",
"{",
"newsTypeTermTopicShort",
"=",
"'TC'",
";",
"newsTypeTermTopicLong",
"=",
"'TECHNOLOGY'",
";",
"}",
"if",
"(",
"newsTypeTermTopicShort",
"==",
"null",
")",
"return",
"parseGoogleNewsRSSParamsErrorHelper",
"(",
"'Parameter newsTypeTerms is unknown for newsType TOPIC.'",
")",
";",
"var",
"newsURL",
"=",
"'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&topic='",
"+",
"newsTypeTermTopicShort",
".",
"toLowerCase",
"(",
")",
"+",
"'&output=rss'",
";",
"return",
"{",
"error",
":",
"false",
",",
"errorMessage",
":",
"null",
",",
"type",
":",
"'TOPIC'",
",",
"terms",
":",
"newsTypeTermTopicLong",
",",
"url",
":",
"newsURL",
"}",
";",
"}",
"if",
"(",
"newsType",
"==",
"'QUERY'",
")",
"{",
"var",
"newsTypeTermsQuery",
"=",
"newsTypeTerms",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"','",
",",
"'+OR+'",
")",
".",
"replace",
"(",
"' '",
",",
"'+'",
")",
";",
"var",
"newsURL",
"=",
"'https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&q='",
"+",
"newsTypeTermsQuery",
"+",
"'&output=rss'",
";",
"return",
"{",
"error",
":",
"false",
",",
"errorMessage",
":",
"null",
",",
"type",
":",
"'QUERY'",
",",
"terms",
":",
"newsTypeTerms",
",",
"url",
":",
"newsURL",
"}",
";",
"}",
"return",
"parseGoogleNewsRSSParamsErrorHelper",
"(",
"'Unknown parameter error occured.'",
")",
";",
"}"
] | parse the initial paremeters specfied by the original calling params returns well defined types for type, terms, and the calling RSS URL | [
"parse",
"the",
"initial",
"paremeters",
"specfied",
"by",
"the",
"original",
"calling",
"params",
"returns",
"well",
"defined",
"types",
"for",
"type",
"terms",
"and",
"the",
"calling",
"RSS",
"URL"
] | df62b2d1af2d6154e3a075f30ed152282dd9e2f3 | https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L90-L178 | train |
AdamMoses-GitHub/NPMJS-googlenews-rss-scraper | index.js | requestGoogleNewsRSS | function requestGoogleNewsRSS(params, callback) {
// parse the params
var returnObject = parseGoogleNewsRSSParams(params);
returnObject.newsArray = null;
// if no error from the parsing object
if (!returnObject.error) {
// make a request to the RSS using the URL
var request = require("request");
request({uri: returnObject.url},
function(error, response, body) {
// if no error in the call
if (!error) {
// parse the RSS data
var parsedData = parseGoogleNewsRSSData(body);
// if parsing runs okay, add data to the return object and return it
if (parsedData.error == false) {
returnObject.error = false;
returnObject.errorMessage = null;
returnObject.newsArray = parsedData.data;
callback(returnObject);
}
// otherwise parsing failed, indicate such
else {
returnObject.error = true;
returnObject.errorMessage = 'Error with parsing data return from Google News.';
callback(returnObject);
}
}
// otherwise indicate bad request
else {
returnObject.error = true;
returnObject.errorMessage = 'Error with request for data from Google News.';
callback(returnObject);
}
});
}
// otherwise send back error true object from original params parsing
else {
callback(returnObject);
}
} | javascript | function requestGoogleNewsRSS(params, callback) {
// parse the params
var returnObject = parseGoogleNewsRSSParams(params);
returnObject.newsArray = null;
// if no error from the parsing object
if (!returnObject.error) {
// make a request to the RSS using the URL
var request = require("request");
request({uri: returnObject.url},
function(error, response, body) {
// if no error in the call
if (!error) {
// parse the RSS data
var parsedData = parseGoogleNewsRSSData(body);
// if parsing runs okay, add data to the return object and return it
if (parsedData.error == false) {
returnObject.error = false;
returnObject.errorMessage = null;
returnObject.newsArray = parsedData.data;
callback(returnObject);
}
// otherwise parsing failed, indicate such
else {
returnObject.error = true;
returnObject.errorMessage = 'Error with parsing data return from Google News.';
callback(returnObject);
}
}
// otherwise indicate bad request
else {
returnObject.error = true;
returnObject.errorMessage = 'Error with request for data from Google News.';
callback(returnObject);
}
});
}
// otherwise send back error true object from original params parsing
else {
callback(returnObject);
}
} | [
"function",
"requestGoogleNewsRSS",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"returnObject",
"=",
"parseGoogleNewsRSSParams",
"(",
"params",
")",
";",
"returnObject",
".",
"newsArray",
"=",
"null",
";",
"if",
"(",
"!",
"returnObject",
".",
"error",
")",
"{",
"var",
"request",
"=",
"require",
"(",
"\"request\"",
")",
";",
"request",
"(",
"{",
"uri",
":",
"returnObject",
".",
"url",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"error",
")",
"{",
"var",
"parsedData",
"=",
"parseGoogleNewsRSSData",
"(",
"body",
")",
";",
"if",
"(",
"parsedData",
".",
"error",
"==",
"false",
")",
"{",
"returnObject",
".",
"error",
"=",
"false",
";",
"returnObject",
".",
"errorMessage",
"=",
"null",
";",
"returnObject",
".",
"newsArray",
"=",
"parsedData",
".",
"data",
";",
"callback",
"(",
"returnObject",
")",
";",
"}",
"else",
"{",
"returnObject",
".",
"error",
"=",
"true",
";",
"returnObject",
".",
"errorMessage",
"=",
"'Error with parsing data return from Google News.'",
";",
"callback",
"(",
"returnObject",
")",
";",
"}",
"}",
"else",
"{",
"returnObject",
".",
"error",
"=",
"true",
";",
"returnObject",
".",
"errorMessage",
"=",
"'Error with request for data from Google News.'",
";",
"callback",
"(",
"returnObject",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"returnObject",
")",
";",
"}",
"}"
] | makes a call to get the HTML from the rotten tomatoes front page uses the request package to achieve this | [
"makes",
"a",
"call",
"to",
"get",
"the",
"HTML",
"from",
"the",
"rotten",
"tomatoes",
"front",
"page",
"uses",
"the",
"request",
"package",
"to",
"achieve",
"this"
] | df62b2d1af2d6154e3a075f30ed152282dd9e2f3 | https://github.com/AdamMoses-GitHub/NPMJS-googlenews-rss-scraper/blob/df62b2d1af2d6154e3a075f30ed152282dd9e2f3/index.js#L182-L222 | train |
koopjs/geohub | lib/gist.js | gist | function gist (options, callback) {
if (!options.id) return callback(new Error('missing option: id'))
request({
url: '/gists/' + options.id,
qs: {
access_token: options.token
}
}, function (err, json) {
if (err) return callback(err)
var results = []
async.forEachOf(json.files, function (item, key, callback) {
processGithubFile({
item: item,
key: key,
json: json
}, function (err, geojson) {
if (err) return callback(err)
if (geojson) results.push(geojson)
callback(null)
})
}, function (err) {
if (err) return callback(err)
if (!results.length) return callback(new Error('no geojson found in gist ' + options.id))
callback(null, results)
})
})
} | javascript | function gist (options, callback) {
if (!options.id) return callback(new Error('missing option: id'))
request({
url: '/gists/' + options.id,
qs: {
access_token: options.token
}
}, function (err, json) {
if (err) return callback(err)
var results = []
async.forEachOf(json.files, function (item, key, callback) {
processGithubFile({
item: item,
key: key,
json: json
}, function (err, geojson) {
if (err) return callback(err)
if (geojson) results.push(geojson)
callback(null)
})
}, function (err) {
if (err) return callback(err)
if (!results.length) return callback(new Error('no geojson found in gist ' + options.id))
callback(null, results)
})
})
} | [
"function",
"gist",
"(",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"options",
".",
"id",
")",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'missing option: id'",
")",
")",
"request",
"(",
"{",
"url",
":",
"'/gists/'",
"+",
"options",
".",
"id",
",",
"qs",
":",
"{",
"access_token",
":",
"options",
".",
"token",
"}",
"}",
",",
"function",
"(",
"err",
",",
"json",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"var",
"results",
"=",
"[",
"]",
"async",
".",
"forEachOf",
"(",
"json",
".",
"files",
",",
"function",
"(",
"item",
",",
"key",
",",
"callback",
")",
"{",
"processGithubFile",
"(",
"{",
"item",
":",
"item",
",",
"key",
":",
"key",
",",
"json",
":",
"json",
"}",
",",
"function",
"(",
"err",
",",
"geojson",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"if",
"(",
"geojson",
")",
"results",
".",
"push",
"(",
"geojson",
")",
"callback",
"(",
"null",
")",
"}",
")",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"if",
"(",
"!",
"results",
".",
"length",
")",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'no geojson found in gist '",
"+",
"options",
".",
"id",
")",
")",
"callback",
"(",
"null",
",",
"results",
")",
"}",
")",
"}",
")",
"}"
] | get geojson from a gist
@param {object} options - id, token (optional)
@param {Function} callback - err, data | [
"get",
"geojson",
"from",
"a",
"gist"
] | d58c12daba4b33edc0b70333d440572f9c39e6db | https://github.com/koopjs/geohub/blob/d58c12daba4b33edc0b70333d440572f9c39e6db/lib/gist.js#L10-L39 | train |
koopjs/geohub | lib/gist.js | processGithubFile | function processGithubFile (options, callback) {
var item = options.item
var key = options.key
var json = options.json
function respond (content) {
if (isFeatureCollection(content)) {
content.name = key
content.updated_at = json.updated_at
return content
}
return false
}
if (item.truncated) {
return request({
url: item.raw_url
}, function (err, content) {
if (err) return callback(err)
callback(null, respond(content))
})
}
try {
var content = JSON.parse(item.content)
} catch (e) {
var msg = 'could not parse file contents of ' + key + ': ' + e.message
return callback(new Error(msg))
}
callback(null, respond(content))
} | javascript | function processGithubFile (options, callback) {
var item = options.item
var key = options.key
var json = options.json
function respond (content) {
if (isFeatureCollection(content)) {
content.name = key
content.updated_at = json.updated_at
return content
}
return false
}
if (item.truncated) {
return request({
url: item.raw_url
}, function (err, content) {
if (err) return callback(err)
callback(null, respond(content))
})
}
try {
var content = JSON.parse(item.content)
} catch (e) {
var msg = 'could not parse file contents of ' + key + ': ' + e.message
return callback(new Error(msg))
}
callback(null, respond(content))
} | [
"function",
"processGithubFile",
"(",
"options",
",",
"callback",
")",
"{",
"var",
"item",
"=",
"options",
".",
"item",
"var",
"key",
"=",
"options",
".",
"key",
"var",
"json",
"=",
"options",
".",
"json",
"function",
"respond",
"(",
"content",
")",
"{",
"if",
"(",
"isFeatureCollection",
"(",
"content",
")",
")",
"{",
"content",
".",
"name",
"=",
"key",
"content",
".",
"updated_at",
"=",
"json",
".",
"updated_at",
"return",
"content",
"}",
"return",
"false",
"}",
"if",
"(",
"item",
".",
"truncated",
")",
"{",
"return",
"request",
"(",
"{",
"url",
":",
"item",
".",
"raw_url",
"}",
",",
"function",
"(",
"err",
",",
"content",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"callback",
"(",
"null",
",",
"respond",
"(",
"content",
")",
")",
"}",
")",
"}",
"try",
"{",
"var",
"content",
"=",
"JSON",
".",
"parse",
"(",
"item",
".",
"content",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"msg",
"=",
"'could not parse file contents of '",
"+",
"key",
"+",
"': '",
"+",
"e",
".",
"message",
"return",
"callback",
"(",
"new",
"Error",
"(",
"msg",
")",
")",
"}",
"callback",
"(",
"null",
",",
"respond",
"(",
"content",
")",
")",
"}"
] | find and parse geojson objects in a given github gist api "files" object
@private
@param {object} options - item, key, json
@param {Function} callback - err, geojson | [
"find",
"and",
"parse",
"geojson",
"objects",
"in",
"a",
"given",
"github",
"gist",
"api",
"files",
"object"
] | d58c12daba4b33edc0b70333d440572f9c39e6db | https://github.com/koopjs/geohub/blob/d58c12daba4b33edc0b70333d440572f9c39e6db/lib/gist.js#L48-L80 | train |
karlkfi/ngindox | lib/ngindox.js | parse | function parse(fileString, callback) {
try {
return callback(null, Yaml.safeLoad(fileString));
} catch (err) {
return callback(err);
}
} | javascript | function parse(fileString, callback) {
try {
return callback(null, Yaml.safeLoad(fileString));
} catch (err) {
return callback(err);
}
} | [
"function",
"parse",
"(",
"fileString",
",",
"callback",
")",
"{",
"try",
"{",
"return",
"callback",
"(",
"null",
",",
"Yaml",
".",
"safeLoad",
"(",
"fileString",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"}"
] | Parses a Yaml file string into an Ngindox object | [
"Parses",
"a",
"Yaml",
"file",
"string",
"into",
"an",
"Ngindox",
"object"
] | 2c0e8a682d7bde9e5d73a853f45bf1460f4664e9 | https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L5-L11 | train |
karlkfi/ngindox | lib/ngindox.js | parseFile | function parseFile(filePath, encoding, callback) {
fs.readFile(filePath, encoding, function(err, fileString) {
if (err) {
return callback(err);
}
return parse(fileString, callback);
});
} | javascript | function parseFile(filePath, encoding, callback) {
fs.readFile(filePath, encoding, function(err, fileString) {
if (err) {
return callback(err);
}
return parse(fileString, callback);
});
} | [
"function",
"parseFile",
"(",
"filePath",
",",
"encoding",
",",
"callback",
")",
"{",
"fs",
".",
"readFile",
"(",
"filePath",
",",
"encoding",
",",
"function",
"(",
"err",
",",
"fileString",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"return",
"parse",
"(",
"fileString",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Parses a Yaml file into an Ngindox object | [
"Parses",
"a",
"Yaml",
"file",
"into",
"an",
"Ngindox",
"object"
] | 2c0e8a682d7bde9e5d73a853f45bf1460f4664e9 | https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L14-L21 | train |
karlkfi/ngindox | lib/ngindox.js | write | function write(ngindoxMap, callback) {
try {
return callback(null, Yaml.safeDump(ngindoxMap));
} catch (err) {
return callback(err);
}
} | javascript | function write(ngindoxMap, callback) {
try {
return callback(null, Yaml.safeDump(ngindoxMap));
} catch (err) {
return callback(err);
}
} | [
"function",
"write",
"(",
"ngindoxMap",
",",
"callback",
")",
"{",
"try",
"{",
"return",
"callback",
"(",
"null",
",",
"Yaml",
".",
"safeDump",
"(",
"ngindoxMap",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"}"
] | Writes a Ngindox object to a Yaml file string | [
"Writes",
"a",
"Ngindox",
"object",
"to",
"a",
"Yaml",
"file",
"string"
] | 2c0e8a682d7bde9e5d73a853f45bf1460f4664e9 | https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L24-L30 | train |
karlkfi/ngindox | lib/ngindox.js | writeFile | function writeFile(ngindoxObj, encoding, callback) {
fs.writeFile(filePath, fileString, encoding, function(err) {
if (err) {
return callback(err);
}
return write(ngindoxObj, callback);
});
} | javascript | function writeFile(ngindoxObj, encoding, callback) {
fs.writeFile(filePath, fileString, encoding, function(err) {
if (err) {
return callback(err);
}
return write(ngindoxObj, callback);
});
} | [
"function",
"writeFile",
"(",
"ngindoxObj",
",",
"encoding",
",",
"callback",
")",
"{",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"fileString",
",",
"encoding",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"return",
"write",
"(",
"ngindoxObj",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Writes a Ngindox object to a Yaml file | [
"Writes",
"a",
"Ngindox",
"object",
"to",
"a",
"Yaml",
"file"
] | 2c0e8a682d7bde9e5d73a853f45bf1460f4664e9 | https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/ngindox.js#L33-L40 | train |
nodejitsu/defaultable | defaultable.js | merge_obj | function merge_obj(high, low) {
if(!is_obj(high))
throw new Error('Bad merge high-priority');
if(!is_obj(low))
throw new Error('Bad merge low-priority');
var keys = [];
function add_key(k) {
if(!~ keys.indexOf(k))
keys.push(k);
}
_each(_keys(high), add_key);
_each(_keys(low), add_key);
var result = {};
_each(keys, function (key) {
var high_val = high[key];
var low_val = low[key];
if(is_obj(high_val) && is_obj(low_val))
result[key] = merge_obj(high_val, low_val);
else if (key in high)
result[key] = high[key];
else if (key in low)
result[key] = low[key];
else
throw new Error('Unknown key type: ' + key);
})
return result;
} | javascript | function merge_obj(high, low) {
if(!is_obj(high))
throw new Error('Bad merge high-priority');
if(!is_obj(low))
throw new Error('Bad merge low-priority');
var keys = [];
function add_key(k) {
if(!~ keys.indexOf(k))
keys.push(k);
}
_each(_keys(high), add_key);
_each(_keys(low), add_key);
var result = {};
_each(keys, function (key) {
var high_val = high[key];
var low_val = low[key];
if(is_obj(high_val) && is_obj(low_val))
result[key] = merge_obj(high_val, low_val);
else if (key in high)
result[key] = high[key];
else if (key in low)
result[key] = low[key];
else
throw new Error('Unknown key type: ' + key);
})
return result;
} | [
"function",
"merge_obj",
"(",
"high",
",",
"low",
")",
"{",
"if",
"(",
"!",
"is_obj",
"(",
"high",
")",
")",
"throw",
"new",
"Error",
"(",
"'Bad merge high-priority'",
")",
";",
"if",
"(",
"!",
"is_obj",
"(",
"low",
")",
")",
"throw",
"new",
"Error",
"(",
"'Bad merge low-priority'",
")",
";",
"var",
"keys",
"=",
"[",
"]",
";",
"function",
"add_key",
"(",
"k",
")",
"{",
"if",
"(",
"!",
"~",
"keys",
".",
"indexOf",
"(",
"k",
")",
")",
"keys",
".",
"push",
"(",
"k",
")",
";",
"}",
"_each",
"(",
"_keys",
"(",
"high",
")",
",",
"add_key",
")",
";",
"_each",
"(",
"_keys",
"(",
"low",
")",
",",
"add_key",
")",
";",
"var",
"result",
"=",
"{",
"}",
";",
"_each",
"(",
"keys",
",",
"function",
"(",
"key",
")",
"{",
"var",
"high_val",
"=",
"high",
"[",
"key",
"]",
";",
"var",
"low_val",
"=",
"low",
"[",
"key",
"]",
";",
"if",
"(",
"is_obj",
"(",
"high_val",
")",
"&&",
"is_obj",
"(",
"low_val",
")",
")",
"result",
"[",
"key",
"]",
"=",
"merge_obj",
"(",
"high_val",
",",
"low_val",
")",
";",
"else",
"if",
"(",
"key",
"in",
"high",
")",
"result",
"[",
"key",
"]",
"=",
"high",
"[",
"key",
"]",
";",
"else",
"if",
"(",
"key",
"in",
"low",
")",
"result",
"[",
"key",
"]",
"=",
"low",
"[",
"key",
"]",
";",
"else",
"throw",
"new",
"Error",
"(",
"'Unknown key type: '",
"+",
"key",
")",
";",
"}",
")",
"return",
"result",
";",
"}"
] | Recursively merge higher-priority values into previously-set lower-priority ones. | [
"Recursively",
"merge",
"higher",
"-",
"priority",
"values",
"into",
"previously",
"-",
"set",
"lower",
"-",
"priority",
"ones",
"."
] | aabf6cd1b4382c004689a051ee32461ed923ed54 | https://github.com/nodejitsu/defaultable/blob/aabf6cd1b4382c004689a051ee32461ed923ed54/defaultable.js#L98-L129 | train |
joebandenburg/libaxolotl-javascript | src/Ratchet.js | Ratchet | function Ratchet(crypto) {
const self = this;
const hkdf = new HKDF(crypto);
/**
* Derive the main and sub ratchet states from the shared secrets derived from the handshake.
*
* @method
* @param {number} sessionVersion
* @param {Array.<ArrayBuffer>} agreements - an array of ArrayBuffers containing the shared secrets
* @return {Promise.<Object, Error>} the root and chain keys
*/
this.deriveInitialRootKeyAndChain = co.wrap(function*(sessionVersion, agreements) {
var secrets = [];
if (sessionVersion >= 3) {
secrets.push(discontinuityBytes);
}
secrets = secrets.concat(agreements);
var masterSecret = ArrayBufferUtils.concat(secrets);
var derivedSecret = yield hkdf.deriveSecrets(masterSecret, whisperText,
ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount);
return {
rootKey: derivedSecret.slice(0, ProtocolConstants.rootKeyByteCount),
chain: new Chain(derivedSecret.slice(ProtocolConstants.rootKeyByteCount))
};
});
/**
* Derive the next main and sub ratchet states from the previous state.
* <p>
* This method "clicks" the Diffie-Hellman ratchet forwards.
*
* @method
* @param {ArrayBuffer} rootKey - the current root key
* @param {ArrayBuffer} theirEphemeralPublicKey - the receiving ephemeral/ratchet key
* @param {ArrayBuffer} ourEphemeralPrivateKey - our current ephemeral/ratchet key
* @return {Promise.<Object, Error>} the next root and chain keys
*/
this.deriveNextRootKeyAndChain = co.wrap(function*(rootKey, theirEphemeralPublicKey, ourEphemeralPrivateKey) {
var sharedSecret = yield crypto.calculateAgreement(theirEphemeralPublicKey, ourEphemeralPrivateKey);
var derivedSecretBytes = yield hkdf.deriveSecretsWithSalt(sharedSecret, rootKey, whisperRatchet,
ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount);
return {
rootKey: derivedSecretBytes.slice(0, ProtocolConstants.rootKeyByteCount),
chain: new Chain(derivedSecretBytes.slice(ProtocolConstants.rootKeyByteCount))
};
});
//
/**
* Derive the next sub ratchet state from the previous state.
* <p>
* This method "clicks" the hash iteration ratchet forwards.
*
* @method
* @param {Chain} chain
* @return {Promise.<void, Error>}
*/
this.clickSubRatchet = co.wrap(function*(chain) {
chain.index++;
chain.key = yield deriveNextChainKey(chain.key);
});
/**
* Derive the message keys from the chain key.
*
* @method
* @param {ArrayBuffer} chainKey
* @return {Promise.<object, Error>} an object containing the message keys.
*/
this.deriveMessageKeys = co.wrap(function*(chainKey) {
var messageKey = yield deriveMessageKey(chainKey);
var keyMaterialBytes = yield hkdf.deriveSecrets(messageKey, whisperMessageKeys,
ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount + ProtocolConstants.ivByteCount);
var cipherKeyBytes = keyMaterialBytes.slice(0, ProtocolConstants.cipherKeyByteCount);
var macKeyBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount,
ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount);
var ivBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount);
return {
cipherKey: cipherKeyBytes,
macKey: macKeyBytes,
iv: ivBytes
};
});
var hmacByte = co.wrap(function*(key, byte) {
return yield crypto.hmac(key, ArrayBufferUtils.fromByte(byte));
});
var deriveMessageKey = co.wrap(function*(chainKey) {
return yield hmacByte(chainKey, messageKeySeed);
});
var deriveNextChainKey = co.wrap(function*(chainKey) {
return yield hmacByte(chainKey, chainKeySeed);
});
} | javascript | function Ratchet(crypto) {
const self = this;
const hkdf = new HKDF(crypto);
/**
* Derive the main and sub ratchet states from the shared secrets derived from the handshake.
*
* @method
* @param {number} sessionVersion
* @param {Array.<ArrayBuffer>} agreements - an array of ArrayBuffers containing the shared secrets
* @return {Promise.<Object, Error>} the root and chain keys
*/
this.deriveInitialRootKeyAndChain = co.wrap(function*(sessionVersion, agreements) {
var secrets = [];
if (sessionVersion >= 3) {
secrets.push(discontinuityBytes);
}
secrets = secrets.concat(agreements);
var masterSecret = ArrayBufferUtils.concat(secrets);
var derivedSecret = yield hkdf.deriveSecrets(masterSecret, whisperText,
ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount);
return {
rootKey: derivedSecret.slice(0, ProtocolConstants.rootKeyByteCount),
chain: new Chain(derivedSecret.slice(ProtocolConstants.rootKeyByteCount))
};
});
/**
* Derive the next main and sub ratchet states from the previous state.
* <p>
* This method "clicks" the Diffie-Hellman ratchet forwards.
*
* @method
* @param {ArrayBuffer} rootKey - the current root key
* @param {ArrayBuffer} theirEphemeralPublicKey - the receiving ephemeral/ratchet key
* @param {ArrayBuffer} ourEphemeralPrivateKey - our current ephemeral/ratchet key
* @return {Promise.<Object, Error>} the next root and chain keys
*/
this.deriveNextRootKeyAndChain = co.wrap(function*(rootKey, theirEphemeralPublicKey, ourEphemeralPrivateKey) {
var sharedSecret = yield crypto.calculateAgreement(theirEphemeralPublicKey, ourEphemeralPrivateKey);
var derivedSecretBytes = yield hkdf.deriveSecretsWithSalt(sharedSecret, rootKey, whisperRatchet,
ProtocolConstants.rootKeyByteCount + ProtocolConstants.chainKeyByteCount);
return {
rootKey: derivedSecretBytes.slice(0, ProtocolConstants.rootKeyByteCount),
chain: new Chain(derivedSecretBytes.slice(ProtocolConstants.rootKeyByteCount))
};
});
//
/**
* Derive the next sub ratchet state from the previous state.
* <p>
* This method "clicks" the hash iteration ratchet forwards.
*
* @method
* @param {Chain} chain
* @return {Promise.<void, Error>}
*/
this.clickSubRatchet = co.wrap(function*(chain) {
chain.index++;
chain.key = yield deriveNextChainKey(chain.key);
});
/**
* Derive the message keys from the chain key.
*
* @method
* @param {ArrayBuffer} chainKey
* @return {Promise.<object, Error>} an object containing the message keys.
*/
this.deriveMessageKeys = co.wrap(function*(chainKey) {
var messageKey = yield deriveMessageKey(chainKey);
var keyMaterialBytes = yield hkdf.deriveSecrets(messageKey, whisperMessageKeys,
ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount + ProtocolConstants.ivByteCount);
var cipherKeyBytes = keyMaterialBytes.slice(0, ProtocolConstants.cipherKeyByteCount);
var macKeyBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount,
ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount);
var ivBytes = keyMaterialBytes.slice(ProtocolConstants.cipherKeyByteCount + ProtocolConstants.macKeyByteCount);
return {
cipherKey: cipherKeyBytes,
macKey: macKeyBytes,
iv: ivBytes
};
});
var hmacByte = co.wrap(function*(key, byte) {
return yield crypto.hmac(key, ArrayBufferUtils.fromByte(byte));
});
var deriveMessageKey = co.wrap(function*(chainKey) {
return yield hmacByte(chainKey, messageKeySeed);
});
var deriveNextChainKey = co.wrap(function*(chainKey) {
return yield hmacByte(chainKey, chainKeySeed);
});
} | [
"function",
"Ratchet",
"(",
"crypto",
")",
"{",
"const",
"self",
"=",
"this",
";",
"const",
"hkdf",
"=",
"new",
"HKDF",
"(",
"crypto",
")",
";",
"this",
".",
"deriveInitialRootKeyAndChain",
"=",
"co",
".",
"wrap",
"(",
"function",
"*",
"(",
"sessionVersion",
",",
"agreements",
")",
"{",
"var",
"secrets",
"=",
"[",
"]",
";",
"if",
"(",
"sessionVersion",
">=",
"3",
")",
"{",
"secrets",
".",
"push",
"(",
"discontinuityBytes",
")",
";",
"}",
"secrets",
"=",
"secrets",
".",
"concat",
"(",
"agreements",
")",
";",
"var",
"masterSecret",
"=",
"ArrayBufferUtils",
".",
"concat",
"(",
"secrets",
")",
";",
"var",
"derivedSecret",
"=",
"yield",
"hkdf",
".",
"deriveSecrets",
"(",
"masterSecret",
",",
"whisperText",
",",
"ProtocolConstants",
".",
"rootKeyByteCount",
"+",
"ProtocolConstants",
".",
"chainKeyByteCount",
")",
";",
"return",
"{",
"rootKey",
":",
"derivedSecret",
".",
"slice",
"(",
"0",
",",
"ProtocolConstants",
".",
"rootKeyByteCount",
")",
",",
"chain",
":",
"new",
"Chain",
"(",
"derivedSecret",
".",
"slice",
"(",
"ProtocolConstants",
".",
"rootKeyByteCount",
")",
")",
"}",
";",
"}",
")",
";",
"this",
".",
"deriveNextRootKeyAndChain",
"=",
"co",
".",
"wrap",
"(",
"function",
"*",
"(",
"rootKey",
",",
"theirEphemeralPublicKey",
",",
"ourEphemeralPrivateKey",
")",
"{",
"var",
"sharedSecret",
"=",
"yield",
"crypto",
".",
"calculateAgreement",
"(",
"theirEphemeralPublicKey",
",",
"ourEphemeralPrivateKey",
")",
";",
"var",
"derivedSecretBytes",
"=",
"yield",
"hkdf",
".",
"deriveSecretsWithSalt",
"(",
"sharedSecret",
",",
"rootKey",
",",
"whisperRatchet",
",",
"ProtocolConstants",
".",
"rootKeyByteCount",
"+",
"ProtocolConstants",
".",
"chainKeyByteCount",
")",
";",
"return",
"{",
"rootKey",
":",
"derivedSecretBytes",
".",
"slice",
"(",
"0",
",",
"ProtocolConstants",
".",
"rootKeyByteCount",
")",
",",
"chain",
":",
"new",
"Chain",
"(",
"derivedSecretBytes",
".",
"slice",
"(",
"ProtocolConstants",
".",
"rootKeyByteCount",
")",
")",
"}",
";",
"}",
")",
";",
"this",
".",
"clickSubRatchet",
"=",
"co",
".",
"wrap",
"(",
"function",
"*",
"(",
"chain",
")",
"{",
"chain",
".",
"index",
"++",
";",
"chain",
".",
"key",
"=",
"yield",
"deriveNextChainKey",
"(",
"chain",
".",
"key",
")",
";",
"}",
")",
";",
"this",
".",
"deriveMessageKeys",
"=",
"co",
".",
"wrap",
"(",
"function",
"*",
"(",
"chainKey",
")",
"{",
"var",
"messageKey",
"=",
"yield",
"deriveMessageKey",
"(",
"chainKey",
")",
";",
"var",
"keyMaterialBytes",
"=",
"yield",
"hkdf",
".",
"deriveSecrets",
"(",
"messageKey",
",",
"whisperMessageKeys",
",",
"ProtocolConstants",
".",
"cipherKeyByteCount",
"+",
"ProtocolConstants",
".",
"macKeyByteCount",
"+",
"ProtocolConstants",
".",
"ivByteCount",
")",
";",
"var",
"cipherKeyBytes",
"=",
"keyMaterialBytes",
".",
"slice",
"(",
"0",
",",
"ProtocolConstants",
".",
"cipherKeyByteCount",
")",
";",
"var",
"macKeyBytes",
"=",
"keyMaterialBytes",
".",
"slice",
"(",
"ProtocolConstants",
".",
"cipherKeyByteCount",
",",
"ProtocolConstants",
".",
"cipherKeyByteCount",
"+",
"ProtocolConstants",
".",
"macKeyByteCount",
")",
";",
"var",
"ivBytes",
"=",
"keyMaterialBytes",
".",
"slice",
"(",
"ProtocolConstants",
".",
"cipherKeyByteCount",
"+",
"ProtocolConstants",
".",
"macKeyByteCount",
")",
";",
"return",
"{",
"cipherKey",
":",
"cipherKeyBytes",
",",
"macKey",
":",
"macKeyBytes",
",",
"iv",
":",
"ivBytes",
"}",
";",
"}",
")",
";",
"var",
"hmacByte",
"=",
"co",
".",
"wrap",
"(",
"function",
"*",
"(",
"key",
",",
"byte",
")",
"{",
"return",
"yield",
"crypto",
".",
"hmac",
"(",
"key",
",",
"ArrayBufferUtils",
".",
"fromByte",
"(",
"byte",
")",
")",
";",
"}",
")",
";",
"var",
"deriveMessageKey",
"=",
"co",
".",
"wrap",
"(",
"function",
"*",
"(",
"chainKey",
")",
"{",
"return",
"yield",
"hmacByte",
"(",
"chainKey",
",",
"messageKeySeed",
")",
";",
"}",
")",
";",
"var",
"deriveNextChainKey",
"=",
"co",
".",
"wrap",
"(",
"function",
"*",
"(",
"chainKey",
")",
"{",
"return",
"yield",
"hmacByte",
"(",
"chainKey",
",",
"chainKeySeed",
")",
";",
"}",
")",
";",
"}"
] | A utility class for performing the Axolotl ratcheting.
@param {Crypto} crypto
@constructor | [
"A",
"utility",
"class",
"for",
"performing",
"the",
"Axolotl",
"ratcheting",
"."
] | 046466831f4b2a5c1a225d4db6b8a8bfab9a2adf | https://github.com/joebandenburg/libaxolotl-javascript/blob/046466831f4b2a5c1a225d4db6b8a8bfab9a2adf/src/Ratchet.js#L40-L138 | train |
jonschlinkert/normalize-pkg | index.js | NormalizePkg | function NormalizePkg(options) {
if (!(this instanceof NormalizePkg)) {
return new NormalizePkg(options);
}
this.options = options || {};
this.schema = schema(this.options);
this.data = this.schema.data;
this.schema.on('warning', this.emit.bind(this, 'warning'));
this.schema.on('error', this.emit.bind(this, 'error'));
this.schema.union = function(key, config, arr) {
config[key] = utils.arrayify(config[key]);
config[key] = utils.union([], config[key], utils.arrayify(arr));
};
} | javascript | function NormalizePkg(options) {
if (!(this instanceof NormalizePkg)) {
return new NormalizePkg(options);
}
this.options = options || {};
this.schema = schema(this.options);
this.data = this.schema.data;
this.schema.on('warning', this.emit.bind(this, 'warning'));
this.schema.on('error', this.emit.bind(this, 'error'));
this.schema.union = function(key, config, arr) {
config[key] = utils.arrayify(config[key]);
config[key] = utils.union([], config[key], utils.arrayify(arr));
};
} | [
"function",
"NormalizePkg",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"NormalizePkg",
")",
")",
"{",
"return",
"new",
"NormalizePkg",
"(",
"options",
")",
";",
"}",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"schema",
"=",
"schema",
"(",
"this",
".",
"options",
")",
";",
"this",
".",
"data",
"=",
"this",
".",
"schema",
".",
"data",
";",
"this",
".",
"schema",
".",
"on",
"(",
"'warning'",
",",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'warning'",
")",
")",
";",
"this",
".",
"schema",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'error'",
")",
")",
";",
"this",
".",
"schema",
".",
"union",
"=",
"function",
"(",
"key",
",",
"config",
",",
"arr",
")",
"{",
"config",
"[",
"key",
"]",
"=",
"utils",
".",
"arrayify",
"(",
"config",
"[",
"key",
"]",
")",
";",
"config",
"[",
"key",
"]",
"=",
"utils",
".",
"union",
"(",
"[",
"]",
",",
"config",
"[",
"key",
"]",
",",
"utils",
".",
"arrayify",
"(",
"arr",
")",
")",
";",
"}",
";",
"}"
] | Create an instance of `NormalizePkg` with the given `options`.
```js
var config = new NormalizePkg();
var pkg = config.normalize({
author: {
name: 'Jon Schlinkert',
url: 'https://github.com/jonschlinkert'
}
});
console.log(pkg);
//=> {author: 'Jon Schlinkert (https://github.com/jonschlinkert)'}
```
@param {Object} `options`
@api public | [
"Create",
"an",
"instance",
"of",
"NormalizePkg",
"with",
"the",
"given",
"options",
"."
] | 523c73c5f89b40f0bf5faeab69b2a59bbe9ad7f8 | https://github.com/jonschlinkert/normalize-pkg/blob/523c73c5f89b40f0bf5faeab69b2a59bbe9ad7f8/index.js#L26-L41 | train |
wikimedia/web-stream-util | lib/index.js | readerToStream | function readerToStream(reader) {
return new ReadableStream({
pull(controller) {
return reader.read()
.then(res => {
if (res.done) {
controller.close();
} else {
controller.enqueue(res.value);
}
});
},
cancel(reason) { return reader.cancel(reason); }
});
} | javascript | function readerToStream(reader) {
return new ReadableStream({
pull(controller) {
return reader.read()
.then(res => {
if (res.done) {
controller.close();
} else {
controller.enqueue(res.value);
}
});
},
cancel(reason) { return reader.cancel(reason); }
});
} | [
"function",
"readerToStream",
"(",
"reader",
")",
"{",
"return",
"new",
"ReadableStream",
"(",
"{",
"pull",
"(",
"controller",
")",
"{",
"return",
"reader",
".",
"read",
"(",
")",
".",
"then",
"(",
"res",
"=>",
"{",
"if",
"(",
"res",
".",
"done",
")",
"{",
"controller",
".",
"close",
"(",
")",
";",
"}",
"else",
"{",
"controller",
".",
"enqueue",
"(",
"res",
".",
"value",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"cancel",
"(",
"reason",
")",
"{",
"return",
"reader",
".",
"cancel",
"(",
"reason",
")",
";",
"}",
"}",
")",
";",
"}"
] | Adapt a Reader to an UnderlyingSource, for wrapping into a ReadableStream.
@param {Reader} reader
@return {ReadableStream} | [
"Adapt",
"a",
"Reader",
"to",
"an",
"UnderlyingSource",
"for",
"wrapping",
"into",
"a",
"ReadableStream",
"."
] | fc76740cd6a73dcb044251a233bc3c868d3c9a77 | https://github.com/wikimedia/web-stream-util/blob/fc76740cd6a73dcb044251a233bc3c868d3c9a77/lib/index.js#L131-L145 | train |
DesTincT/bemlint | lib/bemlint.js | validate | function validate (input, source, line, column, bemlintId) {
for (var rule_id in currentRules) {
var messageOptions = lodash.assign({}, {
input: input,
source: source,
bemlintId: bemlintId,
elem: options.elem,
mod: options.mod,
wordPattern: options.wordPattern
}),
message = new Message(cheerio.load(modifiedText), rule_id, messageOptions);
if ( message.text ) {
messages.push({
message: message.text,
line: line,
column: column,
ruleId: rule_id
});
}
}
} | javascript | function validate (input, source, line, column, bemlintId) {
for (var rule_id in currentRules) {
var messageOptions = lodash.assign({}, {
input: input,
source: source,
bemlintId: bemlintId,
elem: options.elem,
mod: options.mod,
wordPattern: options.wordPattern
}),
message = new Message(cheerio.load(modifiedText), rule_id, messageOptions);
if ( message.text ) {
messages.push({
message: message.text,
line: line,
column: column,
ruleId: rule_id
});
}
}
} | [
"function",
"validate",
"(",
"input",
",",
"source",
",",
"line",
",",
"column",
",",
"bemlintId",
")",
"{",
"for",
"(",
"var",
"rule_id",
"in",
"currentRules",
")",
"{",
"var",
"messageOptions",
"=",
"lodash",
".",
"assign",
"(",
"{",
"}",
",",
"{",
"input",
":",
"input",
",",
"source",
":",
"source",
",",
"bemlintId",
":",
"bemlintId",
",",
"elem",
":",
"options",
".",
"elem",
",",
"mod",
":",
"options",
".",
"mod",
",",
"wordPattern",
":",
"options",
".",
"wordPattern",
"}",
")",
",",
"message",
"=",
"new",
"Message",
"(",
"cheerio",
".",
"load",
"(",
"modifiedText",
")",
",",
"rule_id",
",",
"messageOptions",
")",
";",
"if",
"(",
"message",
".",
"text",
")",
"{",
"messages",
".",
"push",
"(",
"{",
"message",
":",
"message",
".",
"text",
",",
"line",
":",
"line",
",",
"column",
":",
"column",
",",
"ruleId",
":",
"rule_id",
"}",
")",
";",
"}",
"}",
"}"
] | Generates messages for given classname in source
@method validate
@param {String} input classname
@param {Array} source Array of classnames from html attribute
@param {Integer} line line number
@param {Integer} column column
@param {String} bemlintId Id for each node matched | [
"Generates",
"messages",
"for",
"given",
"classname",
"in",
"source"
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/bemlint.js#L91-L114 | train |
san650/ceibo | index.js | buildDescriptor | function buildDescriptor(node, blueprintKey, descriptor /*, descriptorBuilder*/) {
if (typeof descriptor.setup === 'function') {
descriptor.setup(node, blueprintKey);
}
if (descriptor.value) {
defineProperty(node, blueprintKey, descriptor.value);
} else {
defineProperty(node, blueprintKey, undefined, function() {
return descriptor.get.call(this, blueprintKey);
});
}
} | javascript | function buildDescriptor(node, blueprintKey, descriptor /*, descriptorBuilder*/) {
if (typeof descriptor.setup === 'function') {
descriptor.setup(node, blueprintKey);
}
if (descriptor.value) {
defineProperty(node, blueprintKey, descriptor.value);
} else {
defineProperty(node, blueprintKey, undefined, function() {
return descriptor.get.call(this, blueprintKey);
});
}
} | [
"function",
"buildDescriptor",
"(",
"node",
",",
"blueprintKey",
",",
"descriptor",
")",
"{",
"if",
"(",
"typeof",
"descriptor",
".",
"setup",
"===",
"'function'",
")",
"{",
"descriptor",
".",
"setup",
"(",
"node",
",",
"blueprintKey",
")",
";",
"}",
"if",
"(",
"descriptor",
".",
"value",
")",
"{",
"defineProperty",
"(",
"node",
",",
"blueprintKey",
",",
"descriptor",
".",
"value",
")",
";",
"}",
"else",
"{",
"defineProperty",
"(",
"node",
",",
"blueprintKey",
",",
"undefined",
",",
"function",
"(",
")",
"{",
"return",
"descriptor",
".",
"get",
".",
"call",
"(",
"this",
",",
"blueprintKey",
")",
";",
"}",
")",
";",
"}",
"}"
] | Default `Descriptor` builder
@param {TreeNode} node - parent node
@param {String} blueprintKey - key to build
@param {Descriptor} descriptor - descriptor to build
@param {Function} defaultBuilder - default function to build this type of node
@return undefined | [
"Default",
"Descriptor",
"builder"
] | a4a9ad944249d0b14d40248f04bc162e5ac024e8 | https://github.com/san650/ceibo/blob/a4a9ad944249d0b14d40248f04bc162e5ac024e8/index.js#L66-L78 | train |
san650/ceibo | index.js | buildObject | function buildObject(node, blueprintKey, blueprint /*, defaultBuilder*/) {
var value = {};
// Create child component
defineProperty(node, blueprintKey, value);
// Set meta to object
setMeta(value, blueprintKey);
return [value, blueprint];
} | javascript | function buildObject(node, blueprintKey, blueprint /*, defaultBuilder*/) {
var value = {};
// Create child component
defineProperty(node, blueprintKey, value);
// Set meta to object
setMeta(value, blueprintKey);
return [value, blueprint];
} | [
"function",
"buildObject",
"(",
"node",
",",
"blueprintKey",
",",
"blueprint",
")",
"{",
"var",
"value",
"=",
"{",
"}",
";",
"defineProperty",
"(",
"node",
",",
"blueprintKey",
",",
"value",
")",
";",
"setMeta",
"(",
"value",
",",
"blueprintKey",
")",
";",
"return",
"[",
"value",
",",
"blueprint",
"]",
";",
"}"
] | Default `Object` builder
@param {TreeNode} node - parent node
@param {String} blueprintKey - key to build
@param {Object} blueprint - blueprint to build
@param {Function} defaultBuilder - default function to build this type of node
@return {Array} [node, blueprint] to build | [
"Default",
"Object",
"builder"
] | a4a9ad944249d0b14d40248f04bc162e5ac024e8 | https://github.com/san650/ceibo/blob/a4a9ad944249d0b14d40248f04bc162e5ac024e8/index.js#L90-L100 | train |
nodef/extra-youtubeuploader | index.js | flags | function flags(o, pre='', z='') {
for(var k in o) {
if(o[k]==null || k==='stdio') continue;
if(Array.isArray(o[k])) z += ` --${pre}${k} "${o[k].join()}"`;
else if(typeof o[k]==='object') z = flags(o[k], `${pre}${k}_`, z);
else if(typeof o[k]==='boolean') z += o[k]? ` --${pre}${k}`:'';
else z += ` --${pre}${k} ${JSON.stringify(o[k])}`;
}
return z;
} | javascript | function flags(o, pre='', z='') {
for(var k in o) {
if(o[k]==null || k==='stdio') continue;
if(Array.isArray(o[k])) z += ` --${pre}${k} "${o[k].join()}"`;
else if(typeof o[k]==='object') z = flags(o[k], `${pre}${k}_`, z);
else if(typeof o[k]==='boolean') z += o[k]? ` --${pre}${k}`:'';
else z += ` --${pre}${k} ${JSON.stringify(o[k])}`;
}
return z;
} | [
"function",
"flags",
"(",
"o",
",",
"pre",
"=",
"''",
",",
"z",
"=",
"''",
")",
"{",
"for",
"(",
"var",
"k",
"in",
"o",
")",
"{",
"if",
"(",
"o",
"[",
"k",
"]",
"==",
"null",
"||",
"k",
"===",
"'stdio'",
")",
"continue",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"o",
"[",
"k",
"]",
")",
")",
"z",
"+=",
"`",
"${",
"pre",
"}",
"${",
"k",
"}",
"${",
"o",
"[",
"k",
"]",
".",
"join",
"(",
")",
"}",
"`",
";",
"else",
"if",
"(",
"typeof",
"o",
"[",
"k",
"]",
"===",
"'object'",
")",
"z",
"=",
"flags",
"(",
"o",
"[",
"k",
"]",
",",
"`",
"${",
"pre",
"}",
"${",
"k",
"}",
"`",
",",
"z",
")",
";",
"else",
"if",
"(",
"typeof",
"o",
"[",
"k",
"]",
"===",
"'boolean'",
")",
"z",
"+=",
"o",
"[",
"k",
"]",
"?",
"`",
"${",
"pre",
"}",
"${",
"k",
"}",
"`",
":",
"''",
";",
"else",
"z",
"+=",
"`",
"${",
"pre",
"}",
"${",
"k",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"o",
"[",
"k",
"]",
")",
"}",
"`",
";",
"}",
"return",
"z",
";",
"}"
] | Generate flags for console. | [
"Generate",
"flags",
"for",
"console",
"."
] | c3e3967b99844e472ba850d785b3f572d15b6230 | https://github.com/nodef/extra-youtubeuploader/blob/c3e3967b99844e472ba850d785b3f572d15b6230/index.js#L9-L18 | train |
nodef/extra-youtubeuploader | index.js | youtubeuploader | function youtubeuploader(o) {
var o = o||{}, cmd = 'youtubeuploader'+flags(o);
var stdio = o.log || o.stdio==null? STDIO:o.stdio;
if(stdio===STDIO) return Promise.resolve({stdout: cp.execSync(cmd, {stdio})});
return new Promise((fres, frej) => cp.exec(cmd, {stdio}, (err, stdout, stderr) => {
return err? frej(err):fres({stdout, stderr});
}));
} | javascript | function youtubeuploader(o) {
var o = o||{}, cmd = 'youtubeuploader'+flags(o);
var stdio = o.log || o.stdio==null? STDIO:o.stdio;
if(stdio===STDIO) return Promise.resolve({stdout: cp.execSync(cmd, {stdio})});
return new Promise((fres, frej) => cp.exec(cmd, {stdio}, (err, stdout, stderr) => {
return err? frej(err):fres({stdout, stderr});
}));
} | [
"function",
"youtubeuploader",
"(",
"o",
")",
"{",
"var",
"o",
"=",
"o",
"||",
"{",
"}",
",",
"cmd",
"=",
"'youtubeuploader'",
"+",
"flags",
"(",
"o",
")",
";",
"var",
"stdio",
"=",
"o",
".",
"log",
"||",
"o",
".",
"stdio",
"==",
"null",
"?",
"STDIO",
":",
"o",
".",
"stdio",
";",
"if",
"(",
"stdio",
"===",
"STDIO",
")",
"return",
"Promise",
".",
"resolve",
"(",
"{",
"stdout",
":",
"cp",
".",
"execSync",
"(",
"cmd",
",",
"{",
"stdio",
"}",
")",
"}",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"fres",
",",
"frej",
")",
"=>",
"cp",
".",
"exec",
"(",
"cmd",
",",
"{",
"stdio",
"}",
",",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"=>",
"{",
"return",
"err",
"?",
"frej",
"(",
"err",
")",
":",
"fres",
"(",
"{",
"stdout",
",",
"stderr",
"}",
")",
";",
"}",
")",
")",
";",
"}"
] | Invoke "youtubeuploader".
@param {object} o upload options. | [
"Invoke",
"youtubeuploader",
"."
] | c3e3967b99844e472ba850d785b3f572d15b6230 | https://github.com/nodef/extra-youtubeuploader/blob/c3e3967b99844e472ba850d785b3f572d15b6230/index.js#L24-L31 | train |
nodef/extra-youtubeuploader | index.js | lines | async function lines(o) {
var {stdout} = await youtubeuploader(Object.assign({}, o, {stdio: []}));
var out = stdout.toString().trim();
return out? out.split('\n'):[];
} | javascript | async function lines(o) {
var {stdout} = await youtubeuploader(Object.assign({}, o, {stdio: []}));
var out = stdout.toString().trim();
return out? out.split('\n'):[];
} | [
"async",
"function",
"lines",
"(",
"o",
")",
"{",
"var",
"{",
"stdout",
"}",
"=",
"await",
"youtubeuploader",
"(",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"o",
",",
"{",
"stdio",
":",
"[",
"]",
"}",
")",
")",
";",
"var",
"out",
"=",
"stdout",
".",
"toString",
"(",
")",
".",
"trim",
"(",
")",
";",
"return",
"out",
"?",
"out",
".",
"split",
"(",
"'\\n'",
")",
":",
"\\n",
";",
"}"
] | Invoke "youtubeuploader", and get stdout lines.
@param {object} o upload options. | [
"Invoke",
"youtubeuploader",
"and",
"get",
"stdout",
"lines",
"."
] | c3e3967b99844e472ba850d785b3f572d15b6230 | https://github.com/nodef/extra-youtubeuploader/blob/c3e3967b99844e472ba850d785b3f572d15b6230/index.js#L37-L41 | train |
DesTincT/bemlint | lib/util/glob-util.js | listFilesToProcess | function listFilesToProcess(globPatterns, options) {
var ignoredPaths,
ignoredPathsList,
files = [],
added = {},
globOptions,
rulesKey = "_rules";
/**
* Executes the linter on a file defined by the `filename`. Skips
* unsupported file extensions and any files that are already linted.
* @param {string} filename The file to be processed
* @returns {void}
*/
function addFile(filename) {
if (ignoredPaths.contains(filename)) {
return;
}
filename = fs.realpathSync(filename);
if (added[filename]) {
return;
}
files.push(filename);
added[filename] = true;
}
options = options || { ignore: true, dotfiles: true };
ignoredPaths = new IgnoredPaths(options);
ignoredPathsList = ignoredPaths.ig.custom[rulesKey].map(function(rule) {
return rule.pattern;
});
globOptions = {
nodir: true,
ignore: ignoredPathsList
};
debug("Creating list of files to process.");
globPatterns.forEach(function(pattern) {
if (shell.test("-f", pattern)) {
addFile(pattern);
} else {
glob.sync(pattern, globOptions).forEach(addFile);
}
});
return files;
} | javascript | function listFilesToProcess(globPatterns, options) {
var ignoredPaths,
ignoredPathsList,
files = [],
added = {},
globOptions,
rulesKey = "_rules";
/**
* Executes the linter on a file defined by the `filename`. Skips
* unsupported file extensions and any files that are already linted.
* @param {string} filename The file to be processed
* @returns {void}
*/
function addFile(filename) {
if (ignoredPaths.contains(filename)) {
return;
}
filename = fs.realpathSync(filename);
if (added[filename]) {
return;
}
files.push(filename);
added[filename] = true;
}
options = options || { ignore: true, dotfiles: true };
ignoredPaths = new IgnoredPaths(options);
ignoredPathsList = ignoredPaths.ig.custom[rulesKey].map(function(rule) {
return rule.pattern;
});
globOptions = {
nodir: true,
ignore: ignoredPathsList
};
debug("Creating list of files to process.");
globPatterns.forEach(function(pattern) {
if (shell.test("-f", pattern)) {
addFile(pattern);
} else {
glob.sync(pattern, globOptions).forEach(addFile);
}
});
return files;
} | [
"function",
"listFilesToProcess",
"(",
"globPatterns",
",",
"options",
")",
"{",
"var",
"ignoredPaths",
",",
"ignoredPathsList",
",",
"files",
"=",
"[",
"]",
",",
"added",
"=",
"{",
"}",
",",
"globOptions",
",",
"rulesKey",
"=",
"\"_rules\"",
";",
"function",
"addFile",
"(",
"filename",
")",
"{",
"if",
"(",
"ignoredPaths",
".",
"contains",
"(",
"filename",
")",
")",
"{",
"return",
";",
"}",
"filename",
"=",
"fs",
".",
"realpathSync",
"(",
"filename",
")",
";",
"if",
"(",
"added",
"[",
"filename",
"]",
")",
"{",
"return",
";",
"}",
"files",
".",
"push",
"(",
"filename",
")",
";",
"added",
"[",
"filename",
"]",
"=",
"true",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"ignore",
":",
"true",
",",
"dotfiles",
":",
"true",
"}",
";",
"ignoredPaths",
"=",
"new",
"IgnoredPaths",
"(",
"options",
")",
";",
"ignoredPathsList",
"=",
"ignoredPaths",
".",
"ig",
".",
"custom",
"[",
"rulesKey",
"]",
".",
"map",
"(",
"function",
"(",
"rule",
")",
"{",
"return",
"rule",
".",
"pattern",
";",
"}",
")",
";",
"globOptions",
"=",
"{",
"nodir",
":",
"true",
",",
"ignore",
":",
"ignoredPathsList",
"}",
";",
"debug",
"(",
"\"Creating list of files to process.\"",
")",
";",
"globPatterns",
".",
"forEach",
"(",
"function",
"(",
"pattern",
")",
"{",
"if",
"(",
"shell",
".",
"test",
"(",
"\"-f\"",
",",
"pattern",
")",
")",
"{",
"addFile",
"(",
"pattern",
")",
";",
"}",
"else",
"{",
"glob",
".",
"sync",
"(",
"pattern",
",",
"globOptions",
")",
".",
"forEach",
"(",
"addFile",
")",
";",
"}",
"}",
")",
";",
"return",
"files",
";",
"}"
] | Build a list of absolute filesnames on which bemlint will act.
Ignored files are excluded from the results, as are duplicates.
@param {string[]} globPatterns Glob patterns.
@param {Object} [options] An options object.
@param {boolean} [options.ignore] False disables use of .bemlintignore.
@param {string} [options.ignorePath] The ignore file to use instead of .bemlintignore.
@param {string} [options.ignorePattern] A pattern of files to ignore.
@returns {string[]} Resolved absolute filenames. | [
"Build",
"a",
"list",
"of",
"absolute",
"filesnames",
"on",
"which",
"bemlint",
"will",
"act",
".",
"Ignored",
"files",
"are",
"excluded",
"from",
"the",
"results",
"as",
"are",
"duplicates",
"."
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/util/glob-util.js#L100-L146 | train |
feathers-plus/common | lib/hash/index.js | hashObject | function hashObject (obj) {
if (!isObject(obj)) return null;
return shortHash(JSON.stringify(sortKeys(obj, { deep: true })));
} | javascript | function hashObject (obj) {
if (!isObject(obj)) return null;
return shortHash(JSON.stringify(sortKeys(obj, { deep: true })));
} | [
"function",
"hashObject",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"isObject",
"(",
"obj",
")",
")",
"return",
"null",
";",
"return",
"shortHash",
"(",
"JSON",
".",
"stringify",
"(",
"sortKeys",
"(",
"obj",
",",
"{",
"deep",
":",
"true",
"}",
")",
")",
")",
";",
"}"
] | Predictable hash for equivalent objects. | [
"Predictable",
"hash",
"for",
"equivalent",
"objects",
"."
] | 4d244d4ee2426e11095fe30542fb0e83721eeb03 | https://github.com/feathers-plus/common/blob/4d244d4ee2426e11095fe30542fb0e83721eeb03/lib/hash/index.js#L12-L15 | train |
hilkenan/formgen-react | dist/validators/Validators.js | length | function length(desiredLength, formatError) {
'use strict';
return function (value) {
value = ((value !== null && value !== undefined) ? value : '');
if (value.length !== desiredLength) {
return formatError(value.length);
}
return '';
};
} | javascript | function length(desiredLength, formatError) {
'use strict';
return function (value) {
value = ((value !== null && value !== undefined) ? value : '');
if (value.length !== desiredLength) {
return formatError(value.length);
}
return '';
};
} | [
"function",
"length",
"(",
"desiredLength",
",",
"formatError",
")",
"{",
"'use strict'",
";",
"return",
"function",
"(",
"value",
")",
"{",
"value",
"=",
"(",
"(",
"value",
"!==",
"null",
"&&",
"value",
"!==",
"undefined",
")",
"?",
"value",
":",
"''",
")",
";",
"if",
"(",
"value",
".",
"length",
"!==",
"desiredLength",
")",
"{",
"return",
"formatError",
"(",
"value",
".",
"length",
")",
";",
"}",
"return",
"''",
";",
"}",
";",
"}"
] | Returns a validator that checks the length of a string and ensures its equal to a value. If input null return -1
@param desiredLength The length of the string
@param formatError a callback which takes the length and formats an appropriate error message for validation failed | [
"Returns",
"a",
"validator",
"that",
"checks",
"the",
"length",
"of",
"a",
"string",
"and",
"ensures",
"its",
"equal",
"to",
"a",
"value",
".",
"If",
"input",
"null",
"return",
"-",
"1"
] | e5c8938312b7e6f8cc32ec442af8787c542e60b6 | https://github.com/hilkenan/formgen-react/blob/e5c8938312b7e6f8cc32ec442af8787c542e60b6/dist/validators/Validators.js#L34-L43 | train |
hilkenan/formgen-react | dist/validators/Validators.js | minValue | function minValue(bound, formatError) {
'use strict';
return function (value) {
if (value || !isNaN(parseFloat(value))) {
var intValue = Number(value);
if (!isNaN(intValue) && intValue < bound) {
return formatError(intValue);
}
}
return '';
};
} | javascript | function minValue(bound, formatError) {
'use strict';
return function (value) {
if (value || !isNaN(parseFloat(value))) {
var intValue = Number(value);
if (!isNaN(intValue) && intValue < bound) {
return formatError(intValue);
}
}
return '';
};
} | [
"function",
"minValue",
"(",
"bound",
",",
"formatError",
")",
"{",
"'use strict'",
";",
"return",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"||",
"!",
"isNaN",
"(",
"parseFloat",
"(",
"value",
")",
")",
")",
"{",
"var",
"intValue",
"=",
"Number",
"(",
"value",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"intValue",
")",
"&&",
"intValue",
"<",
"bound",
")",
"{",
"return",
"formatError",
"(",
"intValue",
")",
";",
"}",
"}",
"return",
"''",
";",
"}",
";",
"}"
] | Returns a validator that checks if a number is greater than the provided bound
@param bound The bound
@param formatError a callback which takes the length and formats an appropriate error message for validation failed | [
"Returns",
"a",
"validator",
"that",
"checks",
"if",
"a",
"number",
"is",
"greater",
"than",
"the",
"provided",
"bound"
] | e5c8938312b7e6f8cc32ec442af8787c542e60b6 | https://github.com/hilkenan/formgen-react/blob/e5c8938312b7e6f8cc32ec442af8787c542e60b6/dist/validators/Validators.js#L100-L111 | train |
arunoda/laika | lib/app_pool.js | detectConfig | function detectConfig(appDir) {
var config = {};
var meteoriteUsed = fs.existsSync(path.resolve(appDir, './smart.json'));
if(meteoriteUsed) {
config.meteorite = true;
config.nodeBinary = helpers.getMeteoriteNode(appDir);
} else {
config.meteorite = false;
config.nodeBinary = helpers.getMeteorNode();
}
return config;
} | javascript | function detectConfig(appDir) {
var config = {};
var meteoriteUsed = fs.existsSync(path.resolve(appDir, './smart.json'));
if(meteoriteUsed) {
config.meteorite = true;
config.nodeBinary = helpers.getMeteoriteNode(appDir);
} else {
config.meteorite = false;
config.nodeBinary = helpers.getMeteorNode();
}
return config;
} | [
"function",
"detectConfig",
"(",
"appDir",
")",
"{",
"var",
"config",
"=",
"{",
"}",
";",
"var",
"meteoriteUsed",
"=",
"fs",
".",
"existsSync",
"(",
"path",
".",
"resolve",
"(",
"appDir",
",",
"'./smart.json'",
")",
")",
";",
"if",
"(",
"meteoriteUsed",
")",
"{",
"config",
".",
"meteorite",
"=",
"true",
";",
"config",
".",
"nodeBinary",
"=",
"helpers",
".",
"getMeteoriteNode",
"(",
"appDir",
")",
";",
"}",
"else",
"{",
"config",
".",
"meteorite",
"=",
"false",
";",
"config",
".",
"nodeBinary",
"=",
"helpers",
".",
"getMeteorNode",
"(",
")",
";",
"}",
"return",
"config",
";",
"}"
] | detect whether uses, meteor or meteorite and get the corret node version accordingly | [
"detect",
"whether",
"uses",
"meteor",
"or",
"meteorite",
"and",
"get",
"the",
"corret",
"node",
"version",
"accordingly"
] | 63199f900756a695aa5ab80341d0185a200c9403 | https://github.com/arunoda/laika/blob/63199f900756a695aa5ab80341d0185a200c9403/lib/app_pool.js#L78-L90 | train |
rewgt/shadow-widget | lib/template.js | assignOneDual | function assignOneDual(bConns, item) {
var fn = exprDict[item];
if (!fn) return;
try {
var bConn = gui.connectTo[item];
if (bConn) {
// this action is listened
var oldValue = comp.state[item];
fn(comp); // try update with expression
var newValue = comp.state[item];
if (newValue !== oldValue) // succ update expression and get a new value
bConns.push([bConn, newValue, oldValue, item]); // wait to fire listen-function
} else fn(comp);
} catch (e) {
console.log(e);
}
} | javascript | function assignOneDual(bConns, item) {
var fn = exprDict[item];
if (!fn) return;
try {
var bConn = gui.connectTo[item];
if (bConn) {
// this action is listened
var oldValue = comp.state[item];
fn(comp); // try update with expression
var newValue = comp.state[item];
if (newValue !== oldValue) // succ update expression and get a new value
bConns.push([bConn, newValue, oldValue, item]); // wait to fire listen-function
} else fn(comp);
} catch (e) {
console.log(e);
}
} | [
"function",
"assignOneDual",
"(",
"bConns",
",",
"item",
")",
"{",
"var",
"fn",
"=",
"exprDict",
"[",
"item",
"]",
";",
"if",
"(",
"!",
"fn",
")",
"return",
";",
"try",
"{",
"var",
"bConn",
"=",
"gui",
".",
"connectTo",
"[",
"item",
"]",
";",
"if",
"(",
"bConn",
")",
"{",
"var",
"oldValue",
"=",
"comp",
".",
"state",
"[",
"item",
"]",
";",
"fn",
"(",
"comp",
")",
";",
"var",
"newValue",
"=",
"comp",
".",
"state",
"[",
"item",
"]",
";",
"if",
"(",
"newValue",
"!==",
"oldValue",
")",
"bConns",
".",
"push",
"(",
"[",
"bConn",
",",
"newValue",
",",
"oldValue",
",",
"item",
"]",
")",
";",
"}",
"else",
"fn",
"(",
"comp",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"e",
")",
";",
"}",
"}"
] | if return true means comp.state.xxx is changed | [
"if",
"return",
"true",
"means",
"comp",
".",
"state",
".",
"xxx",
"is",
"changed"
] | 5baa1f563d647b6d1ecb6c108bc5bcef150ea683 | https://github.com/rewgt/shadow-widget/blob/5baa1f563d647b6d1ecb6c108bc5bcef150ea683/lib/template.js#L3713-L3729 | train |
sproutsocial/es6-import-validate | lib/ES6ModuleFile.js | function (filePath) {
var name = path.relative(this.opts.cwd, filePath);
name = path.join(path.dirname(name), path.basename(name, this.opts.extension));
return name;
} | javascript | function (filePath) {
var name = path.relative(this.opts.cwd, filePath);
name = path.join(path.dirname(name), path.basename(name, this.opts.extension));
return name;
} | [
"function",
"(",
"filePath",
")",
"{",
"var",
"name",
"=",
"path",
".",
"relative",
"(",
"this",
".",
"opts",
".",
"cwd",
",",
"filePath",
")",
";",
"name",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"name",
")",
",",
"path",
".",
"basename",
"(",
"name",
",",
"this",
".",
"opts",
".",
"extension",
")",
")",
";",
"return",
"name",
";",
"}"
] | Only broken out to stub for windows backslash in tests | [
"Only",
"broken",
"out",
"to",
"stub",
"for",
"windows",
"backslash",
"in",
"tests"
] | e93776812c45aaa2a7c6145474c04ed3359ac4b2 | https://github.com/sproutsocial/es6-import-validate/blob/e93776812c45aaa2a7c6145474c04ed3359ac4b2/lib/ES6ModuleFile.js#L122-L128 | train |
|
pllee/luc | lib/array.js | fromIndex | function fromIndex(a, index) {
var arr = is.isArguments(a) ? arraySlice.call(a) : a;
return arraySlice.call(arr, index, arr.length);
} | javascript | function fromIndex(a, index) {
var arr = is.isArguments(a) ? arraySlice.call(a) : a;
return arraySlice.call(arr, index, arr.length);
} | [
"function",
"fromIndex",
"(",
"a",
",",
"index",
")",
"{",
"var",
"arr",
"=",
"is",
".",
"isArguments",
"(",
"a",
")",
"?",
"arraySlice",
".",
"call",
"(",
"a",
")",
":",
"a",
";",
"return",
"arraySlice",
".",
"call",
"(",
"arr",
",",
"index",
",",
"arr",
".",
"length",
")",
";",
"}"
] | Return the items in between the passed in index
and the end of the array.
Luc.Array.fromIndex([1,2,3,4,5], 1)
>[2, 3, 4, 5]
@param {Array/arguments} arr
@param {Number} index
@return {Array} the new array. | [
"Return",
"the",
"items",
"in",
"between",
"the",
"passed",
"in",
"index",
"and",
"the",
"end",
"of",
"the",
"array",
"."
] | eb6db9d3dfa75101c59eb35d8c969bc384c82a2a | https://github.com/pllee/luc/blob/eb6db9d3dfa75101c59eb35d8c969bc384c82a2a/lib/array.js#L164-L167 | train |
pllee/luc | lib/array.js | each | function each(item, fn, thisArg) {
var arr = toArray(item);
return arr.forEach.call(arr, fn, thisArg);
} | javascript | function each(item, fn, thisArg) {
var arr = toArray(item);
return arr.forEach.call(arr, fn, thisArg);
} | [
"function",
"each",
"(",
"item",
",",
"fn",
",",
"thisArg",
")",
"{",
"var",
"arr",
"=",
"toArray",
"(",
"item",
")",
";",
"return",
"arr",
".",
"forEach",
".",
"call",
"(",
"arr",
",",
"fn",
",",
"thisArg",
")",
";",
"}"
] | Runs an Array.forEach after calling Luc.Array.toArray on the item.
It is very useful for setting up flexible api's that can handle none one or many.
Luc.Array.each(this.items, function(item) {
this._addItem(item);
});
vs.
if(Array.isArray(this.items)){
this.items.forEach(function(item) {
this._addItem(item);
})
}
else if(this.items !== undefined) {
this._addItem(this.items);
}
@param {Object} item
@param {Function} callback
@param {Object} thisArg | [
"Runs",
"an",
"Array",
".",
"forEach",
"after",
"calling",
"Luc",
".",
"Array",
".",
"toArray",
"on",
"the",
"item",
".",
"It",
"is",
"very",
"useful",
"for",
"setting",
"up",
"flexible",
"api",
"s",
"that",
"can",
"handle",
"none",
"one",
"or",
"many",
"."
] | eb6db9d3dfa75101c59eb35d8c969bc384c82a2a | https://github.com/pllee/luc/blob/eb6db9d3dfa75101c59eb35d8c969bc384c82a2a/lib/array.js#L193-L196 | train |
koopjs/geohub | lib/request.js | geohubRequest | function geohubRequest (options, callback) {
if (options.url.indexOf('https://') !== 0) {
options.url = apiBase + options.url
}
options.headers = {
'User-Agent': 'geohub/' + pkg.version
}
// delete null/undefined access token to avoid 401 from github
if (options.qs && !options.qs.access_token) {
delete options.qs.access_token
}
debug(options)
request(options, function (err, res, body) {
if (err) return callback(err)
try {
var json = JSON.parse(body)
} catch (e) {
var msg = 'Failed to parse JSON from ' + options.url
msg += ' (status code: ' + res.statusCode + ', body: ' + body + ')'
return callback(new Error(msg))
}
if (json.message) {
return callback(new Error(res.statusCode + ' (github): ' + json.message))
}
callback(null, json)
})
} | javascript | function geohubRequest (options, callback) {
if (options.url.indexOf('https://') !== 0) {
options.url = apiBase + options.url
}
options.headers = {
'User-Agent': 'geohub/' + pkg.version
}
// delete null/undefined access token to avoid 401 from github
if (options.qs && !options.qs.access_token) {
delete options.qs.access_token
}
debug(options)
request(options, function (err, res, body) {
if (err) return callback(err)
try {
var json = JSON.parse(body)
} catch (e) {
var msg = 'Failed to parse JSON from ' + options.url
msg += ' (status code: ' + res.statusCode + ', body: ' + body + ')'
return callback(new Error(msg))
}
if (json.message) {
return callback(new Error(res.statusCode + ' (github): ' + json.message))
}
callback(null, json)
})
} | [
"function",
"geohubRequest",
"(",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"options",
".",
"url",
".",
"indexOf",
"(",
"'https://'",
")",
"!==",
"0",
")",
"{",
"options",
".",
"url",
"=",
"apiBase",
"+",
"options",
".",
"url",
"}",
"options",
".",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'geohub/'",
"+",
"pkg",
".",
"version",
"}",
"if",
"(",
"options",
".",
"qs",
"&&",
"!",
"options",
".",
"qs",
".",
"access_token",
")",
"{",
"delete",
"options",
".",
"qs",
".",
"access_token",
"}",
"debug",
"(",
"options",
")",
"request",
"(",
"options",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"try",
"{",
"var",
"json",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"msg",
"=",
"'Failed to parse JSON from '",
"+",
"options",
".",
"url",
"msg",
"+=",
"' (status code: '",
"+",
"res",
".",
"statusCode",
"+",
"', body: '",
"+",
"body",
"+",
"')'",
"return",
"callback",
"(",
"new",
"Error",
"(",
"msg",
")",
")",
"}",
"if",
"(",
"json",
".",
"message",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"res",
".",
"statusCode",
"+",
"' (github): '",
"+",
"json",
".",
"message",
")",
")",
"}",
"callback",
"(",
"null",
",",
"json",
")",
"}",
")",
"}"
] | handles requests by geohub to the github API
@param {object} options - url (string), qs (object)
@param {Function} callback | [
"handles",
"requests",
"by",
"geohub",
"to",
"the",
"github",
"API"
] | d58c12daba4b33edc0b70333d440572f9c39e6db | https://github.com/koopjs/geohub/blob/d58c12daba4b33edc0b70333d440572f9c39e6db/lib/request.js#L12-L45 | train |
vesln/b | lib/benchmark.js | Benchmark | function Benchmark(name, fn) {
this._name = name;
this._fn = fn;
this._async = fn.length > 1;
} | javascript | function Benchmark(name, fn) {
this._name = name;
this._fn = fn;
this._async = fn.length > 1;
} | [
"function",
"Benchmark",
"(",
"name",
",",
"fn",
")",
"{",
"this",
".",
"_name",
"=",
"name",
";",
"this",
".",
"_fn",
"=",
"fn",
";",
"this",
".",
"_async",
"=",
"fn",
".",
"length",
">",
"1",
";",
"}"
] | Benchmark constructor.
@param {String} name
@param {Function} fn
@constructor | [
"Benchmark",
"constructor",
"."
] | 9bddf3032885ae51095946a2f153e5b03cbec332 | https://github.com/vesln/b/blob/9bddf3032885ae51095946a2f153e5b03cbec332/lib/benchmark.js#L12-L16 | train |
DesTincT/bemlint | lib/cli-engine.js | processText | function processText(text, filename, options) {
var filePath,
messages,
stats;
if (filename) {
filePath = path.resolve(filename);
}
filename = filename || "<text>";
debug("Linting " + filename);
messages = bemlint.verify(text, lodash.assign(Object.create(null), {
filename: filename
}, options));
stats = calculateStatsPerFile(messages);
var result = {
filePath: filename,
messages: messages,
errorCount: stats.errorCount,
warningCount: stats.warningCount
};
return result;
} | javascript | function processText(text, filename, options) {
var filePath,
messages,
stats;
if (filename) {
filePath = path.resolve(filename);
}
filename = filename || "<text>";
debug("Linting " + filename);
messages = bemlint.verify(text, lodash.assign(Object.create(null), {
filename: filename
}, options));
stats = calculateStatsPerFile(messages);
var result = {
filePath: filename,
messages: messages,
errorCount: stats.errorCount,
warningCount: stats.warningCount
};
return result;
} | [
"function",
"processText",
"(",
"text",
",",
"filename",
",",
"options",
")",
"{",
"var",
"filePath",
",",
"messages",
",",
"stats",
";",
"if",
"(",
"filename",
")",
"{",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"filename",
")",
";",
"}",
"filename",
"=",
"filename",
"||",
"\"<text>\"",
";",
"debug",
"(",
"\"Linting \"",
"+",
"filename",
")",
";",
"messages",
"=",
"bemlint",
".",
"verify",
"(",
"text",
",",
"lodash",
".",
"assign",
"(",
"Object",
".",
"create",
"(",
"null",
")",
",",
"{",
"filename",
":",
"filename",
"}",
",",
"options",
")",
")",
";",
"stats",
"=",
"calculateStatsPerFile",
"(",
"messages",
")",
";",
"var",
"result",
"=",
"{",
"filePath",
":",
"filename",
",",
"messages",
":",
"messages",
",",
"errorCount",
":",
"stats",
".",
"errorCount",
",",
"warningCount",
":",
"stats",
".",
"warningCount",
"}",
";",
"return",
"result",
";",
"}"
] | Processes an source code using bemlint.
@param {string} text The source code to check.
@param {string} filename An optional string representing the texts filename.
@returns {Result} The results for linting on this text.
@private | [
"Processes",
"an",
"source",
"code",
"using",
"bemlint",
"."
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/cli-engine.js#L120-L148 | train |
DesTincT/bemlint | lib/cli-engine.js | processFile | function processFile(filename, options) {
var text = fs.readFileSync(path.resolve(filename), "utf8"),
result = processText(text, filename, options);
return result;
} | javascript | function processFile(filename, options) {
var text = fs.readFileSync(path.resolve(filename), "utf8"),
result = processText(text, filename, options);
return result;
} | [
"function",
"processFile",
"(",
"filename",
",",
"options",
")",
"{",
"var",
"text",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"resolve",
"(",
"filename",
")",
",",
"\"utf8\"",
")",
",",
"result",
"=",
"processText",
"(",
"text",
",",
"filename",
",",
"options",
")",
";",
"return",
"result",
";",
"}"
] | Processes an individual file using bemlint. Files used here are known to
exist, so no need to check that here.
@param {string} filename The filename of the file being checked.
@param {Object} configHelper The configuration options for bemlint.
@param {Object} options The CLIEngine options object.
@returns {Result} The results for linting on this file.
@private | [
"Processes",
"an",
"individual",
"file",
"using",
"bemlint",
".",
"Files",
"used",
"here",
"are",
"known",
"to",
"exist",
"so",
"no",
"need",
"to",
"check",
"that",
"here",
"."
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/cli-engine.js#L159-L166 | train |
DesTincT/bemlint | lib/cli-engine.js | function(filePath) {
var ignoredPaths;
if (this.options.ignore) {
ignoredPaths = new IgnoredPaths(this.options);
return ignoredPaths.contains(filePath);
}
return false;
} | javascript | function(filePath) {
var ignoredPaths;
if (this.options.ignore) {
ignoredPaths = new IgnoredPaths(this.options);
return ignoredPaths.contains(filePath);
}
return false;
} | [
"function",
"(",
"filePath",
")",
"{",
"var",
"ignoredPaths",
";",
"if",
"(",
"this",
".",
"options",
".",
"ignore",
")",
"{",
"ignoredPaths",
"=",
"new",
"IgnoredPaths",
"(",
"this",
".",
"options",
")",
";",
"return",
"ignoredPaths",
".",
"contains",
"(",
"filePath",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Checks if a given path is ignored by bemlint.
@param {string} filePath The path of the file to check.
@returns {boolean} Whether or not the given path is ignored. | [
"Checks",
"if",
"a",
"given",
"path",
"is",
"ignored",
"by",
"bemlint",
"."
] | e30963deae2c93f1d5e925389339ad740250dd68 | https://github.com/DesTincT/bemlint/blob/e30963deae2c93f1d5e925389339ad740250dd68/lib/cli-engine.js#L594-L603 | train |
|
djalmaoliveira/djf-xml | src/index.js | extractGroup | function extractGroup (xml, tagName) {
var itens = []
var regex = new RegExp(`<${tagName}.+?>(.+?)</${tagName}>`, 'gi')
var result = ''
for (result = regex.exec(xml); regex.lastIndex !== 0; result = regex.exec(xml)) {
itens.push(result[0])
}
return itens
} | javascript | function extractGroup (xml, tagName) {
var itens = []
var regex = new RegExp(`<${tagName}.+?>(.+?)</${tagName}>`, 'gi')
var result = ''
for (result = regex.exec(xml); regex.lastIndex !== 0; result = regex.exec(xml)) {
itens.push(result[0])
}
return itens
} | [
"function",
"extractGroup",
"(",
"xml",
",",
"tagName",
")",
"{",
"var",
"itens",
"=",
"[",
"]",
"var",
"regex",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"tagName",
"}",
"${",
"tagName",
"}",
"`",
",",
"'gi'",
")",
"var",
"result",
"=",
"''",
"for",
"(",
"result",
"=",
"regex",
".",
"exec",
"(",
"xml",
")",
";",
"regex",
".",
"lastIndex",
"!==",
"0",
";",
"result",
"=",
"regex",
".",
"exec",
"(",
"xml",
")",
")",
"{",
"itens",
".",
"push",
"(",
"result",
"[",
"0",
"]",
")",
"}",
"return",
"itens",
"}"
] | Extract group of tags
@param {<string>} xml The xml
@param {<string>} tagName The tag name | [
"Extract",
"group",
"of",
"tags"
] | 6e70d3544c5c85eb3e5ca00aefee1e3c2e084788 | https://github.com/djalmaoliveira/djf-xml/blob/6e70d3544c5c85eb3e5ca00aefee1e3c2e084788/src/index.js#L7-L16 | train |
djalmaoliveira/djf-xml | src/index.js | extract | function extract (xml, tagName, attributeName) {
if (!Array.isArray(tagName)) {
tagName = [tagName]
}
var found = null
var tagFound = null
for (var i = 0; i < tagName.length; i++) {
// without attributes
found = new RegExp(`<${tagName[i]}\\s*>(.+?)</${tagName[i]}>`, 'i').exec(xml)
if (found) {
tagFound = tagName[i]
break
}
// with attributes
found = new RegExp(`<${tagName[i]} .*?>(.+?)</${tagName[i]}>`, 'i').exec(xml)
if (found) {
tagFound = tagName[i]
break
}
}
if (found && attributeName) {
var attribute = new RegExp(`<${tagFound} .*?${attributeName}=\"(.+?)\".*?>`, 'i').exec(found[0])
if (attribute) {
return attribute[1]
}
}
return found ? found[1] : null
} | javascript | function extract (xml, tagName, attributeName) {
if (!Array.isArray(tagName)) {
tagName = [tagName]
}
var found = null
var tagFound = null
for (var i = 0; i < tagName.length; i++) {
// without attributes
found = new RegExp(`<${tagName[i]}\\s*>(.+?)</${tagName[i]}>`, 'i').exec(xml)
if (found) {
tagFound = tagName[i]
break
}
// with attributes
found = new RegExp(`<${tagName[i]} .*?>(.+?)</${tagName[i]}>`, 'i').exec(xml)
if (found) {
tagFound = tagName[i]
break
}
}
if (found && attributeName) {
var attribute = new RegExp(`<${tagFound} .*?${attributeName}=\"(.+?)\".*?>`, 'i').exec(found[0])
if (attribute) {
return attribute[1]
}
}
return found ? found[1] : null
} | [
"function",
"extract",
"(",
"xml",
",",
"tagName",
",",
"attributeName",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"tagName",
")",
")",
"{",
"tagName",
"=",
"[",
"tagName",
"]",
"}",
"var",
"found",
"=",
"null",
"var",
"tagFound",
"=",
"null",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tagName",
".",
"length",
";",
"i",
"++",
")",
"{",
"found",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"tagName",
"[",
"i",
"]",
"}",
"\\\\",
"${",
"tagName",
"[",
"i",
"]",
"}",
"`",
",",
"'i'",
")",
".",
"exec",
"(",
"xml",
")",
"if",
"(",
"found",
")",
"{",
"tagFound",
"=",
"tagName",
"[",
"i",
"]",
"break",
"}",
"found",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"tagName",
"[",
"i",
"]",
"}",
"${",
"tagName",
"[",
"i",
"]",
"}",
"`",
",",
"'i'",
")",
".",
"exec",
"(",
"xml",
")",
"if",
"(",
"found",
")",
"{",
"tagFound",
"=",
"tagName",
"[",
"i",
"]",
"break",
"}",
"}",
"if",
"(",
"found",
"&&",
"attributeName",
")",
"{",
"var",
"attribute",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"tagFound",
"}",
"${",
"attributeName",
"}",
"\\\"",
"\\\"",
"`",
",",
"'i'",
")",
".",
"exec",
"(",
"found",
"[",
"0",
"]",
")",
"if",
"(",
"attribute",
")",
"{",
"return",
"attribute",
"[",
"1",
"]",
"}",
"}",
"return",
"found",
"?",
"found",
"[",
"1",
"]",
":",
"null",
"}"
] | Extract value between tags.
@param {<string>} xml The xml
@param {<string|array>} tagName The tag name
@param {<string>} attributeName The attribute name
@return {string | null} | [
"Extract",
"value",
"between",
"tags",
"."
] | 6e70d3544c5c85eb3e5ca00aefee1e3c2e084788 | https://github.com/djalmaoliveira/djf-xml/blob/6e70d3544c5c85eb3e5ca00aefee1e3c2e084788/src/index.js#L26-L57 | train |
karlkfi/ngindox | lib/util.js | routeType | function routeType(route) {
var fields = Object.keys(RouteTypeFields);
for (var i = 0, len = fields.length; i < len; i++) {
var field = fields[i];
if (route[field]) {
return RouteTypeFields[field];
}
}
return 'unknown';
} | javascript | function routeType(route) {
var fields = Object.keys(RouteTypeFields);
for (var i = 0, len = fields.length; i < len; i++) {
var field = fields[i];
if (route[field]) {
return RouteTypeFields[field];
}
}
return 'unknown';
} | [
"function",
"routeType",
"(",
"route",
")",
"{",
"var",
"fields",
"=",
"Object",
".",
"keys",
"(",
"RouteTypeFields",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"fields",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"field",
"=",
"fields",
"[",
"i",
"]",
";",
"if",
"(",
"route",
"[",
"field",
"]",
")",
"{",
"return",
"RouteTypeFields",
"[",
"field",
"]",
";",
"}",
"}",
"return",
"'unknown'",
";",
"}"
] | Get the type of a route | [
"Get",
"the",
"type",
"of",
"a",
"route"
] | 2c0e8a682d7bde9e5d73a853f45bf1460f4664e9 | https://github.com/karlkfi/ngindox/blob/2c0e8a682d7bde9e5d73a853f45bf1460f4664e9/lib/util.js#L52-L61 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.