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 |
---|---|---|---|---|---|---|---|---|---|---|---|
puranjayjain/gulp-replace-frommap | index.js | replaceTextWithMap | function replaceTextWithMap(string, map) {
// break the words into tokens using _ and words themselves
const tokens = XRegExp.match(string, /([a-z0-9_]+)/ig);
// for all the tokens replace it in string
for(let token of tokens) {
// try to replace only if the key exists in the map else skip over
if(map.hasOwnProperty(token)) {
string = replaceAll(token, map[token], string);
}
}
return string;
} | javascript | function replaceTextWithMap(string, map) {
// break the words into tokens using _ and words themselves
const tokens = XRegExp.match(string, /([a-z0-9_]+)/ig);
// for all the tokens replace it in string
for(let token of tokens) {
// try to replace only if the key exists in the map else skip over
if(map.hasOwnProperty(token)) {
string = replaceAll(token, map[token], string);
}
}
return string;
} | [
"function",
"replaceTextWithMap",
"(",
"string",
",",
"map",
")",
"{",
"const",
"tokens",
"=",
"XRegExp",
".",
"match",
"(",
"string",
",",
"/",
"([a-z0-9_]+)",
"/",
"ig",
")",
";",
"for",
"(",
"let",
"token",
"of",
"tokens",
")",
"{",
"if",
"(",
"map",
".",
"hasOwnProperty",
"(",
"token",
")",
")",
"{",
"string",
"=",
"replaceAll",
"(",
"token",
",",
"map",
"[",
"token",
"]",
",",
"string",
")",
";",
"}",
"}",
"return",
"string",
";",
"}"
]
| replace until all of the map has are exhausted | [
"replace",
"until",
"all",
"of",
"the",
"map",
"has",
"are",
"exhausted"
]
| def6b6345ebf5341e46ddfe05d7d09974180c718 | https://github.com/puranjayjain/gulp-replace-frommap/blob/def6b6345ebf5341e46ddfe05d7d09974180c718/index.js#L143-L154 | train |
Industryswarm/isnode-mod-data | lib/mysql/mysql/index.js | loadClass | function loadClass(className) {
var Class = Classes[className];
if (Class !== undefined) {
return Class;
}
// This uses a switch for static require analysis
switch (className) {
case 'Connection':
Class = require('./lib/Connection');
break;
case 'ConnectionConfig':
Class = require('./lib/ConnectionConfig');
break;
case 'Pool':
Class = require('./lib/Pool');
break;
case 'PoolCluster':
Class = require('./lib/PoolCluster');
break;
case 'PoolConfig':
Class = require('./lib/PoolConfig');
break;
case 'SqlString':
Class = require('./lib/protocol/SqlString');
break;
case 'Types':
Class = require('./lib/protocol/constants/types');
break;
default:
throw new Error('Cannot find class \'' + className + '\'');
}
// Store to prevent invoking require()
Classes[className] = Class;
return Class;
} | javascript | function loadClass(className) {
var Class = Classes[className];
if (Class !== undefined) {
return Class;
}
// This uses a switch for static require analysis
switch (className) {
case 'Connection':
Class = require('./lib/Connection');
break;
case 'ConnectionConfig':
Class = require('./lib/ConnectionConfig');
break;
case 'Pool':
Class = require('./lib/Pool');
break;
case 'PoolCluster':
Class = require('./lib/PoolCluster');
break;
case 'PoolConfig':
Class = require('./lib/PoolConfig');
break;
case 'SqlString':
Class = require('./lib/protocol/SqlString');
break;
case 'Types':
Class = require('./lib/protocol/constants/types');
break;
default:
throw new Error('Cannot find class \'' + className + '\'');
}
// Store to prevent invoking require()
Classes[className] = Class;
return Class;
} | [
"function",
"loadClass",
"(",
"className",
")",
"{",
"var",
"Class",
"=",
"Classes",
"[",
"className",
"]",
";",
"if",
"(",
"Class",
"!==",
"undefined",
")",
"{",
"return",
"Class",
";",
"}",
"switch",
"(",
"className",
")",
"{",
"case",
"'Connection'",
":",
"Class",
"=",
"require",
"(",
"'./lib/Connection'",
")",
";",
"break",
";",
"case",
"'ConnectionConfig'",
":",
"Class",
"=",
"require",
"(",
"'./lib/ConnectionConfig'",
")",
";",
"break",
";",
"case",
"'Pool'",
":",
"Class",
"=",
"require",
"(",
"'./lib/Pool'",
")",
";",
"break",
";",
"case",
"'PoolCluster'",
":",
"Class",
"=",
"require",
"(",
"'./lib/PoolCluster'",
")",
";",
"break",
";",
"case",
"'PoolConfig'",
":",
"Class",
"=",
"require",
"(",
"'./lib/PoolConfig'",
")",
";",
"break",
";",
"case",
"'SqlString'",
":",
"Class",
"=",
"require",
"(",
"'./lib/protocol/SqlString'",
")",
";",
"break",
";",
"case",
"'Types'",
":",
"Class",
"=",
"require",
"(",
"'./lib/protocol/constants/types'",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Cannot find class \\''",
"+",
"\\'",
"+",
"className",
")",
";",
"}",
"'\\''",
"\\'",
"}"
]
| Load the given class.
@param {string} className Name of class to default
@return {function|object} Class constructor or exports
@private | [
"Load",
"the",
"given",
"class",
"."
]
| 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mysql/mysql/index.js#L123-L161 | train |
Ma3Route/node-sdk | lib/generate.js | newGet | function newGet(endpoint, allowable) {
return function(params, callback) {
// allow options params
var args = utils.allowOptionalParams(params, callback);
// get and detach/remove the uri options
var uriOptions = utils.getURIOptions([utils.setup(), this, args.params]);
utils.removeURIOptions(args.params);
// create the URI
var uri = utils.url(endpoint, uriOptions);
// get the auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, args.params]);
utils.removeAuthOptions(args.params);
// remove params that are not allowed
args.params = utils.pickParams(args.params, allowable);
// add the params as querystring to the URI
utils.addQueries(uri, args.params);
// sign the URI (automatically removes the secret param from the params)
try {
auth.sign(authOptions.key, authOptions.secret, uri);
} catch(err) {
return args.callback(err);
}
var url = uri.toString();
debug("[GET] /%s (%s)", endpoint, url);
return utils.request().get(url, utils.passResponse(args.callback));
};
} | javascript | function newGet(endpoint, allowable) {
return function(params, callback) {
// allow options params
var args = utils.allowOptionalParams(params, callback);
// get and detach/remove the uri options
var uriOptions = utils.getURIOptions([utils.setup(), this, args.params]);
utils.removeURIOptions(args.params);
// create the URI
var uri = utils.url(endpoint, uriOptions);
// get the auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, args.params]);
utils.removeAuthOptions(args.params);
// remove params that are not allowed
args.params = utils.pickParams(args.params, allowable);
// add the params as querystring to the URI
utils.addQueries(uri, args.params);
// sign the URI (automatically removes the secret param from the params)
try {
auth.sign(authOptions.key, authOptions.secret, uri);
} catch(err) {
return args.callback(err);
}
var url = uri.toString();
debug("[GET] /%s (%s)", endpoint, url);
return utils.request().get(url, utils.passResponse(args.callback));
};
} | [
"function",
"newGet",
"(",
"endpoint",
",",
"allowable",
")",
"{",
"return",
"function",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"args",
"=",
"utils",
".",
"allowOptionalParams",
"(",
"params",
",",
"callback",
")",
";",
"var",
"uriOptions",
"=",
"utils",
".",
"getURIOptions",
"(",
"[",
"utils",
".",
"setup",
"(",
")",
",",
"this",
",",
"args",
".",
"params",
"]",
")",
";",
"utils",
".",
"removeURIOptions",
"(",
"args",
".",
"params",
")",
";",
"var",
"uri",
"=",
"utils",
".",
"url",
"(",
"endpoint",
",",
"uriOptions",
")",
";",
"var",
"authOptions",
"=",
"utils",
".",
"getAuthOptions",
"(",
"[",
"utils",
".",
"setup",
"(",
")",
",",
"this",
",",
"args",
".",
"params",
"]",
")",
";",
"utils",
".",
"removeAuthOptions",
"(",
"args",
".",
"params",
")",
";",
"args",
".",
"params",
"=",
"utils",
".",
"pickParams",
"(",
"args",
".",
"params",
",",
"allowable",
")",
";",
"utils",
".",
"addQueries",
"(",
"uri",
",",
"args",
".",
"params",
")",
";",
"try",
"{",
"auth",
".",
"sign",
"(",
"authOptions",
".",
"key",
",",
"authOptions",
".",
"secret",
",",
"uri",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"args",
".",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"url",
"=",
"uri",
".",
"toString",
"(",
")",
";",
"debug",
"(",
"\"[GET] /%s (%s)\"",
",",
"endpoint",
",",
"url",
")",
";",
"return",
"utils",
".",
"request",
"(",
")",
".",
"get",
"(",
"url",
",",
"utils",
".",
"passResponse",
"(",
"args",
".",
"callback",
")",
")",
";",
"}",
";",
"}"
]
| Return a function for retrieving one or more items
@param {Endpoint} endpoint
@param {String[]} [allowable]
@return {itemsGetRequest} | [
"Return",
"a",
"function",
"for",
"retrieving",
"one",
"or",
"more",
"items"
]
| a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/generate.js#L40-L67 | train |
Ma3Route/node-sdk | lib/generate.js | newGetOne | function newGetOne(endpoint, allowable) {
var get = newGet(endpoint, allowable);
return function(id, params, callback) {
var args = utils.allowOptionalParams(params, callback);
if (typeof id === "object") {
_.assign(args.params, id);
} else {
args.params.id = id;
}
return get.call(this, args.params, args.callback);
};
} | javascript | function newGetOne(endpoint, allowable) {
var get = newGet(endpoint, allowable);
return function(id, params, callback) {
var args = utils.allowOptionalParams(params, callback);
if (typeof id === "object") {
_.assign(args.params, id);
} else {
args.params.id = id;
}
return get.call(this, args.params, args.callback);
};
} | [
"function",
"newGetOne",
"(",
"endpoint",
",",
"allowable",
")",
"{",
"var",
"get",
"=",
"newGet",
"(",
"endpoint",
",",
"allowable",
")",
";",
"return",
"function",
"(",
"id",
",",
"params",
",",
"callback",
")",
"{",
"var",
"args",
"=",
"utils",
".",
"allowOptionalParams",
"(",
"params",
",",
"callback",
")",
";",
"if",
"(",
"typeof",
"id",
"===",
"\"object\"",
")",
"{",
"_",
".",
"assign",
"(",
"args",
".",
"params",
",",
"id",
")",
";",
"}",
"else",
"{",
"args",
".",
"params",
".",
"id",
"=",
"id",
";",
"}",
"return",
"get",
".",
"call",
"(",
"this",
",",
"args",
".",
"params",
",",
"args",
".",
"callback",
")",
";",
"}",
";",
"}"
]
| Return a function for retrieving one item
@param {Endpoint} endpoint
@param {String[]} [allowable]
@return {itemsGetOneRequest} | [
"Return",
"a",
"function",
"for",
"retrieving",
"one",
"item"
]
| a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/generate.js#L77-L89 | train |
Ma3Route/node-sdk | lib/generate.js | newPostOne | function newPostOne(endpoint, options) {
// for backwards-compatibility <= 0.11.1
if (_.isArray(options)) {
options = { allowable: options };
}
options = _.defaultsDeep({}, options, {
allowable: [],
method: "post",
});
return function(body, callback) {
// get and remove/detach URI options
var uriOptions = utils.getURIOptions([utils.setup(), options, this, body]);
utils.removeURIOptions(body);
// create a URI
var uri = utils.url(endpoint, uriOptions);
// get auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, body]);
utils.removeAuthOptions(body);
// remove params that are not allowed
body = utils.pickParams(body, options.allowable);
// sign the URI (automatically removes the secret param from body)
try {
auth.sign(authOptions.key, authOptions.secret, uri, body, {
apiVersion: uriOptions.apiVersion,
});
} catch(err) {
return callback(err);
}
var url = uri.toString();
var method;
var resOpts = {};
switch (options.method) {
case "put":
method = "put";
resOpts.put = true;
break;
case "post":
default:
method = "post";
resOpts.post = true;
}
debug("[%s] /%s (%s) [%j]", method.toUpperCase(), endpoint, url, body);
return utils.request()[method]({
url: url,
body: body,
}, utils.passResponse(callback, resOpts));
};
} | javascript | function newPostOne(endpoint, options) {
// for backwards-compatibility <= 0.11.1
if (_.isArray(options)) {
options = { allowable: options };
}
options = _.defaultsDeep({}, options, {
allowable: [],
method: "post",
});
return function(body, callback) {
// get and remove/detach URI options
var uriOptions = utils.getURIOptions([utils.setup(), options, this, body]);
utils.removeURIOptions(body);
// create a URI
var uri = utils.url(endpoint, uriOptions);
// get auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, body]);
utils.removeAuthOptions(body);
// remove params that are not allowed
body = utils.pickParams(body, options.allowable);
// sign the URI (automatically removes the secret param from body)
try {
auth.sign(authOptions.key, authOptions.secret, uri, body, {
apiVersion: uriOptions.apiVersion,
});
} catch(err) {
return callback(err);
}
var url = uri.toString();
var method;
var resOpts = {};
switch (options.method) {
case "put":
method = "put";
resOpts.put = true;
break;
case "post":
default:
method = "post";
resOpts.post = true;
}
debug("[%s] /%s (%s) [%j]", method.toUpperCase(), endpoint, url, body);
return utils.request()[method]({
url: url,
body: body,
}, utils.passResponse(callback, resOpts));
};
} | [
"function",
"newPostOne",
"(",
"endpoint",
",",
"options",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"options",
")",
")",
"{",
"options",
"=",
"{",
"allowable",
":",
"options",
"}",
";",
"}",
"options",
"=",
"_",
".",
"defaultsDeep",
"(",
"{",
"}",
",",
"options",
",",
"{",
"allowable",
":",
"[",
"]",
",",
"method",
":",
"\"post\"",
",",
"}",
")",
";",
"return",
"function",
"(",
"body",
",",
"callback",
")",
"{",
"var",
"uriOptions",
"=",
"utils",
".",
"getURIOptions",
"(",
"[",
"utils",
".",
"setup",
"(",
")",
",",
"options",
",",
"this",
",",
"body",
"]",
")",
";",
"utils",
".",
"removeURIOptions",
"(",
"body",
")",
";",
"var",
"uri",
"=",
"utils",
".",
"url",
"(",
"endpoint",
",",
"uriOptions",
")",
";",
"var",
"authOptions",
"=",
"utils",
".",
"getAuthOptions",
"(",
"[",
"utils",
".",
"setup",
"(",
")",
",",
"this",
",",
"body",
"]",
")",
";",
"utils",
".",
"removeAuthOptions",
"(",
"body",
")",
";",
"body",
"=",
"utils",
".",
"pickParams",
"(",
"body",
",",
"options",
".",
"allowable",
")",
";",
"try",
"{",
"auth",
".",
"sign",
"(",
"authOptions",
".",
"key",
",",
"authOptions",
".",
"secret",
",",
"uri",
",",
"body",
",",
"{",
"apiVersion",
":",
"uriOptions",
".",
"apiVersion",
",",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"url",
"=",
"uri",
".",
"toString",
"(",
")",
";",
"var",
"method",
";",
"var",
"resOpts",
"=",
"{",
"}",
";",
"switch",
"(",
"options",
".",
"method",
")",
"{",
"case",
"\"put\"",
":",
"method",
"=",
"\"put\"",
";",
"resOpts",
".",
"put",
"=",
"true",
";",
"break",
";",
"case",
"\"post\"",
":",
"default",
":",
"method",
"=",
"\"post\"",
";",
"resOpts",
".",
"post",
"=",
"true",
";",
"}",
"debug",
"(",
"\"[%s] /%s (%s) [%j]\"",
",",
"method",
".",
"toUpperCase",
"(",
")",
",",
"endpoint",
",",
"url",
",",
"body",
")",
";",
"return",
"utils",
".",
"request",
"(",
")",
"[",
"method",
"]",
"(",
"{",
"url",
":",
"url",
",",
"body",
":",
"body",
",",
"}",
",",
"utils",
".",
"passResponse",
"(",
"callback",
",",
"resOpts",
")",
")",
";",
"}",
";",
"}"
]
| Return a function for posting items
@param {Endpoint} endpoint
@param {Object} [options]
@param {String[]} [options.allowable]
@param {String} [options.method=post]
@param {Number} [options.apiVersion=2] API version used
@return {itemsPostOneRequest} | [
"Return",
"a",
"function",
"for",
"posting",
"items"
]
| a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/generate.js#L102-L152 | train |
Ma3Route/node-sdk | lib/generate.js | newCustomPostOne | function newCustomPostOne(endpoint, initParams, allowable) {
var modify = newPostOne(endpoint, allowable);
return function(body, callback) {
_.assign(body, initParams);
return modify.call(this, body, callback);
};
} | javascript | function newCustomPostOne(endpoint, initParams, allowable) {
var modify = newPostOne(endpoint, allowable);
return function(body, callback) {
_.assign(body, initParams);
return modify.call(this, body, callback);
};
} | [
"function",
"newCustomPostOne",
"(",
"endpoint",
",",
"initParams",
",",
"allowable",
")",
"{",
"var",
"modify",
"=",
"newPostOne",
"(",
"endpoint",
",",
"allowable",
")",
";",
"return",
"function",
"(",
"body",
",",
"callback",
")",
"{",
"_",
".",
"assign",
"(",
"body",
",",
"initParams",
")",
";",
"return",
"modify",
".",
"call",
"(",
"this",
",",
"body",
",",
"callback",
")",
";",
"}",
";",
"}"
]
| Return a function for custom Post requests
@param {Endpoint} endpoint
@param {Object} initParams - parameters used to indicate we are infact modifying
@param {String[]} [allowable]
@return {itemsPostOneRequest} | [
"Return",
"a",
"function",
"for",
"custom",
"Post",
"requests"
]
| a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/generate.js#L163-L169 | train |
Ma3Route/node-sdk | lib/generate.js | newPutOne | function newPutOne(endpoint, options) {
// for backwards-compatibility <= 0.11.1
if (_.isArray(options)) options = { allowable: options };
else options = options || {};
options.method = "put";
return newPostOne(endpoint, options);
} | javascript | function newPutOne(endpoint, options) {
// for backwards-compatibility <= 0.11.1
if (_.isArray(options)) options = { allowable: options };
else options = options || {};
options.method = "put";
return newPostOne(endpoint, options);
} | [
"function",
"newPutOne",
"(",
"endpoint",
",",
"options",
")",
"{",
"if",
"(",
"_",
".",
"isArray",
"(",
"options",
")",
")",
"options",
"=",
"{",
"allowable",
":",
"options",
"}",
";",
"else",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"method",
"=",
"\"put\"",
";",
"return",
"newPostOne",
"(",
"endpoint",
",",
"options",
")",
";",
"}"
]
| Return a function for editing an item
@param {String} endpoint
@param {Object} [options] Passed to {@link module:generate~newPostOne}
@return {itemsPutOneRequest} | [
"Return",
"a",
"function",
"for",
"editing",
"an",
"item"
]
| a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/generate.js#L179-L185 | train |
Ma3Route/node-sdk | lib/generate.js | newSSEClientFactory | function newSSEClientFactory(endpoint) {
return function(initDict) {
initDict = initDict || { };
// get URI options
var uriOptions = utils.getURIOptions(initDict);
utils.removeURIOptions(initDict);
// create a new URI
var uri = utils.url(endpoint, uriOptions);
// get auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, initDict]);
// sign the URI (automatically removes the secret param from initDict)
auth.sign(authOptions.key, authOptions.secret, uri);
// determine whether to use an eventsource or poll the endpoint
return new EventSource(uri.toString(), initDict);
};
} | javascript | function newSSEClientFactory(endpoint) {
return function(initDict) {
initDict = initDict || { };
// get URI options
var uriOptions = utils.getURIOptions(initDict);
utils.removeURIOptions(initDict);
// create a new URI
var uri = utils.url(endpoint, uriOptions);
// get auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, initDict]);
// sign the URI (automatically removes the secret param from initDict)
auth.sign(authOptions.key, authOptions.secret, uri);
// determine whether to use an eventsource or poll the endpoint
return new EventSource(uri.toString(), initDict);
};
} | [
"function",
"newSSEClientFactory",
"(",
"endpoint",
")",
"{",
"return",
"function",
"(",
"initDict",
")",
"{",
"initDict",
"=",
"initDict",
"||",
"{",
"}",
";",
"var",
"uriOptions",
"=",
"utils",
".",
"getURIOptions",
"(",
"initDict",
")",
";",
"utils",
".",
"removeURIOptions",
"(",
"initDict",
")",
";",
"var",
"uri",
"=",
"utils",
".",
"url",
"(",
"endpoint",
",",
"uriOptions",
")",
";",
"var",
"authOptions",
"=",
"utils",
".",
"getAuthOptions",
"(",
"[",
"utils",
".",
"setup",
"(",
")",
",",
"this",
",",
"initDict",
"]",
")",
";",
"auth",
".",
"sign",
"(",
"authOptions",
".",
"key",
",",
"authOptions",
".",
"secret",
",",
"uri",
")",
";",
"return",
"new",
"EventSource",
"(",
"uri",
".",
"toString",
"(",
")",
",",
"initDict",
")",
";",
"}",
";",
"}"
]
| Return a function that returns a SSE client
@param {Endpoint} endpoint
@return {SSEClientFactory}
@throws Error | [
"Return",
"a",
"function",
"that",
"returns",
"a",
"SSE",
"client"
]
| a2769d97d77d6f762d23e743bf4c749e2bad0d8a | https://github.com/Ma3Route/node-sdk/blob/a2769d97d77d6f762d23e743bf4c749e2bad0d8a/lib/generate.js#L195-L210 | train |
Antyfive/teo-html-compressor-extension | index.js | Compressor | function Compressor() {
var self = this;
var regexps = [/[\n\r\t]+/g, /\s{2,}/g];
/**
* Remover of the html comment blocks
* @param html
* @returns {*}
* @private
*/
function _clearHTMLComments(html) {
var cStart = '<!--',
cEnd = '-->',
beg = html.indexOf(cStart),
end = 0;
while (beg !== -1) {
end = html.indexOf(cEnd, beg + 4);
if (end === -1) {
break;
}
var comment = html.substring(beg, end + 3);
if (comment.indexOf("[if") !== -1 || comment.indexOf("![endif]") !== -1) { // skip
beg = html.indexOf(cStart, end + 3);
continue;
}
html = html.replace(comment, "");
beg = html.indexOf(cStart, end + 3);
}
return html;
}
// ---- ---- ---- ---- ----
/**
* Compressor of the html string
* @param {String} html
* @returns {*}
*/
self.compressHTML = function(html) {
if (html === null || html === "")
return html;
html = _clearHTMLComments(html);
var tags = ["script", "textarea", "pre", "code"],
id = new Date().getTime() + "#",
cache = {},
index = 0;
tags.forEach(function(tag, i) {
var tagS = '<' + tag,
tagE = '</' + tag + '>',
start = html.indexOf(tagS),
end = 0,
len = tagE.length;
while (start !== -1) {
end = html.indexOf(tagE, start);
if (end === -1) {
break;
}
var key = id + (index++),
value = html.substring(start, end + len);
if (i === 0) {
end = value.indexOf(">");
len = value.indexOf('type="text/template"');
if (len < end && len !== -1) {
break;
}
len = value.indexOf('type="text/html"');
if (len < end && len !== -1) {
break;
}
}
cache[key] = value;
html = html.replace(value, key);
start = html.indexOf(tagS, start + tagS.length);
}
});
regexps.forEach(function(regexp) {
html = html.replace(regexp, "");
});
Object.keys(cache).forEach(function(key) {
html = html.replace(key, cache[key]);
});
return html;
};
// api ----
return self;
} | javascript | function Compressor() {
var self = this;
var regexps = [/[\n\r\t]+/g, /\s{2,}/g];
/**
* Remover of the html comment blocks
* @param html
* @returns {*}
* @private
*/
function _clearHTMLComments(html) {
var cStart = '<!--',
cEnd = '-->',
beg = html.indexOf(cStart),
end = 0;
while (beg !== -1) {
end = html.indexOf(cEnd, beg + 4);
if (end === -1) {
break;
}
var comment = html.substring(beg, end + 3);
if (comment.indexOf("[if") !== -1 || comment.indexOf("![endif]") !== -1) { // skip
beg = html.indexOf(cStart, end + 3);
continue;
}
html = html.replace(comment, "");
beg = html.indexOf(cStart, end + 3);
}
return html;
}
// ---- ---- ---- ---- ----
/**
* Compressor of the html string
* @param {String} html
* @returns {*}
*/
self.compressHTML = function(html) {
if (html === null || html === "")
return html;
html = _clearHTMLComments(html);
var tags = ["script", "textarea", "pre", "code"],
id = new Date().getTime() + "#",
cache = {},
index = 0;
tags.forEach(function(tag, i) {
var tagS = '<' + tag,
tagE = '</' + tag + '>',
start = html.indexOf(tagS),
end = 0,
len = tagE.length;
while (start !== -1) {
end = html.indexOf(tagE, start);
if (end === -1) {
break;
}
var key = id + (index++),
value = html.substring(start, end + len);
if (i === 0) {
end = value.indexOf(">");
len = value.indexOf('type="text/template"');
if (len < end && len !== -1) {
break;
}
len = value.indexOf('type="text/html"');
if (len < end && len !== -1) {
break;
}
}
cache[key] = value;
html = html.replace(value, key);
start = html.indexOf(tagS, start + tagS.length);
}
});
regexps.forEach(function(regexp) {
html = html.replace(regexp, "");
});
Object.keys(cache).forEach(function(key) {
html = html.replace(key, cache[key]);
});
return html;
};
// api ----
return self;
} | [
"function",
"Compressor",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"regexps",
"=",
"[",
"/",
"[\\n\\r\\t]+",
"/",
"g",
",",
"/",
"\\s{2,}",
"/",
"g",
"]",
";",
"function",
"_clearHTMLComments",
"(",
"html",
")",
"{",
"var",
"cStart",
"=",
"'<!--'",
",",
"cEnd",
"=",
"'",
",",
"beg",
"=",
"html",
".",
"indexOf",
"(",
"cStart",
")",
",",
"end",
"=",
"0",
";",
"while",
"(",
"beg",
"!==",
"-",
"1",
")",
"{",
"end",
"=",
"html",
".",
"indexOf",
"(",
"cEnd",
",",
"beg",
"+",
"4",
")",
";",
"if",
"(",
"end",
"===",
"-",
"1",
")",
"{",
"break",
";",
"}",
"var",
"comment",
"=",
"html",
".",
"substring",
"(",
"beg",
",",
"end",
"+",
"3",
")",
";",
"if",
"(",
"comment",
".",
"indexOf",
"(",
"\"[if\"",
")",
"!==",
"-",
"1",
"||",
"comment",
".",
"indexOf",
"(",
"\"![endif]\"",
")",
"!==",
"-",
"1",
")",
"{",
"beg",
"=",
"html",
".",
"indexOf",
"(",
"cStart",
",",
"end",
"+",
"3",
")",
";",
"continue",
";",
"}",
"html",
"=",
"html",
".",
"replace",
"(",
"comment",
",",
"\"\"",
")",
";",
"beg",
"=",
"html",
".",
"indexOf",
"(",
"cStart",
",",
"end",
"+",
"3",
")",
";",
"}",
"return",
"html",
";",
"}",
"self",
".",
"compressHTML",
"=",
"function",
"(",
"html",
")",
"{",
"if",
"(",
"html",
"===",
"null",
"||",
"html",
"===",
"\"\"",
")",
"return",
"html",
";",
"html",
"=",
"_clearHTMLComments",
"(",
"html",
")",
";",
"var",
"tags",
"=",
"[",
"\"script\"",
",",
"\"textarea\"",
",",
"\"pre\"",
",",
"\"code\"",
"]",
",",
"id",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"+",
"\"#\"",
",",
"cache",
"=",
"{",
"}",
",",
"index",
"=",
"0",
";",
"tags",
".",
"forEach",
"(",
"function",
"(",
"tag",
",",
"i",
")",
"{",
"var",
"tagS",
"=",
"'<'",
"+",
"tag",
",",
"tagE",
"=",
"'</'",
"+",
"tag",
"+",
"'>'",
",",
"start",
"=",
"html",
".",
"indexOf",
"(",
"tagS",
")",
",",
"end",
"=",
"0",
",",
"len",
"=",
"tagE",
".",
"length",
";",
"while",
"(",
"start",
"!==",
"-",
"1",
")",
"{",
"end",
"=",
"html",
".",
"indexOf",
"(",
"tagE",
",",
"start",
")",
";",
"if",
"(",
"end",
"===",
"-",
"1",
")",
"{",
"break",
";",
"}",
"var",
"key",
"=",
"id",
"+",
"(",
"index",
"++",
")",
",",
"value",
"=",
"html",
".",
"substring",
"(",
"start",
",",
"end",
"+",
"len",
")",
";",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"end",
"=",
"value",
".",
"indexOf",
"(",
"\">\"",
")",
";",
"len",
"=",
"value",
".",
"indexOf",
"(",
"'type=\"text/template\"'",
")",
";",
"if",
"(",
"len",
"<",
"end",
"&&",
"len",
"!==",
"-",
"1",
")",
"{",
"break",
";",
"}",
"len",
"=",
"value",
".",
"indexOf",
"(",
"'type=\"text/html\"'",
")",
";",
"if",
"(",
"len",
"<",
"end",
"&&",
"len",
"!==",
"-",
"1",
")",
"{",
"break",
";",
"}",
"}",
"cache",
"[",
"key",
"]",
"=",
"value",
";",
"html",
"=",
"html",
".",
"replace",
"(",
"value",
",",
"key",
")",
";",
"start",
"=",
"html",
".",
"indexOf",
"(",
"tagS",
",",
"start",
"+",
"tagS",
".",
"length",
")",
";",
"}",
"}",
")",
";",
"regexps",
".",
"forEach",
"(",
"function",
"(",
"regexp",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"regexp",
",",
"\"\"",
")",
";",
"}",
")",
";",
"Object",
".",
"keys",
"(",
"cache",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"html",
"=",
"html",
".",
"replace",
"(",
"key",
",",
"cache",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"return",
"html",
";",
"}",
";",
"return",
"self",
";",
"}"
]
| Compressor of the output html
@returns {Compressor}
@constructor | [
"Compressor",
"of",
"the",
"output",
"html"
]
| 34d10a92b21ec2357c9e8512df358e19741e174d | https://github.com/Antyfive/teo-html-compressor-extension/blob/34d10a92b21ec2357c9e8512df358e19741e174d/index.js#L14-L115 | train |
Antyfive/teo-html-compressor-extension | index.js | _clearHTMLComments | function _clearHTMLComments(html) {
var cStart = '<!--',
cEnd = '-->',
beg = html.indexOf(cStart),
end = 0;
while (beg !== -1) {
end = html.indexOf(cEnd, beg + 4);
if (end === -1) {
break;
}
var comment = html.substring(beg, end + 3);
if (comment.indexOf("[if") !== -1 || comment.indexOf("![endif]") !== -1) { // skip
beg = html.indexOf(cStart, end + 3);
continue;
}
html = html.replace(comment, "");
beg = html.indexOf(cStart, end + 3);
}
return html;
} | javascript | function _clearHTMLComments(html) {
var cStart = '<!--',
cEnd = '-->',
beg = html.indexOf(cStart),
end = 0;
while (beg !== -1) {
end = html.indexOf(cEnd, beg + 4);
if (end === -1) {
break;
}
var comment = html.substring(beg, end + 3);
if (comment.indexOf("[if") !== -1 || comment.indexOf("![endif]") !== -1) { // skip
beg = html.indexOf(cStart, end + 3);
continue;
}
html = html.replace(comment, "");
beg = html.indexOf(cStart, end + 3);
}
return html;
} | [
"function",
"_clearHTMLComments",
"(",
"html",
")",
"{",
"var",
"cStart",
"=",
"'<!--'",
",",
"cEnd",
"=",
"'",
",",
"beg",
"=",
"html",
".",
"indexOf",
"(",
"cStart",
")",
",",
"end",
"=",
"0",
";",
"while",
"(",
"beg",
"!==",
"-",
"1",
")",
"{",
"end",
"=",
"html",
".",
"indexOf",
"(",
"cEnd",
",",
"beg",
"+",
"4",
")",
";",
"if",
"(",
"end",
"===",
"-",
"1",
")",
"{",
"break",
";",
"}",
"var",
"comment",
"=",
"html",
".",
"substring",
"(",
"beg",
",",
"end",
"+",
"3",
")",
";",
"if",
"(",
"comment",
".",
"indexOf",
"(",
"\"[if\"",
")",
"!==",
"-",
"1",
"||",
"comment",
".",
"indexOf",
"(",
"\"![endif]\"",
")",
"!==",
"-",
"1",
")",
"{",
"beg",
"=",
"html",
".",
"indexOf",
"(",
"cStart",
",",
"end",
"+",
"3",
")",
";",
"continue",
";",
"}",
"html",
"=",
"html",
".",
"replace",
"(",
"comment",
",",
"\"\"",
")",
";",
"beg",
"=",
"html",
".",
"indexOf",
"(",
"cStart",
",",
"end",
"+",
"3",
")",
";",
"}",
"return",
"html",
";",
"}"
]
| Remover of the html comment blocks
@param html
@returns {*}
@private | [
"Remover",
"of",
"the",
"html",
"comment",
"blocks"
]
| 34d10a92b21ec2357c9e8512df358e19741e174d | https://github.com/Antyfive/teo-html-compressor-extension/blob/34d10a92b21ec2357c9e8512df358e19741e174d/index.js#L24-L49 | train |
nodys/cssy | lib/processor.js | function (ctx, next) {
var plugins = []
var config = process.cssy.config
ctx.imports = []
var parseImportPlugin = postcss.plugin('cssy-parse-imports', function () {
return function (styles) {
styles.walkAtRules(function (atRule) {
if (atRule.name !== 'import') {
return
}
if (/^url\(|:\/\//.test(atRule.params)) {
return // Absolute
}
ctx.imports.push(parseImport(atRule.params))
atRule.remove()
})
}
})
if (ctx.config.import) {
plugins.push(parseImportPlugin)
}
if (config.minify) {
plugins.push(cssnano(extend({}, (typeof config.minify === 'object')
? config.minify : DEFAULT_MINIFY_OPTIONS)))
}
postcss(plugins)
.process(ctx.src, {
from: ctx.filename,
to: ctx.filename + '.map',
map: {
prev: ctx.map,
inline: config.sourcemap
}
})
.then(function (result) {
ctx.src = result.css
if (config.sourcemap) {
// TODO: Dig sourcemap, dig more.
ctx.src += '\n/*# sourceURL=' + ctx.filename + '.output*/'
}
ctx.map = result.map
next(null, ctx)
})
next(null, ctx)
} | javascript | function (ctx, next) {
var plugins = []
var config = process.cssy.config
ctx.imports = []
var parseImportPlugin = postcss.plugin('cssy-parse-imports', function () {
return function (styles) {
styles.walkAtRules(function (atRule) {
if (atRule.name !== 'import') {
return
}
if (/^url\(|:\/\//.test(atRule.params)) {
return // Absolute
}
ctx.imports.push(parseImport(atRule.params))
atRule.remove()
})
}
})
if (ctx.config.import) {
plugins.push(parseImportPlugin)
}
if (config.minify) {
plugins.push(cssnano(extend({}, (typeof config.minify === 'object')
? config.minify : DEFAULT_MINIFY_OPTIONS)))
}
postcss(plugins)
.process(ctx.src, {
from: ctx.filename,
to: ctx.filename + '.map',
map: {
prev: ctx.map,
inline: config.sourcemap
}
})
.then(function (result) {
ctx.src = result.css
if (config.sourcemap) {
// TODO: Dig sourcemap, dig more.
ctx.src += '\n/*# sourceURL=' + ctx.filename + '.output*/'
}
ctx.map = result.map
next(null, ctx)
})
next(null, ctx)
} | [
"function",
"(",
"ctx",
",",
"next",
")",
"{",
"var",
"plugins",
"=",
"[",
"]",
"var",
"config",
"=",
"process",
".",
"cssy",
".",
"config",
"ctx",
".",
"imports",
"=",
"[",
"]",
"var",
"parseImportPlugin",
"=",
"postcss",
".",
"plugin",
"(",
"'cssy-parse-imports'",
",",
"function",
"(",
")",
"{",
"return",
"function",
"(",
"styles",
")",
"{",
"styles",
".",
"walkAtRules",
"(",
"function",
"(",
"atRule",
")",
"{",
"if",
"(",
"atRule",
".",
"name",
"!==",
"'import'",
")",
"{",
"return",
"}",
"if",
"(",
"/",
"^url\\(|:\\/\\/",
"/",
".",
"test",
"(",
"atRule",
".",
"params",
")",
")",
"{",
"return",
"}",
"ctx",
".",
"imports",
".",
"push",
"(",
"parseImport",
"(",
"atRule",
".",
"params",
")",
")",
"atRule",
".",
"remove",
"(",
")",
"}",
")",
"}",
"}",
")",
"if",
"(",
"ctx",
".",
"config",
".",
"import",
")",
"{",
"plugins",
".",
"push",
"(",
"parseImportPlugin",
")",
"}",
"if",
"(",
"config",
".",
"minify",
")",
"{",
"plugins",
".",
"push",
"(",
"cssnano",
"(",
"extend",
"(",
"{",
"}",
",",
"(",
"typeof",
"config",
".",
"minify",
"===",
"'object'",
")",
"?",
"config",
".",
"minify",
":",
"DEFAULT_MINIFY_OPTIONS",
")",
")",
")",
"}",
"postcss",
"(",
"plugins",
")",
".",
"process",
"(",
"ctx",
".",
"src",
",",
"{",
"from",
":",
"ctx",
".",
"filename",
",",
"to",
":",
"ctx",
".",
"filename",
"+",
"'.map'",
",",
"map",
":",
"{",
"prev",
":",
"ctx",
".",
"map",
",",
"inline",
":",
"config",
".",
"sourcemap",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"ctx",
".",
"src",
"=",
"result",
".",
"css",
"if",
"(",
"config",
".",
"sourcemap",
")",
"{",
"ctx",
".",
"src",
"+=",
"'\\n/*# sourceURL='",
"+",
"\\n",
"+",
"ctx",
".",
"filename",
"}",
"'.output*/'",
"ctx",
".",
"map",
"=",
"result",
".",
"map",
"}",
")",
"next",
"(",
"null",
",",
"ctx",
")",
"}"
]
| 6. Extract importations and generate source | [
"6",
".",
"Extract",
"importations",
"and",
"generate",
"source"
]
| 7b43cf7cfd1899ad54adcbae2701373cff5077a3 | https://github.com/nodys/cssy/blob/7b43cf7cfd1899ad54adcbae2701373cff5077a3/lib/processor.js#L138-L187 | train |
|
nodys/cssy | lib/processor.js | parseCss | function parseCss (ctx, done) {
var result
try {
result = postcss()
.process(ctx.src, {
map: {
sourcesContent: true,
annotation: false,
prev: ctx.map
},
from: ctx.filename
})
ctx.src = result.css
ctx.map = result.map.toJSON()
done(null, ctx)
} catch (e) {
var msg = e.message
var ext = extname(ctx.filename).slice(1).toLowerCase()
if (ext !== 'css') {
msg += ' (Try to use appropriate parser for ' + ext + ')'
}
done(new Error(msg))
}
} | javascript | function parseCss (ctx, done) {
var result
try {
result = postcss()
.process(ctx.src, {
map: {
sourcesContent: true,
annotation: false,
prev: ctx.map
},
from: ctx.filename
})
ctx.src = result.css
ctx.map = result.map.toJSON()
done(null, ctx)
} catch (e) {
var msg = e.message
var ext = extname(ctx.filename).slice(1).toLowerCase()
if (ext !== 'css') {
msg += ' (Try to use appropriate parser for ' + ext + ')'
}
done(new Error(msg))
}
} | [
"function",
"parseCss",
"(",
"ctx",
",",
"done",
")",
"{",
"var",
"result",
"try",
"{",
"result",
"=",
"postcss",
"(",
")",
".",
"process",
"(",
"ctx",
".",
"src",
",",
"{",
"map",
":",
"{",
"sourcesContent",
":",
"true",
",",
"annotation",
":",
"false",
",",
"prev",
":",
"ctx",
".",
"map",
"}",
",",
"from",
":",
"ctx",
".",
"filename",
"}",
")",
"ctx",
".",
"src",
"=",
"result",
".",
"css",
"ctx",
".",
"map",
"=",
"result",
".",
"map",
".",
"toJSON",
"(",
")",
"done",
"(",
"null",
",",
"ctx",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"msg",
"=",
"e",
".",
"message",
"var",
"ext",
"=",
"extname",
"(",
"ctx",
".",
"filename",
")",
".",
"slice",
"(",
"1",
")",
".",
"toLowerCase",
"(",
")",
"if",
"(",
"ext",
"!==",
"'css'",
")",
"{",
"msg",
"+=",
"' (Try to use appropriate parser for '",
"+",
"ext",
"+",
"')'",
"}",
"done",
"(",
"new",
"Error",
"(",
"msg",
")",
")",
"}",
"}"
]
| Default source parser for css source
@param {Object} ctx
Cssy context object with source
@param {Function} done
Async callback | [
"Default",
"source",
"parser",
"for",
"css",
"source"
]
| 7b43cf7cfd1899ad54adcbae2701373cff5077a3 | https://github.com/nodys/cssy/blob/7b43cf7cfd1899ad54adcbae2701373cff5077a3/lib/processor.js#L202-L225 | train |
sydneystockholm/blog.md | lib/network.js | Network | function Network(blogs) {
this.blogs = {};
this.loading = 0;
this.length = 1;
this.blog_names = [];
blogs = blogs || {};
for (var name in blogs) {
this.add(name, blogs[name]);
}
} | javascript | function Network(blogs) {
this.blogs = {};
this.loading = 0;
this.length = 1;
this.blog_names = [];
blogs = blogs || {};
for (var name in blogs) {
this.add(name, blogs[name]);
}
} | [
"function",
"Network",
"(",
"blogs",
")",
"{",
"this",
".",
"blogs",
"=",
"{",
"}",
";",
"this",
".",
"loading",
"=",
"0",
";",
"this",
".",
"length",
"=",
"1",
";",
"this",
".",
"blog_names",
"=",
"[",
"]",
";",
"blogs",
"=",
"blogs",
"||",
"{",
"}",
";",
"for",
"(",
"var",
"name",
"in",
"blogs",
")",
"{",
"this",
".",
"add",
"(",
"name",
",",
"blogs",
"[",
"name",
"]",
")",
";",
"}",
"}"
]
| Create a new blog network.
@param {Object} blogs (optional) - { name: Blog, ... } | [
"Create",
"a",
"new",
"blog",
"network",
"."
]
| 0b145fa1620cbe8b7296eb242241ee93223db9f9 | https://github.com/sydneystockholm/blog.md/blob/0b145fa1620cbe8b7296eb242241ee93223db9f9/lib/network.js#L12-L21 | train |
ahwayakchih/serve-files | lib/MIME.js | getFromFileNameV1 | function getFromFileNameV1 (filename) {
var result = mime.lookup(filename);
// Add charset just in case for some buggy browsers.
if (result === 'application/javascript' || result === 'application/json' || result === 'text/plain') {
result += '; charset=UTF-8';
}
return result;
} | javascript | function getFromFileNameV1 (filename) {
var result = mime.lookup(filename);
// Add charset just in case for some buggy browsers.
if (result === 'application/javascript' || result === 'application/json' || result === 'text/plain') {
result += '; charset=UTF-8';
}
return result;
} | [
"function",
"getFromFileNameV1",
"(",
"filename",
")",
"{",
"var",
"result",
"=",
"mime",
".",
"lookup",
"(",
"filename",
")",
";",
"if",
"(",
"result",
"===",
"'application/javascript'",
"||",
"result",
"===",
"'application/json'",
"||",
"result",
"===",
"'text/plain'",
")",
"{",
"result",
"+=",
"'; charset=UTF-8'",
";",
"}",
"return",
"result",
";",
"}"
]
| Use `mime` v1.x to get type.
@param {String} filename can be a full path
@returns {String} mime type | [
"Use",
"mime",
"v1",
".",
"x",
"to",
"get",
"type",
"."
]
| cd949252a37210bec229146ab519534ef641e942 | https://github.com/ahwayakchih/serve-files/blob/cd949252a37210bec229146ab519534ef641e942/lib/MIME.js#L72-L81 | train |
ahwayakchih/serve-files | lib/MIME.js | getFromFileNameV2 | function getFromFileNameV2 (filename) {
var result = mime.getType(filename);
// Add charset just in case for some buggy browsers.
if (result === 'application/javascript' || result === 'application/json' || result === 'text/plain') {
result += '; charset=UTF-8';
}
return result;
} | javascript | function getFromFileNameV2 (filename) {
var result = mime.getType(filename);
// Add charset just in case for some buggy browsers.
if (result === 'application/javascript' || result === 'application/json' || result === 'text/plain') {
result += '; charset=UTF-8';
}
return result;
} | [
"function",
"getFromFileNameV2",
"(",
"filename",
")",
"{",
"var",
"result",
"=",
"mime",
".",
"getType",
"(",
"filename",
")",
";",
"if",
"(",
"result",
"===",
"'application/javascript'",
"||",
"result",
"===",
"'application/json'",
"||",
"result",
"===",
"'text/plain'",
")",
"{",
"result",
"+=",
"'; charset=UTF-8'",
";",
"}",
"return",
"result",
";",
"}"
]
| Use `mime` v2.x to get type.
@param {String} filename can be a full path
@returns {String} mime type | [
"Use",
"mime",
"v2",
".",
"x",
"to",
"get",
"type",
"."
]
| cd949252a37210bec229146ab519534ef641e942 | https://github.com/ahwayakchih/serve-files/blob/cd949252a37210bec229146ab519534ef641e942/lib/MIME.js#L89-L98 | train |
JulioGold/smart-utils | smartUtils.js | ListDirectoryContentRecursive | function ListDirectoryContentRecursive(directoryPath, callback) {
var fs = fs || require('fs');
var path = path || require('path');
var results = [];
fs.readdir(directoryPath, function(err, list) {
if (err) {
return callback(err);
}
var pending = list.length;
if (!pending) {
return callback(null, results);
}
list.forEach(function(file) {
file = path.join(directoryPath, file);
results.push(file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
ListDirectoryContentRecursive(file, function(err, res) {
results = results.concat(res);
if (!--pending) {
callback(null, results);
}
});
} else {
if (!--pending) {
callback(null, results);
}
}
});
});
});
} | javascript | function ListDirectoryContentRecursive(directoryPath, callback) {
var fs = fs || require('fs');
var path = path || require('path');
var results = [];
fs.readdir(directoryPath, function(err, list) {
if (err) {
return callback(err);
}
var pending = list.length;
if (!pending) {
return callback(null, results);
}
list.forEach(function(file) {
file = path.join(directoryPath, file);
results.push(file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
ListDirectoryContentRecursive(file, function(err, res) {
results = results.concat(res);
if (!--pending) {
callback(null, results);
}
});
} else {
if (!--pending) {
callback(null, results);
}
}
});
});
});
} | [
"function",
"ListDirectoryContentRecursive",
"(",
"directoryPath",
",",
"callback",
")",
"{",
"var",
"fs",
"=",
"fs",
"||",
"require",
"(",
"'fs'",
")",
";",
"var",
"path",
"=",
"path",
"||",
"require",
"(",
"'path'",
")",
";",
"var",
"results",
"=",
"[",
"]",
";",
"fs",
".",
"readdir",
"(",
"directoryPath",
",",
"function",
"(",
"err",
",",
"list",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"pending",
"=",
"list",
".",
"length",
";",
"if",
"(",
"!",
"pending",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
"list",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"file",
"=",
"path",
".",
"join",
"(",
"directoryPath",
",",
"file",
")",
";",
"results",
".",
"push",
"(",
"file",
")",
";",
"fs",
".",
"stat",
"(",
"file",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"stat",
"&&",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"ListDirectoryContentRecursive",
"(",
"file",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"results",
"=",
"results",
".",
"concat",
"(",
"res",
")",
";",
"if",
"(",
"!",
"--",
"pending",
")",
"{",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"--",
"pending",
")",
"{",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| List all files and directories inside a directory recursive, that is asynchronous | [
"List",
"all",
"files",
"and",
"directories",
"inside",
"a",
"directory",
"recursive",
"that",
"is",
"asynchronous"
]
| 2599e17dd5ed7ac656fc7518417a8e8419ea68b9 | https://github.com/JulioGold/smart-utils/blob/2599e17dd5ed7ac656fc7518417a8e8419ea68b9/smartUtils.js#L55-L99 | train |
JulioGold/smart-utils | smartUtils.js | ObjectDeepFind | function ObjectDeepFind(obj, propertyPath) {
// Divide todas as propriedades pelo .
var paths = propertyPath.split('.');
// Copia o objeto
var currentObj = obj;
// Para cada propriedade vou pegar a próxima até encontrar o valor do path inteiro da propriedade
for (var i = 0; i < paths.length; ++i) {
if (currentObj[paths[i]] == undefined) {
return undefined;
} else {
currentObj = currentObj[paths[i]];
}
}
return currentObj;
} | javascript | function ObjectDeepFind(obj, propertyPath) {
// Divide todas as propriedades pelo .
var paths = propertyPath.split('.');
// Copia o objeto
var currentObj = obj;
// Para cada propriedade vou pegar a próxima até encontrar o valor do path inteiro da propriedade
for (var i = 0; i < paths.length; ++i) {
if (currentObj[paths[i]] == undefined) {
return undefined;
} else {
currentObj = currentObj[paths[i]];
}
}
return currentObj;
} | [
"function",
"ObjectDeepFind",
"(",
"obj",
",",
"propertyPath",
")",
"{",
"var",
"paths",
"=",
"propertyPath",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"currentObj",
"=",
"obj",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"paths",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"currentObj",
"[",
"paths",
"[",
"i",
"]",
"]",
"==",
"undefined",
")",
"{",
"return",
"undefined",
";",
"}",
"else",
"{",
"currentObj",
"=",
"currentObj",
"[",
"paths",
"[",
"i",
"]",
"]",
";",
"}",
"}",
"return",
"currentObj",
";",
"}"
]
| Get the value of an property deep into in a object, or not. Do not ask me the utility of it ;D | [
"Get",
"the",
"value",
"of",
"an",
"property",
"deep",
"into",
"in",
"a",
"object",
"or",
"not",
".",
"Do",
"not",
"ask",
"me",
"the",
"utility",
"of",
"it",
";",
"D"
]
| 2599e17dd5ed7ac656fc7518417a8e8419ea68b9 | https://github.com/JulioGold/smart-utils/blob/2599e17dd5ed7ac656fc7518417a8e8419ea68b9/smartUtils.js#L170-L188 | train |
lookyhooky/toolchest | toolchest.js | curry | function curry (fn, ...args) {
if (args.length >= fn.length) {
return fn.apply(null, args)
} else {
return function (...rest) {
return curry(fn, ...args, ...rest)
}
}
} | javascript | function curry (fn, ...args) {
if (args.length >= fn.length) {
return fn.apply(null, args)
} else {
return function (...rest) {
return curry(fn, ...args, ...rest)
}
}
} | [
"function",
"curry",
"(",
"fn",
",",
"...",
"args",
")",
"{",
"if",
"(",
"args",
".",
"length",
">=",
"fn",
".",
"length",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"null",
",",
"args",
")",
"}",
"else",
"{",
"return",
"function",
"(",
"...",
"rest",
")",
"{",
"return",
"curry",
"(",
"fn",
",",
"...",
"args",
",",
"...",
"rest",
")",
"}",
"}",
"}"
]
| The All Mighty Curry!
Any extra arguments are to be handled by the curried function.
Note: Default and Rest parameters are not accounted for in Function#length.
So the curried function will be called as soon as it has recieved all regular
parameters. To utilize Rest parameters use curryN
By the way, the spread operator is so cool! | [
"The",
"All",
"Mighty",
"Curry!",
"Any",
"extra",
"arguments",
"are",
"to",
"be",
"handled",
"by",
"the",
"curried",
"function",
"."
]
| d76213f27d87ca929b1f8652a45db5fab214e881 | https://github.com/lookyhooky/toolchest/blob/d76213f27d87ca929b1f8652a45db5fab214e881/toolchest.js#L284-L292 | train |
thundernet8/mpvue-rc-loader | lib/loader.js | getRawRequest | function getRawRequest(context, excludedPreLoaders) {
excludedPreLoaders = excludedPreLoaders || /eslint-loader/;
return loaderUtils.getRemainingRequest({
resource: context.resource,
loaderIndex: context.loaderIndex,
loaders: context.loaders.filter(loader => !excludedPreLoaders.test(loader.path))
});
} | javascript | function getRawRequest(context, excludedPreLoaders) {
excludedPreLoaders = excludedPreLoaders || /eslint-loader/;
return loaderUtils.getRemainingRequest({
resource: context.resource,
loaderIndex: context.loaderIndex,
loaders: context.loaders.filter(loader => !excludedPreLoaders.test(loader.path))
});
} | [
"function",
"getRawRequest",
"(",
"context",
",",
"excludedPreLoaders",
")",
"{",
"excludedPreLoaders",
"=",
"excludedPreLoaders",
"||",
"/",
"eslint-loader",
"/",
";",
"return",
"loaderUtils",
".",
"getRemainingRequest",
"(",
"{",
"resource",
":",
"context",
".",
"resource",
",",
"loaderIndex",
":",
"context",
".",
"loaderIndex",
",",
"loaders",
":",
"context",
".",
"loaders",
".",
"filter",
"(",
"loader",
"=>",
"!",
"excludedPreLoaders",
".",
"test",
"(",
"loader",
".",
"path",
")",
")",
"}",
")",
";",
"}"
]
| When extracting parts from the source vue file, we want to apply the loaders chained before vue-loader, but exclude some loaders that simply produces side effects such as linting. | [
"When",
"extracting",
"parts",
"from",
"the",
"source",
"vue",
"file",
"we",
"want",
"to",
"apply",
"the",
"loaders",
"chained",
"before",
"vue",
"-",
"loader",
"but",
"exclude",
"some",
"loaders",
"that",
"simply",
"produces",
"side",
"effects",
"such",
"as",
"linting",
"."
]
| 9353432153abbddc2fa673f289edc39f35801b8f | https://github.com/thundernet8/mpvue-rc-loader/blob/9353432153abbddc2fa673f289edc39f35801b8f/lib/loader.js#L40-L47 | train |
shinuza/captain-core | lib/models/tokens.js | findUserFromToken | function findUserFromToken(token, cb) {
var q = "SELECT * FROM users " +
"JOIN tokens t ON t.token = $1 " +
"JOIN users u ON u.id = t.user_id";
db.getClient(function(err, client, done) {
client.query(q, [token], function(err, r) {
var result = r && r.rows[0];
if(!result && !err) { err = new exceptions.NotFound(); }
if(err) {
cb(err);
done(err);
} else {
cb(null, result);
done();
}
});
});
} | javascript | function findUserFromToken(token, cb) {
var q = "SELECT * FROM users " +
"JOIN tokens t ON t.token = $1 " +
"JOIN users u ON u.id = t.user_id";
db.getClient(function(err, client, done) {
client.query(q, [token], function(err, r) {
var result = r && r.rows[0];
if(!result && !err) { err = new exceptions.NotFound(); }
if(err) {
cb(err);
done(err);
} else {
cb(null, result);
done();
}
});
});
} | [
"function",
"findUserFromToken",
"(",
"token",
",",
"cb",
")",
"{",
"var",
"q",
"=",
"\"SELECT * FROM users \"",
"+",
"\"JOIN tokens t ON t.token = $1 \"",
"+",
"\"JOIN users u ON u.id = t.user_id\"",
";",
"db",
".",
"getClient",
"(",
"function",
"(",
"err",
",",
"client",
",",
"done",
")",
"{",
"client",
".",
"query",
"(",
"q",
",",
"[",
"token",
"]",
",",
"function",
"(",
"err",
",",
"r",
")",
"{",
"var",
"result",
"=",
"r",
"&&",
"r",
".",
"rows",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"result",
"&&",
"!",
"err",
")",
"{",
"err",
"=",
"new",
"exceptions",
".",
"NotFound",
"(",
")",
";",
"}",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"done",
"(",
"err",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"result",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Finds associated user with the token matching `token`
`cb` is passed with the matching user or exceptions.NotFound
@param {String} token
@param {Function} cb | [
"Finds",
"associated",
"user",
"with",
"the",
"token",
"matching",
"token"
]
| 02f3a404cdfca608e8726bbacc33e32fec484b21 | https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/tokens.js#L92-L110 | train |
shinuza/captain-core | lib/models/tokens.js | create | function create(body, cb) {
var validates = Schema(body);
if(!validates) {
return cb(new exceptions.BadRequest());
}
body.expires_at = stampify(conf.session_maxage);
var q = qb.insert(body);
db.getClient(function(err, client, done) {
client.query(q[0], q[1], function(err, r) {
if(err) {
if(err.code == 23505) {
err = new exceptions.AlreadyExists();
}
cb(err);
done(err);
} else {
cb(null, r.rows[0]);
done();
}
});
});
} | javascript | function create(body, cb) {
var validates = Schema(body);
if(!validates) {
return cb(new exceptions.BadRequest());
}
body.expires_at = stampify(conf.session_maxage);
var q = qb.insert(body);
db.getClient(function(err, client, done) {
client.query(q[0], q[1], function(err, r) {
if(err) {
if(err.code == 23505) {
err = new exceptions.AlreadyExists();
}
cb(err);
done(err);
} else {
cb(null, r.rows[0]);
done();
}
});
});
} | [
"function",
"create",
"(",
"body",
",",
"cb",
")",
"{",
"var",
"validates",
"=",
"Schema",
"(",
"body",
")",
";",
"if",
"(",
"!",
"validates",
")",
"{",
"return",
"cb",
"(",
"new",
"exceptions",
".",
"BadRequest",
"(",
")",
")",
";",
"}",
"body",
".",
"expires_at",
"=",
"stampify",
"(",
"conf",
".",
"session_maxage",
")",
";",
"var",
"q",
"=",
"qb",
".",
"insert",
"(",
"body",
")",
";",
"db",
".",
"getClient",
"(",
"function",
"(",
"err",
",",
"client",
",",
"done",
")",
"{",
"client",
".",
"query",
"(",
"q",
"[",
"0",
"]",
",",
"q",
"[",
"1",
"]",
",",
"function",
"(",
"err",
",",
"r",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"==",
"23505",
")",
"{",
"err",
"=",
"new",
"exceptions",
".",
"AlreadyExists",
"(",
")",
";",
"}",
"cb",
"(",
"err",
")",
";",
"done",
"(",
"err",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
",",
"r",
".",
"rows",
"[",
"0",
"]",
")",
";",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Creates a new token.
`cb` is passed with the newly created token or:
* exceptions.BadRequest: if `body` does not satisfy the schema
* exceptions.AlreadyExists: if a token with the same `token` already exists
@param {Object} body
@param {Function} cb | [
"Creates",
"a",
"new",
"token",
"."
]
| 02f3a404cdfca608e8726bbacc33e32fec484b21 | https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/tokens.js#L125-L149 | train |
shinuza/captain-core | lib/models/tokens.js | harvest | function harvest() {
var q = "DELETE FROM tokens WHERE expires_at < now() AT TIME ZONE 'UTC'";
db.getClient(function(err, client, done) {
client.query(q, function(err) {
if(err) {
console.error(new Date);
console.error(err.stack);
}
done(err);
});
});
} | javascript | function harvest() {
var q = "DELETE FROM tokens WHERE expires_at < now() AT TIME ZONE 'UTC'";
db.getClient(function(err, client, done) {
client.query(q, function(err) {
if(err) {
console.error(new Date);
console.error(err.stack);
}
done(err);
});
});
} | [
"function",
"harvest",
"(",
")",
"{",
"var",
"q",
"=",
"\"DELETE FROM tokens WHERE expires_at < now() AT TIME ZONE 'UTC'\"",
";",
"db",
".",
"getClient",
"(",
"function",
"(",
"err",
",",
"client",
",",
"done",
")",
"{",
"client",
".",
"query",
"(",
"q",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"new",
"Date",
")",
";",
"console",
".",
"error",
"(",
"err",
".",
"stack",
")",
";",
"}",
"done",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Deletes expired tokens | [
"Deletes",
"expired",
"tokens"
]
| 02f3a404cdfca608e8726bbacc33e32fec484b21 | https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/tokens.js#L183-L194 | train |
justinhelmer/vinyl-tasks | lib/filter.js | filter | function filter(filterName, pattern, options) {
return function() {
options = options || {};
filters[filterName] = gFilter(pattern, options);
return filters[filterName];
};
} | javascript | function filter(filterName, pattern, options) {
return function() {
options = options || {};
filters[filterName] = gFilter(pattern, options);
return filters[filterName];
};
} | [
"function",
"filter",
"(",
"filterName",
",",
"pattern",
",",
"options",
")",
"{",
"return",
"function",
"(",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"filters",
"[",
"filterName",
"]",
"=",
"gFilter",
"(",
"pattern",
",",
"options",
")",
";",
"return",
"filters",
"[",
"filterName",
"]",
";",
"}",
";",
"}"
]
| Creates a filter function that filters a vinyl stream when invoked. Additionally stores the filter in memory
for use with filter.restore.
@name filter
@param {string} filterName - The name of the filter to create. Should be namespaced to avoid collisions.
@param {*} pattern - The source glob pattern(s) to filter the vinyl stream.
@param {object} [options] - The additional options to pass to gulp-filter.
@returns {function} - The partial that generates the vinyl filter when invoked.
@see https://github.com/sindresorhus/gulp-filter | [
"Creates",
"a",
"filter",
"function",
"that",
"filters",
"a",
"vinyl",
"stream",
"when",
"invoked",
".",
"Additionally",
"stores",
"the",
"filter",
"in",
"memory",
"for",
"use",
"with",
"filter",
".",
"restore",
"."
]
| eca1f79065a3653023896c4f546dc44dbac81e62 | https://github.com/justinhelmer/vinyl-tasks/blob/eca1f79065a3653023896c4f546dc44dbac81e62/lib/filter.js#L18-L24 | train |
davidwood/cachetree-redis | lib/store.js | createBuffer | function createBuffer(str, encoding) {
if (BUFFER_FROM) {
return Buffer.from(str, encoding || ENCODING);
}
return new Buffer(str, encoding || ENCODING);
} | javascript | function createBuffer(str, encoding) {
if (BUFFER_FROM) {
return Buffer.from(str, encoding || ENCODING);
}
return new Buffer(str, encoding || ENCODING);
} | [
"function",
"createBuffer",
"(",
"str",
",",
"encoding",
")",
"{",
"if",
"(",
"BUFFER_FROM",
")",
"{",
"return",
"Buffer",
".",
"from",
"(",
"str",
",",
"encoding",
"||",
"ENCODING",
")",
";",
"}",
"return",
"new",
"Buffer",
"(",
"str",
",",
"encoding",
"||",
"ENCODING",
")",
";",
"}"
]
| Create a buffer from a string
@param {String} str String value
@param {String} [encoding] Optional string encoding
@returns {Buffer} string as buffer | [
"Create",
"a",
"buffer",
"from",
"a",
"string"
]
| a44842b77dad9f7a9f87a829a98820284548d874 | https://github.com/davidwood/cachetree-redis/blob/a44842b77dad9f7a9f87a829a98820284548d874/lib/store.js#L31-L36 | train |
davidwood/cachetree-redis | lib/store.js | convertValue | function convertValue(value, cast) {
var val;
if (value === null || value === undefined) {
return value;
}
val = Buffer.isBuffer(value) ? value.toString('utf8') : value;
if (cast !== false && typeof val === 'string') {
try {
return JSON.parse(val);
} catch (e) {}
}
return val;
} | javascript | function convertValue(value, cast) {
var val;
if (value === null || value === undefined) {
return value;
}
val = Buffer.isBuffer(value) ? value.toString('utf8') : value;
if (cast !== false && typeof val === 'string') {
try {
return JSON.parse(val);
} catch (e) {}
}
return val;
} | [
"function",
"convertValue",
"(",
"value",
",",
"cast",
")",
"{",
"var",
"val",
";",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
")",
"{",
"return",
"value",
";",
"}",
"val",
"=",
"Buffer",
".",
"isBuffer",
"(",
"value",
")",
"?",
"value",
".",
"toString",
"(",
"'utf8'",
")",
":",
"value",
";",
"if",
"(",
"cast",
"!==",
"false",
"&&",
"typeof",
"val",
"===",
"'string'",
")",
"{",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"val",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"return",
"val",
";",
"}"
]
| Convert a value
@param {*} value Value to convert
@param {Boolean} rawBuffer true to return a raw buffer
@param {Boolean} cast true to cast the value
@returns {*} converted value | [
"Convert",
"a",
"value"
]
| a44842b77dad9f7a9f87a829a98820284548d874 | https://github.com/davidwood/cachetree-redis/blob/a44842b77dad9f7a9f87a829a98820284548d874/lib/store.js#L46-L58 | train |
davidwood/cachetree-redis | lib/store.js | wrapData | function wrapData(target, name, value, rawBuffer, cast) {
var converted = false;
var val;
if (!target.hasOwnProperty(name)) {
if (value === null || value === undefined || (rawBuffer === true && Buffer.isBuffer(value))) {
converted = true;
val = value;
}
Object.defineProperty(target, name, {
get: function() {
if (!converted) {
val = convertValue(value, cast);
converted = true;
}
return val;
},
enumerable: true,
});
}
} | javascript | function wrapData(target, name, value, rawBuffer, cast) {
var converted = false;
var val;
if (!target.hasOwnProperty(name)) {
if (value === null || value === undefined || (rawBuffer === true && Buffer.isBuffer(value))) {
converted = true;
val = value;
}
Object.defineProperty(target, name, {
get: function() {
if (!converted) {
val = convertValue(value, cast);
converted = true;
}
return val;
},
enumerable: true,
});
}
} | [
"function",
"wrapData",
"(",
"target",
",",
"name",
",",
"value",
",",
"rawBuffer",
",",
"cast",
")",
"{",
"var",
"converted",
"=",
"false",
";",
"var",
"val",
";",
"if",
"(",
"!",
"target",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"if",
"(",
"value",
"===",
"null",
"||",
"value",
"===",
"undefined",
"||",
"(",
"rawBuffer",
"===",
"true",
"&&",
"Buffer",
".",
"isBuffer",
"(",
"value",
")",
")",
")",
"{",
"converted",
"=",
"true",
";",
"val",
"=",
"value",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"target",
",",
"name",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"converted",
")",
"{",
"val",
"=",
"convertValue",
"(",
"value",
",",
"cast",
")",
";",
"converted",
"=",
"true",
";",
"}",
"return",
"val",
";",
"}",
",",
"enumerable",
":",
"true",
",",
"}",
")",
";",
"}",
"}"
]
| Generate a property to lazily convert a Buffer value
@param {Object} target Target object
@param {String} name Property name
@param {*} value Property value
@param {Boolean} rawBuffer true to return a raw buffer
@param {Boolean} cast true to cast the value | [
"Generate",
"a",
"property",
"to",
"lazily",
"convert",
"a",
"Buffer",
"value"
]
| a44842b77dad9f7a9f87a829a98820284548d874 | https://github.com/davidwood/cachetree-redis/blob/a44842b77dad9f7a9f87a829a98820284548d874/lib/store.js#L69-L88 | train |
melvincarvalho/rdf-shell | lib/sub.js | sub | function sub (subURI, callback) {
var PING_TIMEOUT = process.env['PING_TIMEOUT']
if (!subURI) {
callback(new Error('uri is required'))
return
}
var domain = subURI.split('/')[2]
var wss = 'wss://' + domain + '/'
var Socket = new ws(wss, {
origin: 'http://websocket.org'
})
Socket.on('open', function open () {
debug('connected')
Socket.send('sub ' + subURI)
if (PING_TIMEOUT && parseInt(PING_TIMEOUT) && parseInt(PING_TIMEOUT) > 0 ) {
setInterval(function() {
debug('sending ping')
Socket.send('ping')
}, parseInt(PING_TIMEOUT * 1000))
}
})
Socket.on('close', function close () {
debug('disconnected')
})
Socket.on('message', function message (data, flags) {
debug(data)
callback(null, data)
})
} | javascript | function sub (subURI, callback) {
var PING_TIMEOUT = process.env['PING_TIMEOUT']
if (!subURI) {
callback(new Error('uri is required'))
return
}
var domain = subURI.split('/')[2]
var wss = 'wss://' + domain + '/'
var Socket = new ws(wss, {
origin: 'http://websocket.org'
})
Socket.on('open', function open () {
debug('connected')
Socket.send('sub ' + subURI)
if (PING_TIMEOUT && parseInt(PING_TIMEOUT) && parseInt(PING_TIMEOUT) > 0 ) {
setInterval(function() {
debug('sending ping')
Socket.send('ping')
}, parseInt(PING_TIMEOUT * 1000))
}
})
Socket.on('close', function close () {
debug('disconnected')
})
Socket.on('message', function message (data, flags) {
debug(data)
callback(null, data)
})
} | [
"function",
"sub",
"(",
"subURI",
",",
"callback",
")",
"{",
"var",
"PING_TIMEOUT",
"=",
"process",
".",
"env",
"[",
"'PING_TIMEOUT'",
"]",
"if",
"(",
"!",
"subURI",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'uri is required'",
")",
")",
"return",
"}",
"var",
"domain",
"=",
"subURI",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
"]",
"var",
"wss",
"=",
"'wss://'",
"+",
"domain",
"+",
"'/'",
"var",
"Socket",
"=",
"new",
"ws",
"(",
"wss",
",",
"{",
"origin",
":",
"'http://websocket.org'",
"}",
")",
"Socket",
".",
"on",
"(",
"'open'",
",",
"function",
"open",
"(",
")",
"{",
"debug",
"(",
"'connected'",
")",
"Socket",
".",
"send",
"(",
"'sub '",
"+",
"subURI",
")",
"if",
"(",
"PING_TIMEOUT",
"&&",
"parseInt",
"(",
"PING_TIMEOUT",
")",
"&&",
"parseInt",
"(",
"PING_TIMEOUT",
")",
">",
"0",
")",
"{",
"setInterval",
"(",
"function",
"(",
")",
"{",
"debug",
"(",
"'sending ping'",
")",
"Socket",
".",
"send",
"(",
"'ping'",
")",
"}",
",",
"parseInt",
"(",
"PING_TIMEOUT",
"*",
"1000",
")",
")",
"}",
"}",
")",
"Socket",
".",
"on",
"(",
"'close'",
",",
"function",
"close",
"(",
")",
"{",
"debug",
"(",
"'disconnected'",
")",
"}",
")",
"Socket",
".",
"on",
"(",
"'message'",
",",
"function",
"message",
"(",
"data",
",",
"flags",
")",
"{",
"debug",
"(",
"data",
")",
"callback",
"(",
"null",
",",
"data",
")",
"}",
")",
"}"
]
| sub gets list of files for a given container
@param {String} argv[2] url
@callback {bin~cb} callback | [
"sub",
"gets",
"list",
"of",
"files",
"for",
"a",
"given",
"container"
]
| bf2015f6f333855e69a18ce3ec9e917bbddfb425 | https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/sub.js#L12-L47 | train |
antonycourtney/tabli-core | lib/js/searchOps.js | matchTabItem | function matchTabItem(tabItem, searchExp) {
var urlMatches = tabItem.url.match(searchExp);
var titleMatches = tabItem.title.match(searchExp);
if (urlMatches === null && titleMatches === null) {
return null;
}
return new FilteredTabItem({ tabItem: tabItem, urlMatches: urlMatches, titleMatches: titleMatches });
} | javascript | function matchTabItem(tabItem, searchExp) {
var urlMatches = tabItem.url.match(searchExp);
var titleMatches = tabItem.title.match(searchExp);
if (urlMatches === null && titleMatches === null) {
return null;
}
return new FilteredTabItem({ tabItem: tabItem, urlMatches: urlMatches, titleMatches: titleMatches });
} | [
"function",
"matchTabItem",
"(",
"tabItem",
",",
"searchExp",
")",
"{",
"var",
"urlMatches",
"=",
"tabItem",
".",
"url",
".",
"match",
"(",
"searchExp",
")",
";",
"var",
"titleMatches",
"=",
"tabItem",
".",
"title",
".",
"match",
"(",
"searchExp",
")",
";",
"if",
"(",
"urlMatches",
"===",
"null",
"&&",
"titleMatches",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"FilteredTabItem",
"(",
"{",
"tabItem",
":",
"tabItem",
",",
"urlMatches",
":",
"urlMatches",
",",
"titleMatches",
":",
"titleMatches",
"}",
")",
";",
"}"
]
| Use a RegExp to match a particular TabItem
@return {FilteredTabItem} filtered item (or null if no match)
Search and filter operations on TabWindows | [
"Use",
"a",
"RegExp",
"to",
"match",
"a",
"particular",
"TabItem"
]
| 76cc540891421bc6c8bdcf00f277ebb6e716fdd9 | https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/searchOps.js#L42-L51 | train |
antonycourtney/tabli-core | lib/js/searchOps.js | matchTabWindow | function matchTabWindow(tabWindow, searchExp) {
var itemMatches = tabWindow.tabItems.map(function (ti) {
return matchTabItem(ti, searchExp);
}).filter(function (fti) {
return fti !== null;
});
var titleMatches = tabWindow.title.match(searchExp);
if (titleMatches === null && itemMatches.count() === 0) {
return null;
}
return FilteredTabWindow({ tabWindow: tabWindow, titleMatches: titleMatches, itemMatches: itemMatches });
} | javascript | function matchTabWindow(tabWindow, searchExp) {
var itemMatches = tabWindow.tabItems.map(function (ti) {
return matchTabItem(ti, searchExp);
}).filter(function (fti) {
return fti !== null;
});
var titleMatches = tabWindow.title.match(searchExp);
if (titleMatches === null && itemMatches.count() === 0) {
return null;
}
return FilteredTabWindow({ tabWindow: tabWindow, titleMatches: titleMatches, itemMatches: itemMatches });
} | [
"function",
"matchTabWindow",
"(",
"tabWindow",
",",
"searchExp",
")",
"{",
"var",
"itemMatches",
"=",
"tabWindow",
".",
"tabItems",
".",
"map",
"(",
"function",
"(",
"ti",
")",
"{",
"return",
"matchTabItem",
"(",
"ti",
",",
"searchExp",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"fti",
")",
"{",
"return",
"fti",
"!==",
"null",
";",
"}",
")",
";",
"var",
"titleMatches",
"=",
"tabWindow",
".",
"title",
".",
"match",
"(",
"searchExp",
")",
";",
"if",
"(",
"titleMatches",
"===",
"null",
"&&",
"itemMatches",
".",
"count",
"(",
")",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"return",
"FilteredTabWindow",
"(",
"{",
"tabWindow",
":",
"tabWindow",
",",
"titleMatches",
":",
"titleMatches",
",",
"itemMatches",
":",
"itemMatches",
"}",
")",
";",
"}"
]
| Match a TabWindow using a Regexp
matching tab items | [
"Match",
"a",
"TabWindow",
"using",
"a",
"Regexp"
]
| 76cc540891421bc6c8bdcf00f277ebb6e716fdd9 | https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/searchOps.js#L66-L79 | train |
antonycourtney/tabli-core | lib/js/searchOps.js | filterTabWindows | function filterTabWindows(tabWindows, searchExp) {
var res;
if (searchExp === null) {
res = _.map(tabWindows, function (tw) {
return new FilteredTabWindow({ tabWindow: tw });
});
} else {
var mappedWindows = _.map(tabWindows, function (tw) {
return matchTabWindow(tw, searchExp);
});
res = _.filter(mappedWindows, function (fw) {
return fw !== null;
});
}
return res;
} | javascript | function filterTabWindows(tabWindows, searchExp) {
var res;
if (searchExp === null) {
res = _.map(tabWindows, function (tw) {
return new FilteredTabWindow({ tabWindow: tw });
});
} else {
var mappedWindows = _.map(tabWindows, function (tw) {
return matchTabWindow(tw, searchExp);
});
res = _.filter(mappedWindows, function (fw) {
return fw !== null;
});
}
return res;
} | [
"function",
"filterTabWindows",
"(",
"tabWindows",
",",
"searchExp",
")",
"{",
"var",
"res",
";",
"if",
"(",
"searchExp",
"===",
"null",
")",
"{",
"res",
"=",
"_",
".",
"map",
"(",
"tabWindows",
",",
"function",
"(",
"tw",
")",
"{",
"return",
"new",
"FilteredTabWindow",
"(",
"{",
"tabWindow",
":",
"tw",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"var",
"mappedWindows",
"=",
"_",
".",
"map",
"(",
"tabWindows",
",",
"function",
"(",
"tw",
")",
"{",
"return",
"matchTabWindow",
"(",
"tw",
",",
"searchExp",
")",
";",
"}",
")",
";",
"res",
"=",
"_",
".",
"filter",
"(",
"mappedWindows",
",",
"function",
"(",
"fw",
")",
"{",
"return",
"fw",
"!==",
"null",
";",
"}",
")",
";",
"}",
"return",
"res",
";",
"}"
]
| filter an array of TabWindows using a searchRE to obtain
an array of FilteredTabWindow | [
"filter",
"an",
"array",
"of",
"TabWindows",
"using",
"a",
"searchRE",
"to",
"obtain",
"an",
"array",
"of",
"FilteredTabWindow"
]
| 76cc540891421bc6c8bdcf00f277ebb6e716fdd9 | https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/searchOps.js#L85-L101 | train |
angeloocana/joj-core | dist/Position.js | setICanGoHere | function setICanGoHere(positionsWhereCanIGo, position) {
return Object.assign({
iCanGoHere: containsXY(positionsWhereCanIGo, position)
}, position);
} | javascript | function setICanGoHere(positionsWhereCanIGo, position) {
return Object.assign({
iCanGoHere: containsXY(positionsWhereCanIGo, position)
}, position);
} | [
"function",
"setICanGoHere",
"(",
"positionsWhereCanIGo",
",",
"position",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"{",
"iCanGoHere",
":",
"containsXY",
"(",
"positionsWhereCanIGo",
",",
"position",
")",
"}",
",",
"position",
")",
";",
"}"
]
| Takes a position and return a new position with iCanGoHere checked. | [
"Takes",
"a",
"position",
"and",
"return",
"a",
"new",
"position",
"with",
"iCanGoHere",
"checked",
"."
]
| 14bc7801c004271cefafff6cc0abb0c3173c805a | https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist/Position.js#L99-L103 | train |
angeloocana/joj-core | dist/Position.js | printUnicodePosition | function printUnicodePosition(p) {
return isBackGroundBlack(p.x, p.y) ? printUnicodeBackgroundBlack(p) : printUnicodeBackgroundWhite(p);
} | javascript | function printUnicodePosition(p) {
return isBackGroundBlack(p.x, p.y) ? printUnicodeBackgroundBlack(p) : printUnicodeBackgroundWhite(p);
} | [
"function",
"printUnicodePosition",
"(",
"p",
")",
"{",
"return",
"isBackGroundBlack",
"(",
"p",
".",
"x",
",",
"p",
".",
"y",
")",
"?",
"printUnicodeBackgroundBlack",
"(",
"p",
")",
":",
"printUnicodeBackgroundWhite",
"(",
"p",
")",
";",
"}"
]
| Print unicode position to print the board in console.
@param p position | [
"Print",
"unicode",
"position",
"to",
"print",
"the",
"board",
"in",
"console",
"."
]
| 14bc7801c004271cefafff6cc0abb0c3173c805a | https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist/Position.js#L182-L184 | train |
angeloocana/joj-core | dist/Position.js | containsXY | function containsXY(positions, position) {
return positions ? positions.some(function (p) {
return hasSameXY(p, position);
}) : false;
} | javascript | function containsXY(positions, position) {
return positions ? positions.some(function (p) {
return hasSameXY(p, position);
}) : false;
} | [
"function",
"containsXY",
"(",
"positions",
",",
"position",
")",
"{",
"return",
"positions",
"?",
"positions",
".",
"some",
"(",
"function",
"(",
"p",
")",
"{",
"return",
"hasSameXY",
"(",
"p",
",",
"position",
")",
";",
"}",
")",
":",
"false",
";",
"}"
]
| Checks if an array of positions contains a position. | [
"Checks",
"if",
"an",
"array",
"of",
"positions",
"contains",
"a",
"position",
"."
]
| 14bc7801c004271cefafff6cc0abb0c3173c805a | https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist/Position.js#L188-L192 | train |
jtheriault/code-copter-analyzer-jshint | src/index.js | getJshintrc | function getJshintrc () {
var jshintrcPath = process.cwd() + '/.jshintrc';
try {
return JSON.parse(fs.readFileSync(jshintrcPath, 'utf8'));
}
catch (error) {
console.warn(`Expected to find JSHint configuration ${jshintrcPath}. Using default JSHint configuration`);
return undefined;
}
} | javascript | function getJshintrc () {
var jshintrcPath = process.cwd() + '/.jshintrc';
try {
return JSON.parse(fs.readFileSync(jshintrcPath, 'utf8'));
}
catch (error) {
console.warn(`Expected to find JSHint configuration ${jshintrcPath}. Using default JSHint configuration`);
return undefined;
}
} | [
"function",
"getJshintrc",
"(",
")",
"{",
"var",
"jshintrcPath",
"=",
"process",
".",
"cwd",
"(",
")",
"+",
"'/.jshintrc'",
";",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"jshintrcPath",
",",
"'utf8'",
")",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"console",
".",
"warn",
"(",
"`",
"${",
"jshintrcPath",
"}",
"`",
")",
";",
"return",
"undefined",
";",
"}",
"}"
]
| Gets the object representation of the configuration in .jshintrc in the
project root. | [
"Gets",
"the",
"object",
"representation",
"of",
"the",
"configuration",
"in",
".",
"jshintrc",
"in",
"the",
"project",
"root",
"."
]
| 0061f3942c99623f7ba48c521126141ae29bdba1 | https://github.com/jtheriault/code-copter-analyzer-jshint/blob/0061f3942c99623f7ba48c521126141ae29bdba1/src/index.js#L47-L57 | train |
Itee/i-return | sources/i-return.js | returnData | function returnData (data, response) {
if (typeof (response) === 'function') {
return response(null, data)
}
if (!response.headersSent) {
return response.status(200).end(JSON.stringify(data))
}
} | javascript | function returnData (data, response) {
if (typeof (response) === 'function') {
return response(null, data)
}
if (!response.headersSent) {
return response.status(200).end(JSON.stringify(data))
}
} | [
"function",
"returnData",
"(",
"data",
",",
"response",
")",
"{",
"if",
"(",
"typeof",
"(",
"response",
")",
"===",
"'function'",
")",
"{",
"return",
"response",
"(",
"null",
",",
"data",
")",
"}",
"if",
"(",
"!",
"response",
".",
"headersSent",
")",
"{",
"return",
"response",
".",
"status",
"(",
"200",
")",
".",
"end",
"(",
"JSON",
".",
"stringify",
"(",
"data",
")",
")",
"}",
"}"
]
| In case database call return some data.
If response parameter is a function consider this is a returnData callback function to call,
else check if server response headers aren't send yet, and return response with status 200 and
stringified data as content
@param data - The server/database data
@param response - The server response or returnData callback
@returns {*} callback call or response with status 200 and associated data | [
"In",
"case",
"database",
"call",
"return",
"some",
"data",
".",
"If",
"response",
"parameter",
"is",
"a",
"function",
"consider",
"this",
"is",
"a",
"returnData",
"callback",
"function",
"to",
"call",
"else",
"check",
"if",
"server",
"response",
"headers",
"aren",
"t",
"send",
"yet",
"and",
"return",
"response",
"with",
"status",
"200",
"and",
"stringified",
"data",
"as",
"content"
]
| 895953cb344e0929883863808429a3b8fa61d678 | https://github.com/Itee/i-return/blob/895953cb344e0929883863808429a3b8fa61d678/sources/i-return.js#L205-L213 | train |
Itee/i-return | sources/i-return.js | dispatchResult | function dispatchResult (error, data) {
if (_cb.beforeAll) { _cb.beforeAll() }
if (_cb.returnForAll) {
_cb.returnForAll(error, data)
} else if (!_isNullOrEmptyArray(error)) {
var _error = _normalizeError(error)
if (!_isNullOrEmptyArray(data)) {
processErrorAndData(_error, data)
} else {
processError(_error)
}
} else {
if (!_isNullOrEmptyArray(data)) {
processData(data)
} else {
processNotFound()
}
}
if (_cb.afterAll) { _cb.afterAll() }
} | javascript | function dispatchResult (error, data) {
if (_cb.beforeAll) { _cb.beforeAll() }
if (_cb.returnForAll) {
_cb.returnForAll(error, data)
} else if (!_isNullOrEmptyArray(error)) {
var _error = _normalizeError(error)
if (!_isNullOrEmptyArray(data)) {
processErrorAndData(_error, data)
} else {
processError(_error)
}
} else {
if (!_isNullOrEmptyArray(data)) {
processData(data)
} else {
processNotFound()
}
}
if (_cb.afterAll) { _cb.afterAll() }
} | [
"function",
"dispatchResult",
"(",
"error",
",",
"data",
")",
"{",
"if",
"(",
"_cb",
".",
"beforeAll",
")",
"{",
"_cb",
".",
"beforeAll",
"(",
")",
"}",
"if",
"(",
"_cb",
".",
"returnForAll",
")",
"{",
"_cb",
".",
"returnForAll",
"(",
"error",
",",
"data",
")",
"}",
"else",
"if",
"(",
"!",
"_isNullOrEmptyArray",
"(",
"error",
")",
")",
"{",
"var",
"_error",
"=",
"_normalizeError",
"(",
"error",
")",
"if",
"(",
"!",
"_isNullOrEmptyArray",
"(",
"data",
")",
")",
"{",
"processErrorAndData",
"(",
"_error",
",",
"data",
")",
"}",
"else",
"{",
"processError",
"(",
"_error",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"_isNullOrEmptyArray",
"(",
"data",
")",
")",
"{",
"processData",
"(",
"data",
")",
"}",
"else",
"{",
"processNotFound",
"(",
")",
"}",
"}",
"if",
"(",
"_cb",
".",
"afterAll",
")",
"{",
"_cb",
".",
"afterAll",
"(",
")",
"}",
"}"
]
| The callback that will be used for parse database response | [
"The",
"callback",
"that",
"will",
"be",
"used",
"for",
"parse",
"database",
"response"
]
| 895953cb344e0929883863808429a3b8fa61d678 | https://github.com/Itee/i-return/blob/895953cb344e0929883863808429a3b8fa61d678/sources/i-return.js#L352-L373 | train |
undeadway/mircore | demo/lib/util/md5.js | chars_to_bytes | function chars_to_bytes(ac) {
var retval = []
for (var i = 0; i < ac.length; i++) {
retval = retval.concat(str_to_bytes(ac[i]))
}
return retval
} | javascript | function chars_to_bytes(ac) {
var retval = []
for (var i = 0; i < ac.length; i++) {
retval = retval.concat(str_to_bytes(ac[i]))
}
return retval
} | [
"function",
"chars_to_bytes",
"(",
"ac",
")",
"{",
"var",
"retval",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ac",
".",
"length",
";",
"i",
"++",
")",
"{",
"retval",
"=",
"retval",
".",
"concat",
"(",
"str_to_bytes",
"(",
"ac",
"[",
"i",
"]",
")",
")",
"}",
"return",
"retval",
"}"
]
| convert array of chars to array of bytes | [
"convert",
"array",
"of",
"chars",
"to",
"array",
"of",
"bytes"
]
| c44d30f1e5f7f898f4ad7f24150de04a70df43be | https://github.com/undeadway/mircore/blob/c44d30f1e5f7f898f4ad7f24150de04a70df43be/demo/lib/util/md5.js#L69-L75 | train |
undeadway/mircore | demo/lib/util/md5.js | int64_to_bytes | function int64_to_bytes(num) {
var retval = []
for (var i = 0; i < 8; i++) {
retval.push(num & 0xFF)
num = num >>> 8
}
return retval
} | javascript | function int64_to_bytes(num) {
var retval = []
for (var i = 0; i < 8; i++) {
retval.push(num & 0xFF)
num = num >>> 8
}
return retval
} | [
"function",
"int64_to_bytes",
"(",
"num",
")",
"{",
"var",
"retval",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
")",
"{",
"retval",
".",
"push",
"(",
"num",
"&",
"0xFF",
")",
"num",
"=",
"num",
">>>",
"8",
"}",
"return",
"retval",
"}"
]
| convert a 64 bit unsigned number to array of bytes. Little endian | [
"convert",
"a",
"64",
"bit",
"unsigned",
"number",
"to",
"array",
"of",
"bytes",
".",
"Little",
"endian"
]
| c44d30f1e5f7f898f4ad7f24150de04a70df43be | https://github.com/undeadway/mircore/blob/c44d30f1e5f7f898f4ad7f24150de04a70df43be/demo/lib/util/md5.js#L79-L86 | train |
undeadway/mircore | demo/lib/util/md5.js | bytes_to_int32 | function bytes_to_int32(arr, off) {
return (arr[off + 3] << 24) | (arr[off + 2] << 16) | (arr[off + 1] << 8) | (arr[off])
} | javascript | function bytes_to_int32(arr, off) {
return (arr[off + 3] << 24) | (arr[off + 2] << 16) | (arr[off + 1] << 8) | (arr[off])
} | [
"function",
"bytes_to_int32",
"(",
"arr",
",",
"off",
")",
"{",
"return",
"(",
"arr",
"[",
"off",
"+",
"3",
"]",
"<<",
"24",
")",
"|",
"(",
"arr",
"[",
"off",
"+",
"2",
"]",
"<<",
"16",
")",
"|",
"(",
"arr",
"[",
"off",
"+",
"1",
"]",
"<<",
"8",
")",
"|",
"(",
"arr",
"[",
"off",
"]",
")",
"}"
]
| pick 4 bytes at specified offset. Little-endian is assumed | [
"pick",
"4",
"bytes",
"at",
"specified",
"offset",
".",
"Little",
"-",
"endian",
"is",
"assumed"
]
| c44d30f1e5f7f898f4ad7f24150de04a70df43be | https://github.com/undeadway/mircore/blob/c44d30f1e5f7f898f4ad7f24150de04a70df43be/demo/lib/util/md5.js#L111-L113 | train |
undeadway/mircore | demo/lib/util/md5.js | typed_to_plain | function typed_to_plain(tarr) {
var retval = new Array(tarr.length)
for (var i = 0; i < tarr.length; i++) {
retval[i] = tarr[i]
}
return retval
} | javascript | function typed_to_plain(tarr) {
var retval = new Array(tarr.length)
for (var i = 0; i < tarr.length; i++) {
retval[i] = tarr[i]
}
return retval
} | [
"function",
"typed_to_plain",
"(",
"tarr",
")",
"{",
"var",
"retval",
"=",
"new",
"Array",
"(",
"tarr",
".",
"length",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tarr",
".",
"length",
";",
"i",
"++",
")",
"{",
"retval",
"[",
"i",
"]",
"=",
"tarr",
"[",
"i",
"]",
"}",
"return",
"retval",
"}"
]
| conversion from typed byte array to plain javascript array | [
"conversion",
"from",
"typed",
"byte",
"array",
"to",
"plain",
"javascript",
"array"
]
| c44d30f1e5f7f898f4ad7f24150de04a70df43be | https://github.com/undeadway/mircore/blob/c44d30f1e5f7f898f4ad7f24150de04a70df43be/demo/lib/util/md5.js#L160-L166 | train |
undeadway/mircore | demo/lib/util/md5.js | updateRun | function updateRun(nf, sin32, dw32, b32) {
var temp = d
d = c
c = b
//b = b + rol(a + (nf + (sin32 + dw32)), b32)
b = _add(b,
rol(
_add(a,
_add(nf, _add(sin32, dw32))
), b32
)
)
a = temp
} | javascript | function updateRun(nf, sin32, dw32, b32) {
var temp = d
d = c
c = b
//b = b + rol(a + (nf + (sin32 + dw32)), b32)
b = _add(b,
rol(
_add(a,
_add(nf, _add(sin32, dw32))
), b32
)
)
a = temp
} | [
"function",
"updateRun",
"(",
"nf",
",",
"sin32",
",",
"dw32",
",",
"b32",
")",
"{",
"var",
"temp",
"=",
"d",
"d",
"=",
"c",
"c",
"=",
"b",
"b",
"=",
"_add",
"(",
"b",
",",
"rol",
"(",
"_add",
"(",
"a",
",",
"_add",
"(",
"nf",
",",
"_add",
"(",
"sin32",
",",
"dw32",
")",
")",
")",
",",
"b32",
")",
")",
"a",
"=",
"temp",
"}"
]
| function update partial state for each run | [
"function",
"update",
"partial",
"state",
"for",
"each",
"run"
]
| c44d30f1e5f7f898f4ad7f24150de04a70df43be | https://github.com/undeadway/mircore/blob/c44d30f1e5f7f898f4ad7f24150de04a70df43be/demo/lib/util/md5.js#L217-L230 | train |
msikma/grunt-usage | tasks/usage.js | getUsageOptions | function getUsageOptions() {
var configData = this.config.data;
if (configData.usage && configData.usage.options) {
return configData.usage.options;
}
return {};
} | javascript | function getUsageOptions() {
var configData = this.config.data;
if (configData.usage && configData.usage.options) {
return configData.usage.options;
}
return {};
} | [
"function",
"getUsageOptions",
"(",
")",
"{",
"var",
"configData",
"=",
"this",
".",
"config",
".",
"data",
";",
"if",
"(",
"configData",
".",
"usage",
"&&",
"configData",
".",
"usage",
".",
"options",
")",
"{",
"return",
"configData",
".",
"usage",
".",
"options",
";",
"}",
"return",
"{",
"}",
";",
"}"
]
| Returns the options object for grunt-usage.
Helper function in order to avoid a fatal error when the options
object has not been defined yet.
@returns {Object} The usage options object | [
"Returns",
"the",
"options",
"object",
"for",
"grunt",
"-",
"usage",
"."
]
| 395e194d446e25a4a24f3bb7d2f77c56e87619df | https://github.com/msikma/grunt-usage/blob/395e194d446e25a4a24f3bb7d2f77c56e87619df/tasks/usage.js#L15-L21 | train |
msikma/grunt-usage | tasks/usage.js | formatDescription | function formatDescription(str, formattingOptions) {
var end = '.', endRe = new RegExp('[\\.\\!\\?]{1}[\\)\\]"\']*?$');
// Apply a fallback in case we're trying to format a null or undefined.
if (!str) {
str = 'N/A';
}
// Add a period in case no valid end-of-sentence marker is found.
if (formattingOptions.addPeriod) {
if (endRe.test(str) === false) {
str = str + end;
}
}
return str;
} | javascript | function formatDescription(str, formattingOptions) {
var end = '.', endRe = new RegExp('[\\.\\!\\?]{1}[\\)\\]"\']*?$');
// Apply a fallback in case we're trying to format a null or undefined.
if (!str) {
str = 'N/A';
}
// Add a period in case no valid end-of-sentence marker is found.
if (formattingOptions.addPeriod) {
if (endRe.test(str) === false) {
str = str + end;
}
}
return str;
} | [
"function",
"formatDescription",
"(",
"str",
",",
"formattingOptions",
")",
"{",
"var",
"end",
"=",
"'.'",
",",
"endRe",
"=",
"new",
"RegExp",
"(",
"'[\\\\.\\\\!\\\\?]{1}[\\\\)\\\\]\"\\']*?$'",
")",
";",
"\\\\",
"\\\\",
"\\\\",
"}"
]
| Returns a formatted version of a description string. Chiefly, it
ensures that each line ends with a valid end-of-sentence marker,
mostly a period.
@param {String} str The description string to format and return
@param {Object} formattingOptions Formatting options object
@returns {String} The formatted string | [
"Returns",
"a",
"formatted",
"version",
"of",
"a",
"description",
"string",
".",
"Chiefly",
"it",
"ensures",
"that",
"each",
"line",
"ends",
"with",
"a",
"valid",
"end",
"-",
"of",
"-",
"sentence",
"marker",
"mostly",
"a",
"period",
"."
]
| 395e194d446e25a4a24f3bb7d2f77c56e87619df | https://github.com/msikma/grunt-usage/blob/395e194d446e25a4a24f3bb7d2f77c56e87619df/tasks/usage.js#L46-L62 | train |
msikma/grunt-usage | tasks/usage.js | formatUsageHeader | function formatUsageHeader(headerContent) {
var headerString = headerContent instanceof Array ?
headerContent.join(EOL) :
headerContent;
return headerString + EOL;
} | javascript | function formatUsageHeader(headerContent) {
var headerString = headerContent instanceof Array ?
headerContent.join(EOL) :
headerContent;
return headerString + EOL;
} | [
"function",
"formatUsageHeader",
"(",
"headerContent",
")",
"{",
"var",
"headerString",
"=",
"headerContent",
"instanceof",
"Array",
"?",
"headerContent",
".",
"join",
"(",
"EOL",
")",
":",
"headerContent",
";",
"return",
"headerString",
"+",
"EOL",
";",
"}"
]
| Formats and returns the user's header string or array.
@param {Array|String} headerContent The usage header option string or array
@returns {String} The formatted usage header string | [
"Formats",
"and",
"returns",
"the",
"user",
"s",
"header",
"string",
"or",
"array",
"."
]
| 395e194d446e25a4a24f3bb7d2f77c56e87619df | https://github.com/msikma/grunt-usage/blob/395e194d446e25a4a24f3bb7d2f77c56e87619df/tasks/usage.js#L83-L89 | train |
msikma/grunt-usage | tasks/usage.js | formatUsage | function formatUsage(grunt, usageHeader, usageHelp) {
var usageString = '',
reUsage = [new RegExp('\\[-(.+?)\\]', 'g'), '[$1]'],
reTasks = [new RegExp('^[ ]{2}-([^\\s]*)', 'mg'), ' $1 '];
usageString += usageHeader;
usageHelp = usageHelp.replace(reUsage[0], reUsage[1]);
usageHelp = usageHelp.replace(reTasks[0], reTasks[1]);
usageString += usageHelp;
// One final pass to ensure linebreak normalization.
return grunt.util.normalizelf(usageString);
} | javascript | function formatUsage(grunt, usageHeader, usageHelp) {
var usageString = '',
reUsage = [new RegExp('\\[-(.+?)\\]', 'g'), '[$1]'],
reTasks = [new RegExp('^[ ]{2}-([^\\s]*)', 'mg'), ' $1 '];
usageString += usageHeader;
usageHelp = usageHelp.replace(reUsage[0], reUsage[1]);
usageHelp = usageHelp.replace(reTasks[0], reTasks[1]);
usageString += usageHelp;
// One final pass to ensure linebreak normalization.
return grunt.util.normalizelf(usageString);
} | [
"function",
"formatUsage",
"(",
"grunt",
",",
"usageHeader",
",",
"usageHelp",
")",
"{",
"var",
"usageString",
"=",
"''",
",",
"reUsage",
"=",
"[",
"new",
"RegExp",
"(",
"'\\\\[-(.+?)\\\\]'",
",",
"\\\\",
")",
",",
"\\\\",
"]",
",",
"'g'",
";",
"'[$1]'",
"reTasks",
"=",
"[",
"new",
"RegExp",
"(",
"'^[ ]{2}-([^\\\\s]*)'",
",",
"\\\\",
")",
",",
"'mg'",
"]",
"' $1 '",
"usageString",
"+=",
"usageHeader",
";",
"usageHelp",
"=",
"usageHelp",
".",
"replace",
"(",
"reUsage",
"[",
"0",
"]",
",",
"reUsage",
"[",
"1",
"]",
")",
";",
"}"
]
| Performs a final processing run on the usage string and then returns it.
The most major modification we do is removing the dash at the start of
the Grunt task names. This is a hack to work around the fact that
argparse won't show a valid usage string at the top of the help dialog
unless we use optional arguments.
Optional arguments are always indicated with one or more preceding dashes,
so we add them to get argparse to do what we want, and then remove them
just before output. They can be safely filtered out.
@param {Object} grunt The Grunt object
@param {String} usageHeader The formatted usage header string
@param {String} usageHelp The output from Node argparse
@returns {String} The processed string | [
"Performs",
"a",
"final",
"processing",
"run",
"on",
"the",
"usage",
"string",
"and",
"then",
"returns",
"it",
"."
]
| 395e194d446e25a4a24f3bb7d2f77c56e87619df | https://github.com/msikma/grunt-usage/blob/395e194d446e25a4a24f3bb7d2f77c56e87619df/tasks/usage.js#L108-L122 | train |
msikma/grunt-usage | tasks/usage.js | addTaskGroup | function addTaskGroup(taskGroup, grunt, parser, descriptionOverrides,
formattingOptions) {
var parserGruntTasks;
var taskName, taskInfo;
var n;
// Create the parser for this group.
parserGruntTasks = parser.addArgumentGroup({
title: taskGroup.header ? taskGroup.header : 'Grunt tasks',
required: false
});
// Iterate through all tasks that we want to see in the output.
for (n = 0; n < taskGroup.tasks.length; ++n) {
taskName = taskGroup.tasks[n];
taskInfo = grunt.task._tasks[taskName];
// Add a task to the argument parser using either the user's
// description override or its package.json description.
parserGruntTasks.addArgument(['-' + taskName], {
'nargs': 0,
'required': false,
'help': formatDescription(
descriptionOverrides[taskName] ?
descriptionOverrides[taskName] :
taskInfo.info,
formattingOptions
)
}
);
}
} | javascript | function addTaskGroup(taskGroup, grunt, parser, descriptionOverrides,
formattingOptions) {
var parserGruntTasks;
var taskName, taskInfo;
var n;
// Create the parser for this group.
parserGruntTasks = parser.addArgumentGroup({
title: taskGroup.header ? taskGroup.header : 'Grunt tasks',
required: false
});
// Iterate through all tasks that we want to see in the output.
for (n = 0; n < taskGroup.tasks.length; ++n) {
taskName = taskGroup.tasks[n];
taskInfo = grunt.task._tasks[taskName];
// Add a task to the argument parser using either the user's
// description override or its package.json description.
parserGruntTasks.addArgument(['-' + taskName], {
'nargs': 0,
'required': false,
'help': formatDescription(
descriptionOverrides[taskName] ?
descriptionOverrides[taskName] :
taskInfo.info,
formattingOptions
)
}
);
}
} | [
"function",
"addTaskGroup",
"(",
"taskGroup",
",",
"grunt",
",",
"parser",
",",
"descriptionOverrides",
",",
"formattingOptions",
")",
"{",
"var",
"parserGruntTasks",
";",
"var",
"taskName",
",",
"taskInfo",
";",
"var",
"n",
";",
"parserGruntTasks",
"=",
"parser",
".",
"addArgumentGroup",
"(",
"{",
"title",
":",
"taskGroup",
".",
"header",
"?",
"taskGroup",
".",
"header",
":",
"'Grunt tasks'",
",",
"required",
":",
"false",
"}",
")",
";",
"for",
"(",
"n",
"=",
"0",
";",
"n",
"<",
"taskGroup",
".",
"tasks",
".",
"length",
";",
"++",
"n",
")",
"{",
"taskName",
"=",
"taskGroup",
".",
"tasks",
"[",
"n",
"]",
";",
"taskInfo",
"=",
"grunt",
".",
"task",
".",
"_tasks",
"[",
"taskName",
"]",
";",
"parserGruntTasks",
".",
"addArgument",
"(",
"[",
"'-'",
"+",
"taskName",
"]",
",",
"{",
"'nargs'",
":",
"0",
",",
"'required'",
":",
"false",
",",
"'help'",
":",
"formatDescription",
"(",
"descriptionOverrides",
"[",
"taskName",
"]",
"?",
"descriptionOverrides",
"[",
"taskName",
"]",
":",
"taskInfo",
".",
"info",
",",
"formattingOptions",
")",
"}",
")",
";",
"}",
"}"
]
| Adds a task group to the parser.
@param {Object} taskGroup The task group object
@param {Object} grunt The global Grunt object
@param {ArgumentParser} parser The global ArgumentParser object
@param {Object} descriptionOverrides Task description overrides
@param {Object} formattingOptions Options that determine the formatting | [
"Adds",
"a",
"task",
"group",
"to",
"the",
"parser",
"."
]
| 395e194d446e25a4a24f3bb7d2f77c56e87619df | https://github.com/msikma/grunt-usage/blob/395e194d446e25a4a24f3bb7d2f77c56e87619df/tasks/usage.js#L140-L171 | train |
brycebaril/level-bufferstreams | read.js | createReader | function createReader(db, options) {
if (options == null) options = {}
var iterator = db.iterator(options)
function _read(n) {
// ignore n for now
var self = this
iterator.next(function (err, key, value) {
if (err) {
iterator.end(noop)
self.emit("error", err)
return
}
if (key == null && value == null) {
iterator.end(noop)
self.push(null)
return
}
var record = multibuffer.pack([key, value])
self.push(record)
})
}
return spigot(_read)
} | javascript | function createReader(db, options) {
if (options == null) options = {}
var iterator = db.iterator(options)
function _read(n) {
// ignore n for now
var self = this
iterator.next(function (err, key, value) {
if (err) {
iterator.end(noop)
self.emit("error", err)
return
}
if (key == null && value == null) {
iterator.end(noop)
self.push(null)
return
}
var record = multibuffer.pack([key, value])
self.push(record)
})
}
return spigot(_read)
} | [
"function",
"createReader",
"(",
"db",
",",
"options",
")",
"{",
"if",
"(",
"options",
"==",
"null",
")",
"options",
"=",
"{",
"}",
"var",
"iterator",
"=",
"db",
".",
"iterator",
"(",
"options",
")",
"function",
"_read",
"(",
"n",
")",
"{",
"var",
"self",
"=",
"this",
"iterator",
".",
"next",
"(",
"function",
"(",
"err",
",",
"key",
",",
"value",
")",
"{",
"if",
"(",
"err",
")",
"{",
"iterator",
".",
"end",
"(",
"noop",
")",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
"return",
"}",
"if",
"(",
"key",
"==",
"null",
"&&",
"value",
"==",
"null",
")",
"{",
"iterator",
".",
"end",
"(",
"noop",
")",
"self",
".",
"push",
"(",
"null",
")",
"return",
"}",
"var",
"record",
"=",
"multibuffer",
".",
"pack",
"(",
"[",
"key",
",",
"value",
"]",
")",
"self",
".",
"push",
"(",
"record",
")",
"}",
")",
"}",
"return",
"spigot",
"(",
"_read",
")",
"}"
]
| Create a stream instance that streams data out of a level instance as multibuffers
@param {LevelDOWN} db A LevelDOWN instance
@param {Object} options Read range options (start, end, reverse, limit) | [
"Create",
"a",
"stream",
"instance",
"that",
"streams",
"data",
"out",
"of",
"a",
"level",
"instance",
"as",
"multibuffers"
]
| b78bfddfe1f4cb1a962803d5cc1bba26e277efb9 | https://github.com/brycebaril/level-bufferstreams/blob/b78bfddfe1f4cb1a962803d5cc1bba26e277efb9/read.js#L12-L39 | train |
rwaldron/t2-project | lib/index.js | buildResolverOptions | function buildResolverOptions(options, base) {
var pathFilter = options.pathFilter;
options.basedir = base;
options.pathFilter = function(info, resvPath, relativePath) {
if (relativePath[0] !== '.') {
relativePath = './' + relativePath;
}
var mappedPath;
if (pathFilter) {
mappedPath = pathFilter.apply(this, [info, resvPath, path.normalize(relativePath)]);
}
if (mappedPath) {
return mappedPath;
}
return;
};
return options;
} | javascript | function buildResolverOptions(options, base) {
var pathFilter = options.pathFilter;
options.basedir = base;
options.pathFilter = function(info, resvPath, relativePath) {
if (relativePath[0] !== '.') {
relativePath = './' + relativePath;
}
var mappedPath;
if (pathFilter) {
mappedPath = pathFilter.apply(this, [info, resvPath, path.normalize(relativePath)]);
}
if (mappedPath) {
return mappedPath;
}
return;
};
return options;
} | [
"function",
"buildResolverOptions",
"(",
"options",
",",
"base",
")",
"{",
"var",
"pathFilter",
"=",
"options",
".",
"pathFilter",
";",
"options",
".",
"basedir",
"=",
"base",
";",
"options",
".",
"pathFilter",
"=",
"function",
"(",
"info",
",",
"resvPath",
",",
"relativePath",
")",
"{",
"if",
"(",
"relativePath",
"[",
"0",
"]",
"!==",
"'.'",
")",
"{",
"relativePath",
"=",
"'./'",
"+",
"relativePath",
";",
"}",
"var",
"mappedPath",
";",
"if",
"(",
"pathFilter",
")",
"{",
"mappedPath",
"=",
"pathFilter",
".",
"apply",
"(",
"this",
",",
"[",
"info",
",",
"resvPath",
",",
"path",
".",
"normalize",
"(",
"relativePath",
")",
"]",
")",
";",
"}",
"if",
"(",
"mappedPath",
")",
"{",
"return",
"mappedPath",
";",
"}",
"return",
";",
"}",
";",
"return",
"options",
";",
"}"
]
| Loosely based on an operation found in browser-resolve | [
"Loosely",
"based",
"on",
"an",
"operation",
"found",
"in",
"browser",
"-",
"resolve"
]
| 4c7a8def29b9d0507c1fafb039d25500750b7787 | https://github.com/rwaldron/t2-project/blob/4c7a8def29b9d0507c1fafb039d25500750b7787/lib/index.js#L84-L102 | train |
pauldijou/open-issue | examples/node_error.js | parseError | function parseError(error) {
// If this file is at the root of your project
var pathRegexp = new RegExp(__dirname, 'g');
var display = '';
if (error.code) { display += 'Error code: ' + error.code + '\n\n' };
if (error.stack) { display += error.stack.replace(pathRegexp, ''); }
if (!display) { display = error.toString(); }
return display;
} | javascript | function parseError(error) {
// If this file is at the root of your project
var pathRegexp = new RegExp(__dirname, 'g');
var display = '';
if (error.code) { display += 'Error code: ' + error.code + '\n\n' };
if (error.stack) { display += error.stack.replace(pathRegexp, ''); }
if (!display) { display = error.toString(); }
return display;
} | [
"function",
"parseError",
"(",
"error",
")",
"{",
"var",
"pathRegexp",
"=",
"new",
"RegExp",
"(",
"__dirname",
",",
"'g'",
")",
";",
"var",
"display",
"=",
"''",
";",
"if",
"(",
"error",
".",
"code",
")",
"{",
"display",
"+=",
"'Error code: '",
"+",
"error",
".",
"code",
"+",
"'\\n\\n'",
"}",
"\\n",
"\\n",
";",
"if",
"(",
"error",
".",
"stack",
")",
"{",
"display",
"+=",
"error",
".",
"stack",
".",
"replace",
"(",
"pathRegexp",
",",
"''",
")",
";",
"}",
"}"
]
| Extract stack and hide user paths | [
"Extract",
"stack",
"and",
"hide",
"user",
"paths"
]
| 1044e8c27d996683ffc6684d7cb5c44ef3d1c935 | https://github.com/pauldijou/open-issue/blob/1044e8c27d996683ffc6684d7cb5c44ef3d1c935/examples/node_error.js#L2-L10 | train |
pauldijou/open-issue | examples/node_error.js | openIssue | function openIssue(e) {
require('../lib/node.js')
.github('pauldijou/open-issue')
.title('Unexpected error')
.labels('bug', 'fatal')
.append('The following error occured:')
.appendCode(parseError(e))
.append('You can also add custom infos if necessary...')
.open();
} | javascript | function openIssue(e) {
require('../lib/node.js')
.github('pauldijou/open-issue')
.title('Unexpected error')
.labels('bug', 'fatal')
.append('The following error occured:')
.appendCode(parseError(e))
.append('You can also add custom infos if necessary...')
.open();
} | [
"function",
"openIssue",
"(",
"e",
")",
"{",
"require",
"(",
"'../lib/node.js'",
")",
".",
"github",
"(",
"'pauldijou/open-issue'",
")",
".",
"title",
"(",
"'Unexpected error'",
")",
".",
"labels",
"(",
"'bug'",
",",
"'fatal'",
")",
".",
"append",
"(",
"'The following error occured:'",
")",
".",
"appendCode",
"(",
"parseError",
"(",
"e",
")",
")",
".",
"append",
"(",
"'You can also add custom infos if necessary...'",
")",
".",
"open",
"(",
")",
";",
"}"
]
| Open the issue if user is ok | [
"Open",
"the",
"issue",
"if",
"user",
"is",
"ok"
]
| 1044e8c27d996683ffc6684d7cb5c44ef3d1c935 | https://github.com/pauldijou/open-issue/blob/1044e8c27d996683ffc6684d7cb5c44ef3d1c935/examples/node_error.js#L13-L22 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/div/dialogs/div.js | addSafely | function addSafely( collection, element, database ) {
// 1. IE doesn't support customData on text nodes;
// 2. Text nodes never get chance to appear twice;
if ( !element.is || !element.getCustomData( 'block_processed' ) ) {
element.is && CKEDITOR.dom.element.setMarker( database, element, 'block_processed', true );
collection.push( element );
}
} | javascript | function addSafely( collection, element, database ) {
// 1. IE doesn't support customData on text nodes;
// 2. Text nodes never get chance to appear twice;
if ( !element.is || !element.getCustomData( 'block_processed' ) ) {
element.is && CKEDITOR.dom.element.setMarker( database, element, 'block_processed', true );
collection.push( element );
}
} | [
"function",
"addSafely",
"(",
"collection",
",",
"element",
",",
"database",
")",
"{",
"if",
"(",
"!",
"element",
".",
"is",
"||",
"!",
"element",
".",
"getCustomData",
"(",
"'block_processed'",
")",
")",
"{",
"element",
".",
"is",
"&&",
"CKEDITOR",
".",
"dom",
".",
"element",
".",
"setMarker",
"(",
"database",
",",
"element",
",",
"'block_processed'",
",",
"true",
")",
";",
"collection",
".",
"push",
"(",
"element",
")",
";",
"}",
"}"
]
| Add to collection with DUP examination. @param {Object} collection @param {Object} element @param {Object} database | [
"Add",
"to",
"collection",
"with",
"DUP",
"examination",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/div/dialogs/div.js#L12-L19 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/plugins/div/dialogs/div.js | getDivContainer | function getDivContainer( element ) {
var container = editor.elementPath( element ).blockLimit;
// Never consider read-only (i.e. contenteditable=false) element as
// a first div limit (#11083).
if ( container.isReadOnly() )
container = container.getParent();
// Dont stop at 'td' and 'th' when div should wrap entire table.
if ( editor.config.div_wrapTable && container.is( [ 'td', 'th' ] ) ) {
var parentPath = editor.elementPath( container.getParent() );
container = parentPath.blockLimit;
}
return container;
} | javascript | function getDivContainer( element ) {
var container = editor.elementPath( element ).blockLimit;
// Never consider read-only (i.e. contenteditable=false) element as
// a first div limit (#11083).
if ( container.isReadOnly() )
container = container.getParent();
// Dont stop at 'td' and 'th' when div should wrap entire table.
if ( editor.config.div_wrapTable && container.is( [ 'td', 'th' ] ) ) {
var parentPath = editor.elementPath( container.getParent() );
container = parentPath.blockLimit;
}
return container;
} | [
"function",
"getDivContainer",
"(",
"element",
")",
"{",
"var",
"container",
"=",
"editor",
".",
"elementPath",
"(",
"element",
")",
".",
"blockLimit",
";",
"if",
"(",
"container",
".",
"isReadOnly",
"(",
")",
")",
"container",
"=",
"container",
".",
"getParent",
"(",
")",
";",
"if",
"(",
"editor",
".",
"config",
".",
"div_wrapTable",
"&&",
"container",
".",
"is",
"(",
"[",
"'td'",
",",
"'th'",
"]",
")",
")",
"{",
"var",
"parentPath",
"=",
"editor",
".",
"elementPath",
"(",
"container",
".",
"getParent",
"(",
")",
")",
";",
"container",
"=",
"parentPath",
".",
"blockLimit",
";",
"}",
"return",
"container",
";",
"}"
]
| Get the first div limit element on the element's path. @param {Object} element | [
"Get",
"the",
"first",
"div",
"limit",
"element",
"on",
"the",
"element",
"s",
"path",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/div/dialogs/div.js#L54-L69 | train |
buybrain/storymock | lib/storymock.js | reject | function reject(err, async) {
err = toErr(err);
if (async) {
return Promise.reject(err);
} else {
throw err;
}
} | javascript | function reject(err, async) {
err = toErr(err);
if (async) {
return Promise.reject(err);
} else {
throw err;
}
} | [
"function",
"reject",
"(",
"err",
",",
"async",
")",
"{",
"err",
"=",
"toErr",
"(",
"err",
")",
";",
"if",
"(",
"async",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"throw",
"err",
";",
"}",
"}"
]
| Reject with the given error. Returns a rejected promise if async, throws otherwise. | [
"Reject",
"with",
"the",
"given",
"error",
".",
"Returns",
"a",
"rejected",
"promise",
"if",
"async",
"throws",
"otherwise",
"."
]
| 1292be256377b51c9bffc0b3b4fa4c71f9498464 | https://github.com/buybrain/storymock/blob/1292be256377b51c9bffc0b3b4fa4c71f9498464/lib/storymock.js#L190-L197 | train |
willmark/file-sync | index.js | copyFiles | function copyFiles(srcfile, dstfile, callback) {
var fs = require("fs");
var rs = fs.createReadStream(srcfile);
var ws = fs.createWriteStream(dstfile);
rs.on("data", function(d) {
ws.write(d);
});
rs.on("end", function() {
ws.end();
callback(true);
});
} | javascript | function copyFiles(srcfile, dstfile, callback) {
var fs = require("fs");
var rs = fs.createReadStream(srcfile);
var ws = fs.createWriteStream(dstfile);
rs.on("data", function(d) {
ws.write(d);
});
rs.on("end", function() {
ws.end();
callback(true);
});
} | [
"function",
"copyFiles",
"(",
"srcfile",
",",
"dstfile",
",",
"callback",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"\"fs\"",
")",
";",
"var",
"rs",
"=",
"fs",
".",
"createReadStream",
"(",
"srcfile",
")",
";",
"var",
"ws",
"=",
"fs",
".",
"createWriteStream",
"(",
"dstfile",
")",
";",
"rs",
".",
"on",
"(",
"\"data\"",
",",
"function",
"(",
"d",
")",
"{",
"ws",
".",
"write",
"(",
"d",
")",
";",
"}",
")",
";",
"rs",
".",
"on",
"(",
"\"end\"",
",",
"function",
"(",
")",
"{",
"ws",
".",
"end",
"(",
")",
";",
"callback",
"(",
"true",
")",
";",
"}",
")",
";",
"}"
]
| Copy file1 to file2 | [
"Copy",
"file1",
"to",
"file2"
]
| 499bd8b1c88edb5d122dc85731d7a3fa330f42ec | https://github.com/willmark/file-sync/blob/499bd8b1c88edb5d122dc85731d7a3fa330f42ec/index.js#L50-L61 | train |
VasoBolkvadze/noderaven | index.js | function (db, index, term, field, cb) {
var url = host +
'databases/' + db +
'/suggest/' + index +
'?term=' + encodeURIComponent(term) +
'&field=' + field +
'&max=10&distance=Default&accuracy=0.5';
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
cb(null, result);
}
else {
cb(error || new Error(response.statusCode), null);
}
});
} | javascript | function (db, index, term, field, cb) {
var url = host +
'databases/' + db +
'/suggest/' + index +
'?term=' + encodeURIComponent(term) +
'&field=' + field +
'&max=10&distance=Default&accuracy=0.5';
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
cb(null, result);
}
else {
cb(error || new Error(response.statusCode), null);
}
});
} | [
"function",
"(",
"db",
",",
"index",
",",
"term",
",",
"field",
",",
"cb",
")",
"{",
"var",
"url",
"=",
"host",
"+",
"'databases/'",
"+",
"db",
"+",
"'/suggest/'",
"+",
"index",
"+",
"'?term='",
"+",
"encodeURIComponent",
"(",
"term",
")",
"+",
"'&field='",
"+",
"field",
"+",
"'&max=10&distance=Default&accuracy=0.5'",
";",
"request",
"(",
"url",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"cb",
"(",
"null",
",",
"result",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"error",
"||",
"new",
"Error",
"(",
"response",
".",
"statusCode",
")",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Returns Suggestions for given query and fieldName.
@param {string} db
@param {string} index
@param {string} term
@param {string} field
@param {Function} cb | [
"Returns",
"Suggestions",
"for",
"given",
"query",
"and",
"fieldName",
"."
]
| 62353a62f634be90f7aa4c36f19574ecd720b463 | https://github.com/VasoBolkvadze/noderaven/blob/62353a62f634be90f7aa4c36f19574ecd720b463/index.js#L151-L167 | train |
|
VasoBolkvadze/noderaven | index.js | function (db, indexName, facetDoc, query, cb) {
var url = host + "databases/" + db + "/facets/" + indexName + "?facetDoc=" + facetDoc + "&query=" + encodeURIComponent(query);
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
_.each(result.Results, function (v, k) {
if (_.filter(v.Values, function (x) {
return x.Hits > 0;
}).length < 2) {
delete result.Results[k];
return;
}
v.Values = _.chain(v.Values)
.map(function (x) {
var val = JSON.stringify(x.Range)
.replace(/^\"|\"$/gi, "")
.replace(/\:/gi, "\\:")
.replace(/\(/gi, "\\(")
.replace(/\)/gi, "\\)");
if (x.Range.indexOf(" TO ") <= 0 || x.Range.indexOf("[") !== 0) {
val = val.replace(/\ /gi, "\\ ");
}
val = encodeURIComponent(val);
x.q = k + ":" + val;
x.Range = x.Range
.replace(/^\[Dx/, "")
.replace(/ Dx/, " ")
.replace(/\]$/, "")
.replace(/ TO /, "-");
return x;
}).filter(function (x) {
return x.Hits > 0;
}).sortBy(function (x) {
return x.Range;
}).value();
});
cb(null, result.Results);
} else
cb(error || new Error(response.statusCode), null);
});
} | javascript | function (db, indexName, facetDoc, query, cb) {
var url = host + "databases/" + db + "/facets/" + indexName + "?facetDoc=" + facetDoc + "&query=" + encodeURIComponent(query);
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
_.each(result.Results, function (v, k) {
if (_.filter(v.Values, function (x) {
return x.Hits > 0;
}).length < 2) {
delete result.Results[k];
return;
}
v.Values = _.chain(v.Values)
.map(function (x) {
var val = JSON.stringify(x.Range)
.replace(/^\"|\"$/gi, "")
.replace(/\:/gi, "\\:")
.replace(/\(/gi, "\\(")
.replace(/\)/gi, "\\)");
if (x.Range.indexOf(" TO ") <= 0 || x.Range.indexOf("[") !== 0) {
val = val.replace(/\ /gi, "\\ ");
}
val = encodeURIComponent(val);
x.q = k + ":" + val;
x.Range = x.Range
.replace(/^\[Dx/, "")
.replace(/ Dx/, " ")
.replace(/\]$/, "")
.replace(/ TO /, "-");
return x;
}).filter(function (x) {
return x.Hits > 0;
}).sortBy(function (x) {
return x.Range;
}).value();
});
cb(null, result.Results);
} else
cb(error || new Error(response.statusCode), null);
});
} | [
"function",
"(",
"db",
",",
"indexName",
",",
"facetDoc",
",",
"query",
",",
"cb",
")",
"{",
"var",
"url",
"=",
"host",
"+",
"\"databases/\"",
"+",
"db",
"+",
"\"/facets/\"",
"+",
"indexName",
"+",
"\"?facetDoc=\"",
"+",
"facetDoc",
"+",
"\"&query=\"",
"+",
"encodeURIComponent",
"(",
"query",
")",
";",
"request",
"(",
"url",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"_",
".",
"each",
"(",
"result",
".",
"Results",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"if",
"(",
"_",
".",
"filter",
"(",
"v",
".",
"Values",
",",
"function",
"(",
"x",
")",
"{",
"return",
"x",
".",
"Hits",
">",
"0",
";",
"}",
")",
".",
"length",
"<",
"2",
")",
"{",
"delete",
"result",
".",
"Results",
"[",
"k",
"]",
";",
"return",
";",
"}",
"v",
".",
"Values",
"=",
"_",
".",
"chain",
"(",
"v",
".",
"Values",
")",
".",
"map",
"(",
"function",
"(",
"x",
")",
"{",
"var",
"val",
"=",
"JSON",
".",
"stringify",
"(",
"x",
".",
"Range",
")",
".",
"replace",
"(",
"/",
"^\\\"|\\\"$",
"/",
"gi",
",",
"\"\"",
")",
".",
"replace",
"(",
"/",
"\\:",
"/",
"gi",
",",
"\"\\\\:\"",
")",
".",
"\\\\",
"replace",
".",
"(",
"/",
"\\(",
"/",
"gi",
",",
"\"\\\\(\"",
")",
"\\\\",
";",
"replace",
"(",
"/",
"\\)",
"/",
"gi",
",",
"\"\\\\)\"",
")",
"\\\\",
"if",
"(",
"x",
".",
"Range",
".",
"indexOf",
"(",
"\" TO \"",
")",
"<=",
"0",
"||",
"x",
".",
"Range",
".",
"indexOf",
"(",
"\"[\"",
")",
"!==",
"0",
")",
"{",
"val",
"=",
"val",
".",
"replace",
"(",
"/",
"\\ ",
"/",
"gi",
",",
"\"\\\\ \"",
")",
";",
"}",
"\\\\",
"}",
")",
".",
"val",
"=",
"encodeURIComponent",
"(",
"val",
")",
";",
"x",
".",
"q",
"=",
"k",
"+",
"\":\"",
"+",
"val",
";",
".",
"x",
".",
"Range",
"=",
"x",
".",
"Range",
".",
"replace",
"(",
"/",
"^\\[Dx",
"/",
",",
"\"\"",
")",
".",
"replace",
"(",
"/",
" Dx",
"/",
",",
"\" \"",
")",
".",
"replace",
"(",
"/",
"\\]$",
"/",
",",
"\"\"",
")",
".",
"replace",
"(",
"/",
" TO ",
"/",
",",
"\"-\"",
")",
";",
"return",
"x",
";",
".",
"filter",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"x",
".",
"Hits",
">",
"0",
";",
"}",
")",
";",
"}",
")",
";",
"sortBy",
"}",
"else",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"x",
".",
"Range",
";",
"}",
")",
"}",
")",
";",
"}"
]
| Returns Facet Results.
@param {string} db
@param {string} indexName
@param {string} facetDoc
@param {string} query
@param {Function} cb | [
"Returns",
"Facet",
"Results",
"."
]
| 62353a62f634be90f7aa4c36f19574ecd720b463 | https://github.com/VasoBolkvadze/noderaven/blob/62353a62f634be90f7aa4c36f19574ecd720b463/index.js#L175-L215 | train |
|
VasoBolkvadze/noderaven | index.js | function (db, indexName, whereClause, groupBy, fieldsToSum, cb) {
var url = host + 'databases/' + db + '/facets/' + indexName + '?';
url += whereClause ? '&query=' + encodeURIComponent(whereClause) : '';
url += '&facetStart=0&facetPageSize=1024';
var facets = fieldsToSum
.map(function (field) {
return {
"Mode": 0,
"Aggregation": 16,
"AggregationField": field,
"Name": groupBy,
"DisplayName": field,
"Ranges": [],
"MaxResults": null,
"TermSortMode": 0,
"IncludeRemainingTerms": false
};
});
url += '&facets=' + JSON.stringify(facets);
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | javascript | function (db, indexName, whereClause, groupBy, fieldsToSum, cb) {
var url = host + 'databases/' + db + '/facets/' + indexName + '?';
url += whereClause ? '&query=' + encodeURIComponent(whereClause) : '';
url += '&facetStart=0&facetPageSize=1024';
var facets = fieldsToSum
.map(function (field) {
return {
"Mode": 0,
"Aggregation": 16,
"AggregationField": field,
"Name": groupBy,
"DisplayName": field,
"Ranges": [],
"MaxResults": null,
"TermSortMode": 0,
"IncludeRemainingTerms": false
};
});
url += '&facets=' + JSON.stringify(facets);
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | [
"function",
"(",
"db",
",",
"indexName",
",",
"whereClause",
",",
"groupBy",
",",
"fieldsToSum",
",",
"cb",
")",
"{",
"var",
"url",
"=",
"host",
"+",
"'databases/'",
"+",
"db",
"+",
"'/facets/'",
"+",
"indexName",
"+",
"'?'",
";",
"url",
"+=",
"whereClause",
"?",
"'&query='",
"+",
"encodeURIComponent",
"(",
"whereClause",
")",
":",
"''",
";",
"url",
"+=",
"'&facetStart=0&facetPageSize=1024'",
";",
"var",
"facets",
"=",
"fieldsToSum",
".",
"map",
"(",
"function",
"(",
"field",
")",
"{",
"return",
"{",
"\"Mode\"",
":",
"0",
",",
"\"Aggregation\"",
":",
"16",
",",
"\"AggregationField\"",
":",
"field",
",",
"\"Name\"",
":",
"groupBy",
",",
"\"DisplayName\"",
":",
"field",
",",
"\"Ranges\"",
":",
"[",
"]",
",",
"\"MaxResults\"",
":",
"null",
",",
"\"TermSortMode\"",
":",
"0",
",",
"\"IncludeRemainingTerms\"",
":",
"false",
"}",
";",
"}",
")",
";",
"url",
"+=",
"'&facets='",
"+",
"JSON",
".",
"stringify",
"(",
"facets",
")",
";",
"request",
"(",
"url",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"cb",
"(",
"null",
",",
"result",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"error",
"||",
"new",
"Error",
"(",
"response",
".",
"statusCode",
")",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Generates and returns Dynamic Report.
@param {string} db
@param {string} indexName
@param {string} whereClause
@param {string} groupBy
@param {Array<string>} fieldsToSum
@param {Function} cb | [
"Generates",
"and",
"returns",
"Dynamic",
"Report",
"."
]
| 62353a62f634be90f7aa4c36f19574ecd720b463 | https://github.com/VasoBolkvadze/noderaven/blob/62353a62f634be90f7aa4c36f19574ecd720b463/index.js#L224-L251 | train |
|
VasoBolkvadze/noderaven | index.js | function (db, id, wantedPropsFromMetadata, cb) {
if(Object.prototype.toString.call(wantedPropsFromMetadata) == '[object Function]'){
cb = wantedPropsFromMetadata;
wantedPropsFromMetadata = [];
}
var url = host + 'databases/' + db + '/docs/' + id;
request(url, function (error, response, body) {
if(error || response.statusCode != 200)
return cb(error || new Error(response.statusCode));
var doc = JSON.parse(body);
var meta = _.reduce(response.headers
, function (memo, val, key) {
if (key.indexOf('raven') === 0 || wantedPropsFromMetadata.indexOf(key) != -1)
memo[key] = val;
return memo;
}, {});
meta['@id'] = response.headers['__document_id'];
meta.etag = response.headers['etag'];
meta.dateCreated = response.headers['DateCreated'] || response.headers['datecreated'];
doc['@metadata'] = meta;
cb(null, doc);
});
} | javascript | function (db, id, wantedPropsFromMetadata, cb) {
if(Object.prototype.toString.call(wantedPropsFromMetadata) == '[object Function]'){
cb = wantedPropsFromMetadata;
wantedPropsFromMetadata = [];
}
var url = host + 'databases/' + db + '/docs/' + id;
request(url, function (error, response, body) {
if(error || response.statusCode != 200)
return cb(error || new Error(response.statusCode));
var doc = JSON.parse(body);
var meta = _.reduce(response.headers
, function (memo, val, key) {
if (key.indexOf('raven') === 0 || wantedPropsFromMetadata.indexOf(key) != -1)
memo[key] = val;
return memo;
}, {});
meta['@id'] = response.headers['__document_id'];
meta.etag = response.headers['etag'];
meta.dateCreated = response.headers['DateCreated'] || response.headers['datecreated'];
doc['@metadata'] = meta;
cb(null, doc);
});
} | [
"function",
"(",
"db",
",",
"id",
",",
"wantedPropsFromMetadata",
",",
"cb",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"wantedPropsFromMetadata",
")",
"==",
"'[object Function]'",
")",
"{",
"cb",
"=",
"wantedPropsFromMetadata",
";",
"wantedPropsFromMetadata",
"=",
"[",
"]",
";",
"}",
"var",
"url",
"=",
"host",
"+",
"'databases/'",
"+",
"db",
"+",
"'/docs/'",
"+",
"id",
";",
"request",
"(",
"url",
",",
"function",
"(",
"error",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"error",
"||",
"response",
".",
"statusCode",
"!=",
"200",
")",
"return",
"cb",
"(",
"error",
"||",
"new",
"Error",
"(",
"response",
".",
"statusCode",
")",
")",
";",
"var",
"doc",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"var",
"meta",
"=",
"_",
".",
"reduce",
"(",
"response",
".",
"headers",
",",
"function",
"(",
"memo",
",",
"val",
",",
"key",
")",
"{",
"if",
"(",
"key",
".",
"indexOf",
"(",
"'raven'",
")",
"===",
"0",
"||",
"wantedPropsFromMetadata",
".",
"indexOf",
"(",
"key",
")",
"!=",
"-",
"1",
")",
"memo",
"[",
"key",
"]",
"=",
"val",
";",
"return",
"memo",
";",
"}",
",",
"{",
"}",
")",
";",
"meta",
"[",
"'@id'",
"]",
"=",
"response",
".",
"headers",
"[",
"'__document_id'",
"]",
";",
"meta",
".",
"etag",
"=",
"response",
".",
"headers",
"[",
"'etag'",
"]",
";",
"meta",
".",
"dateCreated",
"=",
"response",
".",
"headers",
"[",
"'DateCreated'",
"]",
"||",
"response",
".",
"headers",
"[",
"'datecreated'",
"]",
";",
"doc",
"[",
"'@metadata'",
"]",
"=",
"meta",
";",
"cb",
"(",
"null",
",",
"doc",
")",
";",
"}",
")",
";",
"}"
]
| Loads document with given id.
@param {string} db
@param {string} id
@param {string} wantedPropsFromMetadata(OPTIONAL)
@param {Function} cb | [
"Loads",
"document",
"with",
"given",
"id",
"."
]
| 62353a62f634be90f7aa4c36f19574ecd720b463 | https://github.com/VasoBolkvadze/noderaven/blob/62353a62f634be90f7aa4c36f19574ecd720b463/index.js#L258-L280 | train |
|
VasoBolkvadze/noderaven | index.js | function (db, id, doc, metadata, cb) {
var operations = [
{
Method: "PUT",
Document: doc,
Metadata: metadata,
Key: id
}
];
request.post({
url: host + 'databases/' + db + '/bulk_docs',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(operations)
}, function (error, response, resBody) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | javascript | function (db, id, doc, metadata, cb) {
var operations = [
{
Method: "PUT",
Document: doc,
Metadata: metadata,
Key: id
}
];
request.post({
url: host + 'databases/' + db + '/bulk_docs',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(operations)
}, function (error, response, resBody) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | [
"function",
"(",
"db",
",",
"id",
",",
"doc",
",",
"metadata",
",",
"cb",
")",
"{",
"var",
"operations",
"=",
"[",
"{",
"Method",
":",
"\"PUT\"",
",",
"Document",
":",
"doc",
",",
"Metadata",
":",
"metadata",
",",
"Key",
":",
"id",
"}",
"]",
";",
"request",
".",
"post",
"(",
"{",
"url",
":",
"host",
"+",
"'databases/'",
"+",
"db",
"+",
"'/bulk_docs'",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'application/json; charset=utf-8'",
"}",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"operations",
")",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"resBody",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"resBody",
")",
";",
"cb",
"(",
"null",
",",
"result",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"error",
"||",
"new",
"Error",
"(",
"response",
".",
"statusCode",
")",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Overwrites given document with given id.
@param {string} db
@param {string} id
@param {Object} doc
@param {Object} metadata
@param {Function} cb | [
"Overwrites",
"given",
"document",
"with",
"given",
"id",
"."
]
| 62353a62f634be90f7aa4c36f19574ecd720b463 | https://github.com/VasoBolkvadze/noderaven/blob/62353a62f634be90f7aa4c36f19574ecd720b463/index.js#L288-L311 | train |
|
VasoBolkvadze/noderaven | index.js | function (db, id, operations, cb) {
request.patch({
url: host + 'databases/' + db + '/docs/' + id,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(operations)
}, function (error, response, resBody) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | javascript | function (db, id, operations, cb) {
request.patch({
url: host + 'databases/' + db + '/docs/' + id,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(operations)
}, function (error, response, resBody) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | [
"function",
"(",
"db",
",",
"id",
",",
"operations",
",",
"cb",
")",
"{",
"request",
".",
"patch",
"(",
"{",
"url",
":",
"host",
"+",
"'databases/'",
"+",
"db",
"+",
"'/docs/'",
"+",
"id",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'application/json; charset=utf-8'",
"}",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"operations",
")",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"resBody",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"response",
".",
"statusCode",
"===",
"200",
")",
"{",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"resBody",
")",
";",
"cb",
"(",
"null",
",",
"result",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"error",
"||",
"new",
"Error",
"(",
"response",
".",
"statusCode",
")",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Applies patch operations to document with given id.
@param {string} db
@param {string} id
@param {Array<Object>} operations
@param {Function} cb | [
"Applies",
"patch",
"operations",
"to",
"document",
"with",
"given",
"id",
"."
]
| 62353a62f634be90f7aa4c36f19574ecd720b463 | https://github.com/VasoBolkvadze/noderaven/blob/62353a62f634be90f7aa4c36f19574ecd720b463/index.js#L318-L333 | train |
|
VasoBolkvadze/noderaven | index.js | function (db, entityName, doc, cb) {
request.post({
url: host + 'databases/' + db + '/docs',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Raven-Entity-Name': entityName
},
body: JSON.stringify(doc)
}, function (error, response, resBody) {
if (!error && (response.statusCode === 201 || response.statusCode === 200)) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | javascript | function (db, entityName, doc, cb) {
request.post({
url: host + 'databases/' + db + '/docs',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Raven-Entity-Name': entityName
},
body: JSON.stringify(doc)
}, function (error, response, resBody) {
if (!error && (response.statusCode === 201 || response.statusCode === 200)) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
} | [
"function",
"(",
"db",
",",
"entityName",
",",
"doc",
",",
"cb",
")",
"{",
"request",
".",
"post",
"(",
"{",
"url",
":",
"host",
"+",
"'databases/'",
"+",
"db",
"+",
"'/docs'",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'application/json; charset=utf-8'",
",",
"'Raven-Entity-Name'",
":",
"entityName",
"}",
",",
"body",
":",
"JSON",
".",
"stringify",
"(",
"doc",
")",
"}",
",",
"function",
"(",
"error",
",",
"response",
",",
"resBody",
")",
"{",
"if",
"(",
"!",
"error",
"&&",
"(",
"response",
".",
"statusCode",
"===",
"201",
"||",
"response",
".",
"statusCode",
"===",
"200",
")",
")",
"{",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"resBody",
")",
";",
"cb",
"(",
"null",
",",
"result",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"error",
"||",
"new",
"Error",
"(",
"response",
".",
"statusCode",
")",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Stores given document, returns raven generated id in callback.
@param {string} db
@param {string} entityName
@param {Object} doc
@param {Function} cb | [
"Stores",
"given",
"document",
"returns",
"raven",
"generated",
"id",
"in",
"callback",
"."
]
| 62353a62f634be90f7aa4c36f19574ecd720b463 | https://github.com/VasoBolkvadze/noderaven/blob/62353a62f634be90f7aa4c36f19574ecd720b463/index.js#L340-L356 | train |
|
jfseb/mgnlq_er | js/match/inputFilter.js | reinforceDistWeight | function reinforceDistWeight(dist, category) {
var abs = Math.abs(dist);
return 1.0 + (Algol.aReinforceDistWeight[abs] || 0);
} | javascript | function reinforceDistWeight(dist, category) {
var abs = Math.abs(dist);
return 1.0 + (Algol.aReinforceDistWeight[abs] || 0);
} | [
"function",
"reinforceDistWeight",
"(",
"dist",
",",
"category",
")",
"{",
"var",
"abs",
"=",
"Math",
".",
"abs",
"(",
"dist",
")",
";",
"return",
"1.0",
"+",
"(",
"Algol",
".",
"aReinforceDistWeight",
"[",
"abs",
"]",
"||",
"0",
")",
";",
"}"
]
| Calculate a weight factor for a given distance and
category
@param {integer} dist distance in words
@param {string} category category to use
@returns {number} a distance factor >= 1
1.0 for no effect | [
"Calculate",
"a",
"weight",
"factor",
"for",
"a",
"given",
"distance",
"and",
"category"
]
| 2fbfb65aabab39f7708d09e98b3e2618a7ebac30 | https://github.com/jfseb/mgnlq_er/blob/2fbfb65aabab39f7708d09e98b3e2618a7ebac30/js/match/inputFilter.js#L963-L966 | train |
jfseb/mgnlq_er | js/match/inputFilter.js | extractCategoryMap | function extractCategoryMap(oSentence) {
var res = {};
debuglog(debuglog.enabled ? ('extractCategoryMap ' + JSON.stringify(oSentence)) : '-');
oSentence.forEach(function (oWord, iIndex) {
if (oWord.category === IFMatch.CAT_CATEGORY) {
res[oWord.matchedString] = res[oWord.matchedString] || [];
res[oWord.matchedString].push({ pos: iIndex });
}
});
utils.deepFreeze(res);
return res;
} | javascript | function extractCategoryMap(oSentence) {
var res = {};
debuglog(debuglog.enabled ? ('extractCategoryMap ' + JSON.stringify(oSentence)) : '-');
oSentence.forEach(function (oWord, iIndex) {
if (oWord.category === IFMatch.CAT_CATEGORY) {
res[oWord.matchedString] = res[oWord.matchedString] || [];
res[oWord.matchedString].push({ pos: iIndex });
}
});
utils.deepFreeze(res);
return res;
} | [
"function",
"extractCategoryMap",
"(",
"oSentence",
")",
"{",
"var",
"res",
"=",
"{",
"}",
";",
"debuglog",
"(",
"debuglog",
".",
"enabled",
"?",
"(",
"'extractCategoryMap '",
"+",
"JSON",
".",
"stringify",
"(",
"oSentence",
")",
")",
":",
"'-'",
")",
";",
"oSentence",
".",
"forEach",
"(",
"function",
"(",
"oWord",
",",
"iIndex",
")",
"{",
"if",
"(",
"oWord",
".",
"category",
"===",
"IFMatch",
".",
"CAT_CATEGORY",
")",
"{",
"res",
"[",
"oWord",
".",
"matchedString",
"]",
"=",
"res",
"[",
"oWord",
".",
"matchedString",
"]",
"||",
"[",
"]",
";",
"res",
"[",
"oWord",
".",
"matchedString",
"]",
".",
"push",
"(",
"{",
"pos",
":",
"iIndex",
"}",
")",
";",
"}",
"}",
")",
";",
"utils",
".",
"deepFreeze",
"(",
"res",
")",
";",
"return",
"res",
";",
"}"
]
| Given a sentence, extact categories | [
"Given",
"a",
"sentence",
"extact",
"categories"
]
| 2fbfb65aabab39f7708d09e98b3e2618a7ebac30 | https://github.com/jfseb/mgnlq_er/blob/2fbfb65aabab39f7708d09e98b3e2618a7ebac30/js/match/inputFilter.js#L971-L982 | train |
constantology/id8 | id8.js | alias | function alias( name_current, name_alias ) {
if ( util.type( this ) != desc_class_type.value )
return null;
var name, proto = this.prototype;
if ( is_obj( name_current ) ) {
for ( name in name_current )
!util.has( name_current, name ) || alias.call( this, name, name_current[name] );
}
else if ( typeof proto[name_current] == 'function' )
util.def( proto, name_alias, get_method_descriptor( proto, name_current ), true );
return this;
} | javascript | function alias( name_current, name_alias ) {
if ( util.type( this ) != desc_class_type.value )
return null;
var name, proto = this.prototype;
if ( is_obj( name_current ) ) {
for ( name in name_current )
!util.has( name_current, name ) || alias.call( this, name, name_current[name] );
}
else if ( typeof proto[name_current] == 'function' )
util.def( proto, name_alias, get_method_descriptor( proto, name_current ), true );
return this;
} | [
"function",
"alias",
"(",
"name_current",
",",
"name_alias",
")",
"{",
"if",
"(",
"util",
".",
"type",
"(",
"this",
")",
"!=",
"desc_class_type",
".",
"value",
")",
"return",
"null",
";",
"var",
"name",
",",
"proto",
"=",
"this",
".",
"prototype",
";",
"if",
"(",
"is_obj",
"(",
"name_current",
")",
")",
"{",
"for",
"(",
"name",
"in",
"name_current",
")",
"!",
"util",
".",
"has",
"(",
"name_current",
",",
"name",
")",
"||",
"alias",
".",
"call",
"(",
"this",
",",
"name",
",",
"name_current",
"[",
"name",
"]",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"proto",
"[",
"name_current",
"]",
"==",
"'function'",
")",
"util",
".",
"def",
"(",
"proto",
",",
"name_alias",
",",
"get_method_descriptor",
"(",
"proto",
",",
"name_current",
")",
",",
"true",
")",
";",
"return",
"this",
";",
"}"
]
| Class static methods | [
"Class",
"static",
"methods"
]
| 8e97cbf56406da2cd53f825fa4f24ae2263971ce | https://github.com/constantology/id8/blob/8e97cbf56406da2cd53f825fa4f24ae2263971ce/id8.js#L232-L246 | train |
constantology/id8 | id8.js | get_args | function get_args( args, fn_curr, fn_prev ) {
if ( args.length && OP.toString.call( args[0] ) === '[object Arguments]' ) {
if ( args.length < 2 && arguments.length > 1 ) {
if ( fn_curr in internal_method_names )
return get_args( args[0] );
if ( fn_prev && fn_curr === fn_prev )
return args[0];
}
}
return args;
} | javascript | function get_args( args, fn_curr, fn_prev ) {
if ( args.length && OP.toString.call( args[0] ) === '[object Arguments]' ) {
if ( args.length < 2 && arguments.length > 1 ) {
if ( fn_curr in internal_method_names )
return get_args( args[0] );
if ( fn_prev && fn_curr === fn_prev )
return args[0];
}
}
return args;
} | [
"function",
"get_args",
"(",
"args",
",",
"fn_curr",
",",
"fn_prev",
")",
"{",
"if",
"(",
"args",
".",
"length",
"&&",
"OP",
".",
"toString",
".",
"call",
"(",
"args",
"[",
"0",
"]",
")",
"===",
"'[object Arguments]'",
")",
"{",
"if",
"(",
"args",
".",
"length",
"<",
"2",
"&&",
"arguments",
".",
"length",
">",
"1",
")",
"{",
"if",
"(",
"fn_curr",
"in",
"internal_method_names",
")",
"return",
"get_args",
"(",
"args",
"[",
"0",
"]",
")",
";",
"if",
"(",
"fn_prev",
"&&",
"fn_curr",
"===",
"fn_prev",
")",
"return",
"args",
"[",
"0",
"]",
";",
"}",
"}",
"return",
"args",
";",
"}"
]
| Class instance method helpers | [
"Class",
"instance",
"method",
"helpers"
]
| 8e97cbf56406da2cd53f825fa4f24ae2263971ce | https://github.com/constantology/id8/blob/8e97cbf56406da2cd53f825fa4f24ae2263971ce/id8.js#L277-L287 | train |
constantology/id8 | id8.js | add | function add( key, value ) {
var desc;
switch ( typeof value ) {
case 'object' : desc = util.type( value ) == 'descriptor' ? value : util.describe( { value : value }, 'cw' ); break;
case 'function' : desc = util.describe( make_method( 'parent', value, get_method_descriptor( this, key ), key ), 'cw' ); break;
default : desc = util.describe( value, 'cew' );
}
util.def( this, key, desc, true );
return this.constructor;
} | javascript | function add( key, value ) {
var desc;
switch ( typeof value ) {
case 'object' : desc = util.type( value ) == 'descriptor' ? value : util.describe( { value : value }, 'cw' ); break;
case 'function' : desc = util.describe( make_method( 'parent', value, get_method_descriptor( this, key ), key ), 'cw' ); break;
default : desc = util.describe( value, 'cew' );
}
util.def( this, key, desc, true );
return this.constructor;
} | [
"function",
"add",
"(",
"key",
",",
"value",
")",
"{",
"var",
"desc",
";",
"switch",
"(",
"typeof",
"value",
")",
"{",
"case",
"'object'",
":",
"desc",
"=",
"util",
".",
"type",
"(",
"value",
")",
"==",
"'descriptor'",
"?",
"value",
":",
"util",
".",
"describe",
"(",
"{",
"value",
":",
"value",
"}",
",",
"'cw'",
")",
";",
"break",
";",
"case",
"'function'",
":",
"desc",
"=",
"util",
".",
"describe",
"(",
"make_method",
"(",
"'parent'",
",",
"value",
",",
"get_method_descriptor",
"(",
"this",
",",
"key",
")",
",",
"key",
")",
",",
"'cw'",
")",
";",
"break",
";",
"default",
":",
"desc",
"=",
"util",
".",
"describe",
"(",
"value",
",",
"'cew'",
")",
";",
"}",
"util",
".",
"def",
"(",
"this",
",",
"key",
",",
"desc",
",",
"true",
")",
";",
"return",
"this",
".",
"constructor",
";",
"}"
]
| Class construction methods | [
"Class",
"construction",
"methods"
]
| 8e97cbf56406da2cd53f825fa4f24ae2263971ce | https://github.com/constantology/id8/blob/8e97cbf56406da2cd53f825fa4f24ae2263971ce/id8.js#L304-L313 | train |
crispy1989/crisphooks | crisphooks.js | CrispHooks | function CrispHooks(options) {
if (options && options.eventEmitter) {
this.on = CrispHooks.prototype.hookSync;
this.emit = CrispHooks.prototype.triggerSync;
}
this._hooks = {};
} | javascript | function CrispHooks(options) {
if (options && options.eventEmitter) {
this.on = CrispHooks.prototype.hookSync;
this.emit = CrispHooks.prototype.triggerSync;
}
this._hooks = {};
} | [
"function",
"CrispHooks",
"(",
"options",
")",
"{",
"if",
"(",
"options",
"&&",
"options",
".",
"eventEmitter",
")",
"{",
"this",
".",
"on",
"=",
"CrispHooks",
".",
"prototype",
".",
"hookSync",
";",
"this",
".",
"emit",
"=",
"CrispHooks",
".",
"prototype",
".",
"triggerSync",
";",
"}",
"this",
".",
"_hooks",
"=",
"{",
"}",
";",
"}"
]
| Main CrispHooks constructor. This creates an object to which hooks can be added, and
on which hooks can be called.
@class CrispHooks
@constructor
@param {Object} options - Options changing the behavior of the hooks object
@param {Boolean} options.eventEmitter - Add EventEmitter-style aliases | [
"Main",
"CrispHooks",
"constructor",
".",
"This",
"creates",
"an",
"object",
"to",
"which",
"hooks",
"can",
"be",
"added",
"and",
"on",
"which",
"hooks",
"can",
"be",
"called",
"."
]
| 6251a5a0b650086ec7207d17dca623581f7f5d66 | https://github.com/crispy1989/crisphooks/blob/6251a5a0b650086ec7207d17dca623581f7f5d66/crisphooks.js#L12-L18 | train |
chrisJohn404/ljswitchboard-modbus_map | lib/json_constants_parser.js | function(options) {
var constantsData = options.constantsData;
var location = options.location;
var index = options.index;
var name = options.name;
var bufferInfo;
var addData = false;
// Search for a buffer's info
array_registers.forEach(function(arrayRegister) {
if(name === arrayRegister.data) {
bufferInfo = {
'size': arrayRegister.size,
};
var importTypeData = true;
if(arrayRegister.type) {
if(arrayRegister.type !== 'raw') {
bufferInfo.type = arrayRegister.type;
importTypeData = false;
}
}
if(importTypeData) {
bufferInfo.type = constantsData[location][index].type;
}
addData = true;
}
});
if(addData) {
constantsData[location][index].bufferInfo = bufferInfo;
}
} | javascript | function(options) {
var constantsData = options.constantsData;
var location = options.location;
var index = options.index;
var name = options.name;
var bufferInfo;
var addData = false;
// Search for a buffer's info
array_registers.forEach(function(arrayRegister) {
if(name === arrayRegister.data) {
bufferInfo = {
'size': arrayRegister.size,
};
var importTypeData = true;
if(arrayRegister.type) {
if(arrayRegister.type !== 'raw') {
bufferInfo.type = arrayRegister.type;
importTypeData = false;
}
}
if(importTypeData) {
bufferInfo.type = constantsData[location][index].type;
}
addData = true;
}
});
if(addData) {
constantsData[location][index].bufferInfo = bufferInfo;
}
} | [
"function",
"(",
"options",
")",
"{",
"var",
"constantsData",
"=",
"options",
".",
"constantsData",
";",
"var",
"location",
"=",
"options",
".",
"location",
";",
"var",
"index",
"=",
"options",
".",
"index",
";",
"var",
"name",
"=",
"options",
".",
"name",
";",
"var",
"bufferInfo",
";",
"var",
"addData",
"=",
"false",
";",
"array_registers",
".",
"forEach",
"(",
"function",
"(",
"arrayRegister",
")",
"{",
"if",
"(",
"name",
"===",
"arrayRegister",
".",
"data",
")",
"{",
"bufferInfo",
"=",
"{",
"'size'",
":",
"arrayRegister",
".",
"size",
",",
"}",
";",
"var",
"importTypeData",
"=",
"true",
";",
"if",
"(",
"arrayRegister",
".",
"type",
")",
"{",
"if",
"(",
"arrayRegister",
".",
"type",
"!==",
"'raw'",
")",
"{",
"bufferInfo",
".",
"type",
"=",
"arrayRegister",
".",
"type",
";",
"importTypeData",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"importTypeData",
")",
"{",
"bufferInfo",
".",
"type",
"=",
"constantsData",
"[",
"location",
"]",
"[",
"index",
"]",
".",
"type",
";",
"}",
"addData",
"=",
"true",
";",
"}",
"}",
")",
";",
"if",
"(",
"addData",
")",
"{",
"constantsData",
"[",
"location",
"]",
"[",
"index",
"]",
".",
"bufferInfo",
"=",
"bufferInfo",
";",
"}",
"}"
]
| This function forces the creation of the bufferInfo attribute to registers
that contains more information about them. | [
"This",
"function",
"forces",
"the",
"creation",
"of",
"the",
"bufferInfo",
"attribute",
"to",
"registers",
"that",
"contains",
"more",
"information",
"about",
"them",
"."
]
| 886e32778e854bc3d2a0170d3c27e1bb3adf200d | https://github.com/chrisJohn404/ljswitchboard-modbus_map/blob/886e32778e854bc3d2a0170d3c27e1bb3adf200d/lib/json_constants_parser.js#L237-L269 | train |
|
chrisJohn404/ljswitchboard-modbus_map | lib/json_constants_parser.js | function(constantsData) {
var i;
var registerName;
try {
for(i = 0; i < constantsData.registers.length; i++) {
registerName = constantsData.registers[i].name;
if(buffer_registers.indexOf(registerName) >= 0) {
constantsData.registers[i].isBuffer = true;
addMissingBufferRegisterInfoObject({
'constantsData': constantsData,
'location': 'registers',
'index': i,
'name': registerName,
});
}
}
for(i = 0; i < constantsData.registers_beta.length; i++) {
registerName = constantsData.registers_beta[i].name;
if(buffer_registers.indexOf(registerName) >= 0) {
constantsData.registers_beta[i].isBuffer = true;
addMissingBufferRegisterInfoObject({
'constantsData': constantsData,
'location': 'registers_beta',
'index': i,
'name': registerName,
});
}
}
} catch(err) {
console.log('Error adding missing buffer register flags', err, i);
}
return constantsData;
} | javascript | function(constantsData) {
var i;
var registerName;
try {
for(i = 0; i < constantsData.registers.length; i++) {
registerName = constantsData.registers[i].name;
if(buffer_registers.indexOf(registerName) >= 0) {
constantsData.registers[i].isBuffer = true;
addMissingBufferRegisterInfoObject({
'constantsData': constantsData,
'location': 'registers',
'index': i,
'name': registerName,
});
}
}
for(i = 0; i < constantsData.registers_beta.length; i++) {
registerName = constantsData.registers_beta[i].name;
if(buffer_registers.indexOf(registerName) >= 0) {
constantsData.registers_beta[i].isBuffer = true;
addMissingBufferRegisterInfoObject({
'constantsData': constantsData,
'location': 'registers_beta',
'index': i,
'name': registerName,
});
}
}
} catch(err) {
console.log('Error adding missing buffer register flags', err, i);
}
return constantsData;
} | [
"function",
"(",
"constantsData",
")",
"{",
"var",
"i",
";",
"var",
"registerName",
";",
"try",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"constantsData",
".",
"registers",
".",
"length",
";",
"i",
"++",
")",
"{",
"registerName",
"=",
"constantsData",
".",
"registers",
"[",
"i",
"]",
".",
"name",
";",
"if",
"(",
"buffer_registers",
".",
"indexOf",
"(",
"registerName",
")",
">=",
"0",
")",
"{",
"constantsData",
".",
"registers",
"[",
"i",
"]",
".",
"isBuffer",
"=",
"true",
";",
"addMissingBufferRegisterInfoObject",
"(",
"{",
"'constantsData'",
":",
"constantsData",
",",
"'location'",
":",
"'registers'",
",",
"'index'",
":",
"i",
",",
"'name'",
":",
"registerName",
",",
"}",
")",
";",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"constantsData",
".",
"registers_beta",
".",
"length",
";",
"i",
"++",
")",
"{",
"registerName",
"=",
"constantsData",
".",
"registers_beta",
"[",
"i",
"]",
".",
"name",
";",
"if",
"(",
"buffer_registers",
".",
"indexOf",
"(",
"registerName",
")",
">=",
"0",
")",
"{",
"constantsData",
".",
"registers_beta",
"[",
"i",
"]",
".",
"isBuffer",
"=",
"true",
";",
"addMissingBufferRegisterInfoObject",
"(",
"{",
"'constantsData'",
":",
"constantsData",
",",
"'location'",
":",
"'registers_beta'",
",",
"'index'",
":",
"i",
",",
"'name'",
":",
"registerName",
",",
"}",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'Error adding missing buffer register flags'",
",",
"err",
",",
"i",
")",
";",
"}",
"return",
"constantsData",
";",
"}"
]
| This function forces the isBuffer register flag to be set for known buffer
registers. | [
"This",
"function",
"forces",
"the",
"isBuffer",
"register",
"flag",
"to",
"be",
"set",
"for",
"known",
"buffer",
"registers",
"."
]
| 886e32778e854bc3d2a0170d3c27e1bb3adf200d | https://github.com/chrisJohn404/ljswitchboard-modbus_map/blob/886e32778e854bc3d2a0170d3c27e1bb3adf200d/lib/json_constants_parser.js#L274-L308 | train |
|
maenuLabs/ch.maenulabs.validation | ch.maenulabs.validation.js | function (checks) {
checks = checks || [];
this.checks = [];
for (var i = 0; i < checks.length; i = i + 1) {
this.add(checks[i]);
}
} | javascript | function (checks) {
checks = checks || [];
this.checks = [];
for (var i = 0; i < checks.length; i = i + 1) {
this.add(checks[i]);
}
} | [
"function",
"(",
"checks",
")",
"{",
"checks",
"=",
"checks",
"||",
"[",
"]",
";",
"this",
".",
"checks",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"checks",
".",
"length",
";",
"i",
"=",
"i",
"+",
"1",
")",
"{",
"this",
".",
"add",
"(",
"checks",
"[",
"i",
"]",
")",
";",
"}",
"}"
]
| The checks to perform.
@protected
@property checks
@type Array
Creates a Validation.
@constructor
@param Array [checks=[]] The Checks to add | [
"The",
"checks",
"to",
"perform",
"."
]
| 92fd70edf5aa69aa46757c1b1c7d107b8a7ede08 | https://github.com/maenuLabs/ch.maenulabs.validation/blob/92fd70edf5aa69aa46757c1b1c7d107b8a7ede08/ch.maenulabs.validation.js#L43-L49 | train |
|
maenuLabs/ch.maenulabs.validation | ch.maenulabs.validation.js | function (object) {
var values = [];
for (var i = 0; i < this.properties.length; i = i + 1) {
if (object == null) {
values.push(undefined);
} else {
values.push(object[this.properties[i]]);
}
}
return values;
} | javascript | function (object) {
var values = [];
for (var i = 0; i < this.properties.length; i = i + 1) {
if (object == null) {
values.push(undefined);
} else {
values.push(object[this.properties[i]]);
}
}
return values;
} | [
"function",
"(",
"object",
")",
"{",
"var",
"values",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"properties",
".",
"length",
";",
"i",
"=",
"i",
"+",
"1",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"values",
".",
"push",
"(",
"undefined",
")",
";",
"}",
"else",
"{",
"values",
".",
"push",
"(",
"object",
"[",
"this",
".",
"properties",
"[",
"i",
"]",
"]",
")",
";",
"}",
"}",
"return",
"values",
";",
"}"
]
| Gets the values of the properties to check.
@protected
@method getValues
@param * object The object to inspect
@return Array The values of the properties in the same order | [
"Gets",
"the",
"values",
"of",
"the",
"properties",
"to",
"check",
"."
]
| 92fd70edf5aa69aa46757c1b1c7d107b8a7ede08 | https://github.com/maenuLabs/ch.maenulabs.validation/blob/92fd70edf5aa69aa46757c1b1c7d107b8a7ede08/ch.maenulabs.validation.js#L190-L200 | train |
|
maenuLabs/ch.maenulabs.validation | ch.maenulabs.validation.js | function (property, validation, required) {
if (required == null) {
required = true;
}
this.property = property;
this.validation = validation;
this.required = required;
} | javascript | function (property, validation, required) {
if (required == null) {
required = true;
}
this.property = property;
this.validation = validation;
this.required = required;
} | [
"function",
"(",
"property",
",",
"validation",
",",
"required",
")",
"{",
"if",
"(",
"required",
"==",
"null",
")",
"{",
"required",
"=",
"true",
";",
"}",
"this",
".",
"property",
"=",
"property",
";",
"this",
".",
"validation",
"=",
"validation",
";",
"this",
".",
"required",
"=",
"required",
";",
"}"
]
| The property name.
@private
@property property
@type String
The validation to perform on property.
@private
@property validation
@type Validation
Creates an ObjectCheck.
@constructor
@param String property The property name
@param Validation validation The validation to perform on property
@param Boolean [required=true] Whether or not the validation is
performed if the property is undefined | [
"The",
"property",
"name",
"."
]
| 92fd70edf5aa69aa46757c1b1c7d107b8a7ede08 | https://github.com/maenuLabs/ch.maenulabs.validation/blob/92fd70edf5aa69aa46757c1b1c7d107b8a7ede08/ch.maenulabs.validation.js#L237-L244 | train |
|
maenuLabs/ch.maenulabs.validation | ch.maenulabs.validation.js | function (property, messager) {
this.base('initialize')([property], function (value) {
return value != null;
}, messager || function () {
return i18n['ch/maenulabs/validation/ExistenceCheck'].message();
});
} | javascript | function (property, messager) {
this.base('initialize')([property], function (value) {
return value != null;
}, messager || function () {
return i18n['ch/maenulabs/validation/ExistenceCheck'].message();
});
} | [
"function",
"(",
"property",
",",
"messager",
")",
"{",
"this",
".",
"base",
"(",
"'initialize'",
")",
"(",
"[",
"property",
"]",
",",
"function",
"(",
"value",
")",
"{",
"return",
"value",
"!=",
"null",
";",
"}",
",",
"messager",
"||",
"function",
"(",
")",
"{",
"return",
"i18n",
"[",
"'ch/maenulabs/validation/ExistenceCheck'",
"]",
".",
"message",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Creates an ExistenceCheck.
@constructor
@param String property The property name
@param Function [messager] The messager | [
"Creates",
"an",
"ExistenceCheck",
"."
]
| 92fd70edf5aa69aa46757c1b1c7d107b8a7ede08 | https://github.com/maenuLabs/ch.maenulabs.validation/blob/92fd70edf5aa69aa46757c1b1c7d107b8a7ede08/ch.maenulabs.validation.js#L290-L296 | train |
|
maenuLabs/ch.maenulabs.validation | ch.maenulabs.validation.js | function (property, limit, messager) {
this.base('initialize')([property], function (value) {
return value > limit;
}, messager || function () {
return i18n['ch/maenulabs/validation/GreaterThanCheck'].message({
amount: limit
});
});
} | javascript | function (property, limit, messager) {
this.base('initialize')([property], function (value) {
return value > limit;
}, messager || function () {
return i18n['ch/maenulabs/validation/GreaterThanCheck'].message({
amount: limit
});
});
} | [
"function",
"(",
"property",
",",
"limit",
",",
"messager",
")",
"{",
"this",
".",
"base",
"(",
"'initialize'",
")",
"(",
"[",
"property",
"]",
",",
"function",
"(",
"value",
")",
"{",
"return",
"value",
">",
"limit",
";",
"}",
",",
"messager",
"||",
"function",
"(",
")",
"{",
"return",
"i18n",
"[",
"'ch/maenulabs/validation/GreaterThanCheck'",
"]",
".",
"message",
"(",
"{",
"amount",
":",
"limit",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Creates an GreaterThanCheck.
@constructor
@param String property The property name
@param Number limit The value must be at least this limit
@param Function [messager] The messager | [
"Creates",
"an",
"GreaterThanCheck",
"."
]
| 92fd70edf5aa69aa46757c1b1c7d107b8a7ede08 | https://github.com/maenuLabs/ch.maenulabs.validation/blob/92fd70edf5aa69aa46757c1b1c7d107b8a7ede08/ch.maenulabs.validation.js#L378-L386 | train |
|
maenuLabs/ch.maenulabs.validation | ch.maenulabs.validation.js | function (property, minimum, maximum, required) {
this.base('initialize')(property, new Validation([
new AtLeastCheck('length', minimum, function () {
return i18n['ch/maenulabs/validation/StringLengthRangeCheck'].minimum({
amount: minimum
});
}),
new AtMostCheck('length', maximum, function () {
return i18n['ch/maenulabs/validation/StringLengthRangeCheck'].maximum({
amount: maximum
});
})
]), required);
} | javascript | function (property, minimum, maximum, required) {
this.base('initialize')(property, new Validation([
new AtLeastCheck('length', minimum, function () {
return i18n['ch/maenulabs/validation/StringLengthRangeCheck'].minimum({
amount: minimum
});
}),
new AtMostCheck('length', maximum, function () {
return i18n['ch/maenulabs/validation/StringLengthRangeCheck'].maximum({
amount: maximum
});
})
]), required);
} | [
"function",
"(",
"property",
",",
"minimum",
",",
"maximum",
",",
"required",
")",
"{",
"this",
".",
"base",
"(",
"'initialize'",
")",
"(",
"property",
",",
"new",
"Validation",
"(",
"[",
"new",
"AtLeastCheck",
"(",
"'length'",
",",
"minimum",
",",
"function",
"(",
")",
"{",
"return",
"i18n",
"[",
"'ch/maenulabs/validation/StringLengthRangeCheck'",
"]",
".",
"minimum",
"(",
"{",
"amount",
":",
"minimum",
"}",
")",
";",
"}",
")",
",",
"new",
"AtMostCheck",
"(",
"'length'",
",",
"maximum",
",",
"function",
"(",
")",
"{",
"return",
"i18n",
"[",
"'ch/maenulabs/validation/StringLengthRangeCheck'",
"]",
".",
"maximum",
"(",
"{",
"amount",
":",
"maximum",
"}",
")",
";",
"}",
")",
"]",
")",
",",
"required",
")",
";",
"}"
]
| Creates an StringLengthRangeCheck.
@constructor
@param String property The property name
@param Number minimum The minimum length
@param Number maximum The maximum length
@param Boolean [required=true] Whether or not the validation is
performed if the property is undefined | [
"Creates",
"an",
"StringLengthRangeCheck",
"."
]
| 92fd70edf5aa69aa46757c1b1c7d107b8a7ede08 | https://github.com/maenuLabs/ch.maenulabs.validation/blob/92fd70edf5aa69aa46757c1b1c7d107b8a7ede08/ch.maenulabs.validation.js#L443-L456 | train |
|
byu-oit/fully-typed | bin/typed.js | Typed | function Typed (config) {
const typed = this;
const hasDefault = config.hasOwnProperty('default');
// enum
if (config.hasOwnProperty('enum')) {
if (!Array.isArray(config.enum) || config.enum.length === 0) {
throw Error(util.propertyErrorMessage('enum', config.enum, 'Expected a non-empty array'));
}
const copy = [];
config.enum.forEach(function(v) {
if (copy.indexOf(v) === -1) copy.push(v);
});
config.enum = copy;
}
// transform
if (config.transform && typeof config.transform !== 'function') {
throw Error(util.propertyErrorMessage('transform', config.transform, 'Expected a function'));
}
// validate
if (config.validator && typeof config.validator !== 'function') {
throw Error(util.propertyErrorMessage('validator', config.validator, 'Expected a function'));
}
// define properties
Object.defineProperties(typed, {
default: {
/**
* @property
* @name Typed#default
* @type {function,*}
*/
value: config.default,
writable: false
},
enum: {
/**
* @property
* @name Typed#enum
* @readonly
* @type {function,*}
*/
value: config.enum,
writable: false
},
hasDefault: {
/**
* @property
* @name Typed#hasDefault
* @type {boolean}
*/
value: hasDefault,
writable: false
},
transform: {
/**
* @property
* @name Typed#transform
* @readonly
* @type {function}
*/
value: config.transform,
writable: false
},
type: {
/**
* @property
* @name Typed#type
* @readonly
* @type {string,function}
*/
value: config.type,
writable: false
},
validator: {
/**
* @property
* @name Typed#validator
* @readonly
* @type {function}
*/
value: config.validator,
writable: false
}
});
return typed;
} | javascript | function Typed (config) {
const typed = this;
const hasDefault = config.hasOwnProperty('default');
// enum
if (config.hasOwnProperty('enum')) {
if (!Array.isArray(config.enum) || config.enum.length === 0) {
throw Error(util.propertyErrorMessage('enum', config.enum, 'Expected a non-empty array'));
}
const copy = [];
config.enum.forEach(function(v) {
if (copy.indexOf(v) === -1) copy.push(v);
});
config.enum = copy;
}
// transform
if (config.transform && typeof config.transform !== 'function') {
throw Error(util.propertyErrorMessage('transform', config.transform, 'Expected a function'));
}
// validate
if (config.validator && typeof config.validator !== 'function') {
throw Error(util.propertyErrorMessage('validator', config.validator, 'Expected a function'));
}
// define properties
Object.defineProperties(typed, {
default: {
/**
* @property
* @name Typed#default
* @type {function,*}
*/
value: config.default,
writable: false
},
enum: {
/**
* @property
* @name Typed#enum
* @readonly
* @type {function,*}
*/
value: config.enum,
writable: false
},
hasDefault: {
/**
* @property
* @name Typed#hasDefault
* @type {boolean}
*/
value: hasDefault,
writable: false
},
transform: {
/**
* @property
* @name Typed#transform
* @readonly
* @type {function}
*/
value: config.transform,
writable: false
},
type: {
/**
* @property
* @name Typed#type
* @readonly
* @type {string,function}
*/
value: config.type,
writable: false
},
validator: {
/**
* @property
* @name Typed#validator
* @readonly
* @type {function}
*/
value: config.validator,
writable: false
}
});
return typed;
} | [
"function",
"Typed",
"(",
"config",
")",
"{",
"const",
"typed",
"=",
"this",
";",
"const",
"hasDefault",
"=",
"config",
".",
"hasOwnProperty",
"(",
"'default'",
")",
";",
"if",
"(",
"config",
".",
"hasOwnProperty",
"(",
"'enum'",
")",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"config",
".",
"enum",
")",
"||",
"config",
".",
"enum",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"Error",
"(",
"util",
".",
"propertyErrorMessage",
"(",
"'enum'",
",",
"config",
".",
"enum",
",",
"'Expected a non-empty array'",
")",
")",
";",
"}",
"const",
"copy",
"=",
"[",
"]",
";",
"config",
".",
"enum",
".",
"forEach",
"(",
"function",
"(",
"v",
")",
"{",
"if",
"(",
"copy",
".",
"indexOf",
"(",
"v",
")",
"===",
"-",
"1",
")",
"copy",
".",
"push",
"(",
"v",
")",
";",
"}",
")",
";",
"config",
".",
"enum",
"=",
"copy",
";",
"}",
"if",
"(",
"config",
".",
"transform",
"&&",
"typeof",
"config",
".",
"transform",
"!==",
"'function'",
")",
"{",
"throw",
"Error",
"(",
"util",
".",
"propertyErrorMessage",
"(",
"'transform'",
",",
"config",
".",
"transform",
",",
"'Expected a function'",
")",
")",
";",
"}",
"if",
"(",
"config",
".",
"validator",
"&&",
"typeof",
"config",
".",
"validator",
"!==",
"'function'",
")",
"{",
"throw",
"Error",
"(",
"util",
".",
"propertyErrorMessage",
"(",
"'validator'",
",",
"config",
".",
"validator",
",",
"'Expected a function'",
")",
")",
";",
"}",
"Object",
".",
"defineProperties",
"(",
"typed",
",",
"{",
"default",
":",
"{",
"value",
":",
"config",
".",
"default",
",",
"writable",
":",
"false",
"}",
",",
"enum",
":",
"{",
"value",
":",
"config",
".",
"enum",
",",
"writable",
":",
"false",
"}",
",",
"hasDefault",
":",
"{",
"value",
":",
"hasDefault",
",",
"writable",
":",
"false",
"}",
",",
"transform",
":",
"{",
"value",
":",
"config",
".",
"transform",
",",
"writable",
":",
"false",
"}",
",",
"type",
":",
"{",
"value",
":",
"config",
".",
"type",
",",
"writable",
":",
"false",
"}",
",",
"validator",
":",
"{",
"value",
":",
"config",
".",
"validator",
",",
"writable",
":",
"false",
"}",
"}",
")",
";",
"return",
"typed",
";",
"}"
]
| Create a Typed instance.
@param {object} config
@returns {Typed}
@constructor | [
"Create",
"a",
"Typed",
"instance",
"."
]
| ed6b3ed88ffc72990acffb765232eaaee261afef | https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/typed.js#L29-L124 | train |
greggman/hft-sample-ui | src/hft/scripts/misc/mobilehacks.js | function() {
// Also fix all fucked up sizing
var elements = document.querySelectorAll(".fixheight");
for (var ii = 0; ii < elements.length; ++ii) {
var element = elements[ii];
var parent = element.parentNode;
if (parseInt(element.style.height) !== parent.clientHeight) {
element.style.height = parent.clientHeight + "px";
}
}
} | javascript | function() {
// Also fix all fucked up sizing
var elements = document.querySelectorAll(".fixheight");
for (var ii = 0; ii < elements.length; ++ii) {
var element = elements[ii];
var parent = element.parentNode;
if (parseInt(element.style.height) !== parent.clientHeight) {
element.style.height = parent.clientHeight + "px";
}
}
} | [
"function",
"(",
")",
"{",
"var",
"elements",
"=",
"document",
".",
"querySelectorAll",
"(",
"\".fixheight\"",
")",
";",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"elements",
".",
"length",
";",
"++",
"ii",
")",
"{",
"var",
"element",
"=",
"elements",
"[",
"ii",
"]",
";",
"var",
"parent",
"=",
"element",
".",
"parentNode",
";",
"if",
"(",
"parseInt",
"(",
"element",
".",
"style",
".",
"height",
")",
"!==",
"parent",
".",
"clientHeight",
")",
"{",
"element",
".",
"style",
".",
"height",
"=",
"parent",
".",
"clientHeight",
"+",
"\"px\"",
";",
"}",
"}",
"}"
]
| resets the height of any element with CSS class "fixeight"
by setting its hight to the cliehgtHeight of its parent
The problem this is trying to solve is sometimes you have
an element set to 100% but when the phone rotates
the browser does not reset the size of the element even
though it's parent has been resized.
This will be called automatically when the phone rotates
or the window is resized but I found I often needed to
call it manually at the start of a controller
@memberOf module:MobileHacks | [
"resets",
"the",
"height",
"of",
"any",
"element",
"with",
"CSS",
"class",
"fixeight",
"by",
"setting",
"its",
"hight",
"to",
"the",
"cliehgtHeight",
"of",
"its",
"parent"
]
| b9e20afd5183db73522bcfae48225c87e01f68c0 | https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/mobilehacks.js#L95-L105 | train |
|
greggman/hft-sample-ui | src/hft/scripts/misc/mobilehacks.js | function() {
if (!document.body) {
setTimeout(stopSliding, 4);
} else {
document.body.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);
}
} | javascript | function() {
if (!document.body) {
setTimeout(stopSliding, 4);
} else {
document.body.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"document",
".",
"body",
")",
"{",
"setTimeout",
"(",
"stopSliding",
",",
"4",
")",
";",
"}",
"else",
"{",
"document",
".",
"body",
".",
"addEventListener",
"(",
"'touchmove'",
",",
"function",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"}",
",",
"false",
")",
";",
"}",
"}"
]
| Prevents the browser from sliding the page when the user slides their finger. At least on iOS. | [
"Prevents",
"the",
"browser",
"from",
"sliding",
"the",
"page",
"when",
"the",
"user",
"slides",
"their",
"finger",
".",
"At",
"least",
"on",
"iOS",
"."
]
| b9e20afd5183db73522bcfae48225c87e01f68c0 | https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/mobilehacks.js#L143-L151 | train |
|
greggman/hft-sample-ui | src/hft/scripts/misc/mobilehacks.js | function() {
// Note: This code is for games that require a certain orientation
// on phones only. I'm making the assuption that tablets don't need
// this.
//
// The issue I ran into is I tried to show several people games
// and they had their phone orientation locked to portrait. Having
// to go unlock just to play the game was frustrating. So, for
// controllers than require landscape just try to make the page
// show up in landscape. They'll understand they need to turn the phone.
//
// If the orientation is unlocked they'll turn and the page will
// switch to landscape. If the orientation is locked then turning
// the phone will not switch to landscape NOR will we get an orientation
// event.
var everything = $("hft-everything");
var detectPortrait = function() {
if (screen.width < screen.height) {
everything.className = "hft-portrait-to-landscape";
everything.style.width = window.innerHeight + "px";
everything.style.height = window.innerWidth + "px";
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-height, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui');
} else {
everything.className = "";
}
};
detectPortrait();
window.addEventListener('resize', detectPortrait, false);
} | javascript | function() {
// Note: This code is for games that require a certain orientation
// on phones only. I'm making the assuption that tablets don't need
// this.
//
// The issue I ran into is I tried to show several people games
// and they had their phone orientation locked to portrait. Having
// to go unlock just to play the game was frustrating. So, for
// controllers than require landscape just try to make the page
// show up in landscape. They'll understand they need to turn the phone.
//
// If the orientation is unlocked they'll turn and the page will
// switch to landscape. If the orientation is locked then turning
// the phone will not switch to landscape NOR will we get an orientation
// event.
var everything = $("hft-everything");
var detectPortrait = function() {
if (screen.width < screen.height) {
everything.className = "hft-portrait-to-landscape";
everything.style.width = window.innerHeight + "px";
everything.style.height = window.innerWidth + "px";
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-height, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui');
} else {
everything.className = "";
}
};
detectPortrait();
window.addEventListener('resize', detectPortrait, false);
} | [
"function",
"(",
")",
"{",
"var",
"everything",
"=",
"$",
"(",
"\"hft-everything\"",
")",
";",
"var",
"detectPortrait",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"screen",
".",
"width",
"<",
"screen",
".",
"height",
")",
"{",
"everything",
".",
"className",
"=",
"\"hft-portrait-to-landscape\"",
";",
"everything",
".",
"style",
".",
"width",
"=",
"window",
".",
"innerHeight",
"+",
"\"px\"",
";",
"everything",
".",
"style",
".",
"height",
"=",
"window",
".",
"innerWidth",
"+",
"\"px\"",
";",
"var",
"viewport",
"=",
"document",
".",
"querySelector",
"(",
"\"meta[name=viewport]\"",
")",
";",
"viewport",
".",
"setAttribute",
"(",
"'content'",
",",
"'width=device-height, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui'",
")",
";",
"}",
"else",
"{",
"everything",
".",
"className",
"=",
"\"\"",
";",
"}",
"}",
";",
"detectPortrait",
"(",
")",
";",
"window",
".",
"addEventListener",
"(",
"'resize'",
",",
"detectPortrait",
",",
"false",
")",
";",
"}"
]
| This DOESN'T WORK! I'm leaving it here so I can revisit it. The issue is all kinds of things mess up. Events are not rotated, the page does strange things. | [
"This",
"DOESN",
"T",
"WORK!",
"I",
"m",
"leaving",
"it",
"here",
"so",
"I",
"can",
"revisit",
"it",
".",
"The",
"issue",
"is",
"all",
"kinds",
"of",
"things",
"mess",
"up",
".",
"Events",
"are",
"not",
"rotated",
"the",
"page",
"does",
"strange",
"things",
"."
]
| b9e20afd5183db73522bcfae48225c87e01f68c0 | https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/mobilehacks.js#L158-L189 | train |
|
waka/node-bowl | lib/logger.js | createLogger | function createLogger(opt_level, opt_dir) {
var config = getLogConfig(opt_level, opt_dir);
var transports = getTransports(config);
// check logdir
if (!fs.existsSync(config.file.dir)) {
throw new Error(
util.format('The logdir does not exist: %s', config.file.dir));
}
// create instance
var logger = new (winston.Logger)({
transports: [
new winston.transports.Console(transports.console),
new winston.transports.File(transports.file)
],
exitOnError: false,
exceptionHandlers: [
new winston.transports.File(transports.error)
]
});
// use syslog's levels
logger.setLevels(winston.config.syslog.levels);
// if production env, remove console logger
if (process.env.NODE_ENV === 'production') {
logger.remove(winston.transports.Console);
}
return logger;
} | javascript | function createLogger(opt_level, opt_dir) {
var config = getLogConfig(opt_level, opt_dir);
var transports = getTransports(config);
// check logdir
if (!fs.existsSync(config.file.dir)) {
throw new Error(
util.format('The logdir does not exist: %s', config.file.dir));
}
// create instance
var logger = new (winston.Logger)({
transports: [
new winston.transports.Console(transports.console),
new winston.transports.File(transports.file)
],
exitOnError: false,
exceptionHandlers: [
new winston.transports.File(transports.error)
]
});
// use syslog's levels
logger.setLevels(winston.config.syslog.levels);
// if production env, remove console logger
if (process.env.NODE_ENV === 'production') {
logger.remove(winston.transports.Console);
}
return logger;
} | [
"function",
"createLogger",
"(",
"opt_level",
",",
"opt_dir",
")",
"{",
"var",
"config",
"=",
"getLogConfig",
"(",
"opt_level",
",",
"opt_dir",
")",
";",
"var",
"transports",
"=",
"getTransports",
"(",
"config",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"config",
".",
"file",
".",
"dir",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"'The logdir does not exist: %s'",
",",
"config",
".",
"file",
".",
"dir",
")",
")",
";",
"}",
"var",
"logger",
"=",
"new",
"(",
"winston",
".",
"Logger",
")",
"(",
"{",
"transports",
":",
"[",
"new",
"winston",
".",
"transports",
".",
"Console",
"(",
"transports",
".",
"console",
")",
",",
"new",
"winston",
".",
"transports",
".",
"File",
"(",
"transports",
".",
"file",
")",
"]",
",",
"exitOnError",
":",
"false",
",",
"exceptionHandlers",
":",
"[",
"new",
"winston",
".",
"transports",
".",
"File",
"(",
"transports",
".",
"error",
")",
"]",
"}",
")",
";",
"logger",
".",
"setLevels",
"(",
"winston",
".",
"config",
".",
"syslog",
".",
"levels",
")",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'production'",
")",
"{",
"logger",
".",
"remove",
"(",
"winston",
".",
"transports",
".",
"Console",
")",
";",
"}",
"return",
"logger",
";",
"}"
]
| Instantiate winston logger.
@param {string=} opt_level .
@param {string=} opt_dir .
@return {winston.Logger} . | [
"Instantiate",
"winston",
"logger",
"."
]
| 671e8b16371a279e23b65bb9b2ff9dae047b6644 | https://github.com/waka/node-bowl/blob/671e8b16371a279e23b65bb9b2ff9dae047b6644/lib/logger.js#L65-L96 | train |
waka/node-bowl | lib/logger.js | getLogConfig | function getLogConfig(opt_level, opt_dir) {
var config = _.clone(defaultConfig);
if (opt_level) {
config.level = opt_level;
}
if (opt_dir) {
config.file.dir = opt_dir;
}
return config;
} | javascript | function getLogConfig(opt_level, opt_dir) {
var config = _.clone(defaultConfig);
if (opt_level) {
config.level = opt_level;
}
if (opt_dir) {
config.file.dir = opt_dir;
}
return config;
} | [
"function",
"getLogConfig",
"(",
"opt_level",
",",
"opt_dir",
")",
"{",
"var",
"config",
"=",
"_",
".",
"clone",
"(",
"defaultConfig",
")",
";",
"if",
"(",
"opt_level",
")",
"{",
"config",
".",
"level",
"=",
"opt_level",
";",
"}",
"if",
"(",
"opt_dir",
")",
"{",
"config",
".",
"file",
".",
"dir",
"=",
"opt_dir",
";",
"}",
"return",
"config",
";",
"}"
]
| Merge user's configurations.
@param {string=} opt_level .
@param {string=} opt_dir .
@return {Object} . | [
"Merge",
"user",
"s",
"configurations",
"."
]
| 671e8b16371a279e23b65bb9b2ff9dae047b6644 | https://github.com/waka/node-bowl/blob/671e8b16371a279e23b65bb9b2ff9dae047b6644/lib/logger.js#L106-L115 | train |
waka/node-bowl | lib/logger.js | getTransports | function getTransports(config) {
var transports = {
console: {
level: config.level,
handleExceptions: true,
colorize: true,
prettyPrint: true
},
file: {
level: config.level,
filename: path.join(config.file.dir, FILE_NAME),
maxsize: config.file.maxsize,
maxFiles: config.file.maxfiles,
json: false,
timestamp: true
}
};
transports.error = {
filename: path.join(config.file.dir, ERROR_FILE_NAME),
maxsize: config.file.maxsize,
maxFiles: config.file.maxfiles,
timestamp: true,
json: true,
prettyPrint: true
};
return transports;
} | javascript | function getTransports(config) {
var transports = {
console: {
level: config.level,
handleExceptions: true,
colorize: true,
prettyPrint: true
},
file: {
level: config.level,
filename: path.join(config.file.dir, FILE_NAME),
maxsize: config.file.maxsize,
maxFiles: config.file.maxfiles,
json: false,
timestamp: true
}
};
transports.error = {
filename: path.join(config.file.dir, ERROR_FILE_NAME),
maxsize: config.file.maxsize,
maxFiles: config.file.maxfiles,
timestamp: true,
json: true,
prettyPrint: true
};
return transports;
} | [
"function",
"getTransports",
"(",
"config",
")",
"{",
"var",
"transports",
"=",
"{",
"console",
":",
"{",
"level",
":",
"config",
".",
"level",
",",
"handleExceptions",
":",
"true",
",",
"colorize",
":",
"true",
",",
"prettyPrint",
":",
"true",
"}",
",",
"file",
":",
"{",
"level",
":",
"config",
".",
"level",
",",
"filename",
":",
"path",
".",
"join",
"(",
"config",
".",
"file",
".",
"dir",
",",
"FILE_NAME",
")",
",",
"maxsize",
":",
"config",
".",
"file",
".",
"maxsize",
",",
"maxFiles",
":",
"config",
".",
"file",
".",
"maxfiles",
",",
"json",
":",
"false",
",",
"timestamp",
":",
"true",
"}",
"}",
";",
"transports",
".",
"error",
"=",
"{",
"filename",
":",
"path",
".",
"join",
"(",
"config",
".",
"file",
".",
"dir",
",",
"ERROR_FILE_NAME",
")",
",",
"maxsize",
":",
"config",
".",
"file",
".",
"maxsize",
",",
"maxFiles",
":",
"config",
".",
"file",
".",
"maxfiles",
",",
"timestamp",
":",
"true",
",",
"json",
":",
"true",
",",
"prettyPrint",
":",
"true",
"}",
";",
"return",
"transports",
";",
"}"
]
| winston transports.
@param {Object} config .
@return {Object} . | [
"winston",
"transports",
"."
]
| 671e8b16371a279e23b65bb9b2ff9dae047b6644 | https://github.com/waka/node-bowl/blob/671e8b16371a279e23b65bb9b2ff9dae047b6644/lib/logger.js#L124-L151 | train |
ctalau/gulp-closure-builder-list | index.js | googAddDependency | function googAddDependency(file, provides, requires) {
provides.forEach(function(provided) {
symbolsFile[provided] = file;
deps[provided] = deps[provided] || [];
Array.prototype.push.apply(deps[provided], requires)
});
} | javascript | function googAddDependency(file, provides, requires) {
provides.forEach(function(provided) {
symbolsFile[provided] = file;
deps[provided] = deps[provided] || [];
Array.prototype.push.apply(deps[provided], requires)
});
} | [
"function",
"googAddDependency",
"(",
"file",
",",
"provides",
",",
"requires",
")",
"{",
"provides",
".",
"forEach",
"(",
"function",
"(",
"provided",
")",
"{",
"symbolsFile",
"[",
"provided",
"]",
"=",
"file",
";",
"deps",
"[",
"provided",
"]",
"=",
"deps",
"[",
"provided",
"]",
"||",
"[",
"]",
";",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"deps",
"[",
"provided",
"]",
",",
"requires",
")",
"}",
")",
";",
"}"
]
| Replacement for goog.addDependency to just records the dependencies. | [
"Replacement",
"for",
"goog",
".",
"addDependency",
"to",
"just",
"records",
"the",
"dependencies",
"."
]
| b86492525561c5558fda0c7be6d7ed8bcb11e02f | https://github.com/ctalau/gulp-closure-builder-list/blob/b86492525561c5558fda0c7be6d7ed8bcb11e02f/index.js#L16-L22 | train |
ctalau/gulp-closure-builder-list | index.js | generateManifest | function generateManifest(entryPoint) {
var added = new Set();
var manifest = [];
function addTransitiveDeps(symbol) {
added.add(symbol);
var symDeps = deps[symbol];
if (symDeps) {
symDeps.forEach(function(dependency) {
if (!added.has(dependency)) {
addTransitiveDeps(dependency);
}
});
} else {
gutil.log('No deps found for symbol', symbol, deps);
}
manifest.push(symbolsFile[symbol]);
}
addTransitiveDeps(entryPoint);
return manifest;
} | javascript | function generateManifest(entryPoint) {
var added = new Set();
var manifest = [];
function addTransitiveDeps(symbol) {
added.add(symbol);
var symDeps = deps[symbol];
if (symDeps) {
symDeps.forEach(function(dependency) {
if (!added.has(dependency)) {
addTransitiveDeps(dependency);
}
});
} else {
gutil.log('No deps found for symbol', symbol, deps);
}
manifest.push(symbolsFile[symbol]);
}
addTransitiveDeps(entryPoint);
return manifest;
} | [
"function",
"generateManifest",
"(",
"entryPoint",
")",
"{",
"var",
"added",
"=",
"new",
"Set",
"(",
")",
";",
"var",
"manifest",
"=",
"[",
"]",
";",
"function",
"addTransitiveDeps",
"(",
"symbol",
")",
"{",
"added",
".",
"add",
"(",
"symbol",
")",
";",
"var",
"symDeps",
"=",
"deps",
"[",
"symbol",
"]",
";",
"if",
"(",
"symDeps",
")",
"{",
"symDeps",
".",
"forEach",
"(",
"function",
"(",
"dependency",
")",
"{",
"if",
"(",
"!",
"added",
".",
"has",
"(",
"dependency",
")",
")",
"{",
"addTransitiveDeps",
"(",
"dependency",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"gutil",
".",
"log",
"(",
"'No deps found for symbol'",
",",
"symbol",
",",
"deps",
")",
";",
"}",
"manifest",
".",
"push",
"(",
"symbolsFile",
"[",
"symbol",
"]",
")",
";",
"}",
"addTransitiveDeps",
"(",
"entryPoint",
")",
";",
"return",
"manifest",
";",
"}"
]
| Adds the transitive dependencies of the symbol to the manifest. | [
"Adds",
"the",
"transitive",
"dependencies",
"of",
"the",
"symbol",
"to",
"the",
"manifest",
"."
]
| b86492525561c5558fda0c7be6d7ed8bcb11e02f | https://github.com/ctalau/gulp-closure-builder-list/blob/b86492525561c5558fda0c7be6d7ed8bcb11e02f/index.js#L25-L46 | train |
ctalau/gulp-closure-builder-list | index.js | generateManifestFile | function generateManifestFile() {
if (Object.keys(deps).length === 0) {
this.emit('end');
} else if (!entryPoint) {
this.emit('error',
new gutil.PluginError(PLUGIN_NAME, 'Closure entry point is not specified'));
} else {
var manifest = generateManifest(entryPoint);
var manifestFile = new gutil.File({
contents: new Buffer(manifest.join('\n')),
path: fileName
});
this.emit('data', manifestFile);
this.emit('end');
}
} | javascript | function generateManifestFile() {
if (Object.keys(deps).length === 0) {
this.emit('end');
} else if (!entryPoint) {
this.emit('error',
new gutil.PluginError(PLUGIN_NAME, 'Closure entry point is not specified'));
} else {
var manifest = generateManifest(entryPoint);
var manifestFile = new gutil.File({
contents: new Buffer(manifest.join('\n')),
path: fileName
});
this.emit('data', manifestFile);
this.emit('end');
}
} | [
"function",
"generateManifestFile",
"(",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"deps",
")",
".",
"length",
"===",
"0",
")",
"{",
"this",
".",
"emit",
"(",
"'end'",
")",
";",
"}",
"else",
"if",
"(",
"!",
"entryPoint",
")",
"{",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"gutil",
".",
"PluginError",
"(",
"PLUGIN_NAME",
",",
"'Closure entry point is not specified'",
")",
")",
";",
"}",
"else",
"{",
"var",
"manifest",
"=",
"generateManifest",
"(",
"entryPoint",
")",
";",
"var",
"manifestFile",
"=",
"new",
"gutil",
".",
"File",
"(",
"{",
"contents",
":",
"new",
"Buffer",
"(",
"manifest",
".",
"join",
"(",
"'\\n'",
")",
")",
",",
"\\n",
"}",
")",
";",
"path",
":",
"fileName",
"this",
".",
"emit",
"(",
"'data'",
",",
"manifestFile",
")",
";",
"}",
"}"
]
| Generates a manifest file with one path per line. | [
"Generates",
"a",
"manifest",
"file",
"with",
"one",
"path",
"per",
"line",
"."
]
| b86492525561c5558fda0c7be6d7ed8bcb11e02f | https://github.com/ctalau/gulp-closure-builder-list/blob/b86492525561c5558fda0c7be6d7ed8bcb11e02f/index.js#L49-L66 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client.js | connectNode | function connectNode (subscriptions, host, clientId) {
// Create client
var url = "tcp://" + host + ":1883";
var client = mqtt_lib.connect(url, {clientId : clientId});
// Register incoming message callback
client.on('message', function(channel, message) {
// Execute all the appropriate callbacks:
// the ones specific to this channel with a single parameter (message)
// the ones associated to a wildcard channel, with two parameters (message and channel)
var cbs = findCallbacks(subscriptions, channel);
if (cbs!==undefined) {
cbs.forEach(function(cb) {
if (Object.keys(subscriptions).indexOf(channel)!==-1) {
cb(message.toString());
} else {
cb(message.toString(), channel);
}
});
}
});
return client;
} | javascript | function connectNode (subscriptions, host, clientId) {
// Create client
var url = "tcp://" + host + ":1883";
var client = mqtt_lib.connect(url, {clientId : clientId});
// Register incoming message callback
client.on('message', function(channel, message) {
// Execute all the appropriate callbacks:
// the ones specific to this channel with a single parameter (message)
// the ones associated to a wildcard channel, with two parameters (message and channel)
var cbs = findCallbacks(subscriptions, channel);
if (cbs!==undefined) {
cbs.forEach(function(cb) {
if (Object.keys(subscriptions).indexOf(channel)!==-1) {
cb(message.toString());
} else {
cb(message.toString(), channel);
}
});
}
});
return client;
} | [
"function",
"connectNode",
"(",
"subscriptions",
",",
"host",
",",
"clientId",
")",
"{",
"var",
"url",
"=",
"\"tcp://\"",
"+",
"host",
"+",
"\":1883\"",
";",
"var",
"client",
"=",
"mqtt_lib",
".",
"connect",
"(",
"url",
",",
"{",
"clientId",
":",
"clientId",
"}",
")",
";",
"client",
".",
"on",
"(",
"'message'",
",",
"function",
"(",
"channel",
",",
"message",
")",
"{",
"var",
"cbs",
"=",
"findCallbacks",
"(",
"subscriptions",
",",
"channel",
")",
";",
"if",
"(",
"cbs",
"!==",
"undefined",
")",
"{",
"cbs",
".",
"forEach",
"(",
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"subscriptions",
")",
".",
"indexOf",
"(",
"channel",
")",
"!==",
"-",
"1",
")",
"{",
"cb",
"(",
"message",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"message",
".",
"toString",
"(",
")",
",",
"channel",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"client",
";",
"}"
]
| Helper function that connects the MQTT client in node | [
"Helper",
"function",
"that",
"connects",
"the",
"MQTT",
"client",
"in",
"node"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client.js#L45-L66 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client.js | subscribeNode | function subscribeNode (client, subscriptions, channel, callback, done_callback) {
if (subscriptions[channel]===undefined) {
subscriptions[channel] = [callback];
client.subscribe(channel, {qos: 0}, function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
});
} else {
subscriptions[channel].push(callback);
}
} | javascript | function subscribeNode (client, subscriptions, channel, callback, done_callback) {
if (subscriptions[channel]===undefined) {
subscriptions[channel] = [callback];
client.subscribe(channel, {qos: 0}, function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
});
} else {
subscriptions[channel].push(callback);
}
} | [
"function",
"subscribeNode",
"(",
"client",
",",
"subscriptions",
",",
"channel",
",",
"callback",
",",
"done_callback",
")",
"{",
"if",
"(",
"subscriptions",
"[",
"channel",
"]",
"===",
"undefined",
")",
"{",
"subscriptions",
"[",
"channel",
"]",
"=",
"[",
"callback",
"]",
";",
"client",
".",
"subscribe",
"(",
"channel",
",",
"{",
"qos",
":",
"0",
"}",
",",
"function",
"(",
")",
"{",
"if",
"(",
"done_callback",
"!==",
"undefined",
")",
"done_callback",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"subscriptions",
"[",
"channel",
"]",
".",
"push",
"(",
"callback",
")",
";",
"}",
"}"
]
| Helper function that subscribes to a channel in node | [
"Helper",
"function",
"that",
"subscribes",
"to",
"a",
"channel",
"in",
"node"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client.js#L95-L105 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client.js | function(client, subscriptions, channel, callback, done_callback) {
if (subscriptions[channel]===undefined)
return;
subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1);
if (subscriptions[channel].length===0) {
delete subscriptions[channel];
client.unsubscribe(channel, function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
});
}
} | javascript | function(client, subscriptions, channel, callback, done_callback) {
if (subscriptions[channel]===undefined)
return;
subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1);
if (subscriptions[channel].length===0) {
delete subscriptions[channel];
client.unsubscribe(channel, function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
});
}
} | [
"function",
"(",
"client",
",",
"subscriptions",
",",
"channel",
",",
"callback",
",",
"done_callback",
")",
"{",
"if",
"(",
"subscriptions",
"[",
"channel",
"]",
"===",
"undefined",
")",
"return",
";",
"subscriptions",
"[",
"channel",
"]",
".",
"splice",
"(",
"subscriptions",
"[",
"channel",
"]",
".",
"indexOf",
"(",
"callback",
")",
",",
"1",
")",
";",
"if",
"(",
"subscriptions",
"[",
"channel",
"]",
".",
"length",
"===",
"0",
")",
"{",
"delete",
"subscriptions",
"[",
"channel",
"]",
";",
"client",
".",
"unsubscribe",
"(",
"channel",
",",
"function",
"(",
")",
"{",
"if",
"(",
"done_callback",
"!==",
"undefined",
")",
"done_callback",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Helper function that unsubscribes from a channel in node | [
"Helper",
"function",
"that",
"unsubscribes",
"from",
"a",
"channel",
"in",
"node"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client.js#L123-L134 | train |
|
gristlabs/collect-js-deps | index.js | replaceExt | function replaceExt(fpath, newExt) {
const oldExt = path.extname(fpath);
return _nativeExt.includes(oldExt) ? fpath :
path.join(path.dirname(fpath), path.basename(fpath, oldExt) + newExt);
} | javascript | function replaceExt(fpath, newExt) {
const oldExt = path.extname(fpath);
return _nativeExt.includes(oldExt) ? fpath :
path.join(path.dirname(fpath), path.basename(fpath, oldExt) + newExt);
} | [
"function",
"replaceExt",
"(",
"fpath",
",",
"newExt",
")",
"{",
"const",
"oldExt",
"=",
"path",
".",
"extname",
"(",
"fpath",
")",
";",
"return",
"_nativeExt",
".",
"includes",
"(",
"oldExt",
")",
"?",
"fpath",
":",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"fpath",
")",
",",
"path",
".",
"basename",
"(",
"fpath",
",",
"oldExt",
")",
"+",
"newExt",
")",
";",
"}"
]
| Replaces extension of fpath with newExt unless fpath has a .js or .json extension. | [
"Replaces",
"extension",
"of",
"fpath",
"with",
"newExt",
"unless",
"fpath",
"has",
"a",
".",
"js",
"or",
".",
"json",
"extension",
"."
]
| cc7c58e38acb03b150d260bf1b39f76b9e95e5cc | https://github.com/gristlabs/collect-js-deps/blob/cc7c58e38acb03b150d260bf1b39f76b9e95e5cc/index.js#L14-L18 | train |
gristlabs/collect-js-deps | index.js | main | function main(args) {
return new Promise((resolve, reject) => {
let b = browserifyArgs(['--node', '--no-detect-globals'].concat(args));
let outdir = (b.argv.outdir || b.argv.o);
if (b.argv._[0] === 'help' || b.argv.h || b.argv.help ||
(process.argv.length <= 2 && process.stdin.isTTY)) {
reject(new Error('Usage: collect-js-deps --outdir <path> [--list] ' +
'{BROWSERIFY-OPTIONS} [entry files]'));
return;
}
if (!outdir && !b.argv.list) {
reject(new Error('collect-js-deps requires --outdir (-o) option for output directory, or --list'));
return;
}
collect_js_deps(b, { list: b.argv.list, outdir });
b.bundle((err, body) => err ? reject(err) : resolve());
});
} | javascript | function main(args) {
return new Promise((resolve, reject) => {
let b = browserifyArgs(['--node', '--no-detect-globals'].concat(args));
let outdir = (b.argv.outdir || b.argv.o);
if (b.argv._[0] === 'help' || b.argv.h || b.argv.help ||
(process.argv.length <= 2 && process.stdin.isTTY)) {
reject(new Error('Usage: collect-js-deps --outdir <path> [--list] ' +
'{BROWSERIFY-OPTIONS} [entry files]'));
return;
}
if (!outdir && !b.argv.list) {
reject(new Error('collect-js-deps requires --outdir (-o) option for output directory, or --list'));
return;
}
collect_js_deps(b, { list: b.argv.list, outdir });
b.bundle((err, body) => err ? reject(err) : resolve());
});
} | [
"function",
"main",
"(",
"args",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"b",
"=",
"browserifyArgs",
"(",
"[",
"'--node'",
",",
"'--no-detect-globals'",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"let",
"outdir",
"=",
"(",
"b",
".",
"argv",
".",
"outdir",
"||",
"b",
".",
"argv",
".",
"o",
")",
";",
"if",
"(",
"b",
".",
"argv",
".",
"_",
"[",
"0",
"]",
"===",
"'help'",
"||",
"b",
".",
"argv",
".",
"h",
"||",
"b",
".",
"argv",
".",
"help",
"||",
"(",
"process",
".",
"argv",
".",
"length",
"<=",
"2",
"&&",
"process",
".",
"stdin",
".",
"isTTY",
")",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Usage: collect-js-deps --outdir <path> [--list] '",
"+",
"'{BROWSERIFY-OPTIONS} [entry files]'",
")",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"outdir",
"&&",
"!",
"b",
".",
"argv",
".",
"list",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'collect-js-deps requires --outdir (-o) option for output directory, or --list'",
")",
")",
";",
"return",
";",
"}",
"collect_js_deps",
"(",
"b",
",",
"{",
"list",
":",
"b",
".",
"argv",
".",
"list",
",",
"outdir",
"}",
")",
";",
"b",
".",
"bundle",
"(",
"(",
"err",
",",
"body",
")",
"=>",
"err",
"?",
"reject",
"(",
"err",
")",
":",
"resolve",
"(",
")",
")",
";",
"}",
")",
";",
"}"
]
| Command-line interface to collect_js_deps. Takes an array of arguments as may be passed to
collect-js-deps on the command-line.
@returns Promise resolved on success, rejected on error. | [
"Command",
"-",
"line",
"interface",
"to",
"collect_js_deps",
".",
"Takes",
"an",
"array",
"of",
"arguments",
"as",
"may",
"be",
"passed",
"to",
"collect",
"-",
"js",
"-",
"deps",
"on",
"the",
"command",
"-",
"line",
"."
]
| cc7c58e38acb03b150d260bf1b39f76b9e95e5cc | https://github.com/gristlabs/collect-js-deps/blob/cc7c58e38acb03b150d260bf1b39f76b9e95e5cc/index.js#L108-L125 | train |
char1e5/ot-webdriverjs | chrome.js | createDriver | function createDriver(opt_options, opt_service) {
var service = opt_service || getDefaultService();
var executor = executors.createExecutor(service.start());
var options = opt_options || new Options();
if (opt_options instanceof webdriver.Capabilities) {
// Extract the Chrome-specific options so we do not send unnecessary
// data across the wire.
options = Options.fromCapabilities(options);
}
return webdriver.WebDriver.createSession(
executor, options.toCapabilities());
} | javascript | function createDriver(opt_options, opt_service) {
var service = opt_service || getDefaultService();
var executor = executors.createExecutor(service.start());
var options = opt_options || new Options();
if (opt_options instanceof webdriver.Capabilities) {
// Extract the Chrome-specific options so we do not send unnecessary
// data across the wire.
options = Options.fromCapabilities(options);
}
return webdriver.WebDriver.createSession(
executor, options.toCapabilities());
} | [
"function",
"createDriver",
"(",
"opt_options",
",",
"opt_service",
")",
"{",
"var",
"service",
"=",
"opt_service",
"||",
"getDefaultService",
"(",
")",
";",
"var",
"executor",
"=",
"executors",
".",
"createExecutor",
"(",
"service",
".",
"start",
"(",
")",
")",
";",
"var",
"options",
"=",
"opt_options",
"||",
"new",
"Options",
"(",
")",
";",
"if",
"(",
"opt_options",
"instanceof",
"webdriver",
".",
"Capabilities",
")",
"{",
"options",
"=",
"Options",
".",
"fromCapabilities",
"(",
"options",
")",
";",
"}",
"return",
"webdriver",
".",
"WebDriver",
".",
"createSession",
"(",
"executor",
",",
"options",
".",
"toCapabilities",
"(",
")",
")",
";",
"}"
]
| Creates a new ChromeDriver session.
@param {(webdriver.Capabilities|Options)=} opt_options The session options.
@param {remote.DriverService=} opt_service The session to use; will use
the {@link getDefaultService default service} by default.
@return {!webdriver.WebDriver} A new WebDriver instance. | [
"Creates",
"a",
"new",
"ChromeDriver",
"session",
"."
]
| 5fc8cabcb481602673f1d47cdf544d681c35f784 | https://github.com/char1e5/ot-webdriverjs/blob/5fc8cabcb481602673f1d47cdf544d681c35f784/chrome.js#L449-L462 | train |
mcccclean/node-gamesprites | lib/spritesheet.js | rectshift | function rectshift(a, b) {
if(a.x > b.x + b.width ||
a.x + a.width < b.x ||
a.y > b.y + b.height ||
a.y + a.height < b.y) {
return 0;
} else {
var overlap = b.x + b.width - a.x;
return overlap;
}
} | javascript | function rectshift(a, b) {
if(a.x > b.x + b.width ||
a.x + a.width < b.x ||
a.y > b.y + b.height ||
a.y + a.height < b.y) {
return 0;
} else {
var overlap = b.x + b.width - a.x;
return overlap;
}
} | [
"function",
"rectshift",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"x",
">",
"b",
".",
"x",
"+",
"b",
".",
"width",
"||",
"a",
".",
"x",
"+",
"a",
".",
"width",
"<",
"b",
".",
"x",
"||",
"a",
".",
"y",
">",
"b",
".",
"y",
"+",
"b",
".",
"height",
"||",
"a",
".",
"y",
"+",
"a",
".",
"height",
"<",
"b",
".",
"y",
")",
"{",
"return",
"0",
";",
"}",
"else",
"{",
"var",
"overlap",
"=",
"b",
".",
"x",
"+",
"b",
".",
"width",
"-",
"a",
".",
"x",
";",
"return",
"overlap",
";",
"}",
"}"
]
| see if two rectangles overlap. if so, return the distance that A needs to shift to the right to avoid overlapping. | [
"see",
"if",
"two",
"rectangles",
"overlap",
".",
"if",
"so",
"return",
"the",
"distance",
"that",
"A",
"needs",
"to",
"shift",
"to",
"the",
"right",
"to",
"avoid",
"overlapping",
"."
]
| 9c430065cda394c82f8074b7bf6b07ff807c1431 | https://github.com/mcccclean/node-gamesprites/blob/9c430065cda394c82f8074b7bf6b07ff807c1431/lib/spritesheet.js#L10-L20 | train |
Pocketbrain/native-ads-web-ad-library | src/util/crossDomainStorage.js | function () {
this.isReady = false;
this._requestID = -1;
this._iframe = null;
this._initCallback = null;
this._requests = {};
this._options = {
iframeID: "pm-lib-iframe"
};
} | javascript | function () {
this.isReady = false;
this._requestID = -1;
this._iframe = null;
this._initCallback = null;
this._requests = {};
this._options = {
iframeID: "pm-lib-iframe"
};
} | [
"function",
"(",
")",
"{",
"this",
".",
"isReady",
"=",
"false",
";",
"this",
".",
"_requestID",
"=",
"-",
"1",
";",
"this",
".",
"_iframe",
"=",
"null",
";",
"this",
".",
"_initCallback",
"=",
"null",
";",
"this",
".",
"_requests",
"=",
"{",
"}",
";",
"this",
".",
"_options",
"=",
"{",
"iframeID",
":",
"\"pm-lib-iframe\"",
"}",
";",
"}"
]
| Create a new instance of the CrossDomainStorage object
@constructor | [
"Create",
"a",
"new",
"instance",
"of",
"the",
"CrossDomainStorage",
"object"
]
| aafee1c42e0569ee77f334fc2c4eb71eb146957e | https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/util/crossDomainStorage.js#L29-L39 | train |
|
Schoonology/once-later | later.js | long | function long(callback) {
var called = false
return function cbOnceLater() {
var args
if (called) {
return
}
called = true
args = Array.prototype.slice.call(arguments)
process.nextTick(function () {
callback.apply(null, args)
})
}
} | javascript | function long(callback) {
var called = false
return function cbOnceLater() {
var args
if (called) {
return
}
called = true
args = Array.prototype.slice.call(arguments)
process.nextTick(function () {
callback.apply(null, args)
})
}
} | [
"function",
"long",
"(",
"callback",
")",
"{",
"var",
"called",
"=",
"false",
"return",
"function",
"cbOnceLater",
"(",
")",
"{",
"var",
"args",
"if",
"(",
"called",
")",
"{",
"return",
"}",
"called",
"=",
"true",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"callback",
".",
"apply",
"(",
"null",
",",
"args",
")",
"}",
")",
"}",
"}"
]
| Slower, uncommon version | [
"Slower",
"uncommon",
"version"
]
| 0b2fd2c144d727a71534db32f075491051974c19 | https://github.com/Schoonology/once-later/blob/0b2fd2c144d727a71534db32f075491051974c19/later.js#L5-L22 | train |
Schoonology/once-later | later.js | short | function short(callback) {
var called = false
return function cbOnceLater(err, data) {
if (called) {
return
}
called = true
process.nextTick(function () {
callback(err, data)
})
}
} | javascript | function short(callback) {
var called = false
return function cbOnceLater(err, data) {
if (called) {
return
}
called = true
process.nextTick(function () {
callback(err, data)
})
}
} | [
"function",
"short",
"(",
"callback",
")",
"{",
"var",
"called",
"=",
"false",
"return",
"function",
"cbOnceLater",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"called",
")",
"{",
"return",
"}",
"called",
"=",
"true",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"err",
",",
"data",
")",
"}",
")",
"}",
"}"
]
| Faster, common version | [
"Faster",
"common",
"version"
]
| 0b2fd2c144d727a71534db32f075491051974c19 | https://github.com/Schoonology/once-later/blob/0b2fd2c144d727a71534db32f075491051974c19/later.js#L25-L39 | train |
DmitryMyadzelets/u-machine | index.js | constructor | function constructor(o) {
var f = main.bind(o);
o.current = o.states.initial || o.initial();
o.machine = f;
return f;
} | javascript | function constructor(o) {
var f = main.bind(o);
o.current = o.states.initial || o.initial();
o.machine = f;
return f;
} | [
"function",
"constructor",
"(",
"o",
")",
"{",
"var",
"f",
"=",
"main",
".",
"bind",
"(",
"o",
")",
";",
"o",
".",
"current",
"=",
"o",
".",
"states",
".",
"initial",
"||",
"o",
".",
"initial",
"(",
")",
";",
"o",
".",
"machine",
"=",
"f",
";",
"return",
"f",
";",
"}"
]
| Returns the machine object main function. Sets the initial state as current | [
"Returns",
"the",
"machine",
"object",
"main",
"function",
".",
"Sets",
"the",
"initial",
"state",
"as",
"current"
]
| 1a01636b0211abc148feeda4108383d93368c4c7 | https://github.com/DmitryMyadzelets/u-machine/blob/1a01636b0211abc148feeda4108383d93368c4c7/index.js#L39-L44 | train |
Knorcedger/reqlog | index.js | log | function log(type, label, data) {
var typeLabel = type.charAt(0).toUpperCase() + type.slice(1);
var color;
if (typeLabel === 'Error') {
typeLabel = chalk.red(typeLabel);
color = 'red';
} else if (typeLabel === 'Warn') {
typeLabel = chalk.yellow(typeLabel);
color = 'yellow';
} else if (typeLabel === 'Info') {
typeLabel = chalk.green(typeLabel);
color = 'green';
} else if (typeLabel === 'Log') {
typeLabel = chalk.gray(typeLabel);
color = 'gray';
}
// used to avoid logging "undefined" in the console
if (useTypeLabels) {
label = typeLabel + ': ' + chalk.cyan(label);
} else {
label = chalk[color](label);
}
if (data) {
console[type](label, data);
} else {
console[type](label);
}
} | javascript | function log(type, label, data) {
var typeLabel = type.charAt(0).toUpperCase() + type.slice(1);
var color;
if (typeLabel === 'Error') {
typeLabel = chalk.red(typeLabel);
color = 'red';
} else if (typeLabel === 'Warn') {
typeLabel = chalk.yellow(typeLabel);
color = 'yellow';
} else if (typeLabel === 'Info') {
typeLabel = chalk.green(typeLabel);
color = 'green';
} else if (typeLabel === 'Log') {
typeLabel = chalk.gray(typeLabel);
color = 'gray';
}
// used to avoid logging "undefined" in the console
if (useTypeLabels) {
label = typeLabel + ': ' + chalk.cyan(label);
} else {
label = chalk[color](label);
}
if (data) {
console[type](label, data);
} else {
console[type](label);
}
} | [
"function",
"log",
"(",
"type",
",",
"label",
",",
"data",
")",
"{",
"var",
"typeLabel",
"=",
"type",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"type",
".",
"slice",
"(",
"1",
")",
";",
"var",
"color",
";",
"if",
"(",
"typeLabel",
"===",
"'Error'",
")",
"{",
"typeLabel",
"=",
"chalk",
".",
"red",
"(",
"typeLabel",
")",
";",
"color",
"=",
"'red'",
";",
"}",
"else",
"if",
"(",
"typeLabel",
"===",
"'Warn'",
")",
"{",
"typeLabel",
"=",
"chalk",
".",
"yellow",
"(",
"typeLabel",
")",
";",
"color",
"=",
"'yellow'",
";",
"}",
"else",
"if",
"(",
"typeLabel",
"===",
"'Info'",
")",
"{",
"typeLabel",
"=",
"chalk",
".",
"green",
"(",
"typeLabel",
")",
";",
"color",
"=",
"'green'",
";",
"}",
"else",
"if",
"(",
"typeLabel",
"===",
"'Log'",
")",
"{",
"typeLabel",
"=",
"chalk",
".",
"gray",
"(",
"typeLabel",
")",
";",
"color",
"=",
"'gray'",
";",
"}",
"if",
"(",
"useTypeLabels",
")",
"{",
"label",
"=",
"typeLabel",
"+",
"': '",
"+",
"chalk",
".",
"cyan",
"(",
"label",
")",
";",
"}",
"else",
"{",
"label",
"=",
"chalk",
"[",
"color",
"]",
"(",
"label",
")",
";",
"}",
"if",
"(",
"data",
")",
"{",
"console",
"[",
"type",
"]",
"(",
"label",
",",
"data",
")",
";",
"}",
"else",
"{",
"console",
"[",
"type",
"]",
"(",
"label",
")",
";",
"}",
"}"
]
| Beutifies the log data and logs!
@method log
@param {string} type The log type
@param {string} label The log label
@param {any} data The data to display next to the label (optional) | [
"Beutifies",
"the",
"log",
"data",
"and",
"logs!"
]
| feb9d7faef81f384aa7d60183211c54fe6af3ee6 | https://github.com/Knorcedger/reqlog/blob/feb9d7faef81f384aa7d60183211c54fe6af3ee6/index.js#L14-L43 | train |
antonycourtney/tabli-core | lib/js/actions.js | syncChromeWindowById | function syncChromeWindowById(windowId, cb) {
chrome.windows.get(windowId, { populate: true }, function (chromeWindow) {
cb(function (state) {
return state.syncChromeWindow(chromeWindow);
});
});
} | javascript | function syncChromeWindowById(windowId, cb) {
chrome.windows.get(windowId, { populate: true }, function (chromeWindow) {
cb(function (state) {
return state.syncChromeWindow(chromeWindow);
});
});
} | [
"function",
"syncChromeWindowById",
"(",
"windowId",
",",
"cb",
")",
"{",
"chrome",
".",
"windows",
".",
"get",
"(",
"windowId",
",",
"{",
"populate",
":",
"true",
"}",
",",
"function",
"(",
"chromeWindow",
")",
"{",
"cb",
"(",
"function",
"(",
"state",
")",
"{",
"return",
"state",
".",
"syncChromeWindow",
"(",
"chromeWindow",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| sync a single Chrome window by its Chrome window id
@param {function} cb -- callback to update state | [
"sync",
"a",
"single",
"Chrome",
"window",
"by",
"its",
"Chrome",
"window",
"id"
]
| 76cc540891421bc6c8bdcf00f277ebb6e716fdd9 | https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/actions.js#L36-L42 | train |
PrinceNebulon/github-api-promise | src/issues/comments.js | function(owner, repo, params) {
return req.standardRequest(`${config.host}/repos/${owner}/${repo}/issues/comments?${req.assembleQueryParams(params,
['sort', 'direction', 'since'])}`);
} | javascript | function(owner, repo, params) {
return req.standardRequest(`${config.host}/repos/${owner}/${repo}/issues/comments?${req.assembleQueryParams(params,
['sort', 'direction', 'since'])}`);
} | [
"function",
"(",
"owner",
",",
"repo",
",",
"params",
")",
"{",
"return",
"req",
".",
"standardRequest",
"(",
"`",
"${",
"config",
".",
"host",
"}",
"${",
"owner",
"}",
"${",
"repo",
"}",
"${",
"req",
".",
"assembleQueryParams",
"(",
"params",
",",
"[",
"'sort'",
",",
"'direction'",
",",
"'since'",
"]",
")",
"}",
"`",
")",
";",
"}"
]
| List comments in a repository
By default, Issue Comments are ordered by ascending ID.
@see {@link https://developer.github.com/v3/issues/comments/#list-comments-in-a-repository}
@param {string} owner - The repo's owner
@param {string} repo - The repo's name
@param {object} params - An object of parameters for the request
@param {int} params.sort - Either created or updated. Default: created
@param {int} params.direction - Either asc or desc. Ignored without the sort parameter.
@param {int} params.since - Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
@return {object} Comment data | [
"List",
"comments",
"in",
"a",
"repository",
"By",
"default",
"Issue",
"Comments",
"are",
"ordered",
"by",
"ascending",
"ID",
"."
]
| 990cb2cce19b53f54d9243002fde47428f24e7cc | https://github.com/PrinceNebulon/github-api-promise/blob/990cb2cce19b53f54d9243002fde47428f24e7cc/src/issues/comments.js#L45-L48 | train |
|
PrinceNebulon/github-api-promise | src/issues/comments.js | function(owner, repo, id) {
return req.standardRequest(`${config.host}/repos/${owner}/${repo}/issues/comments/${id}`);
} | javascript | function(owner, repo, id) {
return req.standardRequest(`${config.host}/repos/${owner}/${repo}/issues/comments/${id}`);
} | [
"function",
"(",
"owner",
",",
"repo",
",",
"id",
")",
"{",
"return",
"req",
".",
"standardRequest",
"(",
"`",
"${",
"config",
".",
"host",
"}",
"${",
"owner",
"}",
"${",
"repo",
"}",
"${",
"id",
"}",
"`",
")",
";",
"}"
]
| Get a single comment
@see {@link https://developer.github.com/v3/issues/comments/#get-a-single-comment}
@param {string} owner - The repo's owner
@param {string} repo - The repo's name
@param {string} id - The comment id
@return {object} Comment data | [
"Get",
"a",
"single",
"comment"
]
| 990cb2cce19b53f54d9243002fde47428f24e7cc | https://github.com/PrinceNebulon/github-api-promise/blob/990cb2cce19b53f54d9243002fde47428f24e7cc/src/issues/comments.js#L61-L63 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.