repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
seangenabe/copy-newer | src/copy.js | copyNewerSingle | async function copyNewerSingle(srcpath, destpath, opts) {
let { interval = 1000, verbose = false } = opts
let stat = await FS.stat(srcpath)
// Stat and check the filesystem entry type.
if (stat.isDirectory()) {
// Directory, ensure destination exists and return.
let made = await mkdirp(destpath)
if (verbose && made) { console.log(`${made} - directory created`)}
return 'dir'
}
else if (!stat.isFile()) {
// Not a file.
throw new Error("Not supported.")
}
let srcmtime = stat.mtime
let destmtime
try {
// Stat destpath and get the mtime.
destmtime = (await FS.stat(destpath)).mtime
}
catch (err) {
// path does not exist
}
if (destmtime !== undefined && srcmtime - destmtime <= interval) {
// destpath does not exist or mtime is equal, return.
if (verbose) { console.log(`${srcpath} == ${destpath}`) }
return false
}
// Ensure parent directory exists.
await mkdirp(`${destpath}/..`)
// Commence copying.
let rs = FS.createReadStream(srcpath)
let ws = FS.createWriteStream(destpath)
rs.pipe(ws)
await waitForStreamEnd(ws)
// Set mtime to be equal to the source file.
await FS.utimes(destpath, new Date(), stat.mtime)
if (verbose) { console.log(`${srcpath} -> ${destpath}`) }
return true
} | javascript | async function copyNewerSingle(srcpath, destpath, opts) {
let { interval = 1000, verbose = false } = opts
let stat = await FS.stat(srcpath)
// Stat and check the filesystem entry type.
if (stat.isDirectory()) {
// Directory, ensure destination exists and return.
let made = await mkdirp(destpath)
if (verbose && made) { console.log(`${made} - directory created`)}
return 'dir'
}
else if (!stat.isFile()) {
// Not a file.
throw new Error("Not supported.")
}
let srcmtime = stat.mtime
let destmtime
try {
// Stat destpath and get the mtime.
destmtime = (await FS.stat(destpath)).mtime
}
catch (err) {
// path does not exist
}
if (destmtime !== undefined && srcmtime - destmtime <= interval) {
// destpath does not exist or mtime is equal, return.
if (verbose) { console.log(`${srcpath} == ${destpath}`) }
return false
}
// Ensure parent directory exists.
await mkdirp(`${destpath}/..`)
// Commence copying.
let rs = FS.createReadStream(srcpath)
let ws = FS.createWriteStream(destpath)
rs.pipe(ws)
await waitForStreamEnd(ws)
// Set mtime to be equal to the source file.
await FS.utimes(destpath, new Date(), stat.mtime)
if (verbose) { console.log(`${srcpath} -> ${destpath}`) }
return true
} | [
"async",
"function",
"copyNewerSingle",
"(",
"srcpath",
",",
"destpath",
",",
"opts",
")",
"{",
"let",
"{",
"interval",
"=",
"1000",
",",
"verbose",
"=",
"false",
"}",
"=",
"opts",
"let",
"stat",
"=",
"await",
"FS",
".",
"stat",
"(",
"srcpath",
")",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"let",
"made",
"=",
"await",
"mkdirp",
"(",
"destpath",
")",
"if",
"(",
"verbose",
"&&",
"made",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"made",
"}",
"`",
")",
"}",
"return",
"'dir'",
"}",
"else",
"if",
"(",
"!",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Not supported.\"",
")",
"}",
"let",
"srcmtime",
"=",
"stat",
".",
"mtime",
"let",
"destmtime",
"try",
"{",
"destmtime",
"=",
"(",
"await",
"FS",
".",
"stat",
"(",
"destpath",
")",
")",
".",
"mtime",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"if",
"(",
"destmtime",
"!==",
"undefined",
"&&",
"srcmtime",
"-",
"destmtime",
"<=",
"interval",
")",
"{",
"if",
"(",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"srcpath",
"}",
"${",
"destpath",
"}",
"`",
")",
"}",
"return",
"false",
"}",
"await",
"mkdirp",
"(",
"`",
"${",
"destpath",
"}",
"`",
")",
"let",
"rs",
"=",
"FS",
".",
"createReadStream",
"(",
"srcpath",
")",
"let",
"ws",
"=",
"FS",
".",
"createWriteStream",
"(",
"destpath",
")",
"rs",
".",
"pipe",
"(",
"ws",
")",
"await",
"waitForStreamEnd",
"(",
"ws",
")",
"await",
"FS",
".",
"utimes",
"(",
"destpath",
",",
"new",
"Date",
"(",
")",
",",
"stat",
".",
"mtime",
")",
"if",
"(",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"srcpath",
"}",
"${",
"destpath",
"}",
"`",
")",
"}",
"return",
"true",
"}"
]
| Copies a single file. Returns 'dir' if directory, true if successful, false if not. Throws Error if not a file and not a directory. | [
"Copies",
"a",
"single",
"file",
".",
"Returns",
"dir",
"if",
"directory",
"true",
"if",
"successful",
"false",
"if",
"not",
".",
"Throws",
"Error",
"if",
"not",
"a",
"file",
"and",
"not",
"a",
"directory",
"."
]
| 0be2dacc287ca9ccbd3bcd1049cdf0a86f2b3a1b | https://github.com/seangenabe/copy-newer/blob/0be2dacc287ca9ccbd3bcd1049cdf0a86f2b3a1b/src/copy.js#L33-L80 | train |
marshallswain/amity-mongodb | lib/amity-mongodb.js | function(database, callback){
var dbName = database.databaseName || database.name;
var options = {
name:dbName + '/_collections',
service:feathersMongoColls(amityMongo.db.db(dbName))
};
amityMongo.amity_collManager.push(options);
callback();
} | javascript | function(database, callback){
var dbName = database.databaseName || database.name;
var options = {
name:dbName + '/_collections',
service:feathersMongoColls(amityMongo.db.db(dbName))
};
amityMongo.amity_collManager.push(options);
callback();
} | [
"function",
"(",
"database",
",",
"callback",
")",
"{",
"var",
"dbName",
"=",
"database",
".",
"databaseName",
"||",
"database",
".",
"name",
";",
"var",
"options",
"=",
"{",
"name",
":",
"dbName",
"+",
"'/_collections'",
",",
"service",
":",
"feathersMongoColls",
"(",
"amityMongo",
".",
"db",
".",
"db",
"(",
"dbName",
")",
")",
"}",
";",
"amityMongo",
".",
"amity_collManager",
".",
"push",
"(",
"options",
")",
";",
"callback",
"(",
")",
";",
"}"
]
| Prepares a service to manage collections on the database. This service will be set up by the Amity server. | [
"Prepares",
"a",
"service",
"to",
"manage",
"collections",
"on",
"the",
"database",
".",
"This",
"service",
"will",
"be",
"set",
"up",
"by",
"the",
"Amity",
"server",
"."
]
| 311b85b70ec126d70ce457eb21c7a492076a0b8c | https://github.com/marshallswain/amity-mongodb/blob/311b85b70ec126d70ce457eb21c7a492076a0b8c/lib/amity-mongodb.js#L132-L140 | train |
|
marshallswain/amity-mongodb | lib/amity-mongodb.js | function(collection, callback){
// Prep the collection name.
var colName = collection.name.split('.');
var dbName = colName.shift();
colName = colName.join('.');
var database = amityMongo.db.db(dbName);
var options = {
name:dbName + '/' + colName,
service:feathersMongo({collection:database.collection(collection.name)})
};
amityMongo.amity_collections.push(options);
callback();
} | javascript | function(collection, callback){
// Prep the collection name.
var colName = collection.name.split('.');
var dbName = colName.shift();
colName = colName.join('.');
var database = amityMongo.db.db(dbName);
var options = {
name:dbName + '/' + colName,
service:feathersMongo({collection:database.collection(collection.name)})
};
amityMongo.amity_collections.push(options);
callback();
} | [
"function",
"(",
"collection",
",",
"callback",
")",
"{",
"var",
"colName",
"=",
"collection",
".",
"name",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"dbName",
"=",
"colName",
".",
"shift",
"(",
")",
";",
"colName",
"=",
"colName",
".",
"join",
"(",
"'.'",
")",
";",
"var",
"database",
"=",
"amityMongo",
".",
"db",
".",
"db",
"(",
"dbName",
")",
";",
"var",
"options",
"=",
"{",
"name",
":",
"dbName",
"+",
"'/'",
"+",
"colName",
",",
"service",
":",
"feathersMongo",
"(",
"{",
"collection",
":",
"database",
".",
"collection",
"(",
"collection",
".",
"name",
")",
"}",
")",
"}",
";",
"amityMongo",
".",
"amity_collections",
".",
"push",
"(",
"options",
")",
";",
"callback",
"(",
")",
";",
"}"
]
| Prepares a service to manage documents in the provided collection. This service will be set up by the Amity server. | [
"Prepares",
"a",
"service",
"to",
"manage",
"documents",
"in",
"the",
"provided",
"collection",
".",
"This",
"service",
"will",
"be",
"set",
"up",
"by",
"the",
"Amity",
"server",
"."
]
| 311b85b70ec126d70ce457eb21c7a492076a0b8c | https://github.com/marshallswain/amity-mongodb/blob/311b85b70ec126d70ce457eb21c7a492076a0b8c/lib/amity-mongodb.js#L144-L158 | train |
|
jffry/lb-include | src/index.js | loadFileContents | function loadFileContents(filePath, preloaded)
{
//use pre-supplied contents?
if (typeof preloaded !== 'undefined' && preloaded !== null)
{
//return a promise which will get resolved with the preloaded value
if (preloaded instanceof Buffer)
{
return promiseValue(preloaded.toString());
}
else
{
return promiseValue(String(preloaded));
}
}
else
{
return Q.nfcall(fs.readFile, filePath).invoke('toString');
}
} | javascript | function loadFileContents(filePath, preloaded)
{
//use pre-supplied contents?
if (typeof preloaded !== 'undefined' && preloaded !== null)
{
//return a promise which will get resolved with the preloaded value
if (preloaded instanceof Buffer)
{
return promiseValue(preloaded.toString());
}
else
{
return promiseValue(String(preloaded));
}
}
else
{
return Q.nfcall(fs.readFile, filePath).invoke('toString');
}
} | [
"function",
"loadFileContents",
"(",
"filePath",
",",
"preloaded",
")",
"{",
"if",
"(",
"typeof",
"preloaded",
"!==",
"'undefined'",
"&&",
"preloaded",
"!==",
"null",
")",
"{",
"if",
"(",
"preloaded",
"instanceof",
"Buffer",
")",
"{",
"return",
"promiseValue",
"(",
"preloaded",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"promiseValue",
"(",
"String",
"(",
"preloaded",
")",
")",
";",
"}",
"}",
"else",
"{",
"return",
"Q",
".",
"nfcall",
"(",
"fs",
".",
"readFile",
",",
"filePath",
")",
".",
"invoke",
"(",
"'toString'",
")",
";",
"}",
"}"
]
| helper function to load file; returns promise that's resolved with contents | [
"helper",
"function",
"to",
"load",
"file",
";",
"returns",
"promise",
"that",
"s",
"resolved",
"with",
"contents"
]
| 049f3ff1a86604a43c51391fe273bc6ba02a594b | https://github.com/jffry/lb-include/blob/049f3ff1a86604a43c51391fe273bc6ba02a594b/src/index.js#L186-L205 | train |
viliam-jobko/swagger-client-sync | index.js | returnClient | function returnClient(options, ignoreCache) {
if (typeof options === 'string') {
options = {
url: options,
usePromise: true
};
}
if (ignoreCache === true) {
return generateClient(options);
}
const optionsJSON = JSON.stringify(options);
if (cachedClients[optionsJSON] instanceof Swagger) {
return cachedClients[optionsJSON];
} else {
cachedClients[optionsJSON] = generateClient(options);
return cachedClients[optionsJSON];
}
} | javascript | function returnClient(options, ignoreCache) {
if (typeof options === 'string') {
options = {
url: options,
usePromise: true
};
}
if (ignoreCache === true) {
return generateClient(options);
}
const optionsJSON = JSON.stringify(options);
if (cachedClients[optionsJSON] instanceof Swagger) {
return cachedClients[optionsJSON];
} else {
cachedClients[optionsJSON] = generateClient(options);
return cachedClients[optionsJSON];
}
} | [
"function",
"returnClient",
"(",
"options",
",",
"ignoreCache",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'string'",
")",
"{",
"options",
"=",
"{",
"url",
":",
"options",
",",
"usePromise",
":",
"true",
"}",
";",
"}",
"if",
"(",
"ignoreCache",
"===",
"true",
")",
"{",
"return",
"generateClient",
"(",
"options",
")",
";",
"}",
"const",
"optionsJSON",
"=",
"JSON",
".",
"stringify",
"(",
"options",
")",
";",
"if",
"(",
"cachedClients",
"[",
"optionsJSON",
"]",
"instanceof",
"Swagger",
")",
"{",
"return",
"cachedClients",
"[",
"optionsJSON",
"]",
";",
"}",
"else",
"{",
"cachedClients",
"[",
"optionsJSON",
"]",
"=",
"generateClient",
"(",
"options",
")",
";",
"return",
"cachedClients",
"[",
"optionsJSON",
"]",
";",
"}",
"}"
]
| Create a swagger-client synchronously.
@param {String|Object} options URL to swagger specification or object with options that will be passed to swagger-client constructor.
@param {Boolean=} ignoreCache Created new swagger-client and don't cache it (default: false). | [
"Create",
"a",
"swagger",
"-",
"client",
"synchronously",
"."
]
| b59abf3e645596647c1a0a9d754ae0c2518b09ed | https://github.com/viliam-jobko/swagger-client-sync/blob/b59abf3e645596647c1a0a9d754ae0c2518b09ed/index.js#L24-L43 | train |
stezu/node-stream | lib/_utils/parse.js | parse | function parse(data, callback) {
var parsed;
try {
parsed = JSON.parse(data);
} catch (e) {
return callback(e);
}
return callback(null, parsed);
} | javascript | function parse(data, callback) {
var parsed;
try {
parsed = JSON.parse(data);
} catch (e) {
return callback(e);
}
return callback(null, parsed);
} | [
"function",
"parse",
"(",
"data",
",",
"callback",
")",
"{",
"var",
"parsed",
";",
"try",
"{",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"e",
")",
";",
"}",
"return",
"callback",
"(",
"null",
",",
"parsed",
")",
";",
"}"
]
| Parse the contents of a string as JSON.
@private
@static
@since 1.3.0
@category Utilities
@param {String} data - String you would like to parse as JSON.
@param {Function} callback - Callback with an error or parsed JSON.
@returns {undefined} | [
"Parse",
"the",
"contents",
"of",
"a",
"string",
"as",
"JSON",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/_utils/parse.js#L13-L23 | train |
noderaider/repackage | jspm_packages/npm/[email protected]/lib/transformation/transformers/es6/parameters/rest.js | BindingIdentifier | function BindingIdentifier(node, parent, scope, state) {
if (node.name === state.name) {
state.deopted = true;
}
} | javascript | function BindingIdentifier(node, parent, scope, state) {
if (node.name === state.name) {
state.deopted = true;
}
} | [
"function",
"BindingIdentifier",
"(",
"node",
",",
"parent",
",",
"scope",
",",
"state",
")",
"{",
"if",
"(",
"node",
".",
"name",
"===",
"state",
".",
"name",
")",
"{",
"state",
".",
"deopted",
"=",
"true",
";",
"}",
"}"
]
| Deopt on use of a binding identifier with the same name as our rest param.
See https://github.com/babel/babel/issues/2091 | [
"Deopt",
"on",
"use",
"of",
"a",
"binding",
"identifier",
"with",
"the",
"same",
"name",
"as",
"our",
"rest",
"param",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/transformation/transformers/es6/parameters/rest.js#L103-L107 | train |
briancsparks/aws-json | lib/cf/subnet.js | function(name, zoneLetter, cf, vpc, routeTable) {
var self = this;
self.isPublic = false;
base.Base.call(this, cf, 'EC2::Subnet', name);
self.addProperty('VpcId', vpc.ref());
self.zone = self.addProperty('AvailabilityZone', vpc.az(zoneLetter));
self.cidrBlock = function(cidr) {
self.cidr = vpc.mkSubnetCidrBlock(cidr);
return self.addProperty('CidrBlock', self.cidr);
};
self.mapPublicIpOnLaunch = function(value) {
if (arguments.length === 0) { value = true; }
return self.addProperty('MapPublicIpOnLaunch', !!value);
};
var assocName = name+'RouteTableAssociation';
cf.data.Resources[assocName] = subnet.makeSubnetRouteTableAssociation(assocName, cf, self, routeTable);
//self.output(name+"CidrBlock", self.getAtt("CidrBlock"), "Subnet "+name+"CIDR block"); /* Do not know why CidrBlock is not available */
} | javascript | function(name, zoneLetter, cf, vpc, routeTable) {
var self = this;
self.isPublic = false;
base.Base.call(this, cf, 'EC2::Subnet', name);
self.addProperty('VpcId', vpc.ref());
self.zone = self.addProperty('AvailabilityZone', vpc.az(zoneLetter));
self.cidrBlock = function(cidr) {
self.cidr = vpc.mkSubnetCidrBlock(cidr);
return self.addProperty('CidrBlock', self.cidr);
};
self.mapPublicIpOnLaunch = function(value) {
if (arguments.length === 0) { value = true; }
return self.addProperty('MapPublicIpOnLaunch', !!value);
};
var assocName = name+'RouteTableAssociation';
cf.data.Resources[assocName] = subnet.makeSubnetRouteTableAssociation(assocName, cf, self, routeTable);
//self.output(name+"CidrBlock", self.getAtt("CidrBlock"), "Subnet "+name+"CIDR block"); /* Do not know why CidrBlock is not available */
} | [
"function",
"(",
"name",
",",
"zoneLetter",
",",
"cf",
",",
"vpc",
",",
"routeTable",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"isPublic",
"=",
"false",
";",
"base",
".",
"Base",
".",
"call",
"(",
"this",
",",
"cf",
",",
"'EC2::Subnet'",
",",
"name",
")",
";",
"self",
".",
"addProperty",
"(",
"'VpcId'",
",",
"vpc",
".",
"ref",
"(",
")",
")",
";",
"self",
".",
"zone",
"=",
"self",
".",
"addProperty",
"(",
"'AvailabilityZone'",
",",
"vpc",
".",
"az",
"(",
"zoneLetter",
")",
")",
";",
"self",
".",
"cidrBlock",
"=",
"function",
"(",
"cidr",
")",
"{",
"self",
".",
"cidr",
"=",
"vpc",
".",
"mkSubnetCidrBlock",
"(",
"cidr",
")",
";",
"return",
"self",
".",
"addProperty",
"(",
"'CidrBlock'",
",",
"self",
".",
"cidr",
")",
";",
"}",
";",
"self",
".",
"mapPublicIpOnLaunch",
"=",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
")",
"{",
"value",
"=",
"true",
";",
"}",
"return",
"self",
".",
"addProperty",
"(",
"'MapPublicIpOnLaunch'",
",",
"!",
"!",
"value",
")",
";",
"}",
";",
"var",
"assocName",
"=",
"name",
"+",
"'RouteTableAssociation'",
";",
"cf",
".",
"data",
".",
"Resources",
"[",
"assocName",
"]",
"=",
"subnet",
".",
"makeSubnetRouteTableAssociation",
"(",
"assocName",
",",
"cf",
",",
"self",
",",
"routeTable",
")",
";",
"}"
]
| Base for subnet class. | [
"Base",
"for",
"subnet",
"class",
"."
]
| df224093d0d5018834625f7a6fa640773814a311 | https://github.com/briancsparks/aws-json/blob/df224093d0d5018834625f7a6fa640773814a311/lib/cf/subnet.js#L13-L37 | train |
|
preceptorjs/taxi | lib/connection.js | stringifyStackTrace | function stringifyStackTrace (stackTrace) {
var i, len, result = [];
for (i = 0, len = stackTrace.length; i < len; i++) {
if (stackTrace[i]) {
result.push(stackTrace[i].methodName + "::" + stackTrace[i].className + " (" + stackTrace[i].fileName + ":" + stackTrace[i].lineNumber + ")");
}
}
return result.join("\n");
} | javascript | function stringifyStackTrace (stackTrace) {
var i, len, result = [];
for (i = 0, len = stackTrace.length; i < len; i++) {
if (stackTrace[i]) {
result.push(stackTrace[i].methodName + "::" + stackTrace[i].className + " (" + stackTrace[i].fileName + ":" + stackTrace[i].lineNumber + ")");
}
}
return result.join("\n");
} | [
"function",
"stringifyStackTrace",
"(",
"stackTrace",
")",
"{",
"var",
"i",
",",
"len",
",",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"stackTrace",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"stackTrace",
"[",
"i",
"]",
")",
"{",
"result",
".",
"push",
"(",
"stackTrace",
"[",
"i",
"]",
".",
"methodName",
"+",
"\"::\"",
"+",
"stackTrace",
"[",
"i",
"]",
".",
"className",
"+",
"\" (\"",
"+",
"stackTrace",
"[",
"i",
"]",
".",
"fileName",
"+",
"\":\"",
"+",
"stackTrace",
"[",
"i",
"]",
".",
"lineNumber",
"+",
"\")\"",
")",
";",
"}",
"}",
"return",
"result",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"}"
]
| Turns a selenium stack-trace into a string
@param {Array.<Object>} stackTrace
@return {String} | [
"Turns",
"a",
"selenium",
"stack",
"-",
"trace",
"into",
"a",
"string"
]
| 96ab5a5c5fa9dc50f325ba4de52dd90009073ca3 | https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/connection.js#L248-L259 | train |
preceptorjs/taxi | lib/connection.js | createInternalConnection | function createInternalConnection (mode) {
var result;
switch (mode) {
case 'async':
result = require('then-request');
break;
case 'sync':
result = require('sync-req');
break;
default:
throw new Error('Expected options.mode to be "async" or "sync" but got ' + JSON.stringify(mode));
}
return result;
} | javascript | function createInternalConnection (mode) {
var result;
switch (mode) {
case 'async':
result = require('then-request');
break;
case 'sync':
result = require('sync-req');
break;
default:
throw new Error('Expected options.mode to be "async" or "sync" but got ' + JSON.stringify(mode));
}
return result;
} | [
"function",
"createInternalConnection",
"(",
"mode",
")",
"{",
"var",
"result",
";",
"switch",
"(",
"mode",
")",
"{",
"case",
"'async'",
":",
"result",
"=",
"require",
"(",
"'then-request'",
")",
";",
"break",
";",
"case",
"'sync'",
":",
"result",
"=",
"require",
"(",
"'sync-req'",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Expected options.mode to be \"async\" or \"sync\" but got '",
"+",
"JSON",
".",
"stringify",
"(",
"mode",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Create connection object according to mode-type
@param {String} mode (async|sync)
@return {function} | [
"Create",
"connection",
"object",
"according",
"to",
"mode",
"-",
"type"
]
| 96ab5a5c5fa9dc50f325ba4de52dd90009073ca3 | https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/connection.js#L267-L283 | train |
Dacrol/node-current-branch | get-branch.js | branch | function branch () {
const headpath = path.join(process.cwd(), '.git/HEAD')
if (!fs.existsSync(headpath)) {
console.warn('No HEAD found, aborting.')
return null
}
const headcontent = fs.readFileSync(headpath, 'utf8')
const branchRegex = /ref: refs\/heads\/(\S+)/
const branchname = branchRegex.exec(headcontent)
return branchname && branchname[1]
} | javascript | function branch () {
const headpath = path.join(process.cwd(), '.git/HEAD')
if (!fs.existsSync(headpath)) {
console.warn('No HEAD found, aborting.')
return null
}
const headcontent = fs.readFileSync(headpath, 'utf8')
const branchRegex = /ref: refs\/heads\/(\S+)/
const branchname = branchRegex.exec(headcontent)
return branchname && branchname[1]
} | [
"function",
"branch",
"(",
")",
"{",
"const",
"headpath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'.git/HEAD'",
")",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"headpath",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'No HEAD found, aborting.'",
")",
"return",
"null",
"}",
"const",
"headcontent",
"=",
"fs",
".",
"readFileSync",
"(",
"headpath",
",",
"'utf8'",
")",
"const",
"branchRegex",
"=",
"/",
"ref: refs\\/heads\\/(\\S+)",
"/",
"const",
"branchname",
"=",
"branchRegex",
".",
"exec",
"(",
"headcontent",
")",
"return",
"branchname",
"&&",
"branchname",
"[",
"1",
"]",
"}"
]
| Gets the current branch.
@returns {string} Branch name | [
"Gets",
"the",
"current",
"branch",
"."
]
| d1f76052cce7800cd3aafbbde75d526753240dc7 | https://github.com/Dacrol/node-current-branch/blob/d1f76052cce7800cd3aafbbde75d526753240dc7/get-branch.js#L9-L19 | train |
WASdev/lib.rtcomm.node | lib/RtcConnector.js | function(topic, message) {
/*
* so should a filter manage the last message it has? and give it an ID and store it...
* to prevent duplicates...
* or should this filter do it...
* this shold just execute 1 filter -- NO more than 1. But if a topic matches
* multiple filters then we need to call one filter and mark it dirty or something
*
* maybe save the lastMessage w/ a timestamp and if it matches, then skip it...
*
* given topic A that matches 2 filters so there will be 2 messages...
*
*
* return number of matches...
*
*
*/
for( var key in myFilters) {
if (myFilters.hasOwnProperty(key)) {
myFilters[key].doFilter(topic,message) ;
}
}
// count is how many times filter ran...
} | javascript | function(topic, message) {
/*
* so should a filter manage the last message it has? and give it an ID and store it...
* to prevent duplicates...
* or should this filter do it...
* this shold just execute 1 filter -- NO more than 1. But if a topic matches
* multiple filters then we need to call one filter and mark it dirty or something
*
* maybe save the lastMessage w/ a timestamp and if it matches, then skip it...
*
* given topic A that matches 2 filters so there will be 2 messages...
*
*
* return number of matches...
*
*
*/
for( var key in myFilters) {
if (myFilters.hasOwnProperty(key)) {
myFilters[key].doFilter(topic,message) ;
}
}
// count is how many times filter ran...
} | [
"function",
"(",
"topic",
",",
"message",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"myFilters",
")",
"{",
"if",
"(",
"myFilters",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"myFilters",
"[",
"key",
"]",
".",
"doFilter",
"(",
"topic",
",",
"message",
")",
";",
"}",
"}",
"}"
]
| doFilter - Execute the filter callbacks for the topic passed
@private
@param {String} topic Topic name to filter
@param {String} message Message to pass | [
"doFilter",
"-",
"Execute",
"the",
"filter",
"callbacks",
"for",
"the",
"topic",
"passed"
]
| bac07b57862a0f3c14538a863ae9e76baed894f3 | https://github.com/WASdev/lib.rtcomm.node/blob/bac07b57862a0f3c14538a863ae9e76baed894f3/lib/RtcConnector.js#L296-L320 | train |
|
WASdev/lib.rtcomm.node | lib/RtcConnector.js | function(config) {
var em = new RtcConnector(config);
var unique = (config && config.unique) ? true : false;
l('DEBUG') && console.log('createRtcConnector() config is: ',config);
var key = em.key = createKey(em.config.user||null, em.config.password || null, em.config.server || null, em.config.port || null, em.config.eventPath || 'rtcomm');
var mon = find(key);
// Monitors not requesting to be UNIQUE.
var umon = [];
mon.forEach(function(m){ !m.unique && umon.push(m); });
if (unique || umon.length === 0) {
rtcConnectors[em.id] = em;
return em;
}
// return first nonunique that matched the key
return umon[0] || null;
} | javascript | function(config) {
var em = new RtcConnector(config);
var unique = (config && config.unique) ? true : false;
l('DEBUG') && console.log('createRtcConnector() config is: ',config);
var key = em.key = createKey(em.config.user||null, em.config.password || null, em.config.server || null, em.config.port || null, em.config.eventPath || 'rtcomm');
var mon = find(key);
// Monitors not requesting to be UNIQUE.
var umon = [];
mon.forEach(function(m){ !m.unique && umon.push(m); });
if (unique || umon.length === 0) {
rtcConnectors[em.id] = em;
return em;
}
// return first nonunique that matched the key
return umon[0] || null;
} | [
"function",
"(",
"config",
")",
"{",
"var",
"em",
"=",
"new",
"RtcConnector",
"(",
"config",
")",
";",
"var",
"unique",
"=",
"(",
"config",
"&&",
"config",
".",
"unique",
")",
"?",
"true",
":",
"false",
";",
"l",
"(",
"'DEBUG'",
")",
"&&",
"console",
".",
"log",
"(",
"'createRtcConnector() config is: '",
",",
"config",
")",
";",
"var",
"key",
"=",
"em",
".",
"key",
"=",
"createKey",
"(",
"em",
".",
"config",
".",
"user",
"||",
"null",
",",
"em",
".",
"config",
".",
"password",
"||",
"null",
",",
"em",
".",
"config",
".",
"server",
"||",
"null",
",",
"em",
".",
"config",
".",
"port",
"||",
"null",
",",
"em",
".",
"config",
".",
"eventPath",
"||",
"'rtcomm'",
")",
";",
"var",
"mon",
"=",
"find",
"(",
"key",
")",
";",
"var",
"umon",
"=",
"[",
"]",
";",
"mon",
".",
"forEach",
"(",
"function",
"(",
"m",
")",
"{",
"!",
"m",
".",
"unique",
"&&",
"umon",
".",
"push",
"(",
"m",
")",
";",
"}",
")",
";",
"if",
"(",
"unique",
"||",
"umon",
".",
"length",
"===",
"0",
")",
"{",
"rtcConnectors",
"[",
"em",
".",
"id",
"]",
"=",
"em",
";",
"return",
"em",
";",
"}",
"return",
"umon",
"[",
"0",
"]",
"||",
"null",
";",
"}"
]
| Create an RtcConnector and add it to the rtcConnectors pool | [
"Create",
"an",
"RtcConnector",
"and",
"add",
"it",
"to",
"the",
"rtcConnectors",
"pool"
]
| bac07b57862a0f3c14538a863ae9e76baed894f3 | https://github.com/WASdev/lib.rtcomm.node/blob/bac07b57862a0f3c14538a863ae9e76baed894f3/lib/RtcConnector.js#L441-L457 | train |
|
stezu/node-stream | lib/modifiers/stringify.js | stringify | function stringify() {
return map(function (chunk, next) {
var stringified;
try {
stringified = JSON.stringify(chunk);
} catch (e) {
return next(e);
}
return next(null, stringified);
});
} | javascript | function stringify() {
return map(function (chunk, next) {
var stringified;
try {
stringified = JSON.stringify(chunk);
} catch (e) {
return next(e);
}
return next(null, stringified);
});
} | [
"function",
"stringify",
"(",
")",
"{",
"return",
"map",
"(",
"function",
"(",
"chunk",
",",
"next",
")",
"{",
"var",
"stringified",
";",
"try",
"{",
"stringified",
"=",
"JSON",
".",
"stringify",
"(",
"chunk",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"next",
"(",
"e",
")",
";",
"}",
"return",
"next",
"(",
"null",
",",
"stringified",
")",
";",
"}",
")",
";",
"}"
]
| Creates a new stream where every element in the source stream
is converted to a string by using `JSON.stringify`.
@static
@since 1.1.0
@category Modifiers
@returns {Stream.Transform} - Transform stream.
@example
// stringify every element in an object stream so it can be
// piped to a non-object stream.
objStream
.pipe(nodeStream.stringify())
.pipe(process.stdout); | [
"Creates",
"a",
"new",
"stream",
"where",
"every",
"element",
"in",
"the",
"source",
"stream",
"is",
"converted",
"to",
"a",
"string",
"by",
"using",
"JSON",
".",
"stringify",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/stringify.js#L21-L34 | train |
codius-deprecated/codius-engine | lib/crypto.js | deriveSecret | function deriveSecret(parent_secret, child_name, hash_algorithm) {
if (!hash_algorithm) {
hash_algorithm = 'sha512';
}
return crypto.createHmac(hash_algorithm, parent_secret).update(child_name).digest('hex');
} | javascript | function deriveSecret(parent_secret, child_name, hash_algorithm) {
if (!hash_algorithm) {
hash_algorithm = 'sha512';
}
return crypto.createHmac(hash_algorithm, parent_secret).update(child_name).digest('hex');
} | [
"function",
"deriveSecret",
"(",
"parent_secret",
",",
"child_name",
",",
"hash_algorithm",
")",
"{",
"if",
"(",
"!",
"hash_algorithm",
")",
"{",
"hash_algorithm",
"=",
"'sha512'",
";",
"}",
"return",
"crypto",
".",
"createHmac",
"(",
"hash_algorithm",
",",
"parent_secret",
")",
".",
"update",
"(",
"child_name",
")",
".",
"digest",
"(",
"'hex'",
")",
";",
"}"
]
| Derive a "child" secret from a "parent" one using HMAC.
@param {String} parent_secret
@param {String} child_name
@param {String} ['sha512'] hash_algorithm
@returns {String} Note that the number of bits depends on the hash algorithm used | [
"Derive",
"a",
"child",
"secret",
"from",
"a",
"parent",
"one",
"using",
"HMAC",
"."
]
| 48aaea3d1a0dd2cf755a1905ff040e1667e8d131 | https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L44-L50 | train |
codius-deprecated/codius-engine | lib/crypto.js | deriveKeypair | function deriveKeypair(parent_secret, child_name, signature_scheme) {
if (!signature_scheme) {
signature_scheme = 'ec_secp256k1';
}
var pair = {};
if (signature_scheme === 'ec_secp256k1') {
pair.private = deriveSecret(parent_secret, child_name, 'sha256');
// If the private key is greater than the curve modulus we
// use a counter to get a new random secret
var modulus = new BigInteger(ecurve.getCurveByName('secp256k1').n, 16);
var counter = 1;
while (!pair.private || modulus.compareTo(pair.private) < 0) {
pair.private = deriveSecret(parent_secret, child_name + '_' + counter, 'sha256');
counter += 1;
}
pair.public = new bitcoinjs.ECKey(new BigInteger(pair.private, 16), false).pub.toHex();
} else {
throw new Error('Signature scheme: ' + signature_scheme + ' not currently supported');
}
return pair;
} | javascript | function deriveKeypair(parent_secret, child_name, signature_scheme) {
if (!signature_scheme) {
signature_scheme = 'ec_secp256k1';
}
var pair = {};
if (signature_scheme === 'ec_secp256k1') {
pair.private = deriveSecret(parent_secret, child_name, 'sha256');
// If the private key is greater than the curve modulus we
// use a counter to get a new random secret
var modulus = new BigInteger(ecurve.getCurveByName('secp256k1').n, 16);
var counter = 1;
while (!pair.private || modulus.compareTo(pair.private) < 0) {
pair.private = deriveSecret(parent_secret, child_name + '_' + counter, 'sha256');
counter += 1;
}
pair.public = new bitcoinjs.ECKey(new BigInteger(pair.private, 16), false).pub.toHex();
} else {
throw new Error('Signature scheme: ' + signature_scheme + ' not currently supported');
}
return pair;
} | [
"function",
"deriveKeypair",
"(",
"parent_secret",
",",
"child_name",
",",
"signature_scheme",
")",
"{",
"if",
"(",
"!",
"signature_scheme",
")",
"{",
"signature_scheme",
"=",
"'ec_secp256k1'",
";",
"}",
"var",
"pair",
"=",
"{",
"}",
";",
"if",
"(",
"signature_scheme",
"===",
"'ec_secp256k1'",
")",
"{",
"pair",
".",
"private",
"=",
"deriveSecret",
"(",
"parent_secret",
",",
"child_name",
",",
"'sha256'",
")",
";",
"var",
"modulus",
"=",
"new",
"BigInteger",
"(",
"ecurve",
".",
"getCurveByName",
"(",
"'secp256k1'",
")",
".",
"n",
",",
"16",
")",
";",
"var",
"counter",
"=",
"1",
";",
"while",
"(",
"!",
"pair",
".",
"private",
"||",
"modulus",
".",
"compareTo",
"(",
"pair",
".",
"private",
")",
"<",
"0",
")",
"{",
"pair",
".",
"private",
"=",
"deriveSecret",
"(",
"parent_secret",
",",
"child_name",
"+",
"'_'",
"+",
"counter",
",",
"'sha256'",
")",
";",
"counter",
"+=",
"1",
";",
"}",
"pair",
".",
"public",
"=",
"new",
"bitcoinjs",
".",
"ECKey",
"(",
"new",
"BigInteger",
"(",
"pair",
".",
"private",
",",
"16",
")",
",",
"false",
")",
".",
"pub",
".",
"toHex",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Signature scheme: '",
"+",
"signature_scheme",
"+",
"' not currently supported'",
")",
";",
"}",
"return",
"pair",
";",
"}"
]
| Derive a public and private key from a "parent" secret.
@param {String} parent_secret
@param {String} child_name
@param {String} ['secp256k1'] signature_scheme
@returns {Object} Object with "public" and "private" fields | [
"Derive",
"a",
"public",
"and",
"private",
"key",
"from",
"a",
"parent",
"secret",
"."
]
| 48aaea3d1a0dd2cf755a1905ff040e1667e8d131 | https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L61-L90 | train |
codius-deprecated/codius-engine | lib/crypto.js | sign | function sign(private_key, data) {
var key = new bitcoinjs.ECKey(new BigInteger(private_key, 16), false);
var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex'));
return key.sign(hash).toDER().toString('hex');
} | javascript | function sign(private_key, data) {
var key = new bitcoinjs.ECKey(new BigInteger(private_key, 16), false);
var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex'));
return key.sign(hash).toDER().toString('hex');
} | [
"function",
"sign",
"(",
"private_key",
",",
"data",
")",
"{",
"var",
"key",
"=",
"new",
"bitcoinjs",
".",
"ECKey",
"(",
"new",
"BigInteger",
"(",
"private_key",
",",
"16",
")",
",",
"false",
")",
";",
"var",
"hash",
"=",
"bitcoinjs",
".",
"crypto",
".",
"hash256",
"(",
"new",
"Buffer",
"(",
"data",
",",
"'hex'",
")",
")",
";",
"return",
"key",
".",
"sign",
"(",
"hash",
")",
".",
"toDER",
"(",
")",
".",
"toString",
"(",
"'hex'",
")",
";",
"}"
]
| Sign the given data
** For now assumes ec_secp256k1 **
@param {String} private_key Hex-encoded private key
@param {String} data Hex-encoded data | [
"Sign",
"the",
"given",
"data"
]
| 48aaea3d1a0dd2cf755a1905ff040e1667e8d131 | https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L100-L104 | train |
codius-deprecated/codius-engine | lib/crypto.js | verify | function verify(public_key, data, signature) {
var pubkey = bitcoinjs.ECPubKey.fromHex(public_key);
var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex'));
var ecsignature = bitcoinjs.ECSignature.fromDER(new Buffer(signature, 'hex'));
return pubkey.verify(hash, ecsignature);
} | javascript | function verify(public_key, data, signature) {
var pubkey = bitcoinjs.ECPubKey.fromHex(public_key);
var hash = bitcoinjs.crypto.hash256(new Buffer(data, 'hex'));
var ecsignature = bitcoinjs.ECSignature.fromDER(new Buffer(signature, 'hex'));
return pubkey.verify(hash, ecsignature);
} | [
"function",
"verify",
"(",
"public_key",
",",
"data",
",",
"signature",
")",
"{",
"var",
"pubkey",
"=",
"bitcoinjs",
".",
"ECPubKey",
".",
"fromHex",
"(",
"public_key",
")",
";",
"var",
"hash",
"=",
"bitcoinjs",
".",
"crypto",
".",
"hash256",
"(",
"new",
"Buffer",
"(",
"data",
",",
"'hex'",
")",
")",
";",
"var",
"ecsignature",
"=",
"bitcoinjs",
".",
"ECSignature",
".",
"fromDER",
"(",
"new",
"Buffer",
"(",
"signature",
",",
"'hex'",
")",
")",
";",
"return",
"pubkey",
".",
"verify",
"(",
"hash",
",",
"ecsignature",
")",
";",
"}"
]
| Verify a signature on the given data
** For now assumes ec_secp256k1 **
@param {String} public_key Hex-encoded public key
@param {String} data Hex-encoded data
@param {String} signature Hex-encoded signature | [
"Verify",
"a",
"signature",
"on",
"the",
"given",
"data"
]
| 48aaea3d1a0dd2cf755a1905ff040e1667e8d131 | https://github.com/codius-deprecated/codius-engine/blob/48aaea3d1a0dd2cf755a1905ff040e1667e8d131/lib/crypto.js#L115-L120 | train |
jonkemp/style-selector | index.js | getSpecificity | function getSpecificity(text, parsed) {
var expressions = parsed || parse(text),
spec = [ 0, 0, 0, 0 ],
nots = [],
i,
expression,
pseudos,
p,
ii,
not,
jj;
for (i = 0; i < expressions.length; i++) {
expression = expressions[i];
pseudos = expression.pseudos;
// id awards a point in the second column
if (expression.id) {
spec[1]++;
}
// classes and attributes award a point each in the third column
if (expression.attributes) {
spec[2] += expression.attributes.length;
}
if (expression.classList) {
spec[2] += expression.classList.length;
}
// tag awards a point in the fourth column
if (expression.tag && expression.tag !== '*') {
spec[3]++;
}
// pseudos award a point each in the fourth column
if (pseudos) {
spec[3] += pseudos.length;
for (p = 0; p < pseudos.length; p++) {
if (pseudos[p].key === 'not') {
nots.push(pseudos[p].value);
spec[3]--;
}
}
}
}
for (ii = nots.length; ii--;) {
not = getSpecificity(nots[ii]);
for (jj = 4; jj--;) {
spec[jj] += not[jj];
}
}
return spec;
} | javascript | function getSpecificity(text, parsed) {
var expressions = parsed || parse(text),
spec = [ 0, 0, 0, 0 ],
nots = [],
i,
expression,
pseudos,
p,
ii,
not,
jj;
for (i = 0; i < expressions.length; i++) {
expression = expressions[i];
pseudos = expression.pseudos;
// id awards a point in the second column
if (expression.id) {
spec[1]++;
}
// classes and attributes award a point each in the third column
if (expression.attributes) {
spec[2] += expression.attributes.length;
}
if (expression.classList) {
spec[2] += expression.classList.length;
}
// tag awards a point in the fourth column
if (expression.tag && expression.tag !== '*') {
spec[3]++;
}
// pseudos award a point each in the fourth column
if (pseudos) {
spec[3] += pseudos.length;
for (p = 0; p < pseudos.length; p++) {
if (pseudos[p].key === 'not') {
nots.push(pseudos[p].value);
spec[3]--;
}
}
}
}
for (ii = nots.length; ii--;) {
not = getSpecificity(nots[ii]);
for (jj = 4; jj--;) {
spec[jj] += not[jj];
}
}
return spec;
} | [
"function",
"getSpecificity",
"(",
"text",
",",
"parsed",
")",
"{",
"var",
"expressions",
"=",
"parsed",
"||",
"parse",
"(",
"text",
")",
",",
"spec",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
"nots",
"=",
"[",
"]",
",",
"i",
",",
"expression",
",",
"pseudos",
",",
"p",
",",
"ii",
",",
"not",
",",
"jj",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"expressions",
".",
"length",
";",
"i",
"++",
")",
"{",
"expression",
"=",
"expressions",
"[",
"i",
"]",
";",
"pseudos",
"=",
"expression",
".",
"pseudos",
";",
"if",
"(",
"expression",
".",
"id",
")",
"{",
"spec",
"[",
"1",
"]",
"++",
";",
"}",
"if",
"(",
"expression",
".",
"attributes",
")",
"{",
"spec",
"[",
"2",
"]",
"+=",
"expression",
".",
"attributes",
".",
"length",
";",
"}",
"if",
"(",
"expression",
".",
"classList",
")",
"{",
"spec",
"[",
"2",
"]",
"+=",
"expression",
".",
"classList",
".",
"length",
";",
"}",
"if",
"(",
"expression",
".",
"tag",
"&&",
"expression",
".",
"tag",
"!==",
"'*'",
")",
"{",
"spec",
"[",
"3",
"]",
"++",
";",
"}",
"if",
"(",
"pseudos",
")",
"{",
"spec",
"[",
"3",
"]",
"+=",
"pseudos",
".",
"length",
";",
"for",
"(",
"p",
"=",
"0",
";",
"p",
"<",
"pseudos",
".",
"length",
";",
"p",
"++",
")",
"{",
"if",
"(",
"pseudos",
"[",
"p",
"]",
".",
"key",
"===",
"'not'",
")",
"{",
"nots",
".",
"push",
"(",
"pseudos",
"[",
"p",
"]",
".",
"value",
")",
";",
"spec",
"[",
"3",
"]",
"--",
";",
"}",
"}",
"}",
"}",
"for",
"(",
"ii",
"=",
"nots",
".",
"length",
";",
"ii",
"--",
";",
")",
"{",
"not",
"=",
"getSpecificity",
"(",
"nots",
"[",
"ii",
"]",
")",
";",
"for",
"(",
"jj",
"=",
"4",
";",
"jj",
"--",
";",
")",
"{",
"spec",
"[",
"jj",
"]",
"+=",
"not",
"[",
"jj",
"]",
";",
"}",
"}",
"return",
"spec",
";",
"}"
]
| Returns specificity based on selector text and tokens.
@param {String} selector
@param {Array} tokens
@api private. | [
"Returns",
"specificity",
"based",
"on",
"selector",
"text",
"and",
"tokens",
"."
]
| 2d6ddc06ffdc0030f8814cb682a79f914baa4097 | https://github.com/jonkemp/style-selector/blob/2d6ddc06ffdc0030f8814cb682a79f914baa4097/index.js#L32-L87 | train |
stezu/node-stream | lib/consumers/selectVersion.js | selectVersion | function selectVersion(v1, v2) {
return function (firstParam) {
// the v1 API took a stream as the first argument
if (firstParam instanceof stream.Stream) {
return v1.apply(v1, arguments);
}
// the v2 API returns a stream for piping
return v2.apply(v2, arguments);
};
} | javascript | function selectVersion(v1, v2) {
return function (firstParam) {
// the v1 API took a stream as the first argument
if (firstParam instanceof stream.Stream) {
return v1.apply(v1, arguments);
}
// the v2 API returns a stream for piping
return v2.apply(v2, arguments);
};
} | [
"function",
"selectVersion",
"(",
"v1",
",",
"v2",
")",
"{",
"return",
"function",
"(",
"firstParam",
")",
"{",
"if",
"(",
"firstParam",
"instanceof",
"stream",
".",
"Stream",
")",
"{",
"return",
"v1",
".",
"apply",
"(",
"v1",
",",
"arguments",
")",
";",
"}",
"return",
"v2",
".",
"apply",
"(",
"v2",
",",
"arguments",
")",
";",
"}",
";",
"}"
]
| Determines which version of the API should be used for the given input. If
a stream is provided as the first argument use the v1 API, otherwise use
the v2 API.
@private
@param {Function} v1 - Function to call for a v1 API signature.
@param {Function} v2 - Function to call for a v2 API signature.
@returns {Function} - Function which allows either signature. | [
"Determines",
"which",
"version",
"of",
"the",
"API",
"should",
"be",
"used",
"for",
"the",
"given",
"input",
".",
"If",
"a",
"stream",
"is",
"provided",
"as",
"the",
"first",
"argument",
"use",
"the",
"v1",
"API",
"otherwise",
"use",
"the",
"v2",
"API",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/selectVersion.js#L13-L25 | train |
CTRLLA/ctrllr | lib/util.js | evalPromise | function evalPromise(promise) {
// wrap in `countdown`
exports.countdown(promise, timeout)
.then(function(resolvedValue) {
deferred.resolve(resolvedValue);
}).fail(function(err) {
deferred.reject(err);
});
} | javascript | function evalPromise(promise) {
// wrap in `countdown`
exports.countdown(promise, timeout)
.then(function(resolvedValue) {
deferred.resolve(resolvedValue);
}).fail(function(err) {
deferred.reject(err);
});
} | [
"function",
"evalPromise",
"(",
"promise",
")",
"{",
"exports",
".",
"countdown",
"(",
"promise",
",",
"timeout",
")",
".",
"then",
"(",
"function",
"(",
"resolvedValue",
")",
"{",
"deferred",
".",
"resolve",
"(",
"resolvedValue",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}"
]
| waits for a promise, resolves deferred when resolved
@param promise | [
"waits",
"for",
"a",
"promise",
"resolves",
"deferred",
"when",
"resolved"
]
| bf7a58de221dd8a083a2c72b7aa14d1f05c8d350 | https://github.com/CTRLLA/ctrllr/blob/bf7a58de221dd8a083a2c72b7aa14d1f05c8d350/lib/util.js#L255-L263 | train |
aliaksandr-master/node-verifier | lib/verifier.js | function (rules) {
if (!_.isArray(rules)) {
rules = [ rules ];
}
var that = this;
return _.map(rules, function (rule) {
if (typeof rule === 'string') {
return that._parseString(rule);
}
if (_.isPlainObject(rule)) {
return that._parseObject(rule);
}
throw new Error('#V1: invalid rule type, must be string or plain object');
});
} | javascript | function (rules) {
if (!_.isArray(rules)) {
rules = [ rules ];
}
var that = this;
return _.map(rules, function (rule) {
if (typeof rule === 'string') {
return that._parseString(rule);
}
if (_.isPlainObject(rule)) {
return that._parseObject(rule);
}
throw new Error('#V1: invalid rule type, must be string or plain object');
});
} | [
"function",
"(",
"rules",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"rules",
")",
")",
"{",
"rules",
"=",
"[",
"rules",
"]",
";",
"}",
"var",
"that",
"=",
"this",
";",
"return",
"_",
".",
"map",
"(",
"rules",
",",
"function",
"(",
"rule",
")",
"{",
"if",
"(",
"typeof",
"rule",
"===",
"'string'",
")",
"{",
"return",
"that",
".",
"_parseString",
"(",
"rule",
")",
";",
"}",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"rule",
")",
")",
"{",
"return",
"that",
".",
"_parseObject",
"(",
"rule",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"'#V1: invalid rule type, must be string or plain object'",
")",
";",
"}",
")",
";",
"}"
]
| convert raw rules array to Rule array
@method
@param {Array|String} rules - rules for parsing
@this Verifier
@returns {Rule[]} | [
"convert",
"raw",
"rules",
"array",
"to",
"Rule",
"array"
]
| bc6ae67004be0849476490be9a87ddac22c34c1f | https://github.com/aliaksandr-master/node-verifier/blob/bc6ae67004be0849476490be9a87ddac22c34c1f/lib/verifier.js#L52-L70 | train |
|
aliaksandr-master/node-verifier | lib/verifier.js | function (ruleStr) {
var name;
var params = '';
ruleStr.replace(this._RULE_STRING_FORMAT, function ($0, _name, _params) {
name = _name;
params = _params.trim();
});
params = params.length ? this._parseParamsString(params) : null;
return Rule.create(name, params);
} | javascript | function (ruleStr) {
var name;
var params = '';
ruleStr.replace(this._RULE_STRING_FORMAT, function ($0, _name, _params) {
name = _name;
params = _params.trim();
});
params = params.length ? this._parseParamsString(params) : null;
return Rule.create(name, params);
} | [
"function",
"(",
"ruleStr",
")",
"{",
"var",
"name",
";",
"var",
"params",
"=",
"''",
";",
"ruleStr",
".",
"replace",
"(",
"this",
".",
"_RULE_STRING_FORMAT",
",",
"function",
"(",
"$0",
",",
"_name",
",",
"_params",
")",
"{",
"name",
"=",
"_name",
";",
"params",
"=",
"_params",
".",
"trim",
"(",
")",
";",
"}",
")",
";",
"params",
"=",
"params",
".",
"length",
"?",
"this",
".",
"_parseParamsString",
"(",
"params",
")",
":",
"null",
";",
"return",
"Rule",
".",
"create",
"(",
"name",
",",
"params",
")",
";",
"}"
]
| convert string to Rule object
@private
@method
@param {String} ruleStr - string for parsing
@returns {Rule} | [
"convert",
"string",
"to",
"Rule",
"object"
]
| bc6ae67004be0849476490be9a87ddac22c34c1f | https://github.com/aliaksandr-master/node-verifier/blob/bc6ae67004be0849476490be9a87ddac22c34c1f/lib/verifier.js#L100-L112 | train |
|
aliaksandr-master/node-verifier | lib/verifier.js | function (jsonSource) {
var json = null;
try {
json = JSON.parse(jsonSource);
} catch (err) {
json = jsonSource; // string
}
return json;
} | javascript | function (jsonSource) {
var json = null;
try {
json = JSON.parse(jsonSource);
} catch (err) {
json = jsonSource; // string
}
return json;
} | [
"function",
"(",
"jsonSource",
")",
"{",
"var",
"json",
"=",
"null",
";",
"try",
"{",
"json",
"=",
"JSON",
".",
"parse",
"(",
"jsonSource",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"json",
"=",
"jsonSource",
";",
"}",
"return",
"json",
";",
"}"
]
| parse json params
@private
@method
@param {String} jsonSource - json object for parsing
@returns {*} | [
"parse",
"json",
"params"
]
| bc6ae67004be0849476490be9a87ddac22c34c1f | https://github.com/aliaksandr-master/node-verifier/blob/bc6ae67004be0849476490be9a87ddac22c34c1f/lib/verifier.js#L122-L132 | train |
|
Prestaul/listen-up | index.js | eventData | function eventData(emitter) {
return emitter[eventEmitter.EVENT_DATA_PROPERTY] || Object.defineProperty(emitter, eventEmitter.EVENT_DATA_PROPERTY, {
value: {},
enumerable: false
})[eventEmitter.EVENT_DATA_PROPERTY];
} | javascript | function eventData(emitter) {
return emitter[eventEmitter.EVENT_DATA_PROPERTY] || Object.defineProperty(emitter, eventEmitter.EVENT_DATA_PROPERTY, {
value: {},
enumerable: false
})[eventEmitter.EVENT_DATA_PROPERTY];
} | [
"function",
"eventData",
"(",
"emitter",
")",
"{",
"return",
"emitter",
"[",
"eventEmitter",
".",
"EVENT_DATA_PROPERTY",
"]",
"||",
"Object",
".",
"defineProperty",
"(",
"emitter",
",",
"eventEmitter",
".",
"EVENT_DATA_PROPERTY",
",",
"{",
"value",
":",
"{",
"}",
",",
"enumerable",
":",
"false",
"}",
")",
"[",
"eventEmitter",
".",
"EVENT_DATA_PROPERTY",
"]",
";",
"}"
]
| Get event data from an emitter. Lazily create it if it isn't there. | [
"Get",
"event",
"data",
"from",
"an",
"emitter",
".",
"Lazily",
"create",
"it",
"if",
"it",
"isn",
"t",
"there",
"."
]
| 5ea9b8d97e7140e3a8c7e3ebb9d6f2a2407665b8 | https://github.com/Prestaul/listen-up/blob/5ea9b8d97e7140e3a8c7e3ebb9d6f2a2407665b8/index.js#L49-L54 | train |
KTH/kth-node-redis | index.js | _createClient | function _createClient (name, options, callback) {
const log = logger.child({ redis: name })
log.debug('Redis creating client: ' + name)
let isReady = false
const config = {}
deepAssign(config, _defaults, options)
let client = redis.createClient(config)
callback = _once(callback)
_clients[ name ] = client
_clients[ name ].log = log
log.debug({ clients: Object.keys(_clients) }, 'Redis clients')
client.on('error', function (err) {
log.error({ err: err }, 'Redis client error')
callback(err)
})
client.on('warning', function (err) {
log.warn({ err: err }, 'Redis client warning')
})
client.on('connect', function () {
log.debug('Redis connected: ' + name)
})
client.on('ready', function () {
log.debug('Redis client ready: ' + name)
log.debug({ config: config }, 'Redis client config')
log.debug(`Redis server version: ${safeGet(() => client.server_info.redis_version)}`)
isReady = true
callback(null, client)
})
client.on('reconnecting', function () {
log.debug('Redis client reconnecting: ' + name)
})
client.on('end', function () {
log.debug('Redis client end: ' + name)
// Close the connection before removing reference.
client.quit()
client = null
delete _clients[ name ]
log.debug({ clients: Object.keys(_clients) }, 'Redis clients: ' + _clients.length)
if (!isReady) {
callback(new Error('Done - Failed to connect to Redis'))
}
})
} | javascript | function _createClient (name, options, callback) {
const log = logger.child({ redis: name })
log.debug('Redis creating client: ' + name)
let isReady = false
const config = {}
deepAssign(config, _defaults, options)
let client = redis.createClient(config)
callback = _once(callback)
_clients[ name ] = client
_clients[ name ].log = log
log.debug({ clients: Object.keys(_clients) }, 'Redis clients')
client.on('error', function (err) {
log.error({ err: err }, 'Redis client error')
callback(err)
})
client.on('warning', function (err) {
log.warn({ err: err }, 'Redis client warning')
})
client.on('connect', function () {
log.debug('Redis connected: ' + name)
})
client.on('ready', function () {
log.debug('Redis client ready: ' + name)
log.debug({ config: config }, 'Redis client config')
log.debug(`Redis server version: ${safeGet(() => client.server_info.redis_version)}`)
isReady = true
callback(null, client)
})
client.on('reconnecting', function () {
log.debug('Redis client reconnecting: ' + name)
})
client.on('end', function () {
log.debug('Redis client end: ' + name)
// Close the connection before removing reference.
client.quit()
client = null
delete _clients[ name ]
log.debug({ clients: Object.keys(_clients) }, 'Redis clients: ' + _clients.length)
if (!isReady) {
callback(new Error('Done - Failed to connect to Redis'))
}
})
} | [
"function",
"_createClient",
"(",
"name",
",",
"options",
",",
"callback",
")",
"{",
"const",
"log",
"=",
"logger",
".",
"child",
"(",
"{",
"redis",
":",
"name",
"}",
")",
"log",
".",
"debug",
"(",
"'Redis creating client: '",
"+",
"name",
")",
"let",
"isReady",
"=",
"false",
"const",
"config",
"=",
"{",
"}",
"deepAssign",
"(",
"config",
",",
"_defaults",
",",
"options",
")",
"let",
"client",
"=",
"redis",
".",
"createClient",
"(",
"config",
")",
"callback",
"=",
"_once",
"(",
"callback",
")",
"_clients",
"[",
"name",
"]",
"=",
"client",
"_clients",
"[",
"name",
"]",
".",
"log",
"=",
"log",
"log",
".",
"debug",
"(",
"{",
"clients",
":",
"Object",
".",
"keys",
"(",
"_clients",
")",
"}",
",",
"'Redis clients'",
")",
"client",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"{",
"err",
":",
"err",
"}",
",",
"'Redis client error'",
")",
"callback",
"(",
"err",
")",
"}",
")",
"client",
".",
"on",
"(",
"'warning'",
",",
"function",
"(",
"err",
")",
"{",
"log",
".",
"warn",
"(",
"{",
"err",
":",
"err",
"}",
",",
"'Redis client warning'",
")",
"}",
")",
"client",
".",
"on",
"(",
"'connect'",
",",
"function",
"(",
")",
"{",
"log",
".",
"debug",
"(",
"'Redis connected: '",
"+",
"name",
")",
"}",
")",
"client",
".",
"on",
"(",
"'ready'",
",",
"function",
"(",
")",
"{",
"log",
".",
"debug",
"(",
"'Redis client ready: '",
"+",
"name",
")",
"log",
".",
"debug",
"(",
"{",
"config",
":",
"config",
"}",
",",
"'Redis client config'",
")",
"log",
".",
"debug",
"(",
"`",
"${",
"safeGet",
"(",
"(",
")",
"=>",
"client",
".",
"server_info",
".",
"redis_version",
")",
"}",
"`",
")",
"isReady",
"=",
"true",
"callback",
"(",
"null",
",",
"client",
")",
"}",
")",
"client",
".",
"on",
"(",
"'reconnecting'",
",",
"function",
"(",
")",
"{",
"log",
".",
"debug",
"(",
"'Redis client reconnecting: '",
"+",
"name",
")",
"}",
")",
"client",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"log",
".",
"debug",
"(",
"'Redis client end: '",
"+",
"name",
")",
"client",
".",
"quit",
"(",
")",
"client",
"=",
"null",
"delete",
"_clients",
"[",
"name",
"]",
"log",
".",
"debug",
"(",
"{",
"clients",
":",
"Object",
".",
"keys",
"(",
"_clients",
")",
"}",
",",
"'Redis clients: '",
"+",
"_clients",
".",
"length",
")",
"if",
"(",
"!",
"isReady",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'Done - Failed to connect to Redis'",
")",
")",
"}",
"}",
")",
"}"
]
| Creates a Redis client based on the given name and options.
@param {*} name the given name for the Redis client.
@param {*} options the given options for the Redis client.
@param {*} callback | [
"Creates",
"a",
"Redis",
"client",
"based",
"on",
"the",
"given",
"name",
"and",
"options",
"."
]
| 4eabee3a6447ac9f34ca6a378aac397359250ac6 | https://github.com/KTH/kth-node-redis/blob/4eabee3a6447ac9f34ca6a378aac397359250ac6/index.js#L56-L107 | train |
epii-io/epii-node-html5 | lib/AssetRef.js | getFileMIME | function getFileMIME(file) {
var idx = file.lastIndexOf('.')
var ext = idx > -1 ? file.slice(idx) : null
if (ext) ext = ext.toLowerCase().substring(1)
return MIMES[ext] || MIMES.txt
} | javascript | function getFileMIME(file) {
var idx = file.lastIndexOf('.')
var ext = idx > -1 ? file.slice(idx) : null
if (ext) ext = ext.toLowerCase().substring(1)
return MIMES[ext] || MIMES.txt
} | [
"function",
"getFileMIME",
"(",
"file",
")",
"{",
"var",
"idx",
"=",
"file",
".",
"lastIndexOf",
"(",
"'.'",
")",
"var",
"ext",
"=",
"idx",
">",
"-",
"1",
"?",
"file",
".",
"slice",
"(",
"idx",
")",
":",
"null",
"if",
"(",
"ext",
")",
"ext",
"=",
"ext",
".",
"toLowerCase",
"(",
")",
".",
"substring",
"(",
"1",
")",
"return",
"MIMES",
"[",
"ext",
"]",
"||",
"MIMES",
".",
"txt",
"}"
]
| get MIME by file name
@param {String} file
@return {String} | [
"get",
"MIME",
"by",
"file",
"name"
]
| 69ea36c2be19ac95536925fde4eab9f0e1b16151 | https://github.com/epii-io/epii-node-html5/blob/69ea36c2be19ac95536925fde4eab9f0e1b16151/lib/AssetRef.js#L24-L29 | train |
Kaniwani/KanaWana | src/packages/kanawana/utils/isCharEnglishPunctuation.js | isCharEnglishPunctuation | function isCharEnglishPunctuation(char = '') {
if (isEmpty(char)) return false;
return ENGLISH_PUNCTUATION_RANGES.some(([start, end]) => isCharInRange(char, start, end));
} | javascript | function isCharEnglishPunctuation(char = '') {
if (isEmpty(char)) return false;
return ENGLISH_PUNCTUATION_RANGES.some(([start, end]) => isCharInRange(char, start, end));
} | [
"function",
"isCharEnglishPunctuation",
"(",
"char",
"=",
"''",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"char",
")",
")",
"return",
"false",
";",
"return",
"ENGLISH_PUNCTUATION_RANGES",
".",
"some",
"(",
"(",
"[",
"start",
",",
"end",
"]",
")",
"=>",
"isCharInRange",
"(",
"char",
",",
"start",
",",
"end",
")",
")",
";",
"}"
]
| Tests a character. Returns true if the character is considered English punctuation.
@param {String} char character string to test
@return {Boolean} | [
"Tests",
"a",
"character",
".",
"Returns",
"true",
"if",
"the",
"character",
"is",
"considered",
"English",
"punctuation",
"."
]
| 7084d6c50e68023c225f663f994544f693ff8d3a | https://github.com/Kaniwani/KanaWana/blob/7084d6c50e68023c225f663f994544f693ff8d3a/src/packages/kanawana/utils/isCharEnglishPunctuation.js#L10-L13 | train |
theprotein/shortcss | lib/index.js | expand | function expand(property, value, recurse) {
ASSERT(arguments.length, 'property argument is required');
if (arguments.length < 3) {
if (typeof value === 'boolean') {
recurse = value;
value = undefined;
} else {
recurse = true;
}
}
var undefvalue = typeof value === 'undefined';
return undefvalue?
expandAsArray(property, recurse)
: expandAsObject(property, value, recurse);
} | javascript | function expand(property, value, recurse) {
ASSERT(arguments.length, 'property argument is required');
if (arguments.length < 3) {
if (typeof value === 'boolean') {
recurse = value;
value = undefined;
} else {
recurse = true;
}
}
var undefvalue = typeof value === 'undefined';
return undefvalue?
expandAsArray(property, recurse)
: expandAsObject(property, value, recurse);
} | [
"function",
"expand",
"(",
"property",
",",
"value",
",",
"recurse",
")",
"{",
"ASSERT",
"(",
"arguments",
".",
"length",
",",
"'property argument is required'",
")",
";",
"if",
"(",
"arguments",
".",
"length",
"<",
"3",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'boolean'",
")",
"{",
"recurse",
"=",
"value",
";",
"value",
"=",
"undefined",
";",
"}",
"else",
"{",
"recurse",
"=",
"true",
";",
"}",
"}",
"var",
"undefvalue",
"=",
"typeof",
"value",
"===",
"'undefined'",
";",
"return",
"undefvalue",
"?",
"expandAsArray",
"(",
"property",
",",
"recurse",
")",
":",
"expandAsObject",
"(",
"property",
",",
"value",
",",
"recurse",
")",
";",
"}"
]
| Expand a property to an array of parts or property and value to object
@param {string} property
@param {?string} value
@param {?boolean} recurse
@returns {Array|Object} | [
"Expand",
"a",
"property",
"to",
"an",
"array",
"of",
"parts",
"or",
"property",
"and",
"value",
"to",
"object"
]
| 8c727536eca12479d3ef428058d27b6604750bb7 | https://github.com/theprotein/shortcss/blob/8c727536eca12479d3ef428058d27b6604750bb7/lib/index.js#L16-L33 | train |
dominicbarnes/node-siren-writer | index.js | normalizeEntity | function normalizeEntity(base, input) {
if (!input) return {};
var result = Object.assign(clone(input), {
class: normalizeClass(input.class),
properties: normalizeProperties(input.properties),
entities: normalizeEntities(base, input.entities),
links: normalizeLinks(base, input.links),
actions: normalizeActions(base, input.actions),
title: input.title
});
// strip undefined values from the result
return filter(result, function (v) {
return typeof v !== 'undefined';
});
} | javascript | function normalizeEntity(base, input) {
if (!input) return {};
var result = Object.assign(clone(input), {
class: normalizeClass(input.class),
properties: normalizeProperties(input.properties),
entities: normalizeEntities(base, input.entities),
links: normalizeLinks(base, input.links),
actions: normalizeActions(base, input.actions),
title: input.title
});
// strip undefined values from the result
return filter(result, function (v) {
return typeof v !== 'undefined';
});
} | [
"function",
"normalizeEntity",
"(",
"base",
",",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
"{",
"}",
";",
"var",
"result",
"=",
"Object",
".",
"assign",
"(",
"clone",
"(",
"input",
")",
",",
"{",
"class",
":",
"normalizeClass",
"(",
"input",
".",
"class",
")",
",",
"properties",
":",
"normalizeProperties",
"(",
"input",
".",
"properties",
")",
",",
"entities",
":",
"normalizeEntities",
"(",
"base",
",",
"input",
".",
"entities",
")",
",",
"links",
":",
"normalizeLinks",
"(",
"base",
",",
"input",
".",
"links",
")",
",",
"actions",
":",
"normalizeActions",
"(",
"base",
",",
"input",
".",
"actions",
")",
",",
"title",
":",
"input",
".",
"title",
"}",
")",
";",
"return",
"filter",
"(",
"result",
",",
"function",
"(",
"v",
")",
"{",
"return",
"typeof",
"v",
"!==",
"'undefined'",
";",
"}",
")",
";",
"}"
]
| Takes the `input` entity object and normalizes it into a valid siren object.
@param {String} base The base URL for this API.
@param {Object} input The entity object to normalize.
@return {Object} | [
"Takes",
"the",
"input",
"entity",
"object",
"and",
"normalizes",
"it",
"into",
"a",
"valid",
"siren",
"object",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L32-L48 | train |
dominicbarnes/node-siren-writer | index.js | normalizeRel | function normalizeRel(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).map(function (rel) {
return rel in iana ? rel : url.resolve(base, rel);
});
} | javascript | function normalizeRel(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).map(function (rel) {
return rel in iana ? rel : url.resolve(base, rel);
});
} | [
"function",
"normalizeRel",
"(",
"base",
",",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"input",
"=",
"[",
"input",
"]",
";",
"return",
"flatten",
"(",
"input",
")",
".",
"map",
"(",
"function",
"(",
"rel",
")",
"{",
"return",
"rel",
"in",
"iana",
"?",
"rel",
":",
"url",
".",
"resolve",
"(",
"base",
",",
"rel",
")",
";",
"}",
")",
";",
"}"
]
| Takes the `input` rel value and normalizes it into a valid array.
@param {String} base The base URL for this API.
@param {Mixed} input The rel value to normalize.
@return {Array} | [
"Takes",
"the",
"input",
"rel",
"value",
"and",
"normalizes",
"it",
"into",
"a",
"valid",
"array",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L57-L64 | train |
dominicbarnes/node-siren-writer | index.js | normalizeProperties | function normalizeProperties(input) {
if (!input) return;
if (Array.isArray(input)) {
return flatten(input).reduce(function (acc, o) {
return Object.assign(acc, o);
}, {});
}
return clone(input);
} | javascript | function normalizeProperties(input) {
if (!input) return;
if (Array.isArray(input)) {
return flatten(input).reduce(function (acc, o) {
return Object.assign(acc, o);
}, {});
}
return clone(input);
} | [
"function",
"normalizeProperties",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"{",
"return",
"flatten",
"(",
"input",
")",
".",
"reduce",
"(",
"function",
"(",
"acc",
",",
"o",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"acc",
",",
"o",
")",
";",
"}",
",",
"{",
"}",
")",
";",
"}",
"return",
"clone",
"(",
"input",
")",
";",
"}"
]
| Takes the `input` properties value and normalizes it into a single object.
@param {Mixed} input The properties value to normalize.
@return {Object} | [
"Takes",
"the",
"input",
"properties",
"value",
"and",
"normalizes",
"it",
"into",
"a",
"single",
"object",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L95-L105 | train |
dominicbarnes/node-siren-writer | index.js | normalizeEntities | function normalizeEntities(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(function (entity) {
assert(entity.rel, 'sub-entities must have a rel');
var ret = normalizeEntity(base, entity);
ret.rel = normalizeRel(base, entity.rel);
if (entity.href) ret.href = normalizeHref(base, entity.href);
return ret;
});
} | javascript | function normalizeEntities(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(function (entity) {
assert(entity.rel, 'sub-entities must have a rel');
var ret = normalizeEntity(base, entity);
ret.rel = normalizeRel(base, entity.rel);
if (entity.href) ret.href = normalizeHref(base, entity.href);
return ret;
});
} | [
"function",
"normalizeEntities",
"(",
"base",
",",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"input",
"=",
"[",
"input",
"]",
";",
"return",
"flatten",
"(",
"input",
")",
".",
"filter",
"(",
"Boolean",
")",
".",
"map",
"(",
"function",
"(",
"entity",
")",
"{",
"assert",
"(",
"entity",
".",
"rel",
",",
"'sub-entities must have a rel'",
")",
";",
"var",
"ret",
"=",
"normalizeEntity",
"(",
"base",
",",
"entity",
")",
";",
"ret",
".",
"rel",
"=",
"normalizeRel",
"(",
"base",
",",
"entity",
".",
"rel",
")",
";",
"if",
"(",
"entity",
".",
"href",
")",
"ret",
".",
"href",
"=",
"normalizeHref",
"(",
"base",
",",
"entity",
".",
"href",
")",
";",
"return",
"ret",
";",
"}",
")",
";",
"}"
]
| Takes the `input` entities value and normalizes it into a single array.
@param {String} base The base URL for this API.
@param {Mixed} input The entities value to normalize.
@return {Array} | [
"Takes",
"the",
"input",
"entities",
"value",
"and",
"normalizes",
"it",
"into",
"a",
"single",
"array",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L114-L127 | train |
dominicbarnes/node-siren-writer | index.js | normalizeLinks | function normalizeLinks(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(function (link) {
return normalizeLink(base, link);
});
} | javascript | function normalizeLinks(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(function (link) {
return normalizeLink(base, link);
});
} | [
"function",
"normalizeLinks",
"(",
"base",
",",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"input",
"=",
"[",
"input",
"]",
";",
"return",
"flatten",
"(",
"input",
")",
".",
"filter",
"(",
"Boolean",
")",
".",
"map",
"(",
"function",
"(",
"link",
")",
"{",
"return",
"normalizeLink",
"(",
"base",
",",
"link",
")",
";",
"}",
")",
";",
"}"
]
| Takes the `input` links value and normalizes it into a single array.
@param {String} base The base URL for this API.
@param {Object} input The links value to normalize.
@return {Array} | [
"Takes",
"the",
"input",
"links",
"value",
"and",
"normalizes",
"it",
"into",
"a",
"single",
"array",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L158-L165 | train |
dominicbarnes/node-siren-writer | index.js | normalizeAction | function normalizeAction(base, input) {
assert(input.name, 'actions must have a name');
assert(input.href, 'actions must have an href');
var ret = clone(input);
ret.href = normalizeHref(base, input.href);
if (input.method) ret.method = normalizeMethod(input.method);
var cls = normalizeClass(input.class);
if (cls) ret.class = cls;
var fields = normalizeFields(input.fields);
if (fields) ret.fields = fields;
return ret;
} | javascript | function normalizeAction(base, input) {
assert(input.name, 'actions must have a name');
assert(input.href, 'actions must have an href');
var ret = clone(input);
ret.href = normalizeHref(base, input.href);
if (input.method) ret.method = normalizeMethod(input.method);
var cls = normalizeClass(input.class);
if (cls) ret.class = cls;
var fields = normalizeFields(input.fields);
if (fields) ret.fields = fields;
return ret;
} | [
"function",
"normalizeAction",
"(",
"base",
",",
"input",
")",
"{",
"assert",
"(",
"input",
".",
"name",
",",
"'actions must have a name'",
")",
";",
"assert",
"(",
"input",
".",
"href",
",",
"'actions must have an href'",
")",
";",
"var",
"ret",
"=",
"clone",
"(",
"input",
")",
";",
"ret",
".",
"href",
"=",
"normalizeHref",
"(",
"base",
",",
"input",
".",
"href",
")",
";",
"if",
"(",
"input",
".",
"method",
")",
"ret",
".",
"method",
"=",
"normalizeMethod",
"(",
"input",
".",
"method",
")",
";",
"var",
"cls",
"=",
"normalizeClass",
"(",
"input",
".",
"class",
")",
";",
"if",
"(",
"cls",
")",
"ret",
".",
"class",
"=",
"cls",
";",
"var",
"fields",
"=",
"normalizeFields",
"(",
"input",
".",
"fields",
")",
";",
"if",
"(",
"fields",
")",
"ret",
".",
"fields",
"=",
"fields",
";",
"return",
"ret",
";",
"}"
]
| Takes the `input` action value and normalizes it into a single object.
@param {String} base The base URL for this API.
@param {Object} input The action value to normalize.
@return {Object} | [
"Takes",
"the",
"input",
"action",
"value",
"and",
"normalizes",
"it",
"into",
"a",
"single",
"object",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L185-L201 | train |
dominicbarnes/node-siren-writer | index.js | normalizeActions | function normalizeActions(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(function (action) {
return normalizeAction(base, action);
});
} | javascript | function normalizeActions(base, input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(function (action) {
return normalizeAction(base, action);
});
} | [
"function",
"normalizeActions",
"(",
"base",
",",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"input",
"=",
"[",
"input",
"]",
";",
"return",
"flatten",
"(",
"input",
")",
".",
"filter",
"(",
"Boolean",
")",
".",
"map",
"(",
"function",
"(",
"action",
")",
"{",
"return",
"normalizeAction",
"(",
"base",
",",
"action",
")",
";",
"}",
")",
";",
"}"
]
| Takes the `input` actions value and normalizes it into a single array.
@param {String} base The base URL for this API.
@param {Mixed} input The links value to normalize.
@return {Array} | [
"Takes",
"the",
"input",
"actions",
"value",
"and",
"normalizes",
"it",
"into",
"a",
"single",
"array",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L210-L217 | train |
dominicbarnes/node-siren-writer | index.js | normalizeFields | function normalizeFields(input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(normalizeField);
} | javascript | function normalizeFields(input) {
if (!input) return;
if (!Array.isArray(input)) input = [ input ];
return flatten(input).filter(Boolean).map(normalizeField);
} | [
"function",
"normalizeFields",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"input",
")",
")",
"input",
"=",
"[",
"input",
"]",
";",
"return",
"flatten",
"(",
"input",
")",
".",
"filter",
"(",
"Boolean",
")",
".",
"map",
"(",
"normalizeField",
")",
";",
"}"
]
| Takes the `input` fields value and normalizes it into a single array.
@param {Mixed} input The links value to normalize.
@return {Array} | [
"Takes",
"the",
"input",
"fields",
"value",
"and",
"normalizes",
"it",
"into",
"a",
"single",
"array",
"."
]
| d00b6b32bc8a755c3ae98a6382790d348c7aaffa | https://github.com/dominicbarnes/node-siren-writer/blob/d00b6b32bc8a755c3ae98a6382790d348c7aaffa/index.js#L242-L247 | train |
EikosPartners/scalejs | dist/scalejs.core.js | registerExtension | function registerExtension(extension) {
try {
var ext; // Actual extension
if (is(extension, 'buildCore', 'function')) {
// If extension has buildCore function then give it an instance of the core.
extension.buildCore(self);
addOne(extensions, extension);
return; // No need to extend as that will be handled in buildCore
}
if (is(extension, 'function')) {
// If extension is a function then give it an instance of the core.
ext = extension(self);
} else if (has(extension, 'core')) {
// If extension has `core` property then extend core with it.
ext = extension.core;
} else {
// Otherwise extend core with the extension itself.
ext = extension;
}
if (ext) {
extend(self, ext);
addOne(extensions, extension);
}
} catch (ex) {
error('Fatal error during application initialization. ', 'Failed to build core with extension "', extension, 'See following exception for more details.', ex);
}
return extension;
} | javascript | function registerExtension(extension) {
try {
var ext; // Actual extension
if (is(extension, 'buildCore', 'function')) {
// If extension has buildCore function then give it an instance of the core.
extension.buildCore(self);
addOne(extensions, extension);
return; // No need to extend as that will be handled in buildCore
}
if (is(extension, 'function')) {
// If extension is a function then give it an instance of the core.
ext = extension(self);
} else if (has(extension, 'core')) {
// If extension has `core` property then extend core with it.
ext = extension.core;
} else {
// Otherwise extend core with the extension itself.
ext = extension;
}
if (ext) {
extend(self, ext);
addOne(extensions, extension);
}
} catch (ex) {
error('Fatal error during application initialization. ', 'Failed to build core with extension "', extension, 'See following exception for more details.', ex);
}
return extension;
} | [
"function",
"registerExtension",
"(",
"extension",
")",
"{",
"try",
"{",
"var",
"ext",
";",
"if",
"(",
"is",
"(",
"extension",
",",
"'buildCore'",
",",
"'function'",
")",
")",
"{",
"extension",
".",
"buildCore",
"(",
"self",
")",
";",
"addOne",
"(",
"extensions",
",",
"extension",
")",
";",
"return",
";",
"}",
"if",
"(",
"is",
"(",
"extension",
",",
"'function'",
")",
")",
"{",
"ext",
"=",
"extension",
"(",
"self",
")",
";",
"}",
"else",
"if",
"(",
"has",
"(",
"extension",
",",
"'core'",
")",
")",
"{",
"ext",
"=",
"extension",
".",
"core",
";",
"}",
"else",
"{",
"ext",
"=",
"extension",
";",
"}",
"if",
"(",
"ext",
")",
"{",
"extend",
"(",
"self",
",",
"ext",
")",
";",
"addOne",
"(",
"extensions",
",",
"extension",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"error",
"(",
"'Fatal error during application initialization. '",
",",
"'Failed to build core with extension \"'",
",",
"extension",
",",
"'See following exception for more details.'",
",",
"ex",
")",
";",
"}",
"return",
"extension",
";",
"}"
]
| Registers an extension to the sandbox
@param {Function|Object} extension function to create the extension or
object representing the extension
@memberOf core
Provides core functionality of scalejs
@namespace scalejs.core
@module core
/*global define | [
"Registers",
"an",
"extension",
"to",
"the",
"sandbox"
]
| 115d0eac1a90aebb54f50485ed92de25165f9c30 | https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.core.js#L71-L102 | train |
EikosPartners/scalejs | dist/scalejs.core.js | buildSandbox | function buildSandbox(id) {
if (!has(id)) {
throw new Error('Sandbox name is required to build a sandbox.');
}
// Create module instance specific sandbox
var sandbox = {
type: self.type,
object: self.object,
array: self.array,
log: self.log
};
// Add extensions to sandbox
extensions.forEach(function (extension) {
try {
// If extension has buildSandbox method use it to build sandbox
if (is(extension, 'buildSandbox', 'function')) {
extension.buildSandbox(sandbox);
}
// If extension has a sandbox object add it
else if (has(extension, 'sandbox')) {
extend(sandbox, extension.sandbox);
}
// Otherwise extend the sandbox with the extension
else {
extend(sandbox, extension);
}
} catch (ex) {
error('Fatal error during application initialization. ', 'Failed to build sandbox with extension "', extension, 'See following exception for more details.', ex);
throw ex;
}
});
return sandbox;
} | javascript | function buildSandbox(id) {
if (!has(id)) {
throw new Error('Sandbox name is required to build a sandbox.');
}
// Create module instance specific sandbox
var sandbox = {
type: self.type,
object: self.object,
array: self.array,
log: self.log
};
// Add extensions to sandbox
extensions.forEach(function (extension) {
try {
// If extension has buildSandbox method use it to build sandbox
if (is(extension, 'buildSandbox', 'function')) {
extension.buildSandbox(sandbox);
}
// If extension has a sandbox object add it
else if (has(extension, 'sandbox')) {
extend(sandbox, extension.sandbox);
}
// Otherwise extend the sandbox with the extension
else {
extend(sandbox, extension);
}
} catch (ex) {
error('Fatal error during application initialization. ', 'Failed to build sandbox with extension "', extension, 'See following exception for more details.', ex);
throw ex;
}
});
return sandbox;
} | [
"function",
"buildSandbox",
"(",
"id",
")",
"{",
"if",
"(",
"!",
"has",
"(",
"id",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Sandbox name is required to build a sandbox.'",
")",
";",
"}",
"var",
"sandbox",
"=",
"{",
"type",
":",
"self",
".",
"type",
",",
"object",
":",
"self",
".",
"object",
",",
"array",
":",
"self",
".",
"array",
",",
"log",
":",
"self",
".",
"log",
"}",
";",
"extensions",
".",
"forEach",
"(",
"function",
"(",
"extension",
")",
"{",
"try",
"{",
"if",
"(",
"is",
"(",
"extension",
",",
"'buildSandbox'",
",",
"'function'",
")",
")",
"{",
"extension",
".",
"buildSandbox",
"(",
"sandbox",
")",
";",
"}",
"else",
"if",
"(",
"has",
"(",
"extension",
",",
"'sandbox'",
")",
")",
"{",
"extend",
"(",
"sandbox",
",",
"extension",
".",
"sandbox",
")",
";",
"}",
"else",
"{",
"extend",
"(",
"sandbox",
",",
"extension",
")",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"error",
"(",
"'Fatal error during application initialization. '",
",",
"'Failed to build sandbox with extension \"'",
",",
"extension",
",",
"'See following exception for more details.'",
",",
"ex",
")",
";",
"throw",
"ex",
";",
"}",
"}",
")",
";",
"return",
"sandbox",
";",
"}"
]
| Builds a sandbox from the current list of extensions
@param {String} id identifier for the sandbox
@memberOf core
@return {Object} object representing the built sandbox | [
"Builds",
"a",
"sandbox",
"from",
"the",
"current",
"list",
"of",
"extensions"
]
| 115d0eac1a90aebb54f50485ed92de25165f9c30 | https://github.com/EikosPartners/scalejs/blob/115d0eac1a90aebb54f50485ed92de25165f9c30/dist/scalejs.core.js#L111-L149 | train |
Maples7/express-final-response | lib/index.js | handleErrorRequest | function handleErrorRequest(result, req, res) {
const err = _.isError(result.msg) ? result.msg : result;
const finalResp = STATUSES[result.status] || STATUSES[err.message] || STATUSES['error'];
finalResp.msg = err.message;
if (isDebug) finalResp.ext = err;
logRequestError(err, req, finalResp);
res.status(finalResp.statusCode);
const view = result.view || errorView;
if (view) {
returnHTML(view, finalResp, res);
} else {
returnJSON(finalResp, res);
}
} | javascript | function handleErrorRequest(result, req, res) {
const err = _.isError(result.msg) ? result.msg : result;
const finalResp = STATUSES[result.status] || STATUSES[err.message] || STATUSES['error'];
finalResp.msg = err.message;
if (isDebug) finalResp.ext = err;
logRequestError(err, req, finalResp);
res.status(finalResp.statusCode);
const view = result.view || errorView;
if (view) {
returnHTML(view, finalResp, res);
} else {
returnJSON(finalResp, res);
}
} | [
"function",
"handleErrorRequest",
"(",
"result",
",",
"req",
",",
"res",
")",
"{",
"const",
"err",
"=",
"_",
".",
"isError",
"(",
"result",
".",
"msg",
")",
"?",
"result",
".",
"msg",
":",
"result",
";",
"const",
"finalResp",
"=",
"STATUSES",
"[",
"result",
".",
"status",
"]",
"||",
"STATUSES",
"[",
"err",
".",
"message",
"]",
"||",
"STATUSES",
"[",
"'error'",
"]",
";",
"finalResp",
".",
"msg",
"=",
"err",
".",
"message",
";",
"if",
"(",
"isDebug",
")",
"finalResp",
".",
"ext",
"=",
"err",
";",
"logRequestError",
"(",
"err",
",",
"req",
",",
"finalResp",
")",
";",
"res",
".",
"status",
"(",
"finalResp",
".",
"statusCode",
")",
";",
"const",
"view",
"=",
"result",
".",
"view",
"||",
"errorView",
";",
"if",
"(",
"view",
")",
"{",
"returnHTML",
"(",
"view",
",",
"finalResp",
",",
"res",
")",
";",
"}",
"else",
"{",
"returnJSON",
"(",
"finalResp",
",",
"res",
")",
";",
"}",
"}"
]
| handle result according to its type | [
"handle",
"result",
"according",
"to",
"its",
"type"
]
| fd4d413ba5254adc9bfa86ed4ee204374d5573a8 | https://github.com/Maples7/express-final-response/blob/fd4d413ba5254adc9bfa86ed4ee204374d5573a8/lib/index.js#L84-L99 | train |
miniplug/plug-login | src/index.js | json | function json (opts) {
return {
...opts,
headers: {
...opts.headers,
'content-type': 'application/json'
},
body: JSON.stringify(opts.body)
}
} | javascript | function json (opts) {
return {
...opts,
headers: {
...opts.headers,
'content-type': 'application/json'
},
body: JSON.stringify(opts.body)
}
} | [
"function",
"json",
"(",
"opts",
")",
"{",
"return",
"{",
"...",
"opts",
",",
"headers",
":",
"{",
"...",
"opts",
".",
"headers",
",",
"'content-type'",
":",
"'application/json'",
"}",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"opts",
".",
"body",
")",
"}",
"}"
]
| Enhance a `fetch` options object to use a JSON body when sending data. | [
"Enhance",
"a",
"fetch",
"options",
"object",
"to",
"use",
"a",
"JSON",
"body",
"when",
"sending",
"data",
"."
]
| 6568bca8daaabc385dce92d7e86086ae1c6a5b79 | https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L8-L17 | train |
miniplug/plug-login | src/index.js | error | function error (response, status, message) {
let e = new Error(`${status}: ${message}`)
e.response = response
e.status = status
return e
} | javascript | function error (response, status, message) {
let e = new Error(`${status}: ${message}`)
e.response = response
e.status = status
return e
} | [
"function",
"error",
"(",
"response",
",",
"status",
",",
"message",
")",
"{",
"let",
"e",
"=",
"new",
"Error",
"(",
"`",
"${",
"status",
"}",
"${",
"message",
"}",
"`",
")",
"e",
".",
"response",
"=",
"response",
"e",
".",
"status",
"=",
"status",
"return",
"e",
"}"
]
| Create an HTTP response error. | [
"Create",
"an",
"HTTP",
"response",
"error",
"."
]
| 6568bca8daaabc385dce92d7e86086ae1c6a5b79 | https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L20-L25 | train |
miniplug/plug-login | src/index.js | getJSON | function getJSON (response) {
return response.json().then((body) => {
if (body.status !== 'ok') {
throw error(response, body.status, body.data[0])
}
return body
})
} | javascript | function getJSON (response) {
return response.json().then((body) => {
if (body.status !== 'ok') {
throw error(response, body.status, body.data[0])
}
return body
})
} | [
"function",
"getJSON",
"(",
"response",
")",
"{",
"return",
"response",
".",
"json",
"(",
")",
".",
"then",
"(",
"(",
"body",
")",
"=>",
"{",
"if",
"(",
"body",
".",
"status",
"!==",
"'ok'",
")",
"{",
"throw",
"error",
"(",
"response",
",",
"body",
".",
"status",
",",
"body",
".",
"data",
"[",
"0",
"]",
")",
"}",
"return",
"body",
"}",
")",
"}"
]
| Get the JSON response from the plug.dj API, throwing if it is an error response. | [
"Get",
"the",
"JSON",
"response",
"from",
"the",
"plug",
".",
"dj",
"API",
"throwing",
"if",
"it",
"is",
"an",
"error",
"response",
"."
]
| 6568bca8daaabc385dce92d7e86086ae1c6a5b79 | https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L28-L35 | train |
miniplug/plug-login | src/index.js | getSessionCookie | function getSessionCookie (headers) {
if (!headers) return
const cookie = parse(headers)
if (cookie.session) return cookie.session
} | javascript | function getSessionCookie (headers) {
if (!headers) return
const cookie = parse(headers)
if (cookie.session) return cookie.session
} | [
"function",
"getSessionCookie",
"(",
"headers",
")",
"{",
"if",
"(",
"!",
"headers",
")",
"return",
"const",
"cookie",
"=",
"parse",
"(",
"headers",
")",
"if",
"(",
"cookie",
".",
"session",
")",
"return",
"cookie",
".",
"session",
"}"
]
| Extract the session cookie value from an array of set-cookie headers. | [
"Extract",
"the",
"session",
"cookie",
"value",
"from",
"an",
"array",
"of",
"set",
"-",
"cookie",
"headers",
"."
]
| 6568bca8daaabc385dce92d7e86086ae1c6a5b79 | https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L38-L42 | train |
miniplug/plug-login | src/index.js | getCsrf | function getCsrf (opts) {
// for testing
if (opts._simulateMaintenance) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Could not find CSRF token'))
}, 300)
})
}
return fetch(`${opts.host}/_/mobile/init`, json(opts))
.then((response) => props({
csrf: getJSON(response).then((body) => body.data[0].c),
session: getSessionCookie(response.headers.get('set-cookie'))
}))
} | javascript | function getCsrf (opts) {
// for testing
if (opts._simulateMaintenance) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Could not find CSRF token'))
}, 300)
})
}
return fetch(`${opts.host}/_/mobile/init`, json(opts))
.then((response) => props({
csrf: getJSON(response).then((body) => body.data[0].c),
session: getSessionCookie(response.headers.get('set-cookie'))
}))
} | [
"function",
"getCsrf",
"(",
"opts",
")",
"{",
"if",
"(",
"opts",
".",
"_simulateMaintenance",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Could not find CSRF token'",
")",
")",
"}",
",",
"300",
")",
"}",
")",
"}",
"return",
"fetch",
"(",
"`",
"${",
"opts",
".",
"host",
"}",
"`",
",",
"json",
"(",
"opts",
")",
")",
".",
"then",
"(",
"(",
"response",
")",
"=>",
"props",
"(",
"{",
"csrf",
":",
"getJSON",
"(",
"response",
")",
".",
"then",
"(",
"(",
"body",
")",
"=>",
"body",
".",
"data",
"[",
"0",
"]",
".",
"c",
")",
",",
"session",
":",
"getSessionCookie",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'set-cookie'",
")",
")",
"}",
")",
")",
"}"
]
| Get a CSRF token and session cookie for logging into plug.dj from their main page. Without the CSRF token, login requests will be rejected. | [
"Get",
"a",
"CSRF",
"token",
"and",
"session",
"cookie",
"for",
"logging",
"into",
"plug",
".",
"dj",
"from",
"their",
"main",
"page",
".",
"Without",
"the",
"CSRF",
"token",
"login",
"requests",
"will",
"be",
"rejected",
"."
]
| 6568bca8daaabc385dce92d7e86086ae1c6a5b79 | https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L63-L78 | train |
miniplug/plug-login | src/index.js | doLogin | function doLogin (opts, csrf, email, password) {
return fetch(`${opts.host}/_/auth/login`, json({
...opts,
method: 'post',
body: { csrf, email, password }
})).then((response) => props({
session: getSessionCookie(response.headers.get('set-cookie')),
body: getJSON(response)
}))
} | javascript | function doLogin (opts, csrf, email, password) {
return fetch(`${opts.host}/_/auth/login`, json({
...opts,
method: 'post',
body: { csrf, email, password }
})).then((response) => props({
session: getSessionCookie(response.headers.get('set-cookie')),
body: getJSON(response)
}))
} | [
"function",
"doLogin",
"(",
"opts",
",",
"csrf",
",",
"email",
",",
"password",
")",
"{",
"return",
"fetch",
"(",
"`",
"${",
"opts",
".",
"host",
"}",
"`",
",",
"json",
"(",
"{",
"...",
"opts",
",",
"method",
":",
"'post'",
",",
"body",
":",
"{",
"csrf",
",",
"email",
",",
"password",
"}",
"}",
")",
")",
".",
"then",
"(",
"(",
"response",
")",
"=>",
"props",
"(",
"{",
"session",
":",
"getSessionCookie",
"(",
"response",
".",
"headers",
".",
"get",
"(",
"'set-cookie'",
")",
")",
",",
"body",
":",
"getJSON",
"(",
"response",
")",
"}",
")",
")",
"}"
]
| Log in to plug.dj with an email address and password. `opts` must contain headers with a session cookie. | [
"Log",
"in",
"to",
"plug",
".",
"dj",
"with",
"an",
"email",
"address",
"and",
"password",
".",
"opts",
"must",
"contain",
"headers",
"with",
"a",
"session",
"cookie",
"."
]
| 6568bca8daaabc385dce92d7e86086ae1c6a5b79 | https://github.com/miniplug/plug-login/blob/6568bca8daaabc385dce92d7e86086ae1c6a5b79/src/index.js#L82-L91 | train |
jfrazx/mongoose-enumvalues | index.js | modifyProperties | function modifyProperties(schema, paths) {
if (!paths.length) { return; }
const options = paths[0].options;
/**
* Modify document enum (string) properties to an object, with (original) value and
* values (enumValues)
*
*/
function populatePropertyFor (documents, next) {
if (this._mongooseOptions.lean) {
asArray(documents).forEach(function(doc) {
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
const insert = { values: path.enumValues };
const value = doc[key];
insert.value = determineValue(splitted, value);
doc[key] = nest(splitted, insert);
} catch (error) { return next(error); }
});
});
}
next();
}
/**
* If a document is modified, this method will locate the value on updates and assign it to the
* appropriate property, allowing for proper validations later.
* @param <Function>: next - function that notifies mongoose this middleware is complete
*/
function reformatUpdateProperty(next) {
const document = this._update['$set'];
if (document) {
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
if (document[key] === undefined) { return; }
const value = determineValue(splitted, document[key]);
document[key] = nest(splitted, value);
} catch (error) { return next(error); }
});
}
next();
}
/**
* If a document is modified, this method will locate the value before save/validation and assign it to the
* appropriate property, allowing for proper validations later.
* @param <Function>: next - function that notifies mongoose this middleware is complete
*/
function reformatProperty(next) {
const self = this;
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
const value = determineValue(splitted, self[key]);
self[key] = nest(splitted, value);
} catch (error) { return next(error); }
});
next();
}
/**
* Setup handlers for modifying properties -- ['find', 'findOne']
*/
options.modify.on.forEach(function(on) {
schema.post(on, populatePropertyFor);
});
schema.pre((options.validateBeforeSave ? 'validate' : 'save'), reformatProperty);
/*
* Setup handlers for updating documents (there may be more to consider)
*/
['update', 'findOneAndUpdate'].forEach(function(on) {
schema.pre(on, reformatUpdateProperty);
});
} | javascript | function modifyProperties(schema, paths) {
if (!paths.length) { return; }
const options = paths[0].options;
/**
* Modify document enum (string) properties to an object, with (original) value and
* values (enumValues)
*
*/
function populatePropertyFor (documents, next) {
if (this._mongooseOptions.lean) {
asArray(documents).forEach(function(doc) {
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
const insert = { values: path.enumValues };
const value = doc[key];
insert.value = determineValue(splitted, value);
doc[key] = nest(splitted, insert);
} catch (error) { return next(error); }
});
});
}
next();
}
/**
* If a document is modified, this method will locate the value on updates and assign it to the
* appropriate property, allowing for proper validations later.
* @param <Function>: next - function that notifies mongoose this middleware is complete
*/
function reformatUpdateProperty(next) {
const document = this._update['$set'];
if (document) {
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
if (document[key] === undefined) { return; }
const value = determineValue(splitted, document[key]);
document[key] = nest(splitted, value);
} catch (error) { return next(error); }
});
}
next();
}
/**
* If a document is modified, this method will locate the value before save/validation and assign it to the
* appropriate property, allowing for proper validations later.
* @param <Function>: next - function that notifies mongoose this middleware is complete
*/
function reformatProperty(next) {
const self = this;
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
const value = determineValue(splitted, self[key]);
self[key] = nest(splitted, value);
} catch (error) { return next(error); }
});
next();
}
/**
* Setup handlers for modifying properties -- ['find', 'findOne']
*/
options.modify.on.forEach(function(on) {
schema.post(on, populatePropertyFor);
});
schema.pre((options.validateBeforeSave ? 'validate' : 'save'), reformatProperty);
/*
* Setup handlers for updating documents (there may be more to consider)
*/
['update', 'findOneAndUpdate'].forEach(function(on) {
schema.pre(on, reformatUpdateProperty);
});
} | [
"function",
"modifyProperties",
"(",
"schema",
",",
"paths",
")",
"{",
"if",
"(",
"!",
"paths",
".",
"length",
")",
"{",
"return",
";",
"}",
"const",
"options",
"=",
"paths",
"[",
"0",
"]",
".",
"options",
";",
"function",
"populatePropertyFor",
"(",
"documents",
",",
"next",
")",
"{",
"if",
"(",
"this",
".",
"_mongooseOptions",
".",
"lean",
")",
"{",
"asArray",
"(",
"documents",
")",
".",
"forEach",
"(",
"function",
"(",
"doc",
")",
"{",
"paths",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"try",
"{",
"const",
"splitted",
"=",
"path",
".",
"path",
".",
"split",
"(",
"'.'",
")",
";",
"const",
"key",
"=",
"splitted",
".",
"shift",
"(",
")",
";",
"const",
"insert",
"=",
"{",
"values",
":",
"path",
".",
"enumValues",
"}",
";",
"const",
"value",
"=",
"doc",
"[",
"key",
"]",
";",
"insert",
".",
"value",
"=",
"determineValue",
"(",
"splitted",
",",
"value",
")",
";",
"doc",
"[",
"key",
"]",
"=",
"nest",
"(",
"splitted",
",",
"insert",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"next",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"next",
"(",
")",
";",
"}",
"function",
"reformatUpdateProperty",
"(",
"next",
")",
"{",
"const",
"document",
"=",
"this",
".",
"_update",
"[",
"'$set'",
"]",
";",
"if",
"(",
"document",
")",
"{",
"paths",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"try",
"{",
"const",
"splitted",
"=",
"path",
".",
"path",
".",
"split",
"(",
"'.'",
")",
";",
"const",
"key",
"=",
"splitted",
".",
"shift",
"(",
")",
";",
"if",
"(",
"document",
"[",
"key",
"]",
"===",
"undefined",
")",
"{",
"return",
";",
"}",
"const",
"value",
"=",
"determineValue",
"(",
"splitted",
",",
"document",
"[",
"key",
"]",
")",
";",
"document",
"[",
"key",
"]",
"=",
"nest",
"(",
"splitted",
",",
"value",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"next",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
"next",
"(",
")",
";",
"}",
"function",
"reformatProperty",
"(",
"next",
")",
"{",
"const",
"self",
"=",
"this",
";",
"paths",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"try",
"{",
"const",
"splitted",
"=",
"path",
".",
"path",
".",
"split",
"(",
"'.'",
")",
";",
"const",
"key",
"=",
"splitted",
".",
"shift",
"(",
")",
";",
"const",
"value",
"=",
"determineValue",
"(",
"splitted",
",",
"self",
"[",
"key",
"]",
")",
";",
"self",
"[",
"key",
"]",
"=",
"nest",
"(",
"splitted",
",",
"value",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"next",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"next",
"(",
")",
";",
"}",
"options",
".",
"modify",
".",
"on",
".",
"forEach",
"(",
"function",
"(",
"on",
")",
"{",
"schema",
".",
"post",
"(",
"on",
",",
"populatePropertyFor",
")",
";",
"}",
")",
";",
"schema",
".",
"pre",
"(",
"(",
"options",
".",
"validateBeforeSave",
"?",
"'validate'",
":",
"'save'",
")",
",",
"reformatProperty",
")",
";",
"[",
"'update'",
",",
"'findOneAndUpdate'",
"]",
".",
"forEach",
"(",
"function",
"(",
"on",
")",
"{",
"schema",
".",
"pre",
"(",
"on",
",",
"reformatUpdateProperty",
")",
";",
"}",
")",
";",
"}"
]
| Setup handlers for modifying document properties, must be a `lean` object | [
"Setup",
"handlers",
"for",
"modifying",
"document",
"properties",
"must",
"be",
"a",
"lean",
"object"
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L67-L158 | train |
jfrazx/mongoose-enumvalues | index.js | reformatUpdateProperty | function reformatUpdateProperty(next) {
const document = this._update['$set'];
if (document) {
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
if (document[key] === undefined) { return; }
const value = determineValue(splitted, document[key]);
document[key] = nest(splitted, value);
} catch (error) { return next(error); }
});
}
next();
} | javascript | function reformatUpdateProperty(next) {
const document = this._update['$set'];
if (document) {
paths.forEach(function(path) {
try {
const splitted = path.path.split('.');
const key = splitted.shift();
if (document[key] === undefined) { return; }
const value = determineValue(splitted, document[key]);
document[key] = nest(splitted, value);
} catch (error) { return next(error); }
});
}
next();
} | [
"function",
"reformatUpdateProperty",
"(",
"next",
")",
"{",
"const",
"document",
"=",
"this",
".",
"_update",
"[",
"'$set'",
"]",
";",
"if",
"(",
"document",
")",
"{",
"paths",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"try",
"{",
"const",
"splitted",
"=",
"path",
".",
"path",
".",
"split",
"(",
"'.'",
")",
";",
"const",
"key",
"=",
"splitted",
".",
"shift",
"(",
")",
";",
"if",
"(",
"document",
"[",
"key",
"]",
"===",
"undefined",
")",
"{",
"return",
";",
"}",
"const",
"value",
"=",
"determineValue",
"(",
"splitted",
",",
"document",
"[",
"key",
"]",
")",
";",
"document",
"[",
"key",
"]",
"=",
"nest",
"(",
"splitted",
",",
"value",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"next",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}",
"next",
"(",
")",
";",
"}"
]
| If a document is modified, this method will locate the value on updates and assign it to the
appropriate property, allowing for proper validations later.
@param <Function>: next - function that notifies mongoose this middleware is complete | [
"If",
"a",
"document",
"is",
"modified",
"this",
"method",
"will",
"locate",
"the",
"value",
"on",
"updates",
"and",
"assign",
"it",
"to",
"the",
"appropriate",
"property",
"allowing",
"for",
"proper",
"validations",
"later",
"."
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L102-L121 | train |
jfrazx/mongoose-enumvalues | index.js | findPaths | function findPaths(schema, options) {
const paths = [];
schema.eachPath(function(path, type) {
if (type.enumValues && type.enumValues.length) {
paths.push(
{
path: path,
enumValues: type.enumValues,
options: options
}
);
}
});
return filterPaths(paths, options);
} | javascript | function findPaths(schema, options) {
const paths = [];
schema.eachPath(function(path, type) {
if (type.enumValues && type.enumValues.length) {
paths.push(
{
path: path,
enumValues: type.enumValues,
options: options
}
);
}
});
return filterPaths(paths, options);
} | [
"function",
"findPaths",
"(",
"schema",
",",
"options",
")",
"{",
"const",
"paths",
"=",
"[",
"]",
";",
"schema",
".",
"eachPath",
"(",
"function",
"(",
"path",
",",
"type",
")",
"{",
"if",
"(",
"type",
".",
"enumValues",
"&&",
"type",
".",
"enumValues",
".",
"length",
")",
"{",
"paths",
".",
"push",
"(",
"{",
"path",
":",
"path",
",",
"enumValues",
":",
"type",
".",
"enumValues",
",",
"options",
":",
"options",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"filterPaths",
"(",
"paths",
",",
"options",
")",
";",
"}"
]
| Locate schema paths that are enums
@param | [
"Locate",
"schema",
"paths",
"that",
"are",
"enums"
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L164-L180 | train |
jfrazx/mongoose-enumvalues | index.js | setVirtuals | function setVirtuals(schema, paths) {
paths.forEach(path => {
const props = path.options.virtual.properties;
if (props[path.path]) {
schema.virtual(props[path.path]).get(function() {
return path.enumValues;
});
}
});
} | javascript | function setVirtuals(schema, paths) {
paths.forEach(path => {
const props = path.options.virtual.properties;
if (props[path.path]) {
schema.virtual(props[path.path]).get(function() {
return path.enumValues;
});
}
});
} | [
"function",
"setVirtuals",
"(",
"schema",
",",
"paths",
")",
"{",
"paths",
".",
"forEach",
"(",
"path",
"=>",
"{",
"const",
"props",
"=",
"path",
".",
"options",
".",
"virtual",
".",
"properties",
";",
"if",
"(",
"props",
"[",
"path",
".",
"path",
"]",
")",
"{",
"schema",
".",
"virtual",
"(",
"props",
"[",
"path",
".",
"path",
"]",
")",
".",
"get",
"(",
"function",
"(",
")",
"{",
"return",
"path",
".",
"enumValues",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Setup virtual properties for the document | [
"Setup",
"virtual",
"properties",
"for",
"the",
"document"
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L221-L231 | train |
jfrazx/mongoose-enumvalues | index.js | attachProperties | function attachProperties(schema, paths) {
paths.forEach(path => {
const props = path.options.attach.properties;
if (props[path.path]) {
(props[path.path].on || []).forEach(on => {
/**
* Setup post callbacks
*/
schema.post(on, function(documents, next) {
asArray(documents).forEach(function(doc) {
paths.forEach(function(path) {
doc[props[path.path].as] = path.enumValues;
});
});
next();
});
});
}
});
} | javascript | function attachProperties(schema, paths) {
paths.forEach(path => {
const props = path.options.attach.properties;
if (props[path.path]) {
(props[path.path].on || []).forEach(on => {
/**
* Setup post callbacks
*/
schema.post(on, function(documents, next) {
asArray(documents).forEach(function(doc) {
paths.forEach(function(path) {
doc[props[path.path].as] = path.enumValues;
});
});
next();
});
});
}
});
} | [
"function",
"attachProperties",
"(",
"schema",
",",
"paths",
")",
"{",
"paths",
".",
"forEach",
"(",
"path",
"=>",
"{",
"const",
"props",
"=",
"path",
".",
"options",
".",
"attach",
".",
"properties",
";",
"if",
"(",
"props",
"[",
"path",
".",
"path",
"]",
")",
"{",
"(",
"props",
"[",
"path",
".",
"path",
"]",
".",
"on",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"on",
"=>",
"{",
"schema",
".",
"post",
"(",
"on",
",",
"function",
"(",
"documents",
",",
"next",
")",
"{",
"asArray",
"(",
"documents",
")",
".",
"forEach",
"(",
"function",
"(",
"doc",
")",
"{",
"paths",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"doc",
"[",
"props",
"[",
"path",
".",
"path",
"]",
".",
"as",
"]",
"=",
"path",
".",
"enumValues",
";",
"}",
")",
";",
"}",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Attach properties to the document | [
"Attach",
"properties",
"to",
"the",
"document"
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L237-L259 | train |
jfrazx/mongoose-enumvalues | index.js | determineValue | function determineValue(keys, doc) {
try {
for (const key of keys) {
doc = doc[key];
}
/**
the keys array should transition through any nesting,
so any object is assumed to be enumValues:
{ value: 'string', enumValues: ['strings'] }
*/
return typeof doc === 'object' ? doc.value : doc;
} catch (error) { return doc; }
} | javascript | function determineValue(keys, doc) {
try {
for (const key of keys) {
doc = doc[key];
}
/**
the keys array should transition through any nesting,
so any object is assumed to be enumValues:
{ value: 'string', enumValues: ['strings'] }
*/
return typeof doc === 'object' ? doc.value : doc;
} catch (error) { return doc; }
} | [
"function",
"determineValue",
"(",
"keys",
",",
"doc",
")",
"{",
"try",
"{",
"for",
"(",
"const",
"key",
"of",
"keys",
")",
"{",
"doc",
"=",
"doc",
"[",
"key",
"]",
";",
"}",
"return",
"typeof",
"doc",
"===",
"'object'",
"?",
"doc",
".",
"value",
":",
"doc",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"doc",
";",
"}",
"}"
]
| Traverse the passed document, according to keys, appropriating the desired value
@param [String]: keys -- an array of keys determining the path to value
@param Object: doc -- the document that contains the value at keys path
@return any: -- the value at the end of keys path in document | [
"Traverse",
"the",
"passed",
"document",
"according",
"to",
"keys",
"appropriating",
"the",
"desired",
"value"
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L267-L280 | train |
jfrazx/mongoose-enumvalues | index.js | nest | function nest(array, insert) {
let obj;
array.reverse().forEach(key => {
obj = { [key]: insert };
insert = obj;
});
return insert;
} | javascript | function nest(array, insert) {
let obj;
array.reverse().forEach(key => {
obj = { [key]: insert };
insert = obj;
});
return insert;
} | [
"function",
"nest",
"(",
"array",
",",
"insert",
")",
"{",
"let",
"obj",
";",
"array",
".",
"reverse",
"(",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"obj",
"=",
"{",
"[",
"key",
"]",
":",
"insert",
"}",
";",
"insert",
"=",
"obj",
";",
"}",
")",
";",
"return",
"insert",
";",
"}"
]
| Nest the insert value into objects with keys from array | [
"Nest",
"the",
"insert",
"value",
"into",
"objects",
"with",
"keys",
"from",
"array"
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L286-L295 | train |
jfrazx/mongoose-enumvalues | index.js | setOptions | function setOptions(schema, options) {
function setDefaults(array) {
if (!array.length) {
if (options.find) { array.push('find'); }
if (options.findOne || !options.find) { array.push('findOne'); }
}
}
options = options || {};
options.only = options.only || [];
options.validateBeforeSave = options.validateBeforeSave === undefined
? schema.options.validateBeforeSave
: Boolean(options.validateBeforeSave);
['virtual', 'attach', 'modify'].filter(prop => options[prop])
.forEach(
prop => {
if (typeof options[prop] !== 'object') {
options[prop] = {};
}
options[prop].properties = options[prop].properties || {};
options[prop].only = options[prop].only || Object.keys(options[prop].properties);
}
);
if (options.modify) {
delete options.modify.properties;
options.modify.on = options.modify.on || [];
setDefaults(options.modify.on);
}
if (options.attach) {
Object.keys(options.attach.properties).forEach(property => {
options.attach.properties[property].on = options.attach.properties[property].on || [];
setDefaults(options.attach.properties[property].on);
});
}
return options;
} | javascript | function setOptions(schema, options) {
function setDefaults(array) {
if (!array.length) {
if (options.find) { array.push('find'); }
if (options.findOne || !options.find) { array.push('findOne'); }
}
}
options = options || {};
options.only = options.only || [];
options.validateBeforeSave = options.validateBeforeSave === undefined
? schema.options.validateBeforeSave
: Boolean(options.validateBeforeSave);
['virtual', 'attach', 'modify'].filter(prop => options[prop])
.forEach(
prop => {
if (typeof options[prop] !== 'object') {
options[prop] = {};
}
options[prop].properties = options[prop].properties || {};
options[prop].only = options[prop].only || Object.keys(options[prop].properties);
}
);
if (options.modify) {
delete options.modify.properties;
options.modify.on = options.modify.on || [];
setDefaults(options.modify.on);
}
if (options.attach) {
Object.keys(options.attach.properties).forEach(property => {
options.attach.properties[property].on = options.attach.properties[property].on || [];
setDefaults(options.attach.properties[property].on);
});
}
return options;
} | [
"function",
"setOptions",
"(",
"schema",
",",
"options",
")",
"{",
"function",
"setDefaults",
"(",
"array",
")",
"{",
"if",
"(",
"!",
"array",
".",
"length",
")",
"{",
"if",
"(",
"options",
".",
"find",
")",
"{",
"array",
".",
"push",
"(",
"'find'",
")",
";",
"}",
"if",
"(",
"options",
".",
"findOne",
"||",
"!",
"options",
".",
"find",
")",
"{",
"array",
".",
"push",
"(",
"'findOne'",
")",
";",
"}",
"}",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"only",
"=",
"options",
".",
"only",
"||",
"[",
"]",
";",
"options",
".",
"validateBeforeSave",
"=",
"options",
".",
"validateBeforeSave",
"===",
"undefined",
"?",
"schema",
".",
"options",
".",
"validateBeforeSave",
":",
"Boolean",
"(",
"options",
".",
"validateBeforeSave",
")",
";",
"[",
"'virtual'",
",",
"'attach'",
",",
"'modify'",
"]",
".",
"filter",
"(",
"prop",
"=>",
"options",
"[",
"prop",
"]",
")",
".",
"forEach",
"(",
"prop",
"=>",
"{",
"if",
"(",
"typeof",
"options",
"[",
"prop",
"]",
"!==",
"'object'",
")",
"{",
"options",
"[",
"prop",
"]",
"=",
"{",
"}",
";",
"}",
"options",
"[",
"prop",
"]",
".",
"properties",
"=",
"options",
"[",
"prop",
"]",
".",
"properties",
"||",
"{",
"}",
";",
"options",
"[",
"prop",
"]",
".",
"only",
"=",
"options",
"[",
"prop",
"]",
".",
"only",
"||",
"Object",
".",
"keys",
"(",
"options",
"[",
"prop",
"]",
".",
"properties",
")",
";",
"}",
")",
";",
"if",
"(",
"options",
".",
"modify",
")",
"{",
"delete",
"options",
".",
"modify",
".",
"properties",
";",
"options",
".",
"modify",
".",
"on",
"=",
"options",
".",
"modify",
".",
"on",
"||",
"[",
"]",
";",
"setDefaults",
"(",
"options",
".",
"modify",
".",
"on",
")",
";",
"}",
"if",
"(",
"options",
".",
"attach",
")",
"{",
"Object",
".",
"keys",
"(",
"options",
".",
"attach",
".",
"properties",
")",
".",
"forEach",
"(",
"property",
"=>",
"{",
"options",
".",
"attach",
".",
"properties",
"[",
"property",
"]",
".",
"on",
"=",
"options",
".",
"attach",
".",
"properties",
"[",
"property",
"]",
".",
"on",
"||",
"[",
"]",
";",
"setDefaults",
"(",
"options",
".",
"attach",
".",
"properties",
"[",
"property",
"]",
".",
"on",
")",
";",
"}",
")",
";",
"}",
"return",
"options",
";",
"}"
]
| Setup options and defaults | [
"Setup",
"options",
"and",
"defaults"
]
| 589e792ba5cc39bbb4da9bc84814690f010b7cb2 | https://github.com/jfrazx/mongoose-enumvalues/blob/589e792ba5cc39bbb4da9bc84814690f010b7cb2/index.js#L301-L340 | train |
stezu/node-stream | lib/modifiers/parse.js | parse | function parse(options) {
var settings = _.extend({
error: true
}, options);
return map(function (chunk, next) {
var parsed;
try {
parsed = JSON.parse(chunk);
} catch (e) {
if (settings.error === true) {
return next(e);
}
return next();
}
return next(null, parsed);
});
} | javascript | function parse(options) {
var settings = _.extend({
error: true
}, options);
return map(function (chunk, next) {
var parsed;
try {
parsed = JSON.parse(chunk);
} catch (e) {
if (settings.error === true) {
return next(e);
}
return next();
}
return next(null, parsed);
});
} | [
"function",
"parse",
"(",
"options",
")",
"{",
"var",
"settings",
"=",
"_",
".",
"extend",
"(",
"{",
"error",
":",
"true",
"}",
",",
"options",
")",
";",
"return",
"map",
"(",
"function",
"(",
"chunk",
",",
"next",
")",
"{",
"var",
"parsed",
";",
"try",
"{",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"chunk",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"settings",
".",
"error",
"===",
"true",
")",
"{",
"return",
"next",
"(",
"e",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}",
"return",
"next",
"(",
"null",
",",
"parsed",
")",
";",
"}",
")",
";",
"}"
]
| Creates a new stream where every element in the source stream
is parsed as JSON.
@static
@since 1.1.0
@category Modifiers
@param {Object} [options] - Options to use when parsing items in the stream.
@param {Boolean} [options.error = true] - If true, an error caught when parsing JSON
will be emitted on the stream. If false, the
unparseable item will be removed from the stream
without error.
@returns {Stream.Transform} - Transform stream.
@example
// parse a newline-separated JSON file
fs.createReadStream('example.log')
.pipe(nodeStream.split())
.pipe(nodeStream.parse());
@example
// parse a large JSON file
fs.createReadStream('warandpeace.json')
.pipe(nodeStream.wait())
.pipe(nodeStream.parse()); | [
"Creates",
"a",
"new",
"stream",
"where",
"every",
"element",
"in",
"the",
"source",
"stream",
"is",
"parsed",
"as",
"JSON",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/parse.js#L34-L55 | train |
gabegorelick/hidalgo-cusum-pvalue | index.js | lerp | function lerp (vX, vY, x) {
if (x < vX[0]) {
// Don't interpolate leftward, Cuellar says this is done on purpose
return vY[0];
}
var i = search(vX, x, function (a, b) {return a - b;});
if (i >= 0) {
// found exact match, no need to interpolate
return vY[i];
} else {
// when not found, binary-search returns the -(index_x_should_be + 1),
// see https://github.com/darkskyapp/binary-search/issues/1
i = Math.abs(i + 1);
if (i >= vX.length) {
// extrapolate using last 2 values
i = vX.length - 1;
}
var y0 = vY[i - 1];
var y1 = vY[i];
var x0 = vX[i - 1];
var x1 = vX[i];
return y0 + (y1 - y0) * (x - x0) / (x1 - x0);
}
} | javascript | function lerp (vX, vY, x) {
if (x < vX[0]) {
// Don't interpolate leftward, Cuellar says this is done on purpose
return vY[0];
}
var i = search(vX, x, function (a, b) {return a - b;});
if (i >= 0) {
// found exact match, no need to interpolate
return vY[i];
} else {
// when not found, binary-search returns the -(index_x_should_be + 1),
// see https://github.com/darkskyapp/binary-search/issues/1
i = Math.abs(i + 1);
if (i >= vX.length) {
// extrapolate using last 2 values
i = vX.length - 1;
}
var y0 = vY[i - 1];
var y1 = vY[i];
var x0 = vX[i - 1];
var x1 = vX[i];
return y0 + (y1 - y0) * (x - x0) / (x1 - x0);
}
} | [
"function",
"lerp",
"(",
"vX",
",",
"vY",
",",
"x",
")",
"{",
"if",
"(",
"x",
"<",
"vX",
"[",
"0",
"]",
")",
"{",
"return",
"vY",
"[",
"0",
"]",
";",
"}",
"var",
"i",
"=",
"search",
"(",
"vX",
",",
"x",
",",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
"-",
"b",
";",
"}",
")",
";",
"if",
"(",
"i",
">=",
"0",
")",
"{",
"return",
"vY",
"[",
"i",
"]",
";",
"}",
"else",
"{",
"i",
"=",
"Math",
".",
"abs",
"(",
"i",
"+",
"1",
")",
";",
"if",
"(",
"i",
">=",
"vX",
".",
"length",
")",
"{",
"i",
"=",
"vX",
".",
"length",
"-",
"1",
";",
"}",
"var",
"y0",
"=",
"vY",
"[",
"i",
"-",
"1",
"]",
";",
"var",
"y1",
"=",
"vY",
"[",
"i",
"]",
";",
"var",
"x0",
"=",
"vX",
"[",
"i",
"-",
"1",
"]",
";",
"var",
"x1",
"=",
"vX",
"[",
"i",
"]",
";",
"return",
"y0",
"+",
"(",
"y1",
"-",
"y0",
")",
"*",
"(",
"x",
"-",
"x0",
")",
"/",
"(",
"x1",
"-",
"x0",
")",
";",
"}",
"}"
]
| Linear interpolation with some eccentricities.
@param {number[]} vX - array (vector in math speak) of x values
@param {number[]} vY - array (vector in math speak) of y values
@param {number} x - value to interpolate
@returns {number} interpolated value | [
"Linear",
"interpolation",
"with",
"some",
"eccentricities",
"."
]
| ccdc1a8a2c5068ed244884d7c91bc6f39bfd1974 | https://github.com/gabegorelick/hidalgo-cusum-pvalue/blob/ccdc1a8a2c5068ed244884d7c91bc6f39bfd1974/index.js#L13-L39 | train |
terkelg/eliminate | src/index.js | eliminate | async function eliminate(dir) {
const stat = await lstat(dir);
if (!stat.isDirectory()) {
await unlink(dir);
return;
}
const files = await readdir(dir);
for (const file of files) {
const path = join(dir, file);
if (fs.existsSync(path)) {
await eliminate(path);
} else {
await unlink(path);
}
}
await rmdir(dir);
} | javascript | async function eliminate(dir) {
const stat = await lstat(dir);
if (!stat.isDirectory()) {
await unlink(dir);
return;
}
const files = await readdir(dir);
for (const file of files) {
const path = join(dir, file);
if (fs.existsSync(path)) {
await eliminate(path);
} else {
await unlink(path);
}
}
await rmdir(dir);
} | [
"async",
"function",
"eliminate",
"(",
"dir",
")",
"{",
"const",
"stat",
"=",
"await",
"lstat",
"(",
"dir",
")",
";",
"if",
"(",
"!",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"await",
"unlink",
"(",
"dir",
")",
";",
"return",
";",
"}",
"const",
"files",
"=",
"await",
"readdir",
"(",
"dir",
")",
";",
"for",
"(",
"const",
"file",
"of",
"files",
")",
"{",
"const",
"path",
"=",
"join",
"(",
"dir",
",",
"file",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"path",
")",
")",
"{",
"await",
"eliminate",
"(",
"path",
")",
";",
"}",
"else",
"{",
"await",
"unlink",
"(",
"path",
")",
";",
"}",
"}",
"await",
"rmdir",
"(",
"dir",
")",
";",
"}"
]
| Delete directory or file
@param {String} dir The path/file to delete | [
"Delete",
"directory",
"or",
"file"
]
| 1d00e99bea6c1ed978d4e89fb14c24b0a157d5ce | https://github.com/terkelg/eliminate/blob/1d00e99bea6c1ed978d4e89fb14c24b0a157d5ce/src/index.js#L14-L30 | train |
noderaider/repackage | jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js | JSXAttribute | function JSXAttribute(node, print) {
print.plain(node.name);
if (node.value) {
this.push("=");
print.plain(node.value);
}
} | javascript | function JSXAttribute(node, print) {
print.plain(node.name);
if (node.value) {
this.push("=");
print.plain(node.value);
}
} | [
"function",
"JSXAttribute",
"(",
"node",
",",
"print",
")",
"{",
"print",
".",
"plain",
"(",
"node",
".",
"name",
")",
";",
"if",
"(",
"node",
".",
"value",
")",
"{",
"this",
".",
"push",
"(",
"\"=\"",
")",
";",
"print",
".",
"plain",
"(",
"node",
".",
"value",
")",
";",
"}",
"}"
]
| Prints JSXAttribute, prints name and value. | [
"Prints",
"JSXAttribute",
"prints",
"name",
"and",
"value",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js#L28-L34 | train |
noderaider/repackage | jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js | JSXElement | function JSXElement(node, print) {
var open = node.openingElement;
print.plain(open);
if (open.selfClosing) return;
this.indent();
var _arr = node.children;
for (var _i = 0; _i < _arr.length; _i++) {
var child = _arr[_i];
if (t.isLiteral(child)) {
this.push(child.value, true);
} else {
print.plain(child);
}
}
this.dedent();
print.plain(node.closingElement);
} | javascript | function JSXElement(node, print) {
var open = node.openingElement;
print.plain(open);
if (open.selfClosing) return;
this.indent();
var _arr = node.children;
for (var _i = 0; _i < _arr.length; _i++) {
var child = _arr[_i];
if (t.isLiteral(child)) {
this.push(child.value, true);
} else {
print.plain(child);
}
}
this.dedent();
print.plain(node.closingElement);
} | [
"function",
"JSXElement",
"(",
"node",
",",
"print",
")",
"{",
"var",
"open",
"=",
"node",
".",
"openingElement",
";",
"print",
".",
"plain",
"(",
"open",
")",
";",
"if",
"(",
"open",
".",
"selfClosing",
")",
"return",
";",
"this",
".",
"indent",
"(",
")",
";",
"var",
"_arr",
"=",
"node",
".",
"children",
";",
"for",
"(",
"var",
"_i",
"=",
"0",
";",
"_i",
"<",
"_arr",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"child",
"=",
"_arr",
"[",
"_i",
"]",
";",
"if",
"(",
"t",
".",
"isLiteral",
"(",
"child",
")",
")",
"{",
"this",
".",
"push",
"(",
"child",
".",
"value",
",",
"true",
")",
";",
"}",
"else",
"{",
"print",
".",
"plain",
"(",
"child",
")",
";",
"}",
"}",
"this",
".",
"dedent",
"(",
")",
";",
"print",
".",
"plain",
"(",
"node",
".",
"closingElement",
")",
";",
"}"
]
| Prints JSXElement, prints openingElement, children, and closingElement. | [
"Prints",
"JSXElement",
"prints",
"openingElement",
"children",
"and",
"closingElement",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js#L88-L106 | train |
noderaider/repackage | jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js | JSXOpeningElement | function JSXOpeningElement(node, print) {
this.push("<");
print.plain(node.name);
if (node.attributes.length > 0) {
this.push(" ");
print.join(node.attributes, { separator: " " });
}
this.push(node.selfClosing ? " />" : ">");
} | javascript | function JSXOpeningElement(node, print) {
this.push("<");
print.plain(node.name);
if (node.attributes.length > 0) {
this.push(" ");
print.join(node.attributes, { separator: " " });
}
this.push(node.selfClosing ? " />" : ">");
} | [
"function",
"JSXOpeningElement",
"(",
"node",
",",
"print",
")",
"{",
"this",
".",
"push",
"(",
"\"<\"",
")",
";",
"print",
".",
"plain",
"(",
"node",
".",
"name",
")",
";",
"if",
"(",
"node",
".",
"attributes",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"push",
"(",
"\" \"",
")",
";",
"print",
".",
"join",
"(",
"node",
".",
"attributes",
",",
"{",
"separator",
":",
"\" \"",
"}",
")",
";",
"}",
"this",
".",
"push",
"(",
"node",
".",
"selfClosing",
"?",
"\" />\"",
":",
"\">\"",
")",
";",
"}"
]
| Prints JSXOpeningElement, prints name and attributes, handles selfClosing. | [
"Prints",
"JSXOpeningElement",
"prints",
"name",
"and",
"attributes",
"handles",
"selfClosing",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/jsx.js#L112-L120 | train |
noderaider/repackage | jspm_packages/npm/[email protected]/lib/generation/generators/base.js | BlockStatement | function BlockStatement(node, print) {
this.push("{");
if (node.body.length) {
this.newline();
print.sequence(node.body, { indent: true });
if (!this.format.retainLines) this.removeLast("\n");
this.rightBrace();
} else {
print.printInnerComments();
this.push("}");
}
} | javascript | function BlockStatement(node, print) {
this.push("{");
if (node.body.length) {
this.newline();
print.sequence(node.body, { indent: true });
if (!this.format.retainLines) this.removeLast("\n");
this.rightBrace();
} else {
print.printInnerComments();
this.push("}");
}
} | [
"function",
"BlockStatement",
"(",
"node",
",",
"print",
")",
"{",
"this",
".",
"push",
"(",
"\"{\"",
")",
";",
"if",
"(",
"node",
".",
"body",
".",
"length",
")",
"{",
"this",
".",
"newline",
"(",
")",
";",
"print",
".",
"sequence",
"(",
"node",
".",
"body",
",",
"{",
"indent",
":",
"true",
"}",
")",
";",
"if",
"(",
"!",
"this",
".",
"format",
".",
"retainLines",
")",
"this",
".",
"removeLast",
"(",
"\"\\n\"",
")",
";",
"\\n",
"}",
"else",
"this",
".",
"rightBrace",
"(",
")",
";",
"}"
]
| Print BlockStatement, collapses empty blocks, prints body. | [
"Print",
"BlockStatement",
"collapses",
"empty",
"blocks",
"prints",
"body",
"."
]
| 9f14246db3327abb0c4a5d7a3d55bd7816ebbd40 | https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/generation/generators/base.js#L31-L42 | train |
RobLoach/metalsmith-jstransformer-partials | index.js | getTransformer | function getTransformer(name) {
if (name in transformers) {
return transformers[name]
}
const transformer = toTransformer(name)
transformers[name] = transformer ? jstransformer(transformer) : false
return transformers[name]
} | javascript | function getTransformer(name) {
if (name in transformers) {
return transformers[name]
}
const transformer = toTransformer(name)
transformers[name] = transformer ? jstransformer(transformer) : false
return transformers[name]
} | [
"function",
"getTransformer",
"(",
"name",
")",
"{",
"if",
"(",
"name",
"in",
"transformers",
")",
"{",
"return",
"transformers",
"[",
"name",
"]",
"}",
"const",
"transformer",
"=",
"toTransformer",
"(",
"name",
")",
"transformers",
"[",
"name",
"]",
"=",
"transformer",
"?",
"jstransformer",
"(",
"transformer",
")",
":",
"false",
"return",
"transformers",
"[",
"name",
"]",
"}"
]
| Get the transformer from the given name.
@return The JSTransformer; null if it doesn't exist. | [
"Get",
"the",
"transformer",
"from",
"the",
"given",
"name",
"."
]
| f164b32438e05701837e13fa7852cc909470c321 | https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L29-L36 | train |
RobLoach/metalsmith-jstransformer-partials | index.js | renderPartial | function renderPartial(name) {
// The name is a required input.
if (!name) {
throw new Error('When calling .partial(), name is required.')
}
// Ensure the partial is available in the metadata.
if (!(name in metalsmith.metadata().partials)) {
throw new Error('The partial "' + name + '" was not found.')
}
// Construct the partial function arguments.
const fnarray = []
for (let i = 1; i < arguments.length; i++) {
fnarray.push(arguments[i])
}
// Call the partial function with the given array arguments.
return metalsmith.metadata().partials[name].apply(metalsmith.metadata(), fnarray)
} | javascript | function renderPartial(name) {
// The name is a required input.
if (!name) {
throw new Error('When calling .partial(), name is required.')
}
// Ensure the partial is available in the metadata.
if (!(name in metalsmith.metadata().partials)) {
throw new Error('The partial "' + name + '" was not found.')
}
// Construct the partial function arguments.
const fnarray = []
for (let i = 1; i < arguments.length; i++) {
fnarray.push(arguments[i])
}
// Call the partial function with the given array arguments.
return metalsmith.metadata().partials[name].apply(metalsmith.metadata(), fnarray)
} | [
"function",
"renderPartial",
"(",
"name",
")",
"{",
"if",
"(",
"!",
"name",
")",
"{",
"throw",
"new",
"Error",
"(",
"'When calling .partial(), name is required.'",
")",
"}",
"if",
"(",
"!",
"(",
"name",
"in",
"metalsmith",
".",
"metadata",
"(",
")",
".",
"partials",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The partial \"'",
"+",
"name",
"+",
"'\" was not found.'",
")",
"}",
"const",
"fnarray",
"=",
"[",
"]",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"fnarray",
".",
"push",
"(",
"arguments",
"[",
"i",
"]",
")",
"}",
"return",
"metalsmith",
".",
"metadata",
"(",
")",
".",
"partials",
"[",
"name",
"]",
".",
"apply",
"(",
"metalsmith",
".",
"metadata",
"(",
")",
",",
"fnarray",
")",
"}"
]
| Renders a partial from the given name. | [
"Renders",
"a",
"partial",
"from",
"the",
"given",
"name",
"."
]
| f164b32438e05701837e13fa7852cc909470c321 | https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L46-L65 | train |
RobLoach/metalsmith-jstransformer-partials | index.js | filterFile | function filterFile(file, done) {
if (files[file].partial) {
// Discover whether it is explicitly declared as a partial.
return done(null, files[file].partial)
} else if (opts.pattern) {
// Check if it matches the partial pattern.
return done(null, minimatch(file, opts.pattern))
}
// The file is not a partial.
done(null, false)
} | javascript | function filterFile(file, done) {
if (files[file].partial) {
// Discover whether it is explicitly declared as a partial.
return done(null, files[file].partial)
} else if (opts.pattern) {
// Check if it matches the partial pattern.
return done(null, minimatch(file, opts.pattern))
}
// The file is not a partial.
done(null, false)
} | [
"function",
"filterFile",
"(",
"file",
",",
"done",
")",
"{",
"if",
"(",
"files",
"[",
"file",
"]",
".",
"partial",
")",
"{",
"return",
"done",
"(",
"null",
",",
"files",
"[",
"file",
"]",
".",
"partial",
")",
"}",
"else",
"if",
"(",
"opts",
".",
"pattern",
")",
"{",
"return",
"done",
"(",
"null",
",",
"minimatch",
"(",
"file",
",",
"opts",
".",
"pattern",
")",
")",
"}",
"done",
"(",
"null",
",",
"false",
")",
"}"
]
| Filter out all partials | [
"Filter",
"out",
"all",
"partials"
]
| f164b32438e05701837e13fa7852cc909470c321 | https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L77-L87 | train |
RobLoach/metalsmith-jstransformer-partials | index.js | addPartial | function addPartial(filename, done) {
// Create a copy of the file and delete it from the database.
const file = clone(files[filename])
delete files[filename]
// Compile the partial.
const info = path.parse(filename)
const transform = info.ext ? info.ext.substring(1) : null
const transformer = getTransformer(transform)
if (transformer) {
// Construct the options.
const options = extend({}, metalsmith.metadata(), file, {
filename: path.join(metalsmith.source(), filename)
})
// Compile the partial.
transformer.compileAsync(file.contents.toString(), options).then(template => {
/**
* Define the partial as a function.
*/
metalsmith.metadata().partials[info.name] = locals => {
const opt = extend({}, options, locals)
return template.fn.apply(file, [opt])
}
metalsmith.metadata().partials[info.name].file = file
done()
}, done)
} else {
// Do not error out when the Transformer is not found.
done()
}
} | javascript | function addPartial(filename, done) {
// Create a copy of the file and delete it from the database.
const file = clone(files[filename])
delete files[filename]
// Compile the partial.
const info = path.parse(filename)
const transform = info.ext ? info.ext.substring(1) : null
const transformer = getTransformer(transform)
if (transformer) {
// Construct the options.
const options = extend({}, metalsmith.metadata(), file, {
filename: path.join(metalsmith.source(), filename)
})
// Compile the partial.
transformer.compileAsync(file.contents.toString(), options).then(template => {
/**
* Define the partial as a function.
*/
metalsmith.metadata().partials[info.name] = locals => {
const opt = extend({}, options, locals)
return template.fn.apply(file, [opt])
}
metalsmith.metadata().partials[info.name].file = file
done()
}, done)
} else {
// Do not error out when the Transformer is not found.
done()
}
} | [
"function",
"addPartial",
"(",
"filename",
",",
"done",
")",
"{",
"const",
"file",
"=",
"clone",
"(",
"files",
"[",
"filename",
"]",
")",
"delete",
"files",
"[",
"filename",
"]",
"const",
"info",
"=",
"path",
".",
"parse",
"(",
"filename",
")",
"const",
"transform",
"=",
"info",
".",
"ext",
"?",
"info",
".",
"ext",
".",
"substring",
"(",
"1",
")",
":",
"null",
"const",
"transformer",
"=",
"getTransformer",
"(",
"transform",
")",
"if",
"(",
"transformer",
")",
"{",
"const",
"options",
"=",
"extend",
"(",
"{",
"}",
",",
"metalsmith",
".",
"metadata",
"(",
")",
",",
"file",
",",
"{",
"filename",
":",
"path",
".",
"join",
"(",
"metalsmith",
".",
"source",
"(",
")",
",",
"filename",
")",
"}",
")",
"transformer",
".",
"compileAsync",
"(",
"file",
".",
"contents",
".",
"toString",
"(",
")",
",",
"options",
")",
".",
"then",
"(",
"template",
"=>",
"{",
"metalsmith",
".",
"metadata",
"(",
")",
".",
"partials",
"[",
"info",
".",
"name",
"]",
"=",
"locals",
"=>",
"{",
"const",
"opt",
"=",
"extend",
"(",
"{",
"}",
",",
"options",
",",
"locals",
")",
"return",
"template",
".",
"fn",
".",
"apply",
"(",
"file",
",",
"[",
"opt",
"]",
")",
"}",
"metalsmith",
".",
"metadata",
"(",
")",
".",
"partials",
"[",
"info",
".",
"name",
"]",
".",
"file",
"=",
"file",
"done",
"(",
")",
"}",
",",
"done",
")",
"}",
"else",
"{",
"done",
"(",
")",
"}",
"}"
]
| Add the given file in as a partial. | [
"Add",
"the",
"given",
"file",
"in",
"as",
"a",
"partial",
"."
]
| f164b32438e05701837e13fa7852cc909470c321 | https://github.com/RobLoach/metalsmith-jstransformer-partials/blob/f164b32438e05701837e13fa7852cc909470c321/index.js#L92-L123 | train |
sumeetdas/Meow | lib/jobs.js | publishRobotsTxt | function publishRobotsTxt () {
var path = 'robots.txt';
return fs
.statAsync(path)
.then(function (pStat) {
if (!pStat.isFile()) {
// go to our default course of action, that is create robots.txt file
throw new Error ();
}
})
.catch(Error, function () {
return fs
.openAsync(path, 'w')
.then(function () {
return fs.writeFileAsync(path, 'User-agent: *\nSitemap: ' + config.siteUrl + '/sitemap.xml');
})
.catch(function (pErr) {
log.error(pErr);
});
});
} | javascript | function publishRobotsTxt () {
var path = 'robots.txt';
return fs
.statAsync(path)
.then(function (pStat) {
if (!pStat.isFile()) {
// go to our default course of action, that is create robots.txt file
throw new Error ();
}
})
.catch(Error, function () {
return fs
.openAsync(path, 'w')
.then(function () {
return fs.writeFileAsync(path, 'User-agent: *\nSitemap: ' + config.siteUrl + '/sitemap.xml');
})
.catch(function (pErr) {
log.error(pErr);
});
});
} | [
"function",
"publishRobotsTxt",
"(",
")",
"{",
"var",
"path",
"=",
"'robots.txt'",
";",
"return",
"fs",
".",
"statAsync",
"(",
"path",
")",
".",
"then",
"(",
"function",
"(",
"pStat",
")",
"{",
"if",
"(",
"!",
"pStat",
".",
"isFile",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"Error",
",",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"openAsync",
"(",
"path",
",",
"'w'",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"fs",
".",
"writeFileAsync",
"(",
"path",
",",
"'User-agent: *\\nSitemap: '",
"+",
"\\n",
"+",
"config",
".",
"siteUrl",
")",
";",
"}",
")",
".",
"'/sitemap.xml'",
"catch",
";",
"}",
")",
";",
"}"
]
| Creates a default robots.txt file if it does not exist
@returns {*} | [
"Creates",
"a",
"default",
"robots",
".",
"txt",
"file",
"if",
"it",
"does",
"not",
"exist"
]
| 965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9 | https://github.com/sumeetdas/Meow/blob/965cd8a966aed9fe2fb271bf9a1ba9692eb2f3a9/lib/jobs.js#L129-L149 | train |
divshot/ask | lib/mock-request-response.js | function () {
var self = this;
return function () {
var status = self.statusCode;
if (status === 0 || (status >= 400 && status < 600)) {
return context.asRejectedPromise(self);
}
return context.asPromise(self);
};
} | javascript | function () {
var self = this;
return function () {
var status = self.statusCode;
if (status === 0 || (status >= 400 && status < 600)) {
return context.asRejectedPromise(self);
}
return context.asPromise(self);
};
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"return",
"function",
"(",
")",
"{",
"var",
"status",
"=",
"self",
".",
"statusCode",
";",
"if",
"(",
"status",
"===",
"0",
"||",
"(",
"status",
">=",
"400",
"&&",
"status",
"<",
"600",
")",
")",
"{",
"return",
"context",
".",
"asRejectedPromise",
"(",
"self",
")",
";",
"}",
"return",
"context",
".",
"asPromise",
"(",
"self",
")",
";",
"}",
";",
"}"
]
| Custom function to return when a mock is present | [
"Custom",
"function",
"to",
"return",
"when",
"a",
"mock",
"is",
"present"
]
| bd37e5654374c98d48e9d37c65984579d3bda445 | https://github.com/divshot/ask/blob/bd37e5654374c98d48e9d37c65984579d3bda445/lib/mock-request-response.js#L29-L40 | train |
|
keqingrong/is-same-origin | src/index.js | parseURL | function parseURL(s) {
var url = null;
try {
url = new URL(s);
} catch (error) {
console.error(error);
}
return url;
} | javascript | function parseURL(s) {
var url = null;
try {
url = new URL(s);
} catch (error) {
console.error(error);
}
return url;
} | [
"function",
"parseURL",
"(",
"s",
")",
"{",
"var",
"url",
"=",
"null",
";",
"try",
"{",
"url",
"=",
"new",
"URL",
"(",
"s",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"error",
")",
";",
"}",
"return",
"url",
";",
"}"
]
| Parse the URL string
@param {string} s - URL string
@returns {URL|null} | [
"Parse",
"the",
"URL",
"string"
]
| 5891c5d3a98f9436c16c9d992c710fc1938b05c4 | https://github.com/keqingrong/is-same-origin/blob/5891c5d3a98f9436c16c9d992c710fc1938b05c4/src/index.js#L34-L42 | train |
stezu/node-stream | lib/consumers/v1/first.js | firstObj | function firstObj(stream, onEnd) {
var data;
/**
* Send the correct data to the onEnd callback.
*
* @private
* @param {Error} [err] - Optional error.
* @returns {undefined}
*/
var done = _.once(function (err) {
if (err) {
return onEnd(err);
}
return onEnd(null, data);
});
stream.once('data', function (chunk) {
data = chunk;
});
stream.on('error', done);
stream.on('end', done);
} | javascript | function firstObj(stream, onEnd) {
var data;
/**
* Send the correct data to the onEnd callback.
*
* @private
* @param {Error} [err] - Optional error.
* @returns {undefined}
*/
var done = _.once(function (err) {
if (err) {
return onEnd(err);
}
return onEnd(null, data);
});
stream.once('data', function (chunk) {
data = chunk;
});
stream.on('error', done);
stream.on('end', done);
} | [
"function",
"firstObj",
"(",
"stream",
",",
"onEnd",
")",
"{",
"var",
"data",
";",
"var",
"done",
"=",
"_",
".",
"once",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"onEnd",
"(",
"err",
")",
";",
"}",
"return",
"onEnd",
"(",
"null",
",",
"data",
")",
";",
"}",
")",
";",
"stream",
".",
"once",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"data",
"=",
"chunk",
";",
"}",
")",
";",
"stream",
".",
"on",
"(",
"'error'",
",",
"done",
")",
";",
"stream",
".",
"on",
"(",
"'end'",
",",
"done",
")",
";",
"}"
]
| Get the first item in a stream.
@private
@deprecated
@static
@since 0.0.4
@category Consumers
@param {Stream} stream - Stream that will be read for this function.
@param {Function} onEnd - Callback when the stream has been read completely.
@returns {undefined} | [
"Get",
"the",
"first",
"item",
"in",
"a",
"stream",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/first.js#L18-L42 | train |
stezu/node-stream | lib/consumers/v1/first.js | first | function first(stream, onEnd) {
firstObj(stream, function (err, data) {
if (err) {
return onEnd(err);
}
return onEnd(null, new Buffer(data));
});
} | javascript | function first(stream, onEnd) {
firstObj(stream, function (err, data) {
if (err) {
return onEnd(err);
}
return onEnd(null, new Buffer(data));
});
} | [
"function",
"first",
"(",
"stream",
",",
"onEnd",
")",
"{",
"firstObj",
"(",
"stream",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"onEnd",
"(",
"err",
")",
";",
"}",
"return",
"onEnd",
"(",
"null",
",",
"new",
"Buffer",
"(",
"data",
")",
")",
";",
"}",
")",
";",
"}"
]
| Get the first item in a stream and convert to a buffer.
@private
@deprecated
@static
@since 0.0.4
@category Consumers
@param {Stream} stream - Stream that will be read for this function.
@param {Function} onEnd - Callback when the stream has been read completely.
@returns {undefined} | [
"Get",
"the",
"first",
"item",
"in",
"a",
"stream",
"and",
"convert",
"to",
"a",
"buffer",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/first.js#L57-L67 | train |
stezu/node-stream | lib/consumers/v1/first.js | firstJson | function firstJson(stream, onEnd) {
first(stream, function (err, data) {
if (err) {
return onEnd(err);
}
return parse(data, onEnd);
});
} | javascript | function firstJson(stream, onEnd) {
first(stream, function (err, data) {
if (err) {
return onEnd(err);
}
return parse(data, onEnd);
});
} | [
"function",
"firstJson",
"(",
"stream",
",",
"onEnd",
")",
"{",
"first",
"(",
"stream",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"onEnd",
"(",
"err",
")",
";",
"}",
"return",
"parse",
"(",
"data",
",",
"onEnd",
")",
";",
"}",
")",
";",
"}"
]
| Get the first item in a stream and parse it for JSON.
@private
@deprecated
@static
@since 0.0.4
@category Consumers
@param {Stream} stream - Stream that will be read for this function.
@param {Function} onEnd - Callback when the stream has been read completely.
@returns {undefined} | [
"Get",
"the",
"first",
"item",
"in",
"a",
"stream",
"and",
"parse",
"it",
"for",
"JSON",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v1/first.js#L82-L92 | train |
queicherius/promise-control-flow | src/index.js | parallel | function parallel (promiseFunctions, limit = Infinity, silenceErrors = false) {
const contraMethod = (tasks, callback) => concurrent(tasks, limit, callback)
return generatePromise(promiseFunctions, contraMethod, silenceErrors)
} | javascript | function parallel (promiseFunctions, limit = Infinity, silenceErrors = false) {
const contraMethod = (tasks, callback) => concurrent(tasks, limit, callback)
return generatePromise(promiseFunctions, contraMethod, silenceErrors)
} | [
"function",
"parallel",
"(",
"promiseFunctions",
",",
"limit",
"=",
"Infinity",
",",
"silenceErrors",
"=",
"false",
")",
"{",
"const",
"contraMethod",
"=",
"(",
"tasks",
",",
"callback",
")",
"=>",
"concurrent",
"(",
"tasks",
",",
"limit",
",",
"callback",
")",
"return",
"generatePromise",
"(",
"promiseFunctions",
",",
"contraMethod",
",",
"silenceErrors",
")",
"}"
]
| Work on the tasks in parallel, with a optional concurrency limit | [
"Work",
"on",
"the",
"tasks",
"in",
"parallel",
"with",
"a",
"optional",
"concurrency",
"limit"
]
| 19552ffe90e2f329271b830808393ee6499f4f68 | https://github.com/queicherius/promise-control-flow/blob/19552ffe90e2f329271b830808393ee6499f4f68/src/index.js#L12-L15 | train |
queicherius/promise-control-flow | src/index.js | generatePromise | function generatePromise (promiseFunctions, contraMethod, silenceErrors) {
return new Promise((resolve, reject) => {
// Generate a function that executes the promise function and
// calls back in a way that the contra library requires
for (let i in promiseFunctions) {
let promiseFunction = promiseFunctions[i]
if (!isFunction(promiseFunction)) {
return reject(new Error('One of the supplied promise functions is not a function'))
}
promiseFunctions[i] = (contraCallback) => {
promiseFunction()
.then(data => contraCallback(null, data))
.catch(err => silenceErrors ? contraCallback(null, null) : contraCallback(err))
}
}
contraMethod(promiseFunctions, (err, results) => {
if (err) return reject(err)
resolve(results)
})
})
} | javascript | function generatePromise (promiseFunctions, contraMethod, silenceErrors) {
return new Promise((resolve, reject) => {
// Generate a function that executes the promise function and
// calls back in a way that the contra library requires
for (let i in promiseFunctions) {
let promiseFunction = promiseFunctions[i]
if (!isFunction(promiseFunction)) {
return reject(new Error('One of the supplied promise functions is not a function'))
}
promiseFunctions[i] = (contraCallback) => {
promiseFunction()
.then(data => contraCallback(null, data))
.catch(err => silenceErrors ? contraCallback(null, null) : contraCallback(err))
}
}
contraMethod(promiseFunctions, (err, results) => {
if (err) return reject(err)
resolve(results)
})
})
} | [
"function",
"generatePromise",
"(",
"promiseFunctions",
",",
"contraMethod",
",",
"silenceErrors",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"for",
"(",
"let",
"i",
"in",
"promiseFunctions",
")",
"{",
"let",
"promiseFunction",
"=",
"promiseFunctions",
"[",
"i",
"]",
"if",
"(",
"!",
"isFunction",
"(",
"promiseFunction",
")",
")",
"{",
"return",
"reject",
"(",
"new",
"Error",
"(",
"'One of the supplied promise functions is not a function'",
")",
")",
"}",
"promiseFunctions",
"[",
"i",
"]",
"=",
"(",
"contraCallback",
")",
"=>",
"{",
"promiseFunction",
"(",
")",
".",
"then",
"(",
"data",
"=>",
"contraCallback",
"(",
"null",
",",
"data",
")",
")",
".",
"catch",
"(",
"err",
"=>",
"silenceErrors",
"?",
"contraCallback",
"(",
"null",
",",
"null",
")",
":",
"contraCallback",
"(",
"err",
")",
")",
"}",
"}",
"contraMethod",
"(",
"promiseFunctions",
",",
"(",
"err",
",",
"results",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"resolve",
"(",
"results",
")",
"}",
")",
"}",
")",
"}"
]
| Wrap the contra library with a promise, and convert the promise functions into callbacks | [
"Wrap",
"the",
"contra",
"library",
"with",
"a",
"promise",
"and",
"convert",
"the",
"promise",
"functions",
"into",
"callbacks"
]
| 19552ffe90e2f329271b830808393ee6499f4f68 | https://github.com/queicherius/promise-control-flow/blob/19552ffe90e2f329271b830808393ee6499f4f68/src/index.js#L18-L41 | train |
dominictarr/bipf | index.js | createSeekPathSrc | function createSeekPathSrc(target) {
return (
'"use strict";\n' + //go fast sauce!
target.map(function (e, i) {
return ' var k'+i+' = Buffer.from('+ JSON.stringify(e) +');' //strings only!
}).join('\n') + '\n'+
" return function (buffer, start) {\n"+
target.map(function (_, i) {
return " start = seekKey(buffer, start, k"+i+")"
}).join('\n') + '\n' +
' return start;\n'+
'}\n'
)
} | javascript | function createSeekPathSrc(target) {
return (
'"use strict";\n' + //go fast sauce!
target.map(function (e, i) {
return ' var k'+i+' = Buffer.from('+ JSON.stringify(e) +');' //strings only!
}).join('\n') + '\n'+
" return function (buffer, start) {\n"+
target.map(function (_, i) {
return " start = seekKey(buffer, start, k"+i+")"
}).join('\n') + '\n' +
' return start;\n'+
'}\n'
)
} | [
"function",
"createSeekPathSrc",
"(",
"target",
")",
"{",
"return",
"(",
"'\"use strict\";\\n'",
"+",
"\\n",
"+",
"target",
".",
"map",
"(",
"function",
"(",
"e",
",",
"i",
")",
"{",
"return",
"' var k'",
"+",
"i",
"+",
"' = Buffer.from('",
"+",
"JSON",
".",
"stringify",
"(",
"e",
")",
"+",
"');'",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
"+",
"\\n",
"+",
"'\\n'",
"+",
"\\n",
"+",
"\" return function (buffer, start) {\\n\"",
"+",
"\\n",
")",
"}"
]
| for some reason, seek path | [
"for",
"some",
"reason",
"seek",
"path"
]
| aca01838b706673cd7e64961466232fa8b97fc1c | https://github.com/dominictarr/bipf/blob/aca01838b706673cd7e64961466232fa8b97fc1c/index.js#L269-L282 | train |
ecomfe/edp-module-compiler | src/module.js | Module | function Module(moduleId, ctx, combineConfig) {
this.moduleId = moduleId;
this.compiler = ctx;
this.combineConfig = combineConfig || ctx.getCombineConfig(moduleId);
this.definition = null;
this.prepare();
} | javascript | function Module(moduleId, ctx, combineConfig) {
this.moduleId = moduleId;
this.compiler = ctx;
this.combineConfig = combineConfig || ctx.getCombineConfig(moduleId);
this.definition = null;
this.prepare();
} | [
"function",
"Module",
"(",
"moduleId",
",",
"ctx",
",",
"combineConfig",
")",
"{",
"this",
".",
"moduleId",
"=",
"moduleId",
";",
"this",
".",
"compiler",
"=",
"ctx",
";",
"this",
".",
"combineConfig",
"=",
"combineConfig",
"||",
"ctx",
".",
"getCombineConfig",
"(",
"moduleId",
")",
";",
"this",
".",
"definition",
"=",
"null",
";",
"this",
".",
"prepare",
"(",
")",
";",
"}"
]
| The module constructor
@constructor
@param {string} moduleId 模块的Id.
@param {Compiler} ctx 整个Compiler的上下文环境,提供必要的api和保存一些全局的数据.
@param {CombineConfig=} combineConfig combine配置信息. | [
"The",
"module",
"constructor"
]
| 4fa03db7bd7a059482d39af079b21bf7d47dc551 | https://github.com/ecomfe/edp-module-compiler/blob/4fa03db7bd7a059482d39af079b21bf7d47dc551/src/module.js#L16-L22 | train |
bitbinio/bitbin | src/manifest.js | function(files) {
var collection = {};
files.forEach(function(file) {
var filename = file.name;
if (!collection.hasOwnProperty(filename) || collection[filename].version < file.version) {
collection[filename] = file;
}
});
return Object.keys(collection).map(function(name) {
return collection[name];
});
} | javascript | function(files) {
var collection = {};
files.forEach(function(file) {
var filename = file.name;
if (!collection.hasOwnProperty(filename) || collection[filename].version < file.version) {
collection[filename] = file;
}
});
return Object.keys(collection).map(function(name) {
return collection[name];
});
} | [
"function",
"(",
"files",
")",
"{",
"var",
"collection",
"=",
"{",
"}",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"filename",
"=",
"file",
".",
"name",
";",
"if",
"(",
"!",
"collection",
".",
"hasOwnProperty",
"(",
"filename",
")",
"||",
"collection",
"[",
"filename",
"]",
".",
"version",
"<",
"file",
".",
"version",
")",
"{",
"collection",
"[",
"filename",
"]",
"=",
"file",
";",
"}",
"}",
")",
";",
"return",
"Object",
".",
"keys",
"(",
"collection",
")",
".",
"map",
"(",
"function",
"(",
"name",
")",
"{",
"return",
"collection",
"[",
"name",
"]",
";",
"}",
")",
";",
"}"
]
| Deduplicate the list of files.
Only keep the most recent file versions.
@param array files
@return array | [
"Deduplicate",
"the",
"list",
"of",
"files",
"."
]
| fdb1734f9fd47234eec96d9e61a28e8cb3820e63 | https://github.com/bitbinio/bitbin/blob/fdb1734f9fd47234eec96d9e61a28e8cb3820e63/src/manifest.js#L133-L144 | train |
|
damnit/metalsmith-htmlescape | lib/index.js | plugin | function plugin(options) {
return function(files, metalsmith, done) {
Object.keys(files).forEach(function(file) {
var data = files[file];
data.contents = new Buffer(special(data.contents.toString()));
});
done();
}
} | javascript | function plugin(options) {
return function(files, metalsmith, done) {
Object.keys(files).forEach(function(file) {
var data = files[file];
data.contents = new Buffer(special(data.contents.toString()));
});
done();
}
} | [
"function",
"plugin",
"(",
"options",
")",
"{",
"return",
"function",
"(",
"files",
",",
"metalsmith",
",",
"done",
")",
"{",
"Object",
".",
"keys",
"(",
"files",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"data",
"=",
"files",
"[",
"file",
"]",
";",
"data",
".",
"contents",
"=",
"new",
"Buffer",
"(",
"special",
"(",
"data",
".",
"contents",
".",
"toString",
"(",
")",
")",
")",
";",
"}",
")",
";",
"done",
"(",
")",
";",
"}",
"}"
]
| Metalsmith plugin to sanitize special unicode chars in html
@param {Object or String} options (optional)
@return {Function} | [
"Metalsmith",
"plugin",
"to",
"sanitize",
"special",
"unicode",
"chars",
"in",
"html"
]
| d0581c95dc21520b28f6884a8b52e8601998eeb6 | https://github.com/damnit/metalsmith-htmlescape/blob/d0581c95dc21520b28f6884a8b52e8601998eeb6/lib/index.js#L17-L27 | train |
kevoree/kevoree-js | core/kevoree-core/kevoree-core.js | KevoreeCore | function KevoreeCore(resolver, kevscript, loggerFactory) {
if (!resolver || !kevscript || !loggerFactory) {
throw new Error('KevoreeCore constructor needs: Resolver, KevScript engine and a LoggerFactory');
}
this.resolver = resolver;
this.loggerFactory = loggerFactory;
this.log = loggerFactory.create('Core');
this.kevs = kevscript;
this.stopping = false;
this.currentModel = null;
this.deployModel = null;
this.nodeName = null;
this.nodeInstance = null;
this.firstBoot = true;
this.scriptQueue = [];
this.emitter = new EventEmitter();
} | javascript | function KevoreeCore(resolver, kevscript, loggerFactory) {
if (!resolver || !kevscript || !loggerFactory) {
throw new Error('KevoreeCore constructor needs: Resolver, KevScript engine and a LoggerFactory');
}
this.resolver = resolver;
this.loggerFactory = loggerFactory;
this.log = loggerFactory.create('Core');
this.kevs = kevscript;
this.stopping = false;
this.currentModel = null;
this.deployModel = null;
this.nodeName = null;
this.nodeInstance = null;
this.firstBoot = true;
this.scriptQueue = [];
this.emitter = new EventEmitter();
} | [
"function",
"KevoreeCore",
"(",
"resolver",
",",
"kevscript",
",",
"loggerFactory",
")",
"{",
"if",
"(",
"!",
"resolver",
"||",
"!",
"kevscript",
"||",
"!",
"loggerFactory",
")",
"{",
"throw",
"new",
"Error",
"(",
"'KevoreeCore constructor needs: Resolver, KevScript engine and a LoggerFactory'",
")",
";",
"}",
"this",
".",
"resolver",
"=",
"resolver",
";",
"this",
".",
"loggerFactory",
"=",
"loggerFactory",
";",
"this",
".",
"log",
"=",
"loggerFactory",
".",
"create",
"(",
"'Core'",
")",
";",
"this",
".",
"kevs",
"=",
"kevscript",
";",
"this",
".",
"stopping",
"=",
"false",
";",
"this",
".",
"currentModel",
"=",
"null",
";",
"this",
".",
"deployModel",
"=",
"null",
";",
"this",
".",
"nodeName",
"=",
"null",
";",
"this",
".",
"nodeInstance",
"=",
"null",
";",
"this",
".",
"firstBoot",
"=",
"true",
";",
"this",
".",
"scriptQueue",
"=",
"[",
"]",
";",
"this",
".",
"emitter",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"}"
]
| KevoreeCore is the kernel of the Kevoree JavaScript runtime
@param {Resolver} resolver service to download the DeployUnits
@param {KevScript} kevscript service to interpret the KevScript
@param {LoggerFactory} loggerFactory service to create loggers
@throws {Error} undefined constructor params
@constructor | [
"KevoreeCore",
"is",
"the",
"kernel",
"of",
"the",
"Kevoree",
"JavaScript",
"runtime"
]
| 7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd | https://github.com/kevoree/kevoree-js/blob/7eb62201a3bdf50ab0a6eb7f85424eecb44dbfcd/core/kevoree-core/kevoree-core.js#L16-L33 | train |
stezu/node-stream | lib/modifiers/filter.js | filter | function filter(condition) {
var cb = makeAsync(condition, 2);
return through.obj(function (chunk, enc, next) {
cb(chunk, function (err, keep) {
if (err) {
return next(err);
}
if (keep) {
return next(null, chunk);
}
return next();
});
});
} | javascript | function filter(condition) {
var cb = makeAsync(condition, 2);
return through.obj(function (chunk, enc, next) {
cb(chunk, function (err, keep) {
if (err) {
return next(err);
}
if (keep) {
return next(null, chunk);
}
return next();
});
});
} | [
"function",
"filter",
"(",
"condition",
")",
"{",
"var",
"cb",
"=",
"makeAsync",
"(",
"condition",
",",
"2",
")",
";",
"return",
"through",
".",
"obj",
"(",
"function",
"(",
"chunk",
",",
"enc",
",",
"next",
")",
"{",
"cb",
"(",
"chunk",
",",
"function",
"(",
"err",
",",
"keep",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
";",
"}",
"if",
"(",
"keep",
")",
"{",
"return",
"next",
"(",
"null",
",",
"chunk",
")",
";",
"}",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Creates a new stream with all elements that pass the test implemented by the
provided function. Similar to Array.filter... but on a stream.
@static
@since 1.0.0
@category Modifiers
@param {Function} condition - Function that filters elements on the stream.
Takes one argument, the value of the item at
this position in the stream.
@returns {Stream.Transform} - A transform stream with the filtered values.
@example
// If you wanted to create a new stream whose values all passed a certain criteria,
// you could do something like the following. Assuming "test-scores.txt" is a file
// containing the following data:
// Sally...90
// Tommy...94
// Jimmy...12
// Sarah...82
// Jonny...64
// We can write a function that returns the students who are failing:
fs.createReadStream('test-scores.txt')
.pipe(nodeStream.split()) // split on new lines
.pipe(nodeStream.filter(value => {
const [student, testScore] = value.toString().split('...');
return Number(testScore) < 70;
}));
// The resulting stream would have the following data:
// Jimmy...12
// Jonny...64
@example
// It is also possible to filter a stream asynchronously for more complex actions.
// Note: The signature of the function that you pass as the callback is important. It
// MUST have *two* parameters.
// Assuming "filenames.txt" is a newline-separated list of file names, you could
// create a new stream with only valid names by doing something like the following:
fs.createReadStream('filenames.txt')
.pipe(nodeStream.split()) // split on new lines
.pipe(nodeStream.filter((value, next) => {
fs.stat(value, (err, stats) => {
// Error the stream since this file is not valid
if (err) {
return next(err);
}
next(null, stats.isFile());
});
}));
// The resulting stream will contain the filenames that passed the test. Note: If `next`
// is called with an error as the first argument, the stream will error. This is typical
// behavior for node callbacks. | [
"Creates",
"a",
"new",
"stream",
"with",
"all",
"elements",
"that",
"pass",
"the",
"test",
"implemented",
"by",
"the",
"provided",
"function",
".",
"Similar",
"to",
"Array",
".",
"filter",
"...",
"but",
"on",
"a",
"stream",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/modifiers/filter.js#L68-L86 | train |
stezu/node-stream | lib/creators/fromArray.js | fromArray | function fromArray(source) {
var data;
if (!Array.isArray(source)) {
throw new TypeError('Expected `source` to be an array.');
}
// Copy the source array so we can modify it at will
data = source.slice();
return new Readable({
objectMode: true,
read: function () {
if (data.length > 0) {
this.push(data.shift());
} else {
this.push(null);
}
}
});
} | javascript | function fromArray(source) {
var data;
if (!Array.isArray(source)) {
throw new TypeError('Expected `source` to be an array.');
}
// Copy the source array so we can modify it at will
data = source.slice();
return new Readable({
objectMode: true,
read: function () {
if (data.length > 0) {
this.push(data.shift());
} else {
this.push(null);
}
}
});
} | [
"function",
"fromArray",
"(",
"source",
")",
"{",
"var",
"data",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"source",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expected `source` to be an array.'",
")",
";",
"}",
"data",
"=",
"source",
".",
"slice",
"(",
")",
";",
"return",
"new",
"Readable",
"(",
"{",
"objectMode",
":",
"true",
",",
"read",
":",
"function",
"(",
")",
"{",
"if",
"(",
"data",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"push",
"(",
"data",
".",
"shift",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"push",
"(",
"null",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Creates a new readable stream from an array. This is primarily useful for
piping into additional node-stream methods like map, reduce and filter.
@static
@since 1.6.0
@category Creators
@param {Array} source - An array which will be converted to a stream. If an item
in the array is `null` the stream will end early. Every
other data type is allowed and valid.
@returns {Stream.Readable} - Readable stream.
@throws {TypeError} - If `source` is not an array.
@example
// Create a stream from an array which is then piped to another node-stream method
nodeStream.fromArray(['file1.txt', 'file2.txt', 'file3.txt'])
.pipe(nodeStream.map(fs.readFile));
// => ['contents of file1.txt', 'contents of file2.txt', 'contents of file3.txt'] | [
"Creates",
"a",
"new",
"readable",
"stream",
"from",
"an",
"array",
".",
"This",
"is",
"primarily",
"useful",
"for",
"piping",
"into",
"additional",
"node",
"-",
"stream",
"methods",
"like",
"map",
"reduce",
"and",
"filter",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/creators/fromArray.js#L25-L46 | train |
joeyespo/gesso.js | client/delegate.js | Delegate | function Delegate(subscribed, unsubscribed) {
var handlers = [];
function callable(handler) {
if (arguments.length !== 1) {
throw new Error('Delegate takes exactly 1 argument (' + arguments.length + ' given)');
} else if (typeof handler !== 'function') {
throw new Error('Delegate argument must be a Function object (got ' + typeof handler + ')');
}
// Add the handler
handlers.push(handler);
// Allow custom logic on subscribe, passing in the handler
var subscribedResult;
if (subscribed) {
subscribedResult = subscribed(handler);
}
// Return the unsubscribe function
return function unsubscribe() {
var initialHandler = util.removeLast(handlers, handler);
// Allow custom logic on unsubscribe, passing in the original handler
if (unsubscribed) {
unsubscribed(initialHandler, subscribedResult);
}
// Return the original handler
return initialHandler;
};
}
callable.invoke = function invoke() {
var args = arguments;
util.forEach(handlers, function (handler) {
handler.apply(null, args);
});
};
// Expose handlers for inspection
callable.handlers = handlers;
return callable;
} | javascript | function Delegate(subscribed, unsubscribed) {
var handlers = [];
function callable(handler) {
if (arguments.length !== 1) {
throw new Error('Delegate takes exactly 1 argument (' + arguments.length + ' given)');
} else if (typeof handler !== 'function') {
throw new Error('Delegate argument must be a Function object (got ' + typeof handler + ')');
}
// Add the handler
handlers.push(handler);
// Allow custom logic on subscribe, passing in the handler
var subscribedResult;
if (subscribed) {
subscribedResult = subscribed(handler);
}
// Return the unsubscribe function
return function unsubscribe() {
var initialHandler = util.removeLast(handlers, handler);
// Allow custom logic on unsubscribe, passing in the original handler
if (unsubscribed) {
unsubscribed(initialHandler, subscribedResult);
}
// Return the original handler
return initialHandler;
};
}
callable.invoke = function invoke() {
var args = arguments;
util.forEach(handlers, function (handler) {
handler.apply(null, args);
});
};
// Expose handlers for inspection
callable.handlers = handlers;
return callable;
} | [
"function",
"Delegate",
"(",
"subscribed",
",",
"unsubscribed",
")",
"{",
"var",
"handlers",
"=",
"[",
"]",
";",
"function",
"callable",
"(",
"handler",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"!==",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Delegate takes exactly 1 argument ('",
"+",
"arguments",
".",
"length",
"+",
"' given)'",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"handler",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Delegate argument must be a Function object (got '",
"+",
"typeof",
"handler",
"+",
"')'",
")",
";",
"}",
"handlers",
".",
"push",
"(",
"handler",
")",
";",
"var",
"subscribedResult",
";",
"if",
"(",
"subscribed",
")",
"{",
"subscribedResult",
"=",
"subscribed",
"(",
"handler",
")",
";",
"}",
"return",
"function",
"unsubscribe",
"(",
")",
"{",
"var",
"initialHandler",
"=",
"util",
".",
"removeLast",
"(",
"handlers",
",",
"handler",
")",
";",
"if",
"(",
"unsubscribed",
")",
"{",
"unsubscribed",
"(",
"initialHandler",
",",
"subscribedResult",
")",
";",
"}",
"return",
"initialHandler",
";",
"}",
";",
"}",
"callable",
".",
"invoke",
"=",
"function",
"invoke",
"(",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"util",
".",
"forEach",
"(",
"handlers",
",",
"function",
"(",
"handler",
")",
"{",
"handler",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}",
")",
";",
"}",
";",
"callable",
".",
"handlers",
"=",
"handlers",
";",
"return",
"callable",
";",
"}"
]
| Returns a callable object that, when called with a function, subscribes to the delegate. Call invoke on this object to invoke each handler. | [
"Returns",
"a",
"callable",
"object",
"that",
"when",
"called",
"with",
"a",
"function",
"subscribes",
"to",
"the",
"delegate",
".",
"Call",
"invoke",
"on",
"this",
"object",
"to",
"invoke",
"each",
"handler",
"."
]
| b4858dfc607aab13342474930c174b5b82f98267 | https://github.com/joeyespo/gesso.js/blob/b4858dfc607aab13342474930c174b5b82f98267/client/delegate.js#L5-L42 | train |
wanderview/node-netbios-name | name.js | _decompressName | function _decompressName(buf, offset) {
var name = '';
var bytes = 0;
var octet = buf.readUInt8(offset + bytes);
bytes += 1;
// The name is made up of a variable number of labels. Each label begins
// with a length octet. The string of labels is ended by a zero length octet.
while (octet) {
var label = null;
// The first 2-bits of the octet are flags indicating if this is a length
// value or a label pointer to elsewhere in the packet.
var flags = octet & 0xc0;
// If both the top 2-bits of the octet are set, then this is an offset pointer.
if (flags === 0xc0) {
// NOTE: The number of bytes parsed was already incremented. We need
// to re-read that first byte to incorporate it into our pointer
// value. Therefore subtract one from the offset and only add
// one additional byte to the parsed count.
var pointer = buf.readUInt16BE(offset + bytes - 1) & 0x3fff;
bytes += 1;
// NOTE: This will only work if the start of the buffer corresponds to
// the start of the packet. If the packet is embedded in a larger
// buffer then we need to pass through the offset to the start of
// the packet.
var res = _decompressName(buf, pointer);
if (res.error) {
return res;
}
label = res.name;
if (!label) {
return {bytesRead: bytes, name: name}
}
// Once a pointer is used the name section is complete. We do not need
// to keep looking for a zero length octet. Note there is some logic at
// the end of the loop we still want to execute, so simply set octet to
// zero to terminate the loop instead of breaking.
octet = 0;
// If neither of the bits are set then the name is stored inline in the
// following bytes. The name length is defined by the lower 6-bits of the
// octet.
} else if (flags === 0) {
var length = octet & 0x3f;
if (offset + bytes + length > buf.length) {
return {
error: new Error('Name label too large to fit in remaining packet ' +
'bytes.')
};
}
label = buf.toString('ascii', offset + bytes, offset + bytes + length);
bytes += length;
// Look for the next label's length octet
octet = buf.readUInt8(offset + bytes);
bytes += 1;
// Any other values are undefined, so throw an error.
} else {
return {
error: new Error('Label length octet at offset [' +
(offset + bytes - 1) + '] has unexpected top 2-bits ' +
'of [' + flags + ']; should be [' + 0xc0 + '] or ' +
'[0].')
};
}
// Append to the last parsed label to the name. Separate labels with
// periods.
if (name.length > 0) {
name += '.';
}
name += label;
}
return {bytesRead: bytes, name: name};
} | javascript | function _decompressName(buf, offset) {
var name = '';
var bytes = 0;
var octet = buf.readUInt8(offset + bytes);
bytes += 1;
// The name is made up of a variable number of labels. Each label begins
// with a length octet. The string of labels is ended by a zero length octet.
while (octet) {
var label = null;
// The first 2-bits of the octet are flags indicating if this is a length
// value or a label pointer to elsewhere in the packet.
var flags = octet & 0xc0;
// If both the top 2-bits of the octet are set, then this is an offset pointer.
if (flags === 0xc0) {
// NOTE: The number of bytes parsed was already incremented. We need
// to re-read that first byte to incorporate it into our pointer
// value. Therefore subtract one from the offset and only add
// one additional byte to the parsed count.
var pointer = buf.readUInt16BE(offset + bytes - 1) & 0x3fff;
bytes += 1;
// NOTE: This will only work if the start of the buffer corresponds to
// the start of the packet. If the packet is embedded in a larger
// buffer then we need to pass through the offset to the start of
// the packet.
var res = _decompressName(buf, pointer);
if (res.error) {
return res;
}
label = res.name;
if (!label) {
return {bytesRead: bytes, name: name}
}
// Once a pointer is used the name section is complete. We do not need
// to keep looking for a zero length octet. Note there is some logic at
// the end of the loop we still want to execute, so simply set octet to
// zero to terminate the loop instead of breaking.
octet = 0;
// If neither of the bits are set then the name is stored inline in the
// following bytes. The name length is defined by the lower 6-bits of the
// octet.
} else if (flags === 0) {
var length = octet & 0x3f;
if (offset + bytes + length > buf.length) {
return {
error: new Error('Name label too large to fit in remaining packet ' +
'bytes.')
};
}
label = buf.toString('ascii', offset + bytes, offset + bytes + length);
bytes += length;
// Look for the next label's length octet
octet = buf.readUInt8(offset + bytes);
bytes += 1;
// Any other values are undefined, so throw an error.
} else {
return {
error: new Error('Label length octet at offset [' +
(offset + bytes - 1) + '] has unexpected top 2-bits ' +
'of [' + flags + ']; should be [' + 0xc0 + '] or ' +
'[0].')
};
}
// Append to the last parsed label to the name. Separate labels with
// periods.
if (name.length > 0) {
name += '.';
}
name += label;
}
return {bytesRead: bytes, name: name};
} | [
"function",
"_decompressName",
"(",
"buf",
",",
"offset",
")",
"{",
"var",
"name",
"=",
"''",
";",
"var",
"bytes",
"=",
"0",
";",
"var",
"octet",
"=",
"buf",
".",
"readUInt8",
"(",
"offset",
"+",
"bytes",
")",
";",
"bytes",
"+=",
"1",
";",
"while",
"(",
"octet",
")",
"{",
"var",
"label",
"=",
"null",
";",
"var",
"flags",
"=",
"octet",
"&",
"0xc0",
";",
"if",
"(",
"flags",
"===",
"0xc0",
")",
"{",
"var",
"pointer",
"=",
"buf",
".",
"readUInt16BE",
"(",
"offset",
"+",
"bytes",
"-",
"1",
")",
"&",
"0x3fff",
";",
"bytes",
"+=",
"1",
";",
"var",
"res",
"=",
"_decompressName",
"(",
"buf",
",",
"pointer",
")",
";",
"if",
"(",
"res",
".",
"error",
")",
"{",
"return",
"res",
";",
"}",
"label",
"=",
"res",
".",
"name",
";",
"if",
"(",
"!",
"label",
")",
"{",
"return",
"{",
"bytesRead",
":",
"bytes",
",",
"name",
":",
"name",
"}",
"}",
"octet",
"=",
"0",
";",
"}",
"else",
"if",
"(",
"flags",
"===",
"0",
")",
"{",
"var",
"length",
"=",
"octet",
"&",
"0x3f",
";",
"if",
"(",
"offset",
"+",
"bytes",
"+",
"length",
">",
"buf",
".",
"length",
")",
"{",
"return",
"{",
"error",
":",
"new",
"Error",
"(",
"'Name label too large to fit in remaining packet '",
"+",
"'bytes.'",
")",
"}",
";",
"}",
"label",
"=",
"buf",
".",
"toString",
"(",
"'ascii'",
",",
"offset",
"+",
"bytes",
",",
"offset",
"+",
"bytes",
"+",
"length",
")",
";",
"bytes",
"+=",
"length",
";",
"octet",
"=",
"buf",
".",
"readUInt8",
"(",
"offset",
"+",
"bytes",
")",
";",
"bytes",
"+=",
"1",
";",
"}",
"else",
"{",
"return",
"{",
"error",
":",
"new",
"Error",
"(",
"'Label length octet at offset ['",
"+",
"(",
"offset",
"+",
"bytes",
"-",
"1",
")",
"+",
"'] has unexpected top 2-bits '",
"+",
"'of ['",
"+",
"flags",
"+",
"']; should be ['",
"+",
"0xc0",
"+",
"'] or '",
"+",
"'[0].'",
")",
"}",
";",
"}",
"if",
"(",
"name",
".",
"length",
">",
"0",
")",
"{",
"name",
"+=",
"'.'",
";",
"}",
"name",
"+=",
"label",
";",
"}",
"return",
"{",
"bytesRead",
":",
"bytes",
",",
"name",
":",
"name",
"}",
";",
"}"
]
| Decompress the name from the packet. The compression scheme is defined in RFC 883 and is the same method used in DNS packets. Essentially, names are stored in parts called labels. Each label is preceded by a 2-bit flag field and 6-bit length field. In the common case the 2-bits are zero and the length indicates how many bytes are in that label. The parsing process is terminated by a zero length label. Alternatively, a the 2-bit flags can both be set indicating a label pointer. In that case the following 14-bits indicate an offset into the packet from which to read the remaining labels for the name. | [
"Decompress",
"the",
"name",
"from",
"the",
"packet",
".",
"The",
"compression",
"scheme",
"is",
"defined",
"in",
"RFC",
"883",
"and",
"is",
"the",
"same",
"method",
"used",
"in",
"DNS",
"packets",
".",
"Essentially",
"names",
"are",
"stored",
"in",
"parts",
"called",
"labels",
".",
"Each",
"label",
"is",
"preceded",
"by",
"a",
"2",
"-",
"bit",
"flag",
"field",
"and",
"6",
"-",
"bit",
"length",
"field",
".",
"In",
"the",
"common",
"case",
"the",
"2",
"-",
"bits",
"are",
"zero",
"and",
"the",
"length",
"indicates",
"how",
"many",
"bytes",
"are",
"in",
"that",
"label",
".",
"The",
"parsing",
"process",
"is",
"terminated",
"by",
"a",
"zero",
"length",
"label",
".",
"Alternatively",
"a",
"the",
"2",
"-",
"bit",
"flags",
"can",
"both",
"be",
"set",
"indicating",
"a",
"label",
"pointer",
".",
"In",
"that",
"case",
"the",
"following",
"14",
"-",
"bits",
"indicate",
"an",
"offset",
"into",
"the",
"packet",
"from",
"which",
"to",
"read",
"the",
"remaining",
"labels",
"for",
"the",
"name",
"."
]
| d803bedf260e572ab3470a36d4ddef8ce5bc3d45 | https://github.com/wanderview/node-netbios-name/blob/d803bedf260e572ab3470a36d4ddef8ce5bc3d45/name.js#L187-L272 | train |
wanderview/node-netbios-name | name.js | _decodeName | function _decodeName (name) {
var encoded = name;
var periodIndex = name.indexOf('.');
if (periodIndex > -1) {
encoded = name.slice(0, periodIndex);
}
var decoded = '';
var suffix = 0;
var charValue = 0;;
for (var i = 0, n = encoded.length; i < n; ++i) {
// decode char to first nibble
if (i % 2 === 0) {
charValue = (encoded.charCodeAt(i) - 'A'.charCodeAt(0)) << 4;
// decore char to second nibble and then combine with first nibble
} else {
charValue += encoded.charCodeAt(i) - 'A'.charCodeAt(0);
// Append the newly decoded character for the first 15 bytes
if (i < (encoded.length - 1)) {
decoded += String.fromCharCode(charValue);
// The last byte is reserved by convention as the suffix or type
} else {
suffix = charValue;
}
}
}
// NetBIOS names are always space padded out to 15 characters
decoded = decoded.trim();
// If there was a scope identifier (domain name) after the NetBIOS name
// then re-append it to the newly decoded name.
if (periodIndex > -1) {
decoded += name.slice(periodIndex);
}
return {fqdn: decoded, suffix: suffix};
} | javascript | function _decodeName (name) {
var encoded = name;
var periodIndex = name.indexOf('.');
if (periodIndex > -1) {
encoded = name.slice(0, periodIndex);
}
var decoded = '';
var suffix = 0;
var charValue = 0;;
for (var i = 0, n = encoded.length; i < n; ++i) {
// decode char to first nibble
if (i % 2 === 0) {
charValue = (encoded.charCodeAt(i) - 'A'.charCodeAt(0)) << 4;
// decore char to second nibble and then combine with first nibble
} else {
charValue += encoded.charCodeAt(i) - 'A'.charCodeAt(0);
// Append the newly decoded character for the first 15 bytes
if (i < (encoded.length - 1)) {
decoded += String.fromCharCode(charValue);
// The last byte is reserved by convention as the suffix or type
} else {
suffix = charValue;
}
}
}
// NetBIOS names are always space padded out to 15 characters
decoded = decoded.trim();
// If there was a scope identifier (domain name) after the NetBIOS name
// then re-append it to the newly decoded name.
if (periodIndex > -1) {
decoded += name.slice(periodIndex);
}
return {fqdn: decoded, suffix: suffix};
} | [
"function",
"_decodeName",
"(",
"name",
")",
"{",
"var",
"encoded",
"=",
"name",
";",
"var",
"periodIndex",
"=",
"name",
".",
"indexOf",
"(",
"'.'",
")",
";",
"if",
"(",
"periodIndex",
">",
"-",
"1",
")",
"{",
"encoded",
"=",
"name",
".",
"slice",
"(",
"0",
",",
"periodIndex",
")",
";",
"}",
"var",
"decoded",
"=",
"''",
";",
"var",
"suffix",
"=",
"0",
";",
"var",
"charValue",
"=",
"0",
";",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"encoded",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"if",
"(",
"i",
"%",
"2",
"===",
"0",
")",
"{",
"charValue",
"=",
"(",
"encoded",
".",
"charCodeAt",
"(",
"i",
")",
"-",
"'A'",
".",
"charCodeAt",
"(",
"0",
")",
")",
"<<",
"4",
";",
"}",
"else",
"{",
"charValue",
"+=",
"encoded",
".",
"charCodeAt",
"(",
"i",
")",
"-",
"'A'",
".",
"charCodeAt",
"(",
"0",
")",
";",
"if",
"(",
"i",
"<",
"(",
"encoded",
".",
"length",
"-",
"1",
")",
")",
"{",
"decoded",
"+=",
"String",
".",
"fromCharCode",
"(",
"charValue",
")",
";",
"}",
"else",
"{",
"suffix",
"=",
"charValue",
";",
"}",
"}",
"}",
"decoded",
"=",
"decoded",
".",
"trim",
"(",
")",
";",
"if",
"(",
"periodIndex",
">",
"-",
"1",
")",
"{",
"decoded",
"+=",
"name",
".",
"slice",
"(",
"periodIndex",
")",
";",
"}",
"return",
"{",
"fqdn",
":",
"decoded",
",",
"suffix",
":",
"suffix",
"}",
";",
"}"
]
| Decode the NetBIOS name after it has been decompressed. The NetBIOS name is represented as the first part of the FQDN. See page 26 of RFC 1001 for full details on the encoding algorithm. In short, each byte of the original NetBIOS name is split into two nibbles. Each nibble is then encoded as a separate byte by adding the ASCII value for 'A'. In order to decode we therefore must reverse this logic. | [
"Decode",
"the",
"NetBIOS",
"name",
"after",
"it",
"has",
"been",
"decompressed",
".",
"The",
"NetBIOS",
"name",
"is",
"represented",
"as",
"the",
"first",
"part",
"of",
"the",
"FQDN",
".",
"See",
"page",
"26",
"of",
"RFC",
"1001",
"for",
"full",
"details",
"on",
"the",
"encoding",
"algorithm",
".",
"In",
"short",
"each",
"byte",
"of",
"the",
"original",
"NetBIOS",
"name",
"is",
"split",
"into",
"two",
"nibbles",
".",
"Each",
"nibble",
"is",
"then",
"encoded",
"as",
"a",
"separate",
"byte",
"by",
"adding",
"the",
"ASCII",
"value",
"for",
"A",
".",
"In",
"order",
"to",
"decode",
"we",
"therefore",
"must",
"reverse",
"this",
"logic",
"."
]
| d803bedf260e572ab3470a36d4ddef8ce5bc3d45 | https://github.com/wanderview/node-netbios-name/blob/d803bedf260e572ab3470a36d4ddef8ce5bc3d45/name.js#L280-L322 | train |
stezu/node-stream | lib/creators/fromPromise.js | fromPromise | function fromPromise(source) {
var callCount = 0;
// Throw an error if the source is not a promise
if (
typeof source !== 'object' ||
source === null ||
typeof source.then !== 'function'
) {
throw new TypeError('Expected `source` to be a promise.');
}
return new Readable({
objectMode: true,
read: function () {
var self = this;
// Increment the number of calls so we know when to push null
callCount += 1;
// Listen to the promise and push results if this is the first call
if (callCount === 1) {
source.then(
function onResolve(data) {
self.push(data);
},
function onReject(err) {
process.nextTick(function () {
self.emit('error', err);
});
}
);
return;
}
// End the stream
self.push(null);
}
});
} | javascript | function fromPromise(source) {
var callCount = 0;
// Throw an error if the source is not a promise
if (
typeof source !== 'object' ||
source === null ||
typeof source.then !== 'function'
) {
throw new TypeError('Expected `source` to be a promise.');
}
return new Readable({
objectMode: true,
read: function () {
var self = this;
// Increment the number of calls so we know when to push null
callCount += 1;
// Listen to the promise and push results if this is the first call
if (callCount === 1) {
source.then(
function onResolve(data) {
self.push(data);
},
function onReject(err) {
process.nextTick(function () {
self.emit('error', err);
});
}
);
return;
}
// End the stream
self.push(null);
}
});
} | [
"function",
"fromPromise",
"(",
"source",
")",
"{",
"var",
"callCount",
"=",
"0",
";",
"if",
"(",
"typeof",
"source",
"!==",
"'object'",
"||",
"source",
"===",
"null",
"||",
"typeof",
"source",
".",
"then",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expected `source` to be a promise.'",
")",
";",
"}",
"return",
"new",
"Readable",
"(",
"{",
"objectMode",
":",
"true",
",",
"read",
":",
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"callCount",
"+=",
"1",
";",
"if",
"(",
"callCount",
"===",
"1",
")",
"{",
"source",
".",
"then",
"(",
"function",
"onResolve",
"(",
"data",
")",
"{",
"self",
".",
"push",
"(",
"data",
")",
";",
"}",
",",
"function",
"onReject",
"(",
"err",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"self",
".",
"push",
"(",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Creates a new readable stream from a promise. This is primarily useful for
piping into additional node-stream methods like map, reduce and filter.
@static
@since 1.6.0
@category Creators
@param {Promise} source - A promise which will be converted to a stream. If the promise
resolves, each argument becomes a discrete item in the stream.
If the promise rejects, the stream will emit an "error" event.
@returns {Stream.Readable} - Readable stream.
@throws {TypeError} - If `source` is not a promise.
@example
// Create a stream from a promise
nodeStream.fromPromise(globby('*.js'))
.pipe(nodeStream.map(fs.readFile));
// => ['contents of file1.js', 'contents of file2.js', 'contents of file3.js'] | [
"Creates",
"a",
"new",
"readable",
"stream",
"from",
"a",
"promise",
".",
"This",
"is",
"primarily",
"useful",
"for",
"piping",
"into",
"additional",
"node",
"-",
"stream",
"methods",
"like",
"map",
"reduce",
"and",
"filter",
"."
]
| f70c03351746c958865a854f614932f1df441b9b | https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/creators/fromPromise.js#L25-L66 | train |
skerit/protoblast | lib/informer.js | wait | function wait(type) {
var that = this,
config = this.asyncConfig;
if (type !== 'series') {
type = 'parallel';
}
// Indicate we're going to have to wait
config.async = type;
function next(err) {
config.err = err;
config.ListenerIsDone = true;
if (config.ListenerCallback) {
config.ListenerCallback(err);
}
};
return next;
} | javascript | function wait(type) {
var that = this,
config = this.asyncConfig;
if (type !== 'series') {
type = 'parallel';
}
// Indicate we're going to have to wait
config.async = type;
function next(err) {
config.err = err;
config.ListenerIsDone = true;
if (config.ListenerCallback) {
config.ListenerCallback(err);
}
};
return next;
} | [
"function",
"wait",
"(",
"type",
")",
"{",
"var",
"that",
"=",
"this",
",",
"config",
"=",
"this",
".",
"asyncConfig",
";",
"if",
"(",
"type",
"!==",
"'series'",
")",
"{",
"type",
"=",
"'parallel'",
";",
"}",
"config",
".",
"async",
"=",
"type",
";",
"function",
"next",
"(",
"err",
")",
"{",
"config",
".",
"err",
"=",
"err",
";",
"config",
".",
"ListenerIsDone",
"=",
"true",
";",
"if",
"(",
"config",
".",
"ListenerCallback",
")",
"{",
"config",
".",
"ListenerCallback",
"(",
"err",
")",
";",
"}",
"}",
";",
"return",
"next",
";",
"}"
]
| A method to indicate we have to wait for it to finish,
because it is asynchronous.
@author Jelle De Loecker <[email protected]>
@since 0.1.3
@version 0.1.4
@return {Function} The function to call when done | [
"A",
"method",
"to",
"indicate",
"we",
"have",
"to",
"wait",
"for",
"it",
"to",
"finish",
"because",
"it",
"is",
"asynchronous",
"."
]
| 22f35b05611bd507d380782023179a3f6ec383ae | https://github.com/skerit/protoblast/blob/22f35b05611bd507d380782023179a3f6ec383ae/lib/informer.js#L1194-L1216 | train |
preceptorjs/taxi | lib/json.js | parse | function parse (str) {
if (Buffer.isBuffer(str)) str = str.toString();
type('str', str, 'String');
try {
return JSON.parse(str);
} catch (ex) {
ex.message = 'Unable to parse JSON: ' + ex.message + '\nAttempted to parse: ' + str;
throw ex;
}
} | javascript | function parse (str) {
if (Buffer.isBuffer(str)) str = str.toString();
type('str', str, 'String');
try {
return JSON.parse(str);
} catch (ex) {
ex.message = 'Unable to parse JSON: ' + ex.message + '\nAttempted to parse: ' + str;
throw ex;
}
} | [
"function",
"parse",
"(",
"str",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"str",
")",
")",
"str",
"=",
"str",
".",
"toString",
"(",
")",
";",
"type",
"(",
"'str'",
",",
"str",
",",
"'String'",
")",
";",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"str",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"ex",
".",
"message",
"=",
"'Unable to parse JSON: '",
"+",
"ex",
".",
"message",
"+",
"'\\nAttempted to parse: '",
"+",
"\\n",
";",
"str",
"}",
"}"
]
| Parse a JSON string to a js-value
Note: Small wrapper around standard JSON parser
@param {String} str
@return {*} | [
"Parse",
"a",
"JSON",
"string",
"to",
"a",
"js",
"-",
"value"
]
| 96ab5a5c5fa9dc50f325ba4de52dd90009073ca3 | https://github.com/preceptorjs/taxi/blob/96ab5a5c5fa9dc50f325ba4de52dd90009073ca3/lib/json.js#L26-L35 | train |
romelperez/prhone-log | lib/index.js | function (obj) {
obj = obj || {};
var exts = Array.prototype.slice.call(arguments, 1);
for (var k=0; k<exts.length; k++) {
if (exts[k]) {
for (var i in exts[k]) {
if (exts[k].hasOwnProperty(i)) {
obj[i] = exts[k][i];
}
}
}
}
return obj;
} | javascript | function (obj) {
obj = obj || {};
var exts = Array.prototype.slice.call(arguments, 1);
for (var k=0; k<exts.length; k++) {
if (exts[k]) {
for (var i in exts[k]) {
if (exts[k].hasOwnProperty(i)) {
obj[i] = exts[k][i];
}
}
}
}
return obj;
} | [
"function",
"(",
"obj",
")",
"{",
"obj",
"=",
"obj",
"||",
"{",
"}",
";",
"var",
"exts",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<",
"exts",
".",
"length",
";",
"k",
"++",
")",
"{",
"if",
"(",
"exts",
"[",
"k",
"]",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"exts",
"[",
"k",
"]",
")",
"{",
"if",
"(",
"exts",
"[",
"k",
"]",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"obj",
"[",
"i",
"]",
"=",
"exts",
"[",
"k",
"]",
"[",
"i",
"]",
";",
"}",
"}",
"}",
"}",
"return",
"obj",
";",
"}"
]
| Simple extend object. Receives many objects. It will not copy deep objects.
@private
@param {Object} obj - The object to extend.
@return {Object} - `obj` extended. | [
"Simple",
"extend",
"object",
".",
"Receives",
"many",
"objects",
".",
"It",
"will",
"not",
"copy",
"deep",
"objects",
"."
]
| 52cb8290d1a42240fcea49280e652d0265bd0c92 | https://github.com/romelperez/prhone-log/blob/52cb8290d1a42240fcea49280e652d0265bd0c92/lib/index.js#L23-L36 | train |
|
romelperez/prhone-log | lib/index.js | function (time, n) {
time = Number(time) || 0;
n = n || 2;
if (n === 2) {
time = time < 10 ? time + '0' : time;
} else if (n === 3) {
time = time < 10
? time + '00'
: time < 100
? time + '0'
: time;
}
return String(time);
} | javascript | function (time, n) {
time = Number(time) || 0;
n = n || 2;
if (n === 2) {
time = time < 10 ? time + '0' : time;
} else if (n === 3) {
time = time < 10
? time + '00'
: time < 100
? time + '0'
: time;
}
return String(time);
} | [
"function",
"(",
"time",
",",
"n",
")",
"{",
"time",
"=",
"Number",
"(",
"time",
")",
"||",
"0",
";",
"n",
"=",
"n",
"||",
"2",
";",
"if",
"(",
"n",
"===",
"2",
")",
"{",
"time",
"=",
"time",
"<",
"10",
"?",
"time",
"+",
"'0'",
":",
"time",
";",
"}",
"else",
"if",
"(",
"n",
"===",
"3",
")",
"{",
"time",
"=",
"time",
"<",
"10",
"?",
"time",
"+",
"'00'",
":",
"time",
"<",
"100",
"?",
"time",
"+",
"'0'",
":",
"time",
";",
"}",
"return",
"String",
"(",
"time",
")",
";",
"}"
]
| Format a time number.
@private
@param {Number} time
@param {Number} n - Number of digits to show. Default 2.
@return {String} | [
"Format",
"a",
"time",
"number",
"."
]
| 52cb8290d1a42240fcea49280e652d0265bd0c92 | https://github.com/romelperez/prhone-log/blob/52cb8290d1a42240fcea49280e652d0265bd0c92/lib/index.js#L58-L73 | train |
|
romelperez/prhone-log | lib/index.js | function (level) {
if (!level || typeof level !== 'object') {
throw new Error('The first parameter must be an object describing the level.');
}
if (typeof level.name !== 'string' || !level.name.length) {
throw new Error('The level object must have a name property.');
}
return extend({
name: null,
priority: 3,
color: null
}, level);
} | javascript | function (level) {
if (!level || typeof level !== 'object') {
throw new Error('The first parameter must be an object describing the level.');
}
if (typeof level.name !== 'string' || !level.name.length) {
throw new Error('The level object must have a name property.');
}
return extend({
name: null,
priority: 3,
color: null
}, level);
} | [
"function",
"(",
"level",
")",
"{",
"if",
"(",
"!",
"level",
"||",
"typeof",
"level",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The first parameter must be an object describing the level.'",
")",
";",
"}",
"if",
"(",
"typeof",
"level",
".",
"name",
"!==",
"'string'",
"||",
"!",
"level",
".",
"name",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The level object must have a name property.'",
")",
";",
"}",
"return",
"extend",
"(",
"{",
"name",
":",
"null",
",",
"priority",
":",
"3",
",",
"color",
":",
"null",
"}",
",",
"level",
")",
";",
"}"
]
| Parse new level.
@private
@param {Object} level | [
"Parse",
"new",
"level",
"."
]
| 52cb8290d1a42240fcea49280e652d0265bd0c92 | https://github.com/romelperez/prhone-log/blob/52cb8290d1a42240fcea49280e652d0265bd0c92/lib/index.js#L80-L94 | train |
|
strongloop/strong-github-api | lib/issue-finder.js | IssueFinder | function IssueFinder(options) {
this.octo = options.octo;
this.repo = options.repo;
this.owner = options.owner;
assert(this.octo, 'No octokat instance provided!');
} | javascript | function IssueFinder(options) {
this.octo = options.octo;
this.repo = options.repo;
this.owner = options.owner;
assert(this.octo, 'No octokat instance provided!');
} | [
"function",
"IssueFinder",
"(",
"options",
")",
"{",
"this",
".",
"octo",
"=",
"options",
".",
"octo",
";",
"this",
".",
"repo",
"=",
"options",
".",
"repo",
";",
"this",
".",
"owner",
"=",
"options",
".",
"owner",
";",
"assert",
"(",
"this",
".",
"octo",
",",
"'No octokat instance provided!'",
")",
";",
"}"
]
| A class library for retrieving and filtering
GitHub issues.
@constructor
@param {object} options - The options object.
@param {object} options.octo - The instance of octokat that will be used
for search operations.
@param {string} options.repo - The name of the repository on GitHub.
@param {string} options.owner - The name of the owner or organization on
GitHub to which the repository belongs. | [
"A",
"class",
"library",
"for",
"retrieving",
"and",
"filtering",
"GitHub",
"issues",
"."
]
| 4eb72be7146c830b74e1a43f6e91e8085ce4ed89 | https://github.com/strongloop/strong-github-api/blob/4eb72be7146c830b74e1a43f6e91e8085ce4ed89/lib/issue-finder.js#L23-L28 | train |
ruudboon/node-davis-vantage | main.js | _setupSerialConnection | function _setupSerialConnection() {
var port = availablePorts[0];
debug.log('Trying to connect to Davis VUE via port: ' + port);
// Open serial port connection
var sp = new serialPort(port, config.serialPort);
var received = '';
sp.on('open', function () {
debug.log('Serial connection established, waking up device.');
sp.write('\n', function(err) {
if (err) {
return constructor.emit('Error on write: ', err.message);
}
});
sp.on('data', function (data) {
if (!deviceAwake){
if (data.toString() === '\n\r'){
debug.log('Device is awake');
serialPortUsed = port;
constructor.emit('connected', port);
sp.write('LOOP 1\n');
return;
}
}
debug.log("Received data, length:" + data.length);
if (data.length == 100){
// remove ack
data = data.slice(1);
}
var parsedData = parsePacket(data);
constructor.emit('data', parsedData);
setTimeout(function () {
sp.write('LOOP 1\n');
}, 2000);
});
});
sp.on('error', function (error) {
constructor.emit('error', error);
// Reject this port if we haven't found the correct port yet
if (!serialPortUsed) {
_tryNextSerialPort();
}
});
sp.on('close', function () {
deviceAwake = false;
constructor.emit('close');
});
} | javascript | function _setupSerialConnection() {
var port = availablePorts[0];
debug.log('Trying to connect to Davis VUE via port: ' + port);
// Open serial port connection
var sp = new serialPort(port, config.serialPort);
var received = '';
sp.on('open', function () {
debug.log('Serial connection established, waking up device.');
sp.write('\n', function(err) {
if (err) {
return constructor.emit('Error on write: ', err.message);
}
});
sp.on('data', function (data) {
if (!deviceAwake){
if (data.toString() === '\n\r'){
debug.log('Device is awake');
serialPortUsed = port;
constructor.emit('connected', port);
sp.write('LOOP 1\n');
return;
}
}
debug.log("Received data, length:" + data.length);
if (data.length == 100){
// remove ack
data = data.slice(1);
}
var parsedData = parsePacket(data);
constructor.emit('data', parsedData);
setTimeout(function () {
sp.write('LOOP 1\n');
}, 2000);
});
});
sp.on('error', function (error) {
constructor.emit('error', error);
// Reject this port if we haven't found the correct port yet
if (!serialPortUsed) {
_tryNextSerialPort();
}
});
sp.on('close', function () {
deviceAwake = false;
constructor.emit('close');
});
} | [
"function",
"_setupSerialConnection",
"(",
")",
"{",
"var",
"port",
"=",
"availablePorts",
"[",
"0",
"]",
";",
"debug",
".",
"log",
"(",
"'Trying to connect to Davis VUE via port: '",
"+",
"port",
")",
";",
"var",
"sp",
"=",
"new",
"serialPort",
"(",
"port",
",",
"config",
".",
"serialPort",
")",
";",
"var",
"received",
"=",
"''",
";",
"sp",
".",
"on",
"(",
"'open'",
",",
"function",
"(",
")",
"{",
"debug",
".",
"log",
"(",
"'Serial connection established, waking up device.'",
")",
";",
"sp",
".",
"write",
"(",
"'\\n'",
",",
"\\n",
")",
";",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"constructor",
".",
"emit",
"(",
"'Error on write: '",
",",
"err",
".",
"message",
")",
";",
"}",
"}",
"}",
")",
";",
"sp",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"deviceAwake",
")",
"{",
"if",
"(",
"data",
".",
"toString",
"(",
")",
"===",
"'\\n\\r'",
")",
"\\n",
"}",
"\\r",
"{",
"debug",
".",
"log",
"(",
"'Device is awake'",
")",
";",
"serialPortUsed",
"=",
"port",
";",
"constructor",
".",
"emit",
"(",
"'connected'",
",",
"port",
")",
";",
"sp",
".",
"write",
"(",
"'LOOP 1\\n'",
")",
";",
"\\n",
"}",
"return",
";",
"debug",
".",
"log",
"(",
"\"Received data, length:\"",
"+",
"data",
".",
"length",
")",
";",
"if",
"(",
"data",
".",
"length",
"==",
"100",
")",
"{",
"data",
"=",
"data",
".",
"slice",
"(",
"1",
")",
";",
"}",
"}",
")",
";",
"var",
"parsedData",
"=",
"parsePacket",
"(",
"data",
")",
";",
"}"
]
| Setup serial port connection | [
"Setup",
"serial",
"port",
"connection"
]
| 6ead4d350d19af5dcd9bd22e5882aeca985caf4d | https://github.com/ruudboon/node-davis-vantage/blob/6ead4d350d19af5dcd9bd22e5882aeca985caf4d/main.js#L62-L118 | train |
skazska/nanoDSA | index.js | doSign | function doSign(params, xKey, message, generateHash) {
// Let H be the hashing function and m the message:
// Generate a random per-message value k where 1<k<q
// Calculate r = (g^k mod p) mod q
// In the unlikely case that r=0, start again with a different random k
// Calculate s = k^(-1) * ( H (m) + xr) mod q
// In the unlikely case that s=0, start again with a different random k
// The signature is (r,s)
// The first two steps amount to creating a new per-message key. The modular exponentiation here is the most
// computationally expensive part of the signing operation, and it may be computed before the message hash is known.
// The modular inverse k^(-1) mod q is the second most expensive part, and it may also be computed before the
// message hash is known. It may be computed using the extended Euclidean algorithm or using Fermat's little theorem
// as k^(q-2) mod q .
let hash = generateHash(message);
return hash.map(h => {
let done = false;
let r = 0;
let s = 0;
do {
let k = 0;
let kInverse = 0;
do {
// Generate a random per-message value k where 1<k<q
k = params.q - Math.round(Math.random() * params.q);
// Calculate r = (g^k mod p) mod q
r = myNumbers.modPow(params.g, k, params.p) % params.q;
// Calculate s = (k^(-1) * ( H (m) + xKey * r)) mod q
// (k^(-1) x) mod q -- if q is prime --> x^(q-2) mod q
if (r) kInverse = myNumbers.mInverse(k, params.q);
} while (r === 0 || kInverse === 0); // In the unlikely case that r=0, start again with a different random k
// Calculate s = (k^(-1) * ( H (m) + xKey * r)) mod q
s = ( h + 1 + xKey * r ) * kInverse % params.q;
if (s) done = true;
} while (!done);
return {r: r, s: s}
});
} | javascript | function doSign(params, xKey, message, generateHash) {
// Let H be the hashing function and m the message:
// Generate a random per-message value k where 1<k<q
// Calculate r = (g^k mod p) mod q
// In the unlikely case that r=0, start again with a different random k
// Calculate s = k^(-1) * ( H (m) + xr) mod q
// In the unlikely case that s=0, start again with a different random k
// The signature is (r,s)
// The first two steps amount to creating a new per-message key. The modular exponentiation here is the most
// computationally expensive part of the signing operation, and it may be computed before the message hash is known.
// The modular inverse k^(-1) mod q is the second most expensive part, and it may also be computed before the
// message hash is known. It may be computed using the extended Euclidean algorithm or using Fermat's little theorem
// as k^(q-2) mod q .
let hash = generateHash(message);
return hash.map(h => {
let done = false;
let r = 0;
let s = 0;
do {
let k = 0;
let kInverse = 0;
do {
// Generate a random per-message value k where 1<k<q
k = params.q - Math.round(Math.random() * params.q);
// Calculate r = (g^k mod p) mod q
r = myNumbers.modPow(params.g, k, params.p) % params.q;
// Calculate s = (k^(-1) * ( H (m) + xKey * r)) mod q
// (k^(-1) x) mod q -- if q is prime --> x^(q-2) mod q
if (r) kInverse = myNumbers.mInverse(k, params.q);
} while (r === 0 || kInverse === 0); // In the unlikely case that r=0, start again with a different random k
// Calculate s = (k^(-1) * ( H (m) + xKey * r)) mod q
s = ( h + 1 + xKey * r ) * kInverse % params.q;
if (s) done = true;
} while (!done);
return {r: r, s: s}
});
} | [
"function",
"doSign",
"(",
"params",
",",
"xKey",
",",
"message",
",",
"generateHash",
")",
"{",
"let",
"hash",
"=",
"generateHash",
"(",
"message",
")",
";",
"return",
"hash",
".",
"map",
"(",
"h",
"=>",
"{",
"let",
"done",
"=",
"false",
";",
"let",
"r",
"=",
"0",
";",
"let",
"s",
"=",
"0",
";",
"do",
"{",
"let",
"k",
"=",
"0",
";",
"let",
"kInverse",
"=",
"0",
";",
"do",
"{",
"k",
"=",
"params",
".",
"q",
"-",
"Math",
".",
"round",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"params",
".",
"q",
")",
";",
"r",
"=",
"myNumbers",
".",
"modPow",
"(",
"params",
".",
"g",
",",
"k",
",",
"params",
".",
"p",
")",
"%",
"params",
".",
"q",
";",
"if",
"(",
"r",
")",
"kInverse",
"=",
"myNumbers",
".",
"mInverse",
"(",
"k",
",",
"params",
".",
"q",
")",
";",
"}",
"while",
"(",
"r",
"===",
"0",
"||",
"kInverse",
"===",
"0",
")",
";",
"s",
"=",
"(",
"h",
"+",
"1",
"+",
"xKey",
"*",
"r",
")",
"*",
"kInverse",
"%",
"params",
".",
"q",
";",
"if",
"(",
"s",
")",
"done",
"=",
"true",
";",
"}",
"while",
"(",
"!",
"done",
")",
";",
"return",
"{",
"r",
":",
"r",
",",
"s",
":",
"s",
"}",
"}",
")",
";",
"}"
]
| generates digital signature for data and hash function using private key and shared DSA params
@param {{q: number, p: number, g: number}} params shared DSA params
@param {{number}} xKey - private key
@param {string} message - data to sign
@param {function} generateHash - hash function (should accept {string} and return [number])
@returns {[{r: number, s: number}]} | [
"generates",
"digital",
"signature",
"for",
"data",
"and",
"hash",
"function",
"using",
"private",
"key",
"and",
"shared",
"DSA",
"params"
]
| 0fa053b4b09d7a18d0fcceee150652af6c5bc50c | https://github.com/skazska/nanoDSA/blob/0fa053b4b09d7a18d0fcceee150652af6c5bc50c/index.js#L43-L86 | train |
skazska/nanoDSA | index.js | verify | function verify(params, yKey, sign, message, generateHash) {
// Reject the signature if 0<r<q or 0<s<q is not satisfied.
// Calculate w = s ^ (-1) mod q
// Calculate u_1 = H(m) * w mod q
// Calculate u_2 = r * w mod q
// Calculate v = ( (g^u_1 * y^u_2) mod p) mod q
// The signature is valid if and only if v = r
const hash = generateHash(message);
if (sign.length !== hash.length) return false;
return sign.every(({r, s}, i) => {
if (!(0 < r && r < params.q && 0 < s && s < params.q)) return false;
let w = myNumbers.mInverse(s, params.q);
let u2 = r * w % params.q;
let keyU2Mod = myNumbers.modPow(yKey, u2, params.p);
let h = hash[i];
if (h === null) return false;
let u1 = (h + 1) * w % params.q;
let v = ((myNumbers.modPow(params.g, u1, params.p) * keyU2Mod) % params.p) % params.q;
return v === r;
});
} | javascript | function verify(params, yKey, sign, message, generateHash) {
// Reject the signature if 0<r<q or 0<s<q is not satisfied.
// Calculate w = s ^ (-1) mod q
// Calculate u_1 = H(m) * w mod q
// Calculate u_2 = r * w mod q
// Calculate v = ( (g^u_1 * y^u_2) mod p) mod q
// The signature is valid if and only if v = r
const hash = generateHash(message);
if (sign.length !== hash.length) return false;
return sign.every(({r, s}, i) => {
if (!(0 < r && r < params.q && 0 < s && s < params.q)) return false;
let w = myNumbers.mInverse(s, params.q);
let u2 = r * w % params.q;
let keyU2Mod = myNumbers.modPow(yKey, u2, params.p);
let h = hash[i];
if (h === null) return false;
let u1 = (h + 1) * w % params.q;
let v = ((myNumbers.modPow(params.g, u1, params.p) * keyU2Mod) % params.p) % params.q;
return v === r;
});
} | [
"function",
"verify",
"(",
"params",
",",
"yKey",
",",
"sign",
",",
"message",
",",
"generateHash",
")",
"{",
"const",
"hash",
"=",
"generateHash",
"(",
"message",
")",
";",
"if",
"(",
"sign",
".",
"length",
"!==",
"hash",
".",
"length",
")",
"return",
"false",
";",
"return",
"sign",
".",
"every",
"(",
"(",
"{",
"r",
",",
"s",
"}",
",",
"i",
")",
"=>",
"{",
"if",
"(",
"!",
"(",
"0",
"<",
"r",
"&&",
"r",
"<",
"params",
".",
"q",
"&&",
"0",
"<",
"s",
"&&",
"s",
"<",
"params",
".",
"q",
")",
")",
"return",
"false",
";",
"let",
"w",
"=",
"myNumbers",
".",
"mInverse",
"(",
"s",
",",
"params",
".",
"q",
")",
";",
"let",
"u2",
"=",
"r",
"*",
"w",
"%",
"params",
".",
"q",
";",
"let",
"keyU2Mod",
"=",
"myNumbers",
".",
"modPow",
"(",
"yKey",
",",
"u2",
",",
"params",
".",
"p",
")",
";",
"let",
"h",
"=",
"hash",
"[",
"i",
"]",
";",
"if",
"(",
"h",
"===",
"null",
")",
"return",
"false",
";",
"let",
"u1",
"=",
"(",
"h",
"+",
"1",
")",
"*",
"w",
"%",
"params",
".",
"q",
";",
"let",
"v",
"=",
"(",
"(",
"myNumbers",
".",
"modPow",
"(",
"params",
".",
"g",
",",
"u1",
",",
"params",
".",
"p",
")",
"*",
"keyU2Mod",
")",
"%",
"params",
".",
"p",
")",
"%",
"params",
".",
"q",
";",
"return",
"v",
"===",
"r",
";",
"}",
")",
";",
"}"
]
| verifies digital signature for data and hash function using public key and shared DSA params
@param {{q: number, p: number, g: number}} params shared DSA params
@param {{number}} yKey - public key
@param {[{r: number, s: number}]} sign - digital signature
@param {string} message - data to sign
@param {function} generateHash - hash function (should accept {string} and return [number])
@returns {boolean} | [
"verifies",
"digital",
"signature",
"for",
"data",
"and",
"hash",
"function",
"using",
"public",
"key",
"and",
"shared",
"DSA",
"params"
]
| 0fa053b4b09d7a18d0fcceee150652af6c5bc50c | https://github.com/skazska/nanoDSA/blob/0fa053b4b09d7a18d0fcceee150652af6c5bc50c/index.js#L97-L123 | train |
datagovsg/datagovsg-plottable-charts | lib/pivot-table.js | createAggregator | function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, _baseIteratee(iteratee, 2), accumulator);
};
} | javascript | function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, _baseIteratee(iteratee, 2), accumulator);
};
} | [
"function",
"createAggregator",
"(",
"setter",
",",
"initializer",
")",
"{",
"return",
"function",
"(",
"collection",
",",
"iteratee",
")",
"{",
"var",
"func",
"=",
"isArray_1",
"(",
"collection",
")",
"?",
"_arrayAggregator",
":",
"_baseAggregator",
",",
"accumulator",
"=",
"initializer",
"?",
"initializer",
"(",
")",
":",
"{",
"}",
";",
"return",
"func",
"(",
"collection",
",",
"setter",
",",
"_baseIteratee",
"(",
"iteratee",
",",
"2",
")",
",",
"accumulator",
")",
";",
"}",
";",
"}"
]
| Creates a function like `_.groupBy`.
@private
@param {Function} setter The function to set accumulator values.
@param {Function} [initializer] The accumulator object initializer.
@returns {Function} Returns the new aggregator function. | [
"Creates",
"a",
"function",
"like",
"_",
".",
"groupBy",
"."
]
| f08c65c50f4be32dacb984ba5fd916e23d11e9d2 | https://github.com/datagovsg/datagovsg-plottable-charts/blob/f08c65c50f4be32dacb984ba5fd916e23d11e9d2/lib/pivot-table.js#L3045-L3052 | train |
WindomZ/fmtconv | lib/transcode.js | stringJSON2YAML | function stringJSON2YAML (doc, compact = false) {
if (!doc || (typeof doc !== 'string' && typeof doc !== 'object')) {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = doc
if (typeof doc === 'string') {
obj = JSON.parse(doc)
}
return yaml.safeDump(obj, compact ? { 'flowLevel': 0 } : undefined)
} | javascript | function stringJSON2YAML (doc, compact = false) {
if (!doc || (typeof doc !== 'string' && typeof doc !== 'object')) {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = doc
if (typeof doc === 'string') {
obj = JSON.parse(doc)
}
return yaml.safeDump(obj, compact ? { 'flowLevel': 0 } : undefined)
} | [
"function",
"stringJSON2YAML",
"(",
"doc",
",",
"compact",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"doc",
"||",
"(",
"typeof",
"doc",
"!==",
"'string'",
"&&",
"typeof",
"doc",
"!==",
"'object'",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument must be a string or object, and not empty: '",
"+",
"doc",
")",
"}",
"let",
"obj",
"=",
"doc",
"if",
"(",
"typeof",
"doc",
"===",
"'string'",
")",
"{",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"doc",
")",
"}",
"return",
"yaml",
".",
"safeDump",
"(",
"obj",
",",
"compact",
"?",
"{",
"'flowLevel'",
":",
"0",
"}",
":",
"undefined",
")",
"}"
]
| Transcode JSON to YAML string.
@param {string|Object} doc
@param {boolean} [compact]
@return {string}
@api public | [
"Transcode",
"JSON",
"to",
"YAML",
"string",
"."
]
| 80923dc9d63714a92bac2f7d4f412a2b46c063a1 | https://github.com/WindomZ/fmtconv/blob/80923dc9d63714a92bac2f7d4f412a2b46c063a1/lib/transcode.js#L16-L27 | train |
WindomZ/fmtconv | lib/transcode.js | stringYAML2JSON | function stringYAML2JSON (doc, compact = false) {
if (!doc || typeof doc !== 'string') {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = yaml.safeLoad(doc)
if (!obj || typeof obj !== 'object') {
throw new TypeError('Argument must be in yaml format: ' + doc)
}
return JSON.stringify(obj, undefined, compact ? undefined : 2)
} | javascript | function stringYAML2JSON (doc, compact = false) {
if (!doc || typeof doc !== 'string') {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = yaml.safeLoad(doc)
if (!obj || typeof obj !== 'object') {
throw new TypeError('Argument must be in yaml format: ' + doc)
}
return JSON.stringify(obj, undefined, compact ? undefined : 2)
} | [
"function",
"stringYAML2JSON",
"(",
"doc",
",",
"compact",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"doc",
"||",
"typeof",
"doc",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument must be a string or object, and not empty: '",
"+",
"doc",
")",
"}",
"let",
"obj",
"=",
"yaml",
".",
"safeLoad",
"(",
"doc",
")",
"if",
"(",
"!",
"obj",
"||",
"typeof",
"obj",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument must be in yaml format: '",
"+",
"doc",
")",
"}",
"return",
"JSON",
".",
"stringify",
"(",
"obj",
",",
"undefined",
",",
"compact",
"?",
"undefined",
":",
"2",
")",
"}"
]
| Transcode YAML to JSON string.
@param {string} doc
@param {boolean} [compact]
@return {string}
@api public | [
"Transcode",
"YAML",
"to",
"JSON",
"string",
"."
]
| 80923dc9d63714a92bac2f7d4f412a2b46c063a1 | https://github.com/WindomZ/fmtconv/blob/80923dc9d63714a92bac2f7d4f412a2b46c063a1/lib/transcode.js#L37-L49 | train |
WindomZ/fmtconv | lib/transcode.js | stringJSON2JSON | function stringJSON2JSON (doc, compact = false) {
if (!doc || (typeof doc !== 'string' && typeof doc !== 'object')) {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = doc
if (typeof doc === 'string') {
obj = JSON.parse(doc)
}
return JSON.stringify(obj, undefined, compact ? undefined : 2)
} | javascript | function stringJSON2JSON (doc, compact = false) {
if (!doc || (typeof doc !== 'string' && typeof doc !== 'object')) {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = doc
if (typeof doc === 'string') {
obj = JSON.parse(doc)
}
return JSON.stringify(obj, undefined, compact ? undefined : 2)
} | [
"function",
"stringJSON2JSON",
"(",
"doc",
",",
"compact",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"doc",
"||",
"(",
"typeof",
"doc",
"!==",
"'string'",
"&&",
"typeof",
"doc",
"!==",
"'object'",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument must be a string or object, and not empty: '",
"+",
"doc",
")",
"}",
"let",
"obj",
"=",
"doc",
"if",
"(",
"typeof",
"doc",
"===",
"'string'",
")",
"{",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"doc",
")",
"}",
"return",
"JSON",
".",
"stringify",
"(",
"obj",
",",
"undefined",
",",
"compact",
"?",
"undefined",
":",
"2",
")",
"}"
]
| Transcode JSON to JSON string.
@param {string|Object} doc
@param {boolean} [compact]
@return {string}
@api public | [
"Transcode",
"JSON",
"to",
"JSON",
"string",
"."
]
| 80923dc9d63714a92bac2f7d4f412a2b46c063a1 | https://github.com/WindomZ/fmtconv/blob/80923dc9d63714a92bac2f7d4f412a2b46c063a1/lib/transcode.js#L59-L70 | train |
WindomZ/fmtconv | lib/transcode.js | stringYAML2YAML | function stringYAML2YAML (doc, compact = false) {
if (!doc || typeof doc !== 'string') {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = yaml.safeLoad(doc)
if (!obj || typeof obj !== 'object') {
throw new TypeError('Argument must be in yaml format: ' + doc)
}
return yaml.safeDump(obj, compact ? { 'flowLevel': 0 } : undefined)
} | javascript | function stringYAML2YAML (doc, compact = false) {
if (!doc || typeof doc !== 'string') {
throw new TypeError('Argument must be a string or object, and not empty: ' + doc)
}
let obj = yaml.safeLoad(doc)
if (!obj || typeof obj !== 'object') {
throw new TypeError('Argument must be in yaml format: ' + doc)
}
return yaml.safeDump(obj, compact ? { 'flowLevel': 0 } : undefined)
} | [
"function",
"stringYAML2YAML",
"(",
"doc",
",",
"compact",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"doc",
"||",
"typeof",
"doc",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument must be a string or object, and not empty: '",
"+",
"doc",
")",
"}",
"let",
"obj",
"=",
"yaml",
".",
"safeLoad",
"(",
"doc",
")",
"if",
"(",
"!",
"obj",
"||",
"typeof",
"obj",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Argument must be in yaml format: '",
"+",
"doc",
")",
"}",
"return",
"yaml",
".",
"safeDump",
"(",
"obj",
",",
"compact",
"?",
"{",
"'flowLevel'",
":",
"0",
"}",
":",
"undefined",
")",
"}"
]
| Transcode YAML to YAML string.
@param {string} doc
@param {boolean} [compact]
@return {string}
@api public | [
"Transcode",
"YAML",
"to",
"YAML",
"string",
"."
]
| 80923dc9d63714a92bac2f7d4f412a2b46c063a1 | https://github.com/WindomZ/fmtconv/blob/80923dc9d63714a92bac2f7d4f412a2b46c063a1/lib/transcode.js#L80-L92 | train |
hash-bang/compare-names | index.js | fuzzyStringCompare | function fuzzyStringCompare(a, b, tolerence) {
if (a == b) return true;
var as = stripNoise(a);
as = as.toLowerCase();
if (as.length > 255) as = as.substr(0, 255);
var bs = stripNoise(b);
bs = bs.toLowerCase();
if (bs.length > 255) bs = bs.substr(0, 255);
if (tolerence == undefined && levenshtein(as, bs) < 10) return true;
if (tolerence && levenshtein(as, bs) <= tolerence) return true;
} | javascript | function fuzzyStringCompare(a, b, tolerence) {
if (a == b) return true;
var as = stripNoise(a);
as = as.toLowerCase();
if (as.length > 255) as = as.substr(0, 255);
var bs = stripNoise(b);
bs = bs.toLowerCase();
if (bs.length > 255) bs = bs.substr(0, 255);
if (tolerence == undefined && levenshtein(as, bs) < 10) return true;
if (tolerence && levenshtein(as, bs) <= tolerence) return true;
} | [
"function",
"fuzzyStringCompare",
"(",
"a",
",",
"b",
",",
"tolerence",
")",
"{",
"if",
"(",
"a",
"==",
"b",
")",
"return",
"true",
";",
"var",
"as",
"=",
"stripNoise",
"(",
"a",
")",
";",
"as",
"=",
"as",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"as",
".",
"length",
">",
"255",
")",
"as",
"=",
"as",
".",
"substr",
"(",
"0",
",",
"255",
")",
";",
"var",
"bs",
"=",
"stripNoise",
"(",
"b",
")",
";",
"bs",
"=",
"bs",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"bs",
".",
"length",
">",
"255",
")",
"bs",
"=",
"bs",
".",
"substr",
"(",
"0",
",",
"255",
")",
";",
"if",
"(",
"tolerence",
"==",
"undefined",
"&&",
"levenshtein",
"(",
"as",
",",
"bs",
")",
"<",
"10",
")",
"return",
"true",
";",
"if",
"(",
"tolerence",
"&&",
"levenshtein",
"(",
"as",
",",
"bs",
")",
"<=",
"tolerence",
")",
"return",
"true",
";",
"}"
]
| Fuzzily compare strings a and b
@param string a The first string to compare
@param string b The second string to compare
@param number tolerence The tolerence when comparing using levenshtein, defaults to 10
@return boolean True if a ≈ b | [
"Fuzzily",
"compare",
"strings",
"a",
"and",
"b"
]
| 19a15a8410f05b94b7fd191874c1f5af3ef5cd51 | https://github.com/hash-bang/compare-names/blob/19a15a8410f05b94b7fd191874c1f5af3ef5cd51/index.js#L22-L35 | train |
hash-bang/compare-names | index.js | splitAuthor | function splitAuthor(author) {
return author
.split(/\s*[,\.\s]\s*/)
.filter(function(i) { return !!i }) // Strip out blanks
.filter(function(i) { return !/^[0-9]+(st|nd|rd|th)$/.test(i) }); // Strip out decendent numerics (e.g. '1st', '23rd')
} | javascript | function splitAuthor(author) {
return author
.split(/\s*[,\.\s]\s*/)
.filter(function(i) { return !!i }) // Strip out blanks
.filter(function(i) { return !/^[0-9]+(st|nd|rd|th)$/.test(i) }); // Strip out decendent numerics (e.g. '1st', '23rd')
} | [
"function",
"splitAuthor",
"(",
"author",
")",
"{",
"return",
"author",
".",
"split",
"(",
"/",
"\\s*[,\\.\\s]\\s*",
"/",
")",
".",
"filter",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"!",
"!",
"i",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"!",
"/",
"^[0-9]+(st|nd|rd|th)$",
"/",
".",
"test",
"(",
"i",
")",
"}",
")",
";",
"}"
]
| Splits an author string into its component parts
@param string author The raw author string to split
@return array An array composed of lastname, initial/name | [
"Splits",
"an",
"author",
"string",
"into",
"its",
"component",
"parts"
]
| 19a15a8410f05b94b7fd191874c1f5af3ef5cd51 | https://github.com/hash-bang/compare-names/blob/19a15a8410f05b94b7fd191874c1f5af3ef5cd51/index.js#L43-L48 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.