id
int32 0
58k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
37,700 |
jhermsmeier/node-udif
|
lib/blockmap.js
|
function( buffer, offset ) {
offset = offset || 0
this.signature = buffer.readUInt32BE( offset + 0 )
if( this.signature !== BlockMap.signature ) {
var expected = BlockMap.signature.toString(16)
var actual = this.signature.toString(16)
throw new Error( `Invalid block map signature: Expected 0x${expected}, saw 0x${actual}` )
}
this.version = buffer.readUInt32BE( offset + 4 )
this.sectorNumber = uint64.readBE( buffer, offset + 8, 8 )
this.sectorCount = uint64.readBE( buffer, offset + 16, 8 )
this.dataOffset = uint64.readBE( buffer, offset + 24, 8 )
this.buffersNeeded = buffer.readUInt32BE( offset + 32 )
this.blockDescriptorCount = buffer.readUInt32BE( offset + 36 )
this.reserved1 = buffer.readUInt32BE( offset + 40 )
this.reserved2 = buffer.readUInt32BE( offset + 44 )
this.reserved3 = buffer.readUInt32BE( offset + 48 )
this.reserved4 = buffer.readUInt32BE( offset + 52 )
this.reserved5 = buffer.readUInt32BE( offset + 56 )
this.reserved6 = buffer.readUInt32BE( offset + 60 )
this.checksum.parse( buffer, offset + 64 )
this.blockCount = buffer.readUInt32BE( offset + 200 )
this.blocks = []
for( var i = 0; i < this.blockCount; i++ ) {
this.blocks.push(
BlockMap.Block.parse( buffer, offset + 204 + ( i * 40 ) )
)
}
return this
}
|
javascript
|
function( buffer, offset ) {
offset = offset || 0
this.signature = buffer.readUInt32BE( offset + 0 )
if( this.signature !== BlockMap.signature ) {
var expected = BlockMap.signature.toString(16)
var actual = this.signature.toString(16)
throw new Error( `Invalid block map signature: Expected 0x${expected}, saw 0x${actual}` )
}
this.version = buffer.readUInt32BE( offset + 4 )
this.sectorNumber = uint64.readBE( buffer, offset + 8, 8 )
this.sectorCount = uint64.readBE( buffer, offset + 16, 8 )
this.dataOffset = uint64.readBE( buffer, offset + 24, 8 )
this.buffersNeeded = buffer.readUInt32BE( offset + 32 )
this.blockDescriptorCount = buffer.readUInt32BE( offset + 36 )
this.reserved1 = buffer.readUInt32BE( offset + 40 )
this.reserved2 = buffer.readUInt32BE( offset + 44 )
this.reserved3 = buffer.readUInt32BE( offset + 48 )
this.reserved4 = buffer.readUInt32BE( offset + 52 )
this.reserved5 = buffer.readUInt32BE( offset + 56 )
this.reserved6 = buffer.readUInt32BE( offset + 60 )
this.checksum.parse( buffer, offset + 64 )
this.blockCount = buffer.readUInt32BE( offset + 200 )
this.blocks = []
for( var i = 0; i < this.blockCount; i++ ) {
this.blocks.push(
BlockMap.Block.parse( buffer, offset + 204 + ( i * 40 ) )
)
}
return this
}
|
[
"function",
"(",
"buffer",
",",
"offset",
")",
"{",
"offset",
"=",
"offset",
"||",
"0",
"this",
".",
"signature",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"0",
")",
"if",
"(",
"this",
".",
"signature",
"!==",
"BlockMap",
".",
"signature",
")",
"{",
"var",
"expected",
"=",
"BlockMap",
".",
"signature",
".",
"toString",
"(",
"16",
")",
"var",
"actual",
"=",
"this",
".",
"signature",
".",
"toString",
"(",
"16",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"expected",
"}",
"${",
"actual",
"}",
"`",
")",
"}",
"this",
".",
"version",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"4",
")",
"this",
".",
"sectorNumber",
"=",
"uint64",
".",
"readBE",
"(",
"buffer",
",",
"offset",
"+",
"8",
",",
"8",
")",
"this",
".",
"sectorCount",
"=",
"uint64",
".",
"readBE",
"(",
"buffer",
",",
"offset",
"+",
"16",
",",
"8",
")",
"this",
".",
"dataOffset",
"=",
"uint64",
".",
"readBE",
"(",
"buffer",
",",
"offset",
"+",
"24",
",",
"8",
")",
"this",
".",
"buffersNeeded",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"32",
")",
"this",
".",
"blockDescriptorCount",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"36",
")",
"this",
".",
"reserved1",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"40",
")",
"this",
".",
"reserved2",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"44",
")",
"this",
".",
"reserved3",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"48",
")",
"this",
".",
"reserved4",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"52",
")",
"this",
".",
"reserved5",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"56",
")",
"this",
".",
"reserved6",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"60",
")",
"this",
".",
"checksum",
".",
"parse",
"(",
"buffer",
",",
"offset",
"+",
"64",
")",
"this",
".",
"blockCount",
"=",
"buffer",
".",
"readUInt32BE",
"(",
"offset",
"+",
"200",
")",
"this",
".",
"blocks",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"blockCount",
";",
"i",
"++",
")",
"{",
"this",
".",
"blocks",
".",
"push",
"(",
"BlockMap",
".",
"Block",
".",
"parse",
"(",
"buffer",
",",
"offset",
"+",
"204",
"+",
"(",
"i",
"*",
"40",
")",
")",
")",
"}",
"return",
"this",
"}"
] |
Parse BlockMap data from a buffer
@param {Buffer} buffer
@param {Number} [offset=0]
@returns {BlockMap}
|
[
"Parse",
"BlockMap",
"data",
"from",
"a",
"buffer"
] |
1f5ee84d617e8ebafc8740aec0a734602a1e8b13
|
https://github.com/jhermsmeier/node-udif/blob/1f5ee84d617e8ebafc8740aec0a734602a1e8b13/lib/blockmap.js#L73-L109
|
|
37,701 |
bholloway/persistent-cache-webpack-plugin
|
lib/encode.js
|
encode
|
function encode(object, path, exclusions) {
var failed = [],
result = {};
// ensure valid path and exclusions
path = path || [];
exclusions = exclusions || [];
// enumerable properties
for (var key in object) {
var value = object[key];
// objects
if (value && (typeof value === 'object') && (exclusions.indexOf(value) < 0)) {
var className = classes.getName(value),
analysis = /function ([^\(]+)\(/.exec(Function.prototype.toString.call(value.constructor)),
qualifiedName = ((key.length < 60) ? key : key.slice(0, 30) + '...' + key.slice(-30)) +
':' +
(className ? className.split(/[\\\/]/).pop().split('.').shift() :
(analysis && analysis[1] || Object.prototype.toString.apply(value).slice(8, -1))),
propPath = path.concat(qualifiedName);
// add to exclusions before recursing
exclusions.push(value);
// depth first
var recursed = encode(value, propPath, exclusions);
// propagate failures but don't keep them in the tree
if (recursed.$failed) {
failed.push.apply(failed, recursed.$failed);
delete recursed.$failed;
}
// exclude deleted fields
if (recursed.$deleted) {
failed.push(['read-only-prop ' + qualifiedName + '.' + recursed.$deleted]
.concat(propPath)
.concat(recursed.$deleted));
}
// encode recognised class
else if (className) {
result[key] = {
$class: className,
$props: recursed
};
}
// include otherwise
else {
// unrecognised custom class
if (!isPlainObject(value) && !Array.isArray(value)) {
failed.push(['unknown-custom-class ' + qualifiedName].concat(propPath));
}
// default to plain object
result[key] = recursed;
}
}
// include non-objects
else {
result[key] = value;
}
}
// mark failures
if (failed.length) {
result.$failed = failed;
}
// complete
return result;
}
|
javascript
|
function encode(object, path, exclusions) {
var failed = [],
result = {};
// ensure valid path and exclusions
path = path || [];
exclusions = exclusions || [];
// enumerable properties
for (var key in object) {
var value = object[key];
// objects
if (value && (typeof value === 'object') && (exclusions.indexOf(value) < 0)) {
var className = classes.getName(value),
analysis = /function ([^\(]+)\(/.exec(Function.prototype.toString.call(value.constructor)),
qualifiedName = ((key.length < 60) ? key : key.slice(0, 30) + '...' + key.slice(-30)) +
':' +
(className ? className.split(/[\\\/]/).pop().split('.').shift() :
(analysis && analysis[1] || Object.prototype.toString.apply(value).slice(8, -1))),
propPath = path.concat(qualifiedName);
// add to exclusions before recursing
exclusions.push(value);
// depth first
var recursed = encode(value, propPath, exclusions);
// propagate failures but don't keep them in the tree
if (recursed.$failed) {
failed.push.apply(failed, recursed.$failed);
delete recursed.$failed;
}
// exclude deleted fields
if (recursed.$deleted) {
failed.push(['read-only-prop ' + qualifiedName + '.' + recursed.$deleted]
.concat(propPath)
.concat(recursed.$deleted));
}
// encode recognised class
else if (className) {
result[key] = {
$class: className,
$props: recursed
};
}
// include otherwise
else {
// unrecognised custom class
if (!isPlainObject(value) && !Array.isArray(value)) {
failed.push(['unknown-custom-class ' + qualifiedName].concat(propPath));
}
// default to plain object
result[key] = recursed;
}
}
// include non-objects
else {
result[key] = value;
}
}
// mark failures
if (failed.length) {
result.$failed = failed;
}
// complete
return result;
}
|
[
"function",
"encode",
"(",
"object",
",",
"path",
",",
"exclusions",
")",
"{",
"var",
"failed",
"=",
"[",
"]",
",",
"result",
"=",
"{",
"}",
";",
"// ensure valid path and exclusions",
"path",
"=",
"path",
"||",
"[",
"]",
";",
"exclusions",
"=",
"exclusions",
"||",
"[",
"]",
";",
"// enumerable properties",
"for",
"(",
"var",
"key",
"in",
"object",
")",
"{",
"var",
"value",
"=",
"object",
"[",
"key",
"]",
";",
"// objects",
"if",
"(",
"value",
"&&",
"(",
"typeof",
"value",
"===",
"'object'",
")",
"&&",
"(",
"exclusions",
".",
"indexOf",
"(",
"value",
")",
"<",
"0",
")",
")",
"{",
"var",
"className",
"=",
"classes",
".",
"getName",
"(",
"value",
")",
",",
"analysis",
"=",
"/",
"function ([^\\(]+)\\(",
"/",
".",
"exec",
"(",
"Function",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"value",
".",
"constructor",
")",
")",
",",
"qualifiedName",
"=",
"(",
"(",
"key",
".",
"length",
"<",
"60",
")",
"?",
"key",
":",
"key",
".",
"slice",
"(",
"0",
",",
"30",
")",
"+",
"'...'",
"+",
"key",
".",
"slice",
"(",
"-",
"30",
")",
")",
"+",
"':'",
"+",
"(",
"className",
"?",
"className",
".",
"split",
"(",
"/",
"[\\\\\\/]",
"/",
")",
".",
"pop",
"(",
")",
".",
"split",
"(",
"'.'",
")",
".",
"shift",
"(",
")",
":",
"(",
"analysis",
"&&",
"analysis",
"[",
"1",
"]",
"||",
"Object",
".",
"prototype",
".",
"toString",
".",
"apply",
"(",
"value",
")",
".",
"slice",
"(",
"8",
",",
"-",
"1",
")",
")",
")",
",",
"propPath",
"=",
"path",
".",
"concat",
"(",
"qualifiedName",
")",
";",
"// add to exclusions before recursing",
"exclusions",
".",
"push",
"(",
"value",
")",
";",
"// depth first",
"var",
"recursed",
"=",
"encode",
"(",
"value",
",",
"propPath",
",",
"exclusions",
")",
";",
"// propagate failures but don't keep them in the tree",
"if",
"(",
"recursed",
".",
"$failed",
")",
"{",
"failed",
".",
"push",
".",
"apply",
"(",
"failed",
",",
"recursed",
".",
"$failed",
")",
";",
"delete",
"recursed",
".",
"$failed",
";",
"}",
"// exclude deleted fields",
"if",
"(",
"recursed",
".",
"$deleted",
")",
"{",
"failed",
".",
"push",
"(",
"[",
"'read-only-prop '",
"+",
"qualifiedName",
"+",
"'.'",
"+",
"recursed",
".",
"$deleted",
"]",
".",
"concat",
"(",
"propPath",
")",
".",
"concat",
"(",
"recursed",
".",
"$deleted",
")",
")",
";",
"}",
"// encode recognised class",
"else",
"if",
"(",
"className",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"{",
"$class",
":",
"className",
",",
"$props",
":",
"recursed",
"}",
";",
"}",
"// include otherwise",
"else",
"{",
"// unrecognised custom class",
"if",
"(",
"!",
"isPlainObject",
"(",
"value",
")",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"failed",
".",
"push",
"(",
"[",
"'unknown-custom-class '",
"+",
"qualifiedName",
"]",
".",
"concat",
"(",
"propPath",
")",
")",
";",
"}",
"// default to plain object",
"result",
"[",
"key",
"]",
"=",
"recursed",
";",
"}",
"}",
"// include non-objects",
"else",
"{",
"result",
"[",
"key",
"]",
"=",
"value",
";",
"}",
"}",
"// mark failures",
"if",
"(",
"failed",
".",
"length",
")",
"{",
"result",
".",
"$failed",
"=",
"failed",
";",
"}",
"// complete",
"return",
"result",
";",
"}"
] |
Encode the given acyclic object with class information.
@param {object} object The object to encode
@param {Array.<string>} [path] Optional path information for the object where it is nested in another object
@param {Array.<object>} [exclusions] Optional object list to detect circular references
@returns {object} An acyclic object with additional encoded inforation
|
[
"Encode",
"the",
"given",
"acyclic",
"object",
"with",
"class",
"information",
"."
] |
bd5aec58b1b38477218dcdc0fb144c6981604fa8
|
https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/encode.js#L14-L86
|
37,702 |
openbiz/openbiz
|
lib/routers/ModelRouter.js
|
function(routePrefix, modelController, permission){
var routes = {};
/** if the given controller is not an instance of openbiz ModelController we will not generate it */
if(modelController instanceof openbiz.ModelController){
routes["post "+routePrefix] = [modelController.create];
routes["get "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create];
routes["put "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create];
routes["delete "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create];
/** if preset a permission , then unshift a middle-ware to all routes */
if(typeof permission != 'undefined')
{
var permissionMiddleware = openbiz.ensurePermission(permission);
for(var route in routes)
{
routes[route].unshift(permissionMiddleware);
}
}
}
return routes;
}
|
javascript
|
function(routePrefix, modelController, permission){
var routes = {};
/** if the given controller is not an instance of openbiz ModelController we will not generate it */
if(modelController instanceof openbiz.ModelController){
routes["post "+routePrefix] = [modelController.create];
routes["get "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create];
routes["put "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create];
routes["delete "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create];
/** if preset a permission , then unshift a middle-ware to all routes */
if(typeof permission != 'undefined')
{
var permissionMiddleware = openbiz.ensurePermission(permission);
for(var route in routes)
{
routes[route].unshift(permissionMiddleware);
}
}
}
return routes;
}
|
[
"function",
"(",
"routePrefix",
",",
"modelController",
",",
"permission",
")",
"{",
"var",
"routes",
"=",
"{",
"}",
";",
"/** if the given controller is not an instance of openbiz ModelController we will not generate it */",
"if",
"(",
"modelController",
"instanceof",
"openbiz",
".",
"ModelController",
")",
"{",
"routes",
"[",
"\"post \"",
"+",
"routePrefix",
"]",
"=",
"[",
"modelController",
".",
"create",
"]",
";",
"routes",
"[",
"\"get \"",
"+",
"routePrefix",
"+",
"\"/:id\"",
"]",
"=",
"[",
"modelController",
".",
"exsureExists",
",",
"modelController",
".",
"create",
"]",
";",
"routes",
"[",
"\"put \"",
"+",
"routePrefix",
"+",
"\"/:id\"",
"]",
"=",
"[",
"modelController",
".",
"exsureExists",
",",
"modelController",
".",
"create",
"]",
";",
"routes",
"[",
"\"delete \"",
"+",
"routePrefix",
"+",
"\"/:id\"",
"]",
"=",
"[",
"modelController",
".",
"exsureExists",
",",
"modelController",
".",
"create",
"]",
";",
"/** if preset a permission , then unshift a middle-ware to all routes */",
"if",
"(",
"typeof",
"permission",
"!=",
"'undefined'",
")",
"{",
"var",
"permissionMiddleware",
"=",
"openbiz",
".",
"ensurePermission",
"(",
"permission",
")",
";",
"for",
"(",
"var",
"route",
"in",
"routes",
")",
"{",
"routes",
"[",
"route",
"]",
".",
"unshift",
"(",
"permissionMiddleware",
")",
";",
"}",
"}",
"}",
"return",
"routes",
";",
"}"
] |
Generate default routes for standard data modal
@static
@memberof openbiz.routers.ModelRouter
@param {string} routePrefix - the route name of this resource
@param {openbiz.controllers.ModelController} modelController - the controller which map this route to
@param {string} [permission] - the permission which default to protect this resource
@return {object} Route rules object
@example
//inside a module router e.g. /cubi/routes/account.js
var routes = openbiz.ModelRouter.getDefaultRoutes('/accounts', openbiz.getController(cubi.account.AccountCountroller), 'cubi-account-manage');
module.exports = routes;
// routes entity will looks like below:
// {
// "post /accounts" : [ openbiz.ensurePermission("cubi-account-manage"),
// openbiz.getController("cubi.account.AccountController").create],
//
// "get /accounts/:id" : [ openbiz.ensurePermission("cubi-account-manage"),
// openbiz.getController("cubi.account.AccountController").ensureExists,
// openbiz.getController("cubi.account.AccountController").findById],
//
// "put /accounts/:id" : [ openbiz.ensurePermission("cubi-account-manage"),
// openbiz.getController("cubi.account.AccountController").ensureExists,
// openbiz.getController("cubi.account.AccountController").update],
//
// "delete /accounts/:id" : [ openbiz.ensurePermission("cubi-account-manage"),
// openbiz.getController("cubi.account.AccountController").ensureExists,
// openbiz.getController("cubi.account.AccountController").delete],
// }
|
[
"Generate",
"default",
"routes",
"for",
"standard",
"data",
"modal"
] |
997f1398396683d7ad667b1b360ce74c7c7fcf6f
|
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/routers/ModelRouter.js#L42-L62
|
|
37,703 |
harvest-platform/harvest-api-client
|
src/client.js
|
parseLinks
|
function parseLinks(target, resp) {
target._links = parseLinkHeader(resp.headers.get('link'));
target._linkTemplates = parseLinkHeader(resp.headers.get('link-template'));
return resp
}
|
javascript
|
function parseLinks(target, resp) {
target._links = parseLinkHeader(resp.headers.get('link'));
target._linkTemplates = parseLinkHeader(resp.headers.get('link-template'));
return resp
}
|
[
"function",
"parseLinks",
"(",
"target",
",",
"resp",
")",
"{",
"target",
".",
"_links",
"=",
"parseLinkHeader",
"(",
"resp",
".",
"headers",
".",
"get",
"(",
"'link'",
")",
")",
";",
"target",
".",
"_linkTemplates",
"=",
"parseLinkHeader",
"(",
"resp",
".",
"headers",
".",
"get",
"(",
"'link-template'",
")",
")",
";",
"return",
"resp",
"}"
] |
Parse Link and Link-Template headers and set them on the target.
|
[
"Parse",
"Link",
"and",
"Link",
"-",
"Template",
"headers",
"and",
"set",
"them",
"on",
"the",
"target",
"."
] |
ff5af21f446cd68c69e005c9a5911faad353fb63
|
https://github.com/harvest-platform/harvest-api-client/blob/ff5af21f446cd68c69e005c9a5911faad353fb63/src/client.js#L13-L17
|
37,704 |
harvest-platform/harvest-api-client
|
src/client.js
|
throwStatusError
|
function throwStatusError(resp) {
let err = new Error(resp.statusText || 'http error: ' + resp.status);
err.type = resp.status;
err.response = resp;
err.url = resp.url;
throw err;
}
|
javascript
|
function throwStatusError(resp) {
let err = new Error(resp.statusText || 'http error: ' + resp.status);
err.type = resp.status;
err.response = resp;
err.url = resp.url;
throw err;
}
|
[
"function",
"throwStatusError",
"(",
"resp",
")",
"{",
"let",
"err",
"=",
"new",
"Error",
"(",
"resp",
".",
"statusText",
"||",
"'http error: '",
"+",
"resp",
".",
"status",
")",
";",
"err",
".",
"type",
"=",
"resp",
".",
"status",
";",
"err",
".",
"response",
"=",
"resp",
";",
"err",
".",
"url",
"=",
"resp",
".",
"url",
";",
"throw",
"err",
";",
"}"
] |
Constructs and throws a response status error.
|
[
"Constructs",
"and",
"throws",
"a",
"response",
"status",
"error",
"."
] |
ff5af21f446cd68c69e005c9a5911faad353fb63
|
https://github.com/harvest-platform/harvest-api-client/blob/ff5af21f446cd68c69e005c9a5911faad353fb63/src/client.js#L24-L30
|
37,705 |
harvest-platform/harvest-api-client
|
src/client.js
|
throwTimeoutError
|
function throwTimeoutError(resp) {
let err = new Error('timeout');
err.type = 'timeout';
err.response = resp;
err.url = resp.url;
throw err;
}
|
javascript
|
function throwTimeoutError(resp) {
let err = new Error('timeout');
err.type = 'timeout';
err.response = resp;
err.url = resp.url;
throw err;
}
|
[
"function",
"throwTimeoutError",
"(",
"resp",
")",
"{",
"let",
"err",
"=",
"new",
"Error",
"(",
"'timeout'",
")",
";",
"err",
".",
"type",
"=",
"'timeout'",
";",
"err",
".",
"response",
"=",
"resp",
";",
"err",
".",
"url",
"=",
"resp",
".",
"url",
";",
"throw",
"err",
";",
"}"
] |
Constructs and throws a timeout-based error.
|
[
"Constructs",
"and",
"throws",
"a",
"timeout",
"-",
"based",
"error",
"."
] |
ff5af21f446cd68c69e005c9a5911faad353fb63
|
https://github.com/harvest-platform/harvest-api-client/blob/ff5af21f446cd68c69e005c9a5911faad353fb63/src/client.js#L33-L39
|
37,706 |
LaunchPadLab/lp-redux-api
|
src/handlers/set-on-response.js
|
setOnResponse
|
function setOnResponse (
successPath,
failurePath,
transformSuccess=getDataFromAction,
transformFailure=getDataFromAction,
) {
return handleResponse(
(state, action) => set(successPath, transformSuccess(action, state), state),
(state, action) => set(failurePath, transformFailure(action, state), state),
)
}
|
javascript
|
function setOnResponse (
successPath,
failurePath,
transformSuccess=getDataFromAction,
transformFailure=getDataFromAction,
) {
return handleResponse(
(state, action) => set(successPath, transformSuccess(action, state), state),
(state, action) => set(failurePath, transformFailure(action, state), state),
)
}
|
[
"function",
"setOnResponse",
"(",
"successPath",
",",
"failurePath",
",",
"transformSuccess",
"=",
"getDataFromAction",
",",
"transformFailure",
"=",
"getDataFromAction",
",",
")",
"{",
"return",
"handleResponse",
"(",
"(",
"state",
",",
"action",
")",
"=>",
"set",
"(",
"successPath",
",",
"transformSuccess",
"(",
"action",
",",
"state",
")",
",",
"state",
")",
",",
"(",
"state",
",",
"action",
")",
"=>",
"set",
"(",
"failurePath",
",",
"transformFailure",
"(",
"action",
",",
"state",
")",
",",
"state",
")",
",",
")",
"}"
] |
A function that creates an API action handler that sets one of two given paths in the state with the returned data depending on whether a request succeeds or fails.
@name setOnResponse
@param {String} path - The path in the state to set with the returned data on success
@param {String} path - The path in the state to set with the returned error on failure
@param {Function} [transform] - A function that determines the success data that is set in the state. Passed `action` and `state` params.
@param {Function} [transform] - A function that determines the error data that is set in the state. Passed `action` and `state` params.
@returns {Function} An action handler
@example
handleActions({
// This will do the same thing as the example for handleResponse
[apiActions.fetchUser]: setOnResponse('currentUser', 'userFetchError')
})
|
[
"A",
"function",
"that",
"creates",
"an",
"API",
"action",
"handler",
"that",
"sets",
"one",
"of",
"two",
"given",
"paths",
"in",
"the",
"state",
"with",
"the",
"returned",
"data",
"depending",
"on",
"whether",
"a",
"request",
"succeeds",
"or",
"fails",
"."
] |
73eee231067365326780ddc1dbbfa50d3e65defc
|
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/set-on-response.js#L23-L33
|
37,707 |
junghans-schneider/extjs-dependencies
|
lib/resolver.js
|
function(rootPath, filePath, encoding) {
return fs.readFileSync(path.resolve(rootPath, filePath), encoding || 'utf8');
}
|
javascript
|
function(rootPath, filePath, encoding) {
return fs.readFileSync(path.resolve(rootPath, filePath), encoding || 'utf8');
}
|
[
"function",
"(",
"rootPath",
",",
"filePath",
",",
"encoding",
")",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"resolve",
"(",
"rootPath",
",",
"filePath",
")",
",",
"encoding",
"||",
"'utf8'",
")",
";",
"}"
] |
Returns an object representing the content of a file.
@param rootPath {string} the root path of the project
@param filePath {string} the path of the file (relative to rootPath)
@param encoding {string?} the encoding to use (is null if a default should be used)
@return {object} an object representing the content.
|
[
"Returns",
"an",
"object",
"representing",
"the",
"content",
"of",
"a",
"file",
"."
] |
be36e87339b0973883c490fe2535414e74b1413b
|
https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/resolver.js#L25-L27
|
|
37,708 |
junghans-schneider/extjs-dependencies
|
lib/resolver.js
|
resolve
|
function resolve(options) {
options = extend({
root: '.',
fileProvider: defaultFileProvider
}, options);
var context = {
options: options,
parser: new Parser({
excludeClasses: options.excludeClasses,
skipParse: options.skipParse,
extraDependencies: options.extraDependencies,
parserOptions: options.parserOptions
}),
classNameByAlias: {}, // maps alias className (String) to its real className (String)
providedFileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for provided files
fileInfoByPath: {}, // maps filePath (String) to fileInfo (ExtClass) for files to include
fileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for files to include
fileInfos: []
};
var providedOption = options.provided;
if (providedOption) {
toArray(providedOption).forEach(function(path) {
markProvided(path, context)
});
}
toArray(options.entry).forEach(function(path) {
collectDependencies(path, context)
});
return orderFileInfo(context);
}
|
javascript
|
function resolve(options) {
options = extend({
root: '.',
fileProvider: defaultFileProvider
}, options);
var context = {
options: options,
parser: new Parser({
excludeClasses: options.excludeClasses,
skipParse: options.skipParse,
extraDependencies: options.extraDependencies,
parserOptions: options.parserOptions
}),
classNameByAlias: {}, // maps alias className (String) to its real className (String)
providedFileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for provided files
fileInfoByPath: {}, // maps filePath (String) to fileInfo (ExtClass) for files to include
fileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for files to include
fileInfos: []
};
var providedOption = options.provided;
if (providedOption) {
toArray(providedOption).forEach(function(path) {
markProvided(path, context)
});
}
toArray(options.entry).forEach(function(path) {
collectDependencies(path, context)
});
return orderFileInfo(context);
}
|
[
"function",
"resolve",
"(",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"root",
":",
"'.'",
",",
"fileProvider",
":",
"defaultFileProvider",
"}",
",",
"options",
")",
";",
"var",
"context",
"=",
"{",
"options",
":",
"options",
",",
"parser",
":",
"new",
"Parser",
"(",
"{",
"excludeClasses",
":",
"options",
".",
"excludeClasses",
",",
"skipParse",
":",
"options",
".",
"skipParse",
",",
"extraDependencies",
":",
"options",
".",
"extraDependencies",
",",
"parserOptions",
":",
"options",
".",
"parserOptions",
"}",
")",
",",
"classNameByAlias",
":",
"{",
"}",
",",
"// maps alias className (String) to its real className (String)",
"providedFileInfoByClassName",
":",
"{",
"}",
",",
"// maps className (String) to fileInfo (ExtClass) for provided files",
"fileInfoByPath",
":",
"{",
"}",
",",
"// maps filePath (String) to fileInfo (ExtClass) for files to include",
"fileInfoByClassName",
":",
"{",
"}",
",",
"// maps className (String) to fileInfo (ExtClass) for files to include",
"fileInfos",
":",
"[",
"]",
"}",
";",
"var",
"providedOption",
"=",
"options",
".",
"provided",
";",
"if",
"(",
"providedOption",
")",
"{",
"toArray",
"(",
"providedOption",
")",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"markProvided",
"(",
"path",
",",
"context",
")",
"}",
")",
";",
"}",
"toArray",
"(",
"options",
".",
"entry",
")",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"collectDependencies",
"(",
"path",
",",
"context",
")",
"}",
")",
";",
"return",
"orderFileInfo",
"(",
"context",
")",
";",
"}"
] |
Resolves and sorts all dependencies of an Ext JS project.
@param options Example:
{
// Log verbose? Optional, default is false.
verbose: false,
// Source file encoding. Default: 'utf8'
encoding: 'utf8',
// The root of your project. All paths are relative to this. Default: '.'
root: 'path/to/project',
// Add Ext JS scripts you load independently in your html file.
provided: [ 'extjs/ext-dev.js' ],
// Add all entry points to include with dependencies
entry: [ 'app.js' ],
resolve: {
// The source folders for each class name prefix. Optional.
path: {
'Ext': 'ext/src',
'myapp': 'app'
},
// Alternative class names. Optional.
alias: {
'Ext.Layer': 'Ext.dom.Layer'
}
},
// Optimize source? (removes some statements like `require`) Optional. Default is false.
optimizeSource: false,
// Extra dependencies. Optional.
extraDependencies: {
requires: {
'MyClass': 'MyDependency'
},
uses: {
'MyClass': 'MyDependency'
}
}
// Classes to exclude. Optional.
excludeClasses: ['Ext.*', 'MyApp.some.Class'],
// Files to exclude (excludes also dependencies). Optional.
skipParse: ['app/ux/SkipMe.js'],
// The file provider to use. Optional.
fileProvider: {
// Returns an object representing the content of a file.
createFileContent: function(rootPath, filePath, encoding) { ... },
// Returns the content of a file as string.
getContentAsString: function(content) { ... }
}
}
@return The dependencies as array of ExtClass in correct loading order
|
[
"Resolves",
"and",
"sorts",
"all",
"dependencies",
"of",
"an",
"Ext",
"JS",
"project",
"."
] |
be36e87339b0973883c490fe2535414e74b1413b
|
https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/resolver.js#L105-L138
|
37,709 |
axke/rs-api
|
lib/apis/clan.js
|
Clan
|
function Clan(config) {
//Read the clans data from a csv to an array object
var readClan = function(data) {
var members = [],
space = new RegExp(String.fromCharCode(65533), 'g');
for (var i = 1; i < data.length; i++) {
var member = data[i];
members.push({
player: member[0].replace(space, ' '),
rank: member[1],
exp: Number(member[2]),
kills: Number(member[3])
});
}
return members;
};
/**
* Get a clans member list with exp gained and total kills (available for `rs`)
* @param name The clans name
* @returns {Object} Member list
* @example
* api.rs.hiscores.clan('Efficiency Experts').then(function(clan) {
* console.log(clan);
* }).catch(console.error);
*/
this.members = function(name) {
return new Promise(function(resolve, reject) {
if (typeof config.urls.members === 'undefined') {
reject(new Error('Oldschool RuneScape does not have clans.'));
return;
}
request.csv(config.urls.members + encodeURIComponent(name)).then(function(data) {
resolve(readClan(data));
}).catch(reject);
});
};
}
|
javascript
|
function Clan(config) {
//Read the clans data from a csv to an array object
var readClan = function(data) {
var members = [],
space = new RegExp(String.fromCharCode(65533), 'g');
for (var i = 1; i < data.length; i++) {
var member = data[i];
members.push({
player: member[0].replace(space, ' '),
rank: member[1],
exp: Number(member[2]),
kills: Number(member[3])
});
}
return members;
};
/**
* Get a clans member list with exp gained and total kills (available for `rs`)
* @param name The clans name
* @returns {Object} Member list
* @example
* api.rs.hiscores.clan('Efficiency Experts').then(function(clan) {
* console.log(clan);
* }).catch(console.error);
*/
this.members = function(name) {
return new Promise(function(resolve, reject) {
if (typeof config.urls.members === 'undefined') {
reject(new Error('Oldschool RuneScape does not have clans.'));
return;
}
request.csv(config.urls.members + encodeURIComponent(name)).then(function(data) {
resolve(readClan(data));
}).catch(reject);
});
};
}
|
[
"function",
"Clan",
"(",
"config",
")",
"{",
"//Read the clans data from a csv to an array object",
"var",
"readClan",
"=",
"function",
"(",
"data",
")",
"{",
"var",
"members",
"=",
"[",
"]",
",",
"space",
"=",
"new",
"RegExp",
"(",
"String",
".",
"fromCharCode",
"(",
"65533",
")",
",",
"'g'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"member",
"=",
"data",
"[",
"i",
"]",
";",
"members",
".",
"push",
"(",
"{",
"player",
":",
"member",
"[",
"0",
"]",
".",
"replace",
"(",
"space",
",",
"' '",
")",
",",
"rank",
":",
"member",
"[",
"1",
"]",
",",
"exp",
":",
"Number",
"(",
"member",
"[",
"2",
"]",
")",
",",
"kills",
":",
"Number",
"(",
"member",
"[",
"3",
"]",
")",
"}",
")",
";",
"}",
"return",
"members",
";",
"}",
";",
"/**\n * Get a clans member list with exp gained and total kills (available for `rs`)\n * @param name The clans name\n * @returns {Object} Member list\n * @example\n * api.rs.hiscores.clan('Efficiency Experts').then(function(clan) {\n * console.log(clan);\n * }).catch(console.error);\n */",
"this",
".",
"members",
"=",
"function",
"(",
"name",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"typeof",
"config",
".",
"urls",
".",
"members",
"===",
"'undefined'",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Oldschool RuneScape does not have clans.'",
")",
")",
";",
"return",
";",
"}",
"request",
".",
"csv",
"(",
"config",
".",
"urls",
".",
"members",
"+",
"encodeURIComponent",
"(",
"name",
")",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"resolve",
"(",
"readClan",
"(",
"data",
")",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Module containing Clan functions
@module Clan
|
[
"Module",
"containing",
"Clan",
"functions"
] |
71af4973e1d079f09b7d888b6d24735784185942
|
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/clan.js#L10-L51
|
37,710 |
axke/rs-api
|
lib/apis/clan.js
|
function(data) {
var members = [],
space = new RegExp(String.fromCharCode(65533), 'g');
for (var i = 1; i < data.length; i++) {
var member = data[i];
members.push({
player: member[0].replace(space, ' '),
rank: member[1],
exp: Number(member[2]),
kills: Number(member[3])
});
}
return members;
}
|
javascript
|
function(data) {
var members = [],
space = new RegExp(String.fromCharCode(65533), 'g');
for (var i = 1; i < data.length; i++) {
var member = data[i];
members.push({
player: member[0].replace(space, ' '),
rank: member[1],
exp: Number(member[2]),
kills: Number(member[3])
});
}
return members;
}
|
[
"function",
"(",
"data",
")",
"{",
"var",
"members",
"=",
"[",
"]",
",",
"space",
"=",
"new",
"RegExp",
"(",
"String",
".",
"fromCharCode",
"(",
"65533",
")",
",",
"'g'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"member",
"=",
"data",
"[",
"i",
"]",
";",
"members",
".",
"push",
"(",
"{",
"player",
":",
"member",
"[",
"0",
"]",
".",
"replace",
"(",
"space",
",",
"' '",
")",
",",
"rank",
":",
"member",
"[",
"1",
"]",
",",
"exp",
":",
"Number",
"(",
"member",
"[",
"2",
"]",
")",
",",
"kills",
":",
"Number",
"(",
"member",
"[",
"3",
"]",
")",
"}",
")",
";",
"}",
"return",
"members",
";",
"}"
] |
Read the clans data from a csv to an array object
|
[
"Read",
"the",
"clans",
"data",
"from",
"a",
"csv",
"to",
"an",
"array",
"object"
] |
71af4973e1d079f09b7d888b6d24735784185942
|
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/clan.js#L13-L28
|
|
37,711 |
klaygomes/karma-typescript-preprocessor2
|
index.js
|
_serveFile
|
function _serveFile(requestedFile, done) {
let compiled
, temp = []
, wasCompiled;
log.debug(`Fetching ${transformPath(requestedFile.path)} from buffer`);
if (requestedFile.sha) {
delete requestedFile.sha; //simple hack i used to prevent infinite loop
_feedBuffer(requestedFile, done);
compile();
return;
}
while (compiled = _compiledBuffer.shift()) {
if (_normalize(compiled.path) === _normalize(requestedFile.path)) {
wasCompiled = true;
done(null, compiled.contents.toString());
} else {
temp.unshift(compiled);
}
}
//refeed buffer
_compiledBuffer = temp;
//if file was not found in the stream
//maybe it is not compiled or it is a definition file, so we don't need to worry about
if (!wasCompiled) {
log.debug(`${requestedFile.originalPath} was not found. Maybe it was not compiled or it is a definition file.`);
done(null, dummyFile("This file was not compiled"));
}
}
|
javascript
|
function _serveFile(requestedFile, done) {
let compiled
, temp = []
, wasCompiled;
log.debug(`Fetching ${transformPath(requestedFile.path)} from buffer`);
if (requestedFile.sha) {
delete requestedFile.sha; //simple hack i used to prevent infinite loop
_feedBuffer(requestedFile, done);
compile();
return;
}
while (compiled = _compiledBuffer.shift()) {
if (_normalize(compiled.path) === _normalize(requestedFile.path)) {
wasCompiled = true;
done(null, compiled.contents.toString());
} else {
temp.unshift(compiled);
}
}
//refeed buffer
_compiledBuffer = temp;
//if file was not found in the stream
//maybe it is not compiled or it is a definition file, so we don't need to worry about
if (!wasCompiled) {
log.debug(`${requestedFile.originalPath} was not found. Maybe it was not compiled or it is a definition file.`);
done(null, dummyFile("This file was not compiled"));
}
}
|
[
"function",
"_serveFile",
"(",
"requestedFile",
",",
"done",
")",
"{",
"let",
"compiled",
",",
"temp",
"=",
"[",
"]",
",",
"wasCompiled",
";",
"log",
".",
"debug",
"(",
"`",
"${",
"transformPath",
"(",
"requestedFile",
".",
"path",
")",
"}",
"`",
")",
";",
"if",
"(",
"requestedFile",
".",
"sha",
")",
"{",
"delete",
"requestedFile",
".",
"sha",
";",
"//simple hack i used to prevent infinite loop",
"_feedBuffer",
"(",
"requestedFile",
",",
"done",
")",
";",
"compile",
"(",
")",
";",
"return",
";",
"}",
"while",
"(",
"compiled",
"=",
"_compiledBuffer",
".",
"shift",
"(",
")",
")",
"{",
"if",
"(",
"_normalize",
"(",
"compiled",
".",
"path",
")",
"===",
"_normalize",
"(",
"requestedFile",
".",
"path",
")",
")",
"{",
"wasCompiled",
"=",
"true",
";",
"done",
"(",
"null",
",",
"compiled",
".",
"contents",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"temp",
".",
"unshift",
"(",
"compiled",
")",
";",
"}",
"}",
"//refeed buffer",
"_compiledBuffer",
"=",
"temp",
";",
"//if file was not found in the stream",
"//maybe it is not compiled or it is a definition file, so we don't need to worry about",
"if",
"(",
"!",
"wasCompiled",
")",
"{",
"log",
".",
"debug",
"(",
"`",
"${",
"requestedFile",
".",
"originalPath",
"}",
"`",
")",
";",
"done",
"(",
"null",
",",
"dummyFile",
"(",
"\"This file was not compiled\"",
")",
")",
";",
"}",
"}"
] |
Used to fetch files from buffer if requested file contains a sha defined, it means this file was changed by karma
|
[
"Used",
"to",
"fetch",
"files",
"from",
"buffer",
"if",
"requested",
"file",
"contains",
"a",
"sha",
"defined",
"it",
"means",
"this",
"file",
"was",
"changed",
"by",
"karma"
] |
4a0f23efc6c309aa54d6975e6e688d0a2b165e4a
|
https://github.com/klaygomes/karma-typescript-preprocessor2/blob/4a0f23efc6c309aa54d6975e6e688d0a2b165e4a/index.js#L100-L133
|
37,712 |
Raynos/continuable
|
examples/docs.js
|
function (source, destination) {
return cont.mapAsync(readFileAsJSON(source), function (json, cb) {
json.copied = Date.now()
fs.writeFile(destination, JSON.stringify(json), cb)
})
}
|
javascript
|
function (source, destination) {
return cont.mapAsync(readFileAsJSON(source), function (json, cb) {
json.copied = Date.now()
fs.writeFile(destination, JSON.stringify(json), cb)
})
}
|
[
"function",
"(",
"source",
",",
"destination",
")",
"{",
"return",
"cont",
".",
"mapAsync",
"(",
"readFileAsJSON",
"(",
"source",
")",
",",
"function",
"(",
"json",
",",
"cb",
")",
"{",
"json",
".",
"copied",
"=",
"Date",
".",
"now",
"(",
")",
"fs",
".",
"writeFile",
"(",
"destination",
",",
"JSON",
".",
"stringify",
"(",
"json",
")",
",",
"cb",
")",
"}",
")",
"}"
] |
mapAsync takes an asynchronous transformation function and a source continuable. The new continuable is the value of the first continuable passed through the async transformation.
|
[
"mapAsync",
"takes",
"an",
"asynchronous",
"transformation",
"function",
"and",
"a",
"source",
"continuable",
".",
"The",
"new",
"continuable",
"is",
"the",
"value",
"of",
"the",
"first",
"continuable",
"passed",
"through",
"the",
"async",
"transformation",
"."
] |
f2e2ce2e2ce596a945f784f8942db35a9fbe1e60
|
https://github.com/Raynos/continuable/blob/f2e2ce2e2ce596a945f784f8942db35a9fbe1e60/examples/docs.js#L105-L110
|
|
37,713 |
sballesteros/dcat
|
index.js
|
_getStatsAndParts
|
function _getStatsAndParts (tp, cb){
fs.stat(tp.absPath, function(err, stats){
if (err) return cb(err);
if (stats.isDirectory) {
glob(path.join(tp.absPath, '**/*'), function(err, dirAbsPaths){
if (err) return cb(err);
async.map(dirAbsPaths, fs.stat, function(err, dirAbsPathStats){
if (err) return cb(err);
var parts = dirAbsPathStats
.map(function(x, i){ return {stats: x, absPath: dirAbsPaths[i]}; })
.filter(function(x){ return x.stats.isFile(); });
cb(null, stats, parts);
});
});
} else {
return cb(null, stats);
}
});
}
|
javascript
|
function _getStatsAndParts (tp, cb){
fs.stat(tp.absPath, function(err, stats){
if (err) return cb(err);
if (stats.isDirectory) {
glob(path.join(tp.absPath, '**/*'), function(err, dirAbsPaths){
if (err) return cb(err);
async.map(dirAbsPaths, fs.stat, function(err, dirAbsPathStats){
if (err) return cb(err);
var parts = dirAbsPathStats
.map(function(x, i){ return {stats: x, absPath: dirAbsPaths[i]}; })
.filter(function(x){ return x.stats.isFile(); });
cb(null, stats, parts);
});
});
} else {
return cb(null, stats);
}
});
}
|
[
"function",
"_getStatsAndParts",
"(",
"tp",
",",
"cb",
")",
"{",
"fs",
".",
"stat",
"(",
"tp",
".",
"absPath",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"if",
"(",
"stats",
".",
"isDirectory",
")",
"{",
"glob",
"(",
"path",
".",
"join",
"(",
"tp",
".",
"absPath",
",",
"'**/*'",
")",
",",
"function",
"(",
"err",
",",
"dirAbsPaths",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"async",
".",
"map",
"(",
"dirAbsPaths",
",",
"fs",
".",
"stat",
",",
"function",
"(",
"err",
",",
"dirAbsPathStats",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"var",
"parts",
"=",
"dirAbsPathStats",
".",
"map",
"(",
"function",
"(",
"x",
",",
"i",
")",
"{",
"return",
"{",
"stats",
":",
"x",
",",
"absPath",
":",
"dirAbsPaths",
"[",
"i",
"]",
"}",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"x",
".",
"stats",
".",
"isFile",
"(",
")",
";",
"}",
")",
";",
"cb",
"(",
"null",
",",
"stats",
",",
"parts",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"null",
",",
"stats",
")",
";",
"}",
"}",
")",
";",
"}"
] |
transform abs paths to resources and make source each resource has a unique @id
|
[
"transform",
"abs",
"paths",
"to",
"resources",
"and",
"make",
"source",
"each",
"resource",
"has",
"a",
"unique"
] |
21a2b99c03e55f192aa390b915e340e021eb19c6
|
https://github.com/sballesteros/dcat/blob/21a2b99c03e55f192aa390b915e340e021eb19c6/index.js#L277-L295
|
37,714 |
sballesteros/dcat
|
index.js
|
_check
|
function _check(mnode, cb){
if (mnode.node.filePath) {
fs.stat(path.resolve(root, mnode.node.filePath), function(err, stats){
if (err) return cb(err);
mnode.node.dateModified = stats.mtime.toISOString();
if (psize) { mnode.node[psize] = stats.size; }
cb(null);
});
} else if (mnode.node.hasPart) {
var hasPart = (Array.isArray(mnode.node.hasPart)) ? mnode.node.hasPart : [mnode.node.hasPart];
async.each(hasPart, function(part, cb2){
if (part.filePath) {
fs.stat(path.resolve(root, part.filePath), function(err, stats){
if (err) return cb2(err);
part.dateModified = stats.mtime.toISOString();
var type = packager.getType(part, packager.getRanges('hasPart'));
var isSoftwareApplication = type && packager.isClassOrSubClassOf(type, 'SoftwareApplication');
var isMediaObject = type && packager.isClassOrSubClassOf(type, 'MediaObject');
if (isSoftwareApplication) {
part.fileSize = stats.size;
} else if (isMediaObject) {
part.contentSize = stats.size;
}
cb2(null);
});
} else {
cb2(null);
}
}, cb);
} else {
cb(null);
}
}
|
javascript
|
function _check(mnode, cb){
if (mnode.node.filePath) {
fs.stat(path.resolve(root, mnode.node.filePath), function(err, stats){
if (err) return cb(err);
mnode.node.dateModified = stats.mtime.toISOString();
if (psize) { mnode.node[psize] = stats.size; }
cb(null);
});
} else if (mnode.node.hasPart) {
var hasPart = (Array.isArray(mnode.node.hasPart)) ? mnode.node.hasPart : [mnode.node.hasPart];
async.each(hasPart, function(part, cb2){
if (part.filePath) {
fs.stat(path.resolve(root, part.filePath), function(err, stats){
if (err) return cb2(err);
part.dateModified = stats.mtime.toISOString();
var type = packager.getType(part, packager.getRanges('hasPart'));
var isSoftwareApplication = type && packager.isClassOrSubClassOf(type, 'SoftwareApplication');
var isMediaObject = type && packager.isClassOrSubClassOf(type, 'MediaObject');
if (isSoftwareApplication) {
part.fileSize = stats.size;
} else if (isMediaObject) {
part.contentSize = stats.size;
}
cb2(null);
});
} else {
cb2(null);
}
}, cb);
} else {
cb(null);
}
}
|
[
"function",
"_check",
"(",
"mnode",
",",
"cb",
")",
"{",
"if",
"(",
"mnode",
".",
"node",
".",
"filePath",
")",
"{",
"fs",
".",
"stat",
"(",
"path",
".",
"resolve",
"(",
"root",
",",
"mnode",
".",
"node",
".",
"filePath",
")",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"mnode",
".",
"node",
".",
"dateModified",
"=",
"stats",
".",
"mtime",
".",
"toISOString",
"(",
")",
";",
"if",
"(",
"psize",
")",
"{",
"mnode",
".",
"node",
"[",
"psize",
"]",
"=",
"stats",
".",
"size",
";",
"}",
"cb",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"mnode",
".",
"node",
".",
"hasPart",
")",
"{",
"var",
"hasPart",
"=",
"(",
"Array",
".",
"isArray",
"(",
"mnode",
".",
"node",
".",
"hasPart",
")",
")",
"?",
"mnode",
".",
"node",
".",
"hasPart",
":",
"[",
"mnode",
".",
"node",
".",
"hasPart",
"]",
";",
"async",
".",
"each",
"(",
"hasPart",
",",
"function",
"(",
"part",
",",
"cb2",
")",
"{",
"if",
"(",
"part",
".",
"filePath",
")",
"{",
"fs",
".",
"stat",
"(",
"path",
".",
"resolve",
"(",
"root",
",",
"part",
".",
"filePath",
")",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb2",
"(",
"err",
")",
";",
"part",
".",
"dateModified",
"=",
"stats",
".",
"mtime",
".",
"toISOString",
"(",
")",
";",
"var",
"type",
"=",
"packager",
".",
"getType",
"(",
"part",
",",
"packager",
".",
"getRanges",
"(",
"'hasPart'",
")",
")",
";",
"var",
"isSoftwareApplication",
"=",
"type",
"&&",
"packager",
".",
"isClassOrSubClassOf",
"(",
"type",
",",
"'SoftwareApplication'",
")",
";",
"var",
"isMediaObject",
"=",
"type",
"&&",
"packager",
".",
"isClassOrSubClassOf",
"(",
"type",
",",
"'MediaObject'",
")",
";",
"if",
"(",
"isSoftwareApplication",
")",
"{",
"part",
".",
"fileSize",
"=",
"stats",
".",
"size",
";",
"}",
"else",
"if",
"(",
"isMediaObject",
")",
"{",
"part",
".",
"contentSize",
"=",
"stats",
".",
"size",
";",
"}",
"cb2",
"(",
"null",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"cb2",
"(",
"null",
")",
";",
"}",
"}",
",",
"cb",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"null",
")",
";",
"}",
"}"
] |
check that all the files are here and update dateModified and contentSize
|
[
"check",
"that",
"all",
"the",
"files",
"are",
"here",
"and",
"update",
"dateModified",
"and",
"contentSize"
] |
21a2b99c03e55f192aa390b915e340e021eb19c6
|
https://github.com/sballesteros/dcat/blob/21a2b99c03e55f192aa390b915e340e021eb19c6/index.js#L771-L806
|
37,715 |
oskargustafsson/BFF
|
src/event-emitter.js
|
function (eventName) {
if (RUNTIME_CHECKS && typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; }
for (var i = 0, n = listenersForEvent.length; i < n; ++i) {
var listener = listenersForEvent[i];
// Call the listener without the first item in the "arguments" array
listener.call.apply(listener, arguments);
}
}
|
javascript
|
function (eventName) {
if (RUNTIME_CHECKS && typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; }
for (var i = 0, n = listenersForEvent.length; i < n; ++i) {
var listener = listenersForEvent[i];
// Call the listener without the first item in the "arguments" array
listener.call.apply(listener, arguments);
}
}
|
[
"function",
"(",
"eventName",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
"&&",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"if",
"(",
"!",
"this",
".",
"__private",
"||",
"!",
"this",
".",
"__private",
".",
"listeners",
")",
"{",
"return",
";",
"}",
"var",
"listenersForEvent",
"=",
"this",
".",
"__private",
".",
"listeners",
"[",
"eventName",
"]",
";",
"if",
"(",
"!",
"listenersForEvent",
")",
"{",
"return",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"listenersForEvent",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"var",
"listener",
"=",
"listenersForEvent",
"[",
"i",
"]",
";",
"// Call the listener without the first item in the \"arguments\" array",
"listener",
".",
"call",
".",
"apply",
"(",
"listener",
",",
"arguments",
")",
";",
"}",
"}"
] |
Emit an event. Callbacks will be called with the same arguments as this function was called with, except for the event name argument.
@instance
@arg {string} eventName - Identifier string for the event.
@arg {...any} [eventArguments] - Zero or more arguments that event listeners will be called with.
|
[
"Emit",
"an",
"event",
".",
"Callbacks",
"will",
"be",
"called",
"with",
"the",
"same",
"arguments",
"as",
"this",
"function",
"was",
"called",
"with",
"except",
"for",
"the",
"event",
"name",
"argument",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L19-L34
|
|
37,716 |
oskargustafsson/BFF
|
src/event-emitter.js
|
function (eventName, argsArray) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length > 1 && (!argsArray || argsArray.length === undefined)) {
throw '"argsArray" must have a length property';
}
}
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; }
for (var i = 0, n = listenersForEvent.length; i < n; ++i) {
listenersForEvent[i].apply(undefined, argsArray);
}
}
|
javascript
|
function (eventName, argsArray) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length > 1 && (!argsArray || argsArray.length === undefined)) {
throw '"argsArray" must have a length property';
}
}
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; }
for (var i = 0, n = listenersForEvent.length; i < n; ++i) {
listenersForEvent[i].apply(undefined, argsArray);
}
}
|
[
"function",
"(",
"eventName",
",",
"argsArray",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"(",
"!",
"argsArray",
"||",
"argsArray",
".",
"length",
"===",
"undefined",
")",
")",
"{",
"throw",
"'\"argsArray\" must have a length property'",
";",
"}",
"}",
"if",
"(",
"!",
"this",
".",
"__private",
"||",
"!",
"this",
".",
"__private",
".",
"listeners",
")",
"{",
"return",
";",
"}",
"var",
"listenersForEvent",
"=",
"this",
".",
"__private",
".",
"listeners",
"[",
"eventName",
"]",
";",
"if",
"(",
"!",
"listenersForEvent",
")",
"{",
"return",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"listenersForEvent",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"listenersForEvent",
"[",
"i",
"]",
".",
"apply",
"(",
"undefined",
",",
"argsArray",
")",
";",
"}",
"}"
] |
Emit an event. Callbacks will be called with arguments given as an an array in the second argument
@instance
@arg {string} eventName - Identifier string for the event.
@arg {Array} [argsArray] - An array of arguments with which the callbacks will be called. Each item in
the array will be provided as an individual argument to the callbacks.
|
[
"Emit",
"an",
"event",
".",
"Callbacks",
"will",
"be",
"called",
"with",
"arguments",
"given",
"as",
"an",
"an",
"array",
"in",
"the",
"second",
"argument"
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L43-L61
|
|
37,717 |
oskargustafsson/BFF
|
src/event-emitter.js
|
function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
}
this.__private || Object.defineProperty(this, '__private', { writable: true, value: {}, });
var listeners = this.__private.listeners || (this.__private.listeners = {});
var listenersForEvent = listeners[eventName] || (listeners[eventName] = []);
if (RUNTIME_CHECKS && listenersForEvent.indexOf(callback) !== -1) {
throw 'This listener has already been added (event: ' + eventName + ')';
}
listenersForEvent.push(callback);
}
|
javascript
|
function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
}
this.__private || Object.defineProperty(this, '__private', { writable: true, value: {}, });
var listeners = this.__private.listeners || (this.__private.listeners = {});
var listenersForEvent = listeners[eventName] || (listeners[eventName] = []);
if (RUNTIME_CHECKS && listenersForEvent.indexOf(callback) !== -1) {
throw 'This listener has already been added (event: ' + eventName + ')';
}
listenersForEvent.push(callback);
}
|
[
"function",
"(",
"eventName",
",",
"callback",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"throw",
"'\"callback\" argument must be a function'",
";",
"}",
"}",
"this",
".",
"__private",
"||",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'__private'",
",",
"{",
"writable",
":",
"true",
",",
"value",
":",
"{",
"}",
",",
"}",
")",
";",
"var",
"listeners",
"=",
"this",
".",
"__private",
".",
"listeners",
"||",
"(",
"this",
".",
"__private",
".",
"listeners",
"=",
"{",
"}",
")",
";",
"var",
"listenersForEvent",
"=",
"listeners",
"[",
"eventName",
"]",
"||",
"(",
"listeners",
"[",
"eventName",
"]",
"=",
"[",
"]",
")",
";",
"if",
"(",
"RUNTIME_CHECKS",
"&&",
"listenersForEvent",
".",
"indexOf",
"(",
"callback",
")",
"!==",
"-",
"1",
")",
"{",
"throw",
"'This listener has already been added (event: '",
"+",
"eventName",
"+",
"')'",
";",
"}",
"listenersForEvent",
".",
"push",
"(",
"callback",
")",
";",
"}"
] |
Add an event listener function that will be called whenever the given event is emitted. Trying to add the exact same function twice till throw an error, as that is rarely ever the intention and a common source of errors.
@instance
@arg {string} eventName - Identifier string for the event that is to be listened to.
@arg {function} callback - The function that will be called when the event is emitted.
|
[
"Add",
"an",
"event",
"listener",
"function",
"that",
"will",
"be",
"called",
"whenever",
"the",
"given",
"event",
"is",
"emitted",
".",
"Trying",
"to",
"add",
"the",
"exact",
"same",
"function",
"twice",
"till",
"throw",
"an",
"error",
"as",
"that",
"is",
"rarely",
"ever",
"the",
"intention",
"and",
"a",
"common",
"source",
"of",
"errors",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L69-L88
|
|
37,718 |
oskargustafsson/BFF
|
src/event-emitter.js
|
function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length === 2 && typeof callback !== 'function') {
throw '"callback" argument must be a function'; // Catch a common cause of errors
}
}
// No listeners at all? We are done.
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; } // No listeners for this event? We are done.
if (callback) {
var pos = listenersForEvent.indexOf(callback);
if (pos === -1) { return; }
listenersForEvent.splice(pos, 1);
} else {
listenersForEvent.length = 0;
}
listenersForEvent.length === 0 && (delete this.__private.listeners[eventName]);
}
|
javascript
|
function (eventName, callback) {
if (RUNTIME_CHECKS) {
if (typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
if (arguments.length === 2 && typeof callback !== 'function') {
throw '"callback" argument must be a function'; // Catch a common cause of errors
}
}
// No listeners at all? We are done.
if (!this.__private || !this.__private.listeners) { return; }
var listenersForEvent = this.__private.listeners[eventName];
if (!listenersForEvent) { return; } // No listeners for this event? We are done.
if (callback) {
var pos = listenersForEvent.indexOf(callback);
if (pos === -1) { return; }
listenersForEvent.splice(pos, 1);
} else {
listenersForEvent.length = 0;
}
listenersForEvent.length === 0 && (delete this.__private.listeners[eventName]);
}
|
[
"function",
"(",
"eventName",
",",
"callback",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
"&&",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"throw",
"'\"callback\" argument must be a function'",
";",
"// Catch a common cause of errors",
"}",
"}",
"// No listeners at all? We are done.",
"if",
"(",
"!",
"this",
".",
"__private",
"||",
"!",
"this",
".",
"__private",
".",
"listeners",
")",
"{",
"return",
";",
"}",
"var",
"listenersForEvent",
"=",
"this",
".",
"__private",
".",
"listeners",
"[",
"eventName",
"]",
";",
"if",
"(",
"!",
"listenersForEvent",
")",
"{",
"return",
";",
"}",
"// No listeners for this event? We are done.",
"if",
"(",
"callback",
")",
"{",
"var",
"pos",
"=",
"listenersForEvent",
".",
"indexOf",
"(",
"callback",
")",
";",
"if",
"(",
"pos",
"===",
"-",
"1",
")",
"{",
"return",
";",
"}",
"listenersForEvent",
".",
"splice",
"(",
"pos",
",",
"1",
")",
";",
"}",
"else",
"{",
"listenersForEvent",
".",
"length",
"=",
"0",
";",
"}",
"listenersForEvent",
".",
"length",
"===",
"0",
"&&",
"(",
"delete",
"this",
".",
"__private",
".",
"listeners",
"[",
"eventName",
"]",
")",
";",
"}"
] |
Removes an event listener function. If the function was never a listener, do nothing.
@instance
@arg {string} eventName - Identifier string for the event in question.
@arg {function} [callback] - If not given, all event listeners to the provided eventName will be removed. If given, only the given callback will be removed from the given eventName.
|
[
"Removes",
"an",
"event",
"listener",
"function",
".",
"If",
"the",
"function",
"was",
"never",
"a",
"listener",
"do",
"nothing",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L96-L120
|
|
37,719 |
sofa/sofa-core
|
src/sofa.util.js
|
function (collection, callback) {
var index,
iterable = collection,
result = iterable;
if (!iterable) {
return result;
}
if (!sofa.Util.objectTypes[typeof iterable]) {
return result;
}
for (index in iterable) {
if (Object.prototype.hasOwnProperty.call(iterable, index)) {
if (callback(iterable[index], index, collection) === false) {
return result;
}
}
}
return result;
}
|
javascript
|
function (collection, callback) {
var index,
iterable = collection,
result = iterable;
if (!iterable) {
return result;
}
if (!sofa.Util.objectTypes[typeof iterable]) {
return result;
}
for (index in iterable) {
if (Object.prototype.hasOwnProperty.call(iterable, index)) {
if (callback(iterable[index], index, collection) === false) {
return result;
}
}
}
return result;
}
|
[
"function",
"(",
"collection",
",",
"callback",
")",
"{",
"var",
"index",
",",
"iterable",
"=",
"collection",
",",
"result",
"=",
"iterable",
";",
"if",
"(",
"!",
"iterable",
")",
"{",
"return",
"result",
";",
"}",
"if",
"(",
"!",
"sofa",
".",
"Util",
".",
"objectTypes",
"[",
"typeof",
"iterable",
"]",
")",
"{",
"return",
"result",
";",
"}",
"for",
"(",
"index",
"in",
"iterable",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"iterable",
",",
"index",
")",
")",
"{",
"if",
"(",
"callback",
"(",
"iterable",
"[",
"index",
"]",
",",
"index",
",",
"collection",
")",
"===",
"false",
")",
"{",
"return",
"result",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] |
this method is ripped out from lo-dash
|
[
"this",
"method",
"is",
"ripped",
"out",
"from",
"lo",
"-",
"dash"
] |
654b12bdda24f46e496417beb2d7772a6a50fea1
|
https://github.com/sofa/sofa-core/blob/654b12bdda24f46e496417beb2d7772a6a50fea1/src/sofa.util.js#L278-L299
|
|
37,720 |
juliostanley/websdk
|
build/index.js
|
function(filepath){
filepath = filepath.replace(pathSepExp,'/'); // Use unix paths regardless. Makes these checks easier
if(filepath &&
(
( // If filepath has the jsIncludeDir, but does not include the node_modules directory under them
filepath.match(expressions.jsIncludeDir)
&& !filepath.match(expressions.jsExcludeDir)
)
// Or the filepath has nothing to do with node_modules, app_modules/vendor
|| !filepath.match(expressions.jsAlwaysIncludeDir)
|| filepath.match(/node_modules(\\|\/)@polymer|node_modules(\\|\/)@webcomponents(\\|\/)shadycss/)
)
) {
// console.log('===================================')
// console.log(filepath)
// console.log('### Transpiling: '+filepath);
return true;
}
}
|
javascript
|
function(filepath){
filepath = filepath.replace(pathSepExp,'/'); // Use unix paths regardless. Makes these checks easier
if(filepath &&
(
( // If filepath has the jsIncludeDir, but does not include the node_modules directory under them
filepath.match(expressions.jsIncludeDir)
&& !filepath.match(expressions.jsExcludeDir)
)
// Or the filepath has nothing to do with node_modules, app_modules/vendor
|| !filepath.match(expressions.jsAlwaysIncludeDir)
|| filepath.match(/node_modules(\\|\/)@polymer|node_modules(\\|\/)@webcomponents(\\|\/)shadycss/)
)
) {
// console.log('===================================')
// console.log(filepath)
// console.log('### Transpiling: '+filepath);
return true;
}
}
|
[
"function",
"(",
"filepath",
")",
"{",
"filepath",
"=",
"filepath",
".",
"replace",
"(",
"pathSepExp",
",",
"'/'",
")",
";",
"// Use unix paths regardless. Makes these checks easier",
"if",
"(",
"filepath",
"&&",
"(",
"(",
"// If filepath has the jsIncludeDir, but does not include the node_modules directory under them",
"filepath",
".",
"match",
"(",
"expressions",
".",
"jsIncludeDir",
")",
"&&",
"!",
"filepath",
".",
"match",
"(",
"expressions",
".",
"jsExcludeDir",
")",
")",
"// Or the filepath has nothing to do with node_modules, app_modules/vendor",
"||",
"!",
"filepath",
".",
"match",
"(",
"expressions",
".",
"jsAlwaysIncludeDir",
")",
"||",
"filepath",
".",
"match",
"(",
"/",
"node_modules(\\\\|\\/)@polymer|node_modules(\\\\|\\/)@webcomponents(\\\\|\\/)shadycss",
"/",
")",
")",
")",
"{",
"// console.log('===================================')",
"// console.log(filepath)",
"// console.log('### Transpiling: '+filepath);",
"return",
"true",
";",
"}",
"}"
] |
jQuery is not needed
|
[
"jQuery",
"is",
"not",
"needed"
] |
0657c04eb0ceed488be3f67e95f1d1d3b873c869
|
https://github.com/juliostanley/websdk/blob/0657c04eb0ceed488be3f67e95f1d1d3b873c869/build/index.js#L76-L94
|
|
37,721 |
juliostanley/websdk
|
build/index.js
|
function(config, cb){
// This will tell webpack to create a new chunk
rq.ensure(['INDEX_PATH'],function(rq){
let library = rq('INDEX_PATH');
library = library.default || library; // To preven issues between versions
cb(
// Expected to export an initializing function
library(config)
);
},'NAME');
}
|
javascript
|
function(config, cb){
// This will tell webpack to create a new chunk
rq.ensure(['INDEX_PATH'],function(rq){
let library = rq('INDEX_PATH');
library = library.default || library; // To preven issues between versions
cb(
// Expected to export an initializing function
library(config)
);
},'NAME');
}
|
[
"function",
"(",
"config",
",",
"cb",
")",
"{",
"// This will tell webpack to create a new chunk",
"rq",
".",
"ensure",
"(",
"[",
"'INDEX_PATH'",
"]",
",",
"function",
"(",
"rq",
")",
"{",
"let",
"library",
"=",
"rq",
"(",
"'INDEX_PATH'",
")",
";",
"library",
"=",
"library",
".",
"default",
"||",
"library",
";",
"// To preven issues between versions",
"cb",
"(",
"// Expected to export an initializing function",
"library",
"(",
"config",
")",
")",
";",
"}",
",",
"'NAME'",
")",
";",
"}"
] |
Create a common loader
|
[
"Create",
"a",
"common",
"loader"
] |
0657c04eb0ceed488be3f67e95f1d1d3b873c869
|
https://github.com/juliostanley/websdk/blob/0657c04eb0ceed488be3f67e95f1d1d3b873c869/build/index.js#L675-L685
|
|
37,722 |
emmetio/stylesheet-formatters
|
index.js
|
getFormat
|
function getFormat(syntax, options) {
let format = syntaxFormat[syntax];
if (typeof format === 'string') {
format = syntaxFormat[format];
}
return Object.assign({}, format, options && options.format);
}
|
javascript
|
function getFormat(syntax, options) {
let format = syntaxFormat[syntax];
if (typeof format === 'string') {
format = syntaxFormat[format];
}
return Object.assign({}, format, options && options.format);
}
|
[
"function",
"getFormat",
"(",
"syntax",
",",
"options",
")",
"{",
"let",
"format",
"=",
"syntaxFormat",
"[",
"syntax",
"]",
";",
"if",
"(",
"typeof",
"format",
"===",
"'string'",
")",
"{",
"format",
"=",
"syntaxFormat",
"[",
"format",
"]",
";",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"format",
",",
"options",
"&&",
"options",
".",
"format",
")",
";",
"}"
] |
Returns formatter object for given syntax
@param {String} syntax
@param {Object} [options]
@return {Object} Formatter object as defined in `syntaxFormat`
|
[
"Returns",
"formatter",
"object",
"for",
"given",
"syntax"
] |
1ba9fa2609b8088e7567547990f123106de84b1d
|
https://github.com/emmetio/stylesheet-formatters/blob/1ba9fa2609b8088e7567547990f123106de84b1d/index.js#L75-L82
|
37,723 |
openbiz/openbiz
|
lib/loaders/RouteLoader.js
|
function(newRoutes)
{
for(var key in newRoutes)
{
if(routes.hasOwnProperty(key))
{
if(typeof routes[key] == 'Array')
{
routes[key].push(newRoutes[key]);
}
else
{
routes[key] = [routes[key],newRoutes[key]];
}
}
else
{
routes[key] = newRoutes[key];
}
}
}
|
javascript
|
function(newRoutes)
{
for(var key in newRoutes)
{
if(routes.hasOwnProperty(key))
{
if(typeof routes[key] == 'Array')
{
routes[key].push(newRoutes[key]);
}
else
{
routes[key] = [routes[key],newRoutes[key]];
}
}
else
{
routes[key] = newRoutes[key];
}
}
}
|
[
"function",
"(",
"newRoutes",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"newRoutes",
")",
"{",
"if",
"(",
"routes",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"if",
"(",
"typeof",
"routes",
"[",
"key",
"]",
"==",
"'Array'",
")",
"{",
"routes",
"[",
"key",
"]",
".",
"push",
"(",
"newRoutes",
"[",
"key",
"]",
")",
";",
"}",
"else",
"{",
"routes",
"[",
"key",
"]",
"=",
"[",
"routes",
"[",
"key",
"]",
",",
"newRoutes",
"[",
"key",
"]",
"]",
";",
"}",
"}",
"else",
"{",
"routes",
"[",
"key",
"]",
"=",
"newRoutes",
"[",
"key",
"]",
";",
"}",
"}",
"}"
] |
define route merge method
|
[
"define",
"route",
"merge",
"method"
] |
997f1398396683d7ad667b1b360ce74c7c7fcf6f
|
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/loaders/RouteLoader.js#L10-L30
|
|
37,724 |
mikl/node-drupal
|
lib/user.js
|
role_permissions
|
function role_permissions(roles, callback) {
var permissions = [],
fetch = [];
if (roles) {
// TODO: Here we could do with some caching like Drupal does.
roles.forEach(function (name, rid) {
fetch.push(rid);
});
// Get permissions for the rids.
if (fetch) {
db.query("SELECT rid, permission FROM role_permission WHERE rid IN ($1);", [fetch], function (err, rows) {
if (err) {
callback(err, null);
}
if (rows.length > 0) {
rows.forEach(function (row) {
permissions.push(row.permission);
});
}
callback(null, permissions);
});
}
}
}
|
javascript
|
function role_permissions(roles, callback) {
var permissions = [],
fetch = [];
if (roles) {
// TODO: Here we could do with some caching like Drupal does.
roles.forEach(function (name, rid) {
fetch.push(rid);
});
// Get permissions for the rids.
if (fetch) {
db.query("SELECT rid, permission FROM role_permission WHERE rid IN ($1);", [fetch], function (err, rows) {
if (err) {
callback(err, null);
}
if (rows.length > 0) {
rows.forEach(function (row) {
permissions.push(row.permission);
});
}
callback(null, permissions);
});
}
}
}
|
[
"function",
"role_permissions",
"(",
"roles",
",",
"callback",
")",
"{",
"var",
"permissions",
"=",
"[",
"]",
",",
"fetch",
"=",
"[",
"]",
";",
"if",
"(",
"roles",
")",
"{",
"// TODO: Here we could do with some caching like Drupal does.",
"roles",
".",
"forEach",
"(",
"function",
"(",
"name",
",",
"rid",
")",
"{",
"fetch",
".",
"push",
"(",
"rid",
")",
";",
"}",
")",
";",
"// Get permissions for the rids.",
"if",
"(",
"fetch",
")",
"{",
"db",
".",
"query",
"(",
"\"SELECT rid, permission FROM role_permission WHERE rid IN ($1);\"",
",",
"[",
"fetch",
"]",
",",
"function",
"(",
"err",
",",
"rows",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"}",
"if",
"(",
"rows",
".",
"length",
">",
"0",
")",
"{",
"rows",
".",
"forEach",
"(",
"function",
"(",
"row",
")",
"{",
"permissions",
".",
"push",
"(",
"row",
".",
"permission",
")",
";",
"}",
")",
";",
"}",
"callback",
"(",
"null",
",",
"permissions",
")",
";",
"}",
")",
";",
"}",
"}",
"}"
] |
Get all permissions granted to a set of roles.
Like user_role_permissions() in Drupal core.
|
[
"Get",
"all",
"permissions",
"granted",
"to",
"a",
"set",
"of",
"roles",
"."
] |
0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd
|
https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/user.js#L67-L94
|
37,725 |
mikl/node-drupal
|
lib/user.js
|
access
|
function access(permission, account, callback) {
// User #1 has all privileges:
if (account.uid === 1) {
callback(null, true);
return;
}
// If permissions is already loaded, use them.
if (account.permissions) {
callback(null, account.permissions.indexOf(permission) > -1);
return;
}
role_permissions(account.roles, function (err, permissions) {
if (err) {
callback(err);
return;
}
callback(null, permissions.indexOf(permission) > -1);
});
}
|
javascript
|
function access(permission, account, callback) {
// User #1 has all privileges:
if (account.uid === 1) {
callback(null, true);
return;
}
// If permissions is already loaded, use them.
if (account.permissions) {
callback(null, account.permissions.indexOf(permission) > -1);
return;
}
role_permissions(account.roles, function (err, permissions) {
if (err) {
callback(err);
return;
}
callback(null, permissions.indexOf(permission) > -1);
});
}
|
[
"function",
"access",
"(",
"permission",
",",
"account",
",",
"callback",
")",
"{",
"// User #1 has all privileges:",
"if",
"(",
"account",
".",
"uid",
"===",
"1",
")",
"{",
"callback",
"(",
"null",
",",
"true",
")",
";",
"return",
";",
"}",
"// If permissions is already loaded, use them.",
"if",
"(",
"account",
".",
"permissions",
")",
"{",
"callback",
"(",
"null",
",",
"account",
".",
"permissions",
".",
"indexOf",
"(",
"permission",
")",
">",
"-",
"1",
")",
";",
"return",
";",
"}",
"role_permissions",
"(",
"account",
".",
"roles",
",",
"function",
"(",
"err",
",",
"permissions",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"callback",
"(",
"null",
",",
"permissions",
".",
"indexOf",
"(",
"permission",
")",
">",
"-",
"1",
")",
";",
"}",
")",
";",
"}"
] |
Check if user has a specific permission.
Like user_access() in Drupal core.
Unlike in Drupal, we do not have a global user object, so this
implementation always require the account parameter to be set.
|
[
"Check",
"if",
"user",
"has",
"a",
"specific",
"permission",
"."
] |
0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd
|
https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/user.js#L104-L125
|
37,726 |
mikl/node-drupal
|
lib/user.js
|
session_load
|
function session_load(sid, callback) {
var rows = [];
db.query("SELECT * FROM sessions WHERE sid = $1;", [sid], function (err, rows) {
if (err) {
callback(err, null);
return;
}
if (rows.length > 0) {
callback(null, rows[0]);
}
else {
callback('Session not found', null);
}
});
}
|
javascript
|
function session_load(sid, callback) {
var rows = [];
db.query("SELECT * FROM sessions WHERE sid = $1;", [sid], function (err, rows) {
if (err) {
callback(err, null);
return;
}
if (rows.length > 0) {
callback(null, rows[0]);
}
else {
callback('Session not found', null);
}
});
}
|
[
"function",
"session_load",
"(",
"sid",
",",
"callback",
")",
"{",
"var",
"rows",
"=",
"[",
"]",
";",
"db",
".",
"query",
"(",
"\"SELECT * FROM sessions WHERE sid = $1;\"",
",",
"[",
"sid",
"]",
",",
"function",
"(",
"err",
",",
"rows",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"return",
";",
"}",
"if",
"(",
"rows",
".",
"length",
">",
"0",
")",
"{",
"callback",
"(",
"null",
",",
"rows",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"'Session not found'",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Load a user session.
This function does not exist in Drupal core, as it uses PHPs rather
complex session system we do not attempt to reconstruct here.
This only works when Drupal uses the (default) database session
backend. Memcache and other session backends not supported.
|
[
"Load",
"a",
"user",
"session",
"."
] |
0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd
|
https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/user.js#L136-L152
|
37,727 |
bholloway/persistent-cache-webpack-plugin
|
lib/decode.js
|
decode
|
function decode(object) {
var result = {};
// enumerable properties
for (var key in object) {
var value = object[key];
// nested object
if (value && (typeof value === 'object')) {
// instance
if (value.$class && value.$props) {
result[value] = assign(new classes.getDefinition(value.$class), decode(value.$props));
}
// plain object
else {
result[value] = decode(value);
}
}
// other
else {
result[value] = value;
}
}
// complete
return result;
}
|
javascript
|
function decode(object) {
var result = {};
// enumerable properties
for (var key in object) {
var value = object[key];
// nested object
if (value && (typeof value === 'object')) {
// instance
if (value.$class && value.$props) {
result[value] = assign(new classes.getDefinition(value.$class), decode(value.$props));
}
// plain object
else {
result[value] = decode(value);
}
}
// other
else {
result[value] = value;
}
}
// complete
return result;
}
|
[
"function",
"decode",
"(",
"object",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"// enumerable properties",
"for",
"(",
"var",
"key",
"in",
"object",
")",
"{",
"var",
"value",
"=",
"object",
"[",
"key",
"]",
";",
"// nested object",
"if",
"(",
"value",
"&&",
"(",
"typeof",
"value",
"===",
"'object'",
")",
")",
"{",
"// instance",
"if",
"(",
"value",
".",
"$class",
"&&",
"value",
".",
"$props",
")",
"{",
"result",
"[",
"value",
"]",
"=",
"assign",
"(",
"new",
"classes",
".",
"getDefinition",
"(",
"value",
".",
"$class",
")",
",",
"decode",
"(",
"value",
".",
"$props",
")",
")",
";",
"}",
"// plain object",
"else",
"{",
"result",
"[",
"value",
"]",
"=",
"decode",
"(",
"value",
")",
";",
"}",
"}",
"// other",
"else",
"{",
"result",
"[",
"value",
"]",
"=",
"value",
";",
"}",
"}",
"// complete",
"return",
"result",
";",
"}"
] |
Decode the given acyclic object, instantiating using any embedded class information.
@param {object} object The object to decode
@returns {object} An acyclic object with possibly typed members
|
[
"Decode",
"the",
"given",
"acyclic",
"object",
"instantiating",
"using",
"any",
"embedded",
"class",
"information",
"."
] |
bd5aec58b1b38477218dcdc0fb144c6981604fa8
|
https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/decode.js#L12-L39
|
37,728 |
mikolalysenko/polytope-closest-point
|
lib/closest_point_nd.js
|
closestPointnd
|
function closestPointnd(c, positions, x, result) {
var D = numeric.rep([c.length, c.length], 0.0);
var dvec = numeric.rep([c.length], 0.0);
for(var i=0; i<c.length; ++i) {
var pi = positions[c[i]];
dvec[i] = numeric.dot(pi, x);
for(var j=0; j<c.length; ++j) {
var pj = positions[c[j]];
D[i][j] = D[j][i] = numeric.dot(pi, pj);
}
}
var A = numeric.rep([c.length, c.length+2], 0.0);
var b = numeric.rep([c.length+2], 0.0);
b[0] = 1.0-EPSILON;
b[1] = -(1.0+EPSILON);
for(var i=0; i<c.length; ++i) {
A[i][0] = 1;
A[i][1] = -1
A[i][i+2] = 1;
}
for(var attempts=0; attempts<15; ++attempts) {
var fortran_poop = numeric.solveQP(D, dvec, A, b);
if(fortran_poop.message.length > 0) {
//Quadratic form may be singular, perturb and resolve
for(var i=0; i<c.length; ++i) {
D[i][i] += 1e-8;
}
continue;
} else if(isNaN(fortran_poop.value[0])) {
break;
} else {
//Success!
var solution = fortran_poop.solution;
for(var i=0; i<x.length; ++i) {
result[i] = 0.0;
for(var j=0; j<solution.length; ++j) {
result[i] += solution[j] * positions[c[j]][i];
}
}
return 2.0 * fortran_poop.value[0] + numeric.dot(x,x);
}
}
for(var i=0; i<x.length; ++i) {
result[i] = Number.NaN;
}
return Number.NaN;
}
|
javascript
|
function closestPointnd(c, positions, x, result) {
var D = numeric.rep([c.length, c.length], 0.0);
var dvec = numeric.rep([c.length], 0.0);
for(var i=0; i<c.length; ++i) {
var pi = positions[c[i]];
dvec[i] = numeric.dot(pi, x);
for(var j=0; j<c.length; ++j) {
var pj = positions[c[j]];
D[i][j] = D[j][i] = numeric.dot(pi, pj);
}
}
var A = numeric.rep([c.length, c.length+2], 0.0);
var b = numeric.rep([c.length+2], 0.0);
b[0] = 1.0-EPSILON;
b[1] = -(1.0+EPSILON);
for(var i=0; i<c.length; ++i) {
A[i][0] = 1;
A[i][1] = -1
A[i][i+2] = 1;
}
for(var attempts=0; attempts<15; ++attempts) {
var fortran_poop = numeric.solveQP(D, dvec, A, b);
if(fortran_poop.message.length > 0) {
//Quadratic form may be singular, perturb and resolve
for(var i=0; i<c.length; ++i) {
D[i][i] += 1e-8;
}
continue;
} else if(isNaN(fortran_poop.value[0])) {
break;
} else {
//Success!
var solution = fortran_poop.solution;
for(var i=0; i<x.length; ++i) {
result[i] = 0.0;
for(var j=0; j<solution.length; ++j) {
result[i] += solution[j] * positions[c[j]][i];
}
}
return 2.0 * fortran_poop.value[0] + numeric.dot(x,x);
}
}
for(var i=0; i<x.length; ++i) {
result[i] = Number.NaN;
}
return Number.NaN;
}
|
[
"function",
"closestPointnd",
"(",
"c",
",",
"positions",
",",
"x",
",",
"result",
")",
"{",
"var",
"D",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
",",
"c",
".",
"length",
"]",
",",
"0.0",
")",
";",
"var",
"dvec",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
"]",
",",
"0.0",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"pi",
"=",
"positions",
"[",
"c",
"[",
"i",
"]",
"]",
";",
"dvec",
"[",
"i",
"]",
"=",
"numeric",
".",
"dot",
"(",
"pi",
",",
"x",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"c",
".",
"length",
";",
"++",
"j",
")",
"{",
"var",
"pj",
"=",
"positions",
"[",
"c",
"[",
"j",
"]",
"]",
";",
"D",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"D",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"numeric",
".",
"dot",
"(",
"pi",
",",
"pj",
")",
";",
"}",
"}",
"var",
"A",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
",",
"c",
".",
"length",
"+",
"2",
"]",
",",
"0.0",
")",
";",
"var",
"b",
"=",
"numeric",
".",
"rep",
"(",
"[",
"c",
".",
"length",
"+",
"2",
"]",
",",
"0.0",
")",
";",
"b",
"[",
"0",
"]",
"=",
"1.0",
"-",
"EPSILON",
";",
"b",
"[",
"1",
"]",
"=",
"-",
"(",
"1.0",
"+",
"EPSILON",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c",
".",
"length",
";",
"++",
"i",
")",
"{",
"A",
"[",
"i",
"]",
"[",
"0",
"]",
"=",
"1",
";",
"A",
"[",
"i",
"]",
"[",
"1",
"]",
"=",
"-",
"1",
"A",
"[",
"i",
"]",
"[",
"i",
"+",
"2",
"]",
"=",
"1",
";",
"}",
"for",
"(",
"var",
"attempts",
"=",
"0",
";",
"attempts",
"<",
"15",
";",
"++",
"attempts",
")",
"{",
"var",
"fortran_poop",
"=",
"numeric",
".",
"solveQP",
"(",
"D",
",",
"dvec",
",",
"A",
",",
"b",
")",
";",
"if",
"(",
"fortran_poop",
".",
"message",
".",
"length",
">",
"0",
")",
"{",
"//Quadratic form may be singular, perturb and resolve",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c",
".",
"length",
";",
"++",
"i",
")",
"{",
"D",
"[",
"i",
"]",
"[",
"i",
"]",
"+=",
"1e-8",
";",
"}",
"continue",
";",
"}",
"else",
"if",
"(",
"isNaN",
"(",
"fortran_poop",
".",
"value",
"[",
"0",
"]",
")",
")",
"{",
"break",
";",
"}",
"else",
"{",
"//Success!",
"var",
"solution",
"=",
"fortran_poop",
".",
"solution",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"++",
"i",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"0.0",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"solution",
".",
"length",
";",
"++",
"j",
")",
"{",
"result",
"[",
"i",
"]",
"+=",
"solution",
"[",
"j",
"]",
"*",
"positions",
"[",
"c",
"[",
"j",
"]",
"]",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"2.0",
"*",
"fortran_poop",
".",
"value",
"[",
"0",
"]",
"+",
"numeric",
".",
"dot",
"(",
"x",
",",
"x",
")",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"x",
".",
"length",
";",
"++",
"i",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"Number",
".",
"NaN",
";",
"}",
"return",
"Number",
".",
"NaN",
";",
"}"
] |
General purpose algorithm, uses quadratic programming, very slow
|
[
"General",
"purpose",
"algorithm",
"uses",
"quadratic",
"programming",
"very",
"slow"
] |
de523419bf633743f4333d0768b5e929bc82fd80
|
https://github.com/mikolalysenko/polytope-closest-point/blob/de523419bf633743f4333d0768b5e929bc82fd80/lib/closest_point_nd.js#L7-L53
|
37,729 |
blakeembrey/dombars
|
lib/runtime.js
|
function (subscriptions, fn, context) {
for (var id in subscriptions) {
for (var property in subscriptions[id]) {
fn.call(context, subscriptions[id][property], property, id);
}
}
}
|
javascript
|
function (subscriptions, fn, context) {
for (var id in subscriptions) {
for (var property in subscriptions[id]) {
fn.call(context, subscriptions[id][property], property, id);
}
}
}
|
[
"function",
"(",
"subscriptions",
",",
"fn",
",",
"context",
")",
"{",
"for",
"(",
"var",
"id",
"in",
"subscriptions",
")",
"{",
"for",
"(",
"var",
"property",
"in",
"subscriptions",
"[",
"id",
"]",
")",
"{",
"fn",
".",
"call",
"(",
"context",
",",
"subscriptions",
"[",
"id",
"]",
"[",
"property",
"]",
",",
"property",
",",
"id",
")",
";",
"}",
"}",
"}"
] |
Iterate over a subscriptions object, calling a function with the object
property details and a unique callback function.
@param {Array} subscriptions
@param {Function} fn
@param {Function} callback
|
[
"Iterate",
"over",
"a",
"subscriptions",
"object",
"calling",
"a",
"function",
"with",
"the",
"object",
"property",
"details",
"and",
"a",
"unique",
"callback",
"function",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L28-L34
|
|
37,730 |
blakeembrey/dombars
|
lib/runtime.js
|
function (fn, update, container) {
// Alias passed in variables for later access.
this._fn = fn;
this._update = update;
this._container = container;
// Assign every subscription instance a unique id. This helps with linking
// between parent and child subscription instances.
this.cid = 'c' + Utils.uniqueId();
this.children = {};
this.subscriptions = {};
this.unsubscriptions = [];
// Create statically bound function instances for public consumption.
this.boundUpdate = Utils.bind(this.update, this);
this.boundUnsubscription = Utils.bind(this.unsubscription, this);
}
|
javascript
|
function (fn, update, container) {
// Alias passed in variables for later access.
this._fn = fn;
this._update = update;
this._container = container;
// Assign every subscription instance a unique id. This helps with linking
// between parent and child subscription instances.
this.cid = 'c' + Utils.uniqueId();
this.children = {};
this.subscriptions = {};
this.unsubscriptions = [];
// Create statically bound function instances for public consumption.
this.boundUpdate = Utils.bind(this.update, this);
this.boundUnsubscription = Utils.bind(this.unsubscription, this);
}
|
[
"function",
"(",
"fn",
",",
"update",
",",
"container",
")",
"{",
"// Alias passed in variables for later access.",
"this",
".",
"_fn",
"=",
"fn",
";",
"this",
".",
"_update",
"=",
"update",
";",
"this",
".",
"_container",
"=",
"container",
";",
"// Assign every subscription instance a unique id. This helps with linking",
"// between parent and child subscription instances.",
"this",
".",
"cid",
"=",
"'c'",
"+",
"Utils",
".",
"uniqueId",
"(",
")",
";",
"this",
".",
"children",
"=",
"{",
"}",
";",
"this",
".",
"subscriptions",
"=",
"{",
"}",
";",
"this",
".",
"unsubscriptions",
"=",
"[",
"]",
";",
"// Create statically bound function instances for public consumption.",
"this",
".",
"boundUpdate",
"=",
"Utils",
".",
"bind",
"(",
"this",
".",
"update",
",",
"this",
")",
";",
"this",
".",
"boundUnsubscription",
"=",
"Utils",
".",
"bind",
"(",
"this",
".",
"unsubscription",
",",
"this",
")",
";",
"}"
] |
Create a new subsciption instance. This functionality is tightly coupled to
DOMBars program execution.
@param {Function} fn
@param {Function} update
@param {Object} container
|
[
"Create",
"a",
"new",
"subsciption",
"instance",
".",
"This",
"functionality",
"is",
"tightly",
"coupled",
"to",
"DOMBars",
"program",
"execution",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L44-L60
|
|
37,731 |
blakeembrey/dombars
|
lib/runtime.js
|
function (fn, create, update) {
var subscriber = new Subscription(fn, update, this);
// Immediately alias the starting value.
subscriber.value = subscriber.execute();
Utils.isFunction(create) && (subscriber.value = create(subscriber.value));
return subscriber;
}
|
javascript
|
function (fn, create, update) {
var subscriber = new Subscription(fn, update, this);
// Immediately alias the starting value.
subscriber.value = subscriber.execute();
Utils.isFunction(create) && (subscriber.value = create(subscriber.value));
return subscriber;
}
|
[
"function",
"(",
"fn",
",",
"create",
",",
"update",
")",
"{",
"var",
"subscriber",
"=",
"new",
"Subscription",
"(",
"fn",
",",
"update",
",",
"this",
")",
";",
"// Immediately alias the starting value.",
"subscriber",
".",
"value",
"=",
"subscriber",
".",
"execute",
"(",
")",
";",
"Utils",
".",
"isFunction",
"(",
"create",
")",
"&&",
"(",
"subscriber",
".",
"value",
"=",
"create",
"(",
"subscriber",
".",
"value",
")",
")",
";",
"return",
"subscriber",
";",
"}"
] |
Subscriber to function in the DOMBars execution instance.
@param {Function} fn
@param {Function} create
@param {Function} update
@return {Object}
|
[
"Subscriber",
"to",
"function",
"in",
"the",
"DOMBars",
"execution",
"instance",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L343-L351
|
|
37,732 |
blakeembrey/dombars
|
lib/runtime.js
|
function (fn) {
var container = this;
var program = function () {
var subscriber = new Subscription(fn, null, container);
return subscriber.execute.apply(subscriber, arguments);
};
Utils.extend(program, fn);
return program;
}
|
javascript
|
function (fn) {
var container = this;
var program = function () {
var subscriber = new Subscription(fn, null, container);
return subscriber.execute.apply(subscriber, arguments);
};
Utils.extend(program, fn);
return program;
}
|
[
"function",
"(",
"fn",
")",
"{",
"var",
"container",
"=",
"this",
";",
"var",
"program",
"=",
"function",
"(",
")",
"{",
"var",
"subscriber",
"=",
"new",
"Subscription",
"(",
"fn",
",",
"null",
",",
"container",
")",
";",
"return",
"subscriber",
".",
"execute",
".",
"apply",
"(",
"subscriber",
",",
"arguments",
")",
";",
"}",
";",
"Utils",
".",
"extend",
"(",
"program",
",",
"fn",
")",
";",
"return",
"program",
";",
"}"
] |
Wrap a function with a sanitized public subscriber object.
@param {Function} fn
@return {Function}
|
[
"Wrap",
"a",
"function",
"with",
"a",
"sanitized",
"public",
"subscriber",
"object",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L359-L370
|
|
37,733 |
blakeembrey/dombars
|
lib/runtime.js
|
function (fn, create) {
return subscribe.call(this, fn, function (value) {
return Utils.trackNode(create(value));
}, function (value) {
this.value.replace(create(value));
}).value.fragment;
}
|
javascript
|
function (fn, create) {
return subscribe.call(this, fn, function (value) {
return Utils.trackNode(create(value));
}, function (value) {
this.value.replace(create(value));
}).value.fragment;
}
|
[
"function",
"(",
"fn",
",",
"create",
")",
"{",
"return",
"subscribe",
".",
"call",
"(",
"this",
",",
"fn",
",",
"function",
"(",
"value",
")",
"{",
"return",
"Utils",
".",
"trackNode",
"(",
"create",
"(",
"value",
")",
")",
";",
"}",
",",
"function",
"(",
"value",
")",
"{",
"this",
".",
"value",
".",
"replace",
"(",
"create",
"(",
"value",
")",
")",
";",
"}",
")",
".",
"value",
".",
"fragment",
";",
"}"
] |
Render and subscribe a single DOM node using a custom creation function.
@param {Function} fn
@param {Function} create
@return {Node}
|
[
"Render",
"and",
"subscribe",
"a",
"single",
"DOM",
"node",
"using",
"a",
"custom",
"creation",
"function",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L379-L385
|
|
37,734 |
blakeembrey/dombars
|
lib/runtime.js
|
function (fn, cb) {
return subscribe.call(this, fn, function (value) {
return VM.createElement(value);
}, function (value) {
cb(this.value = VM.setTagName(this.value, value));
}).value;
}
|
javascript
|
function (fn, cb) {
return subscribe.call(this, fn, function (value) {
return VM.createElement(value);
}, function (value) {
cb(this.value = VM.setTagName(this.value, value));
}).value;
}
|
[
"function",
"(",
"fn",
",",
"cb",
")",
"{",
"return",
"subscribe",
".",
"call",
"(",
"this",
",",
"fn",
",",
"function",
"(",
"value",
")",
"{",
"return",
"VM",
".",
"createElement",
"(",
"value",
")",
";",
"}",
",",
"function",
"(",
"value",
")",
"{",
"cb",
"(",
"this",
".",
"value",
"=",
"VM",
".",
"setTagName",
"(",
"this",
".",
"value",
",",
"value",
")",
")",
";",
"}",
")",
".",
"value",
";",
"}"
] |
Create an element and subscribe to any changes. This method requires a
callback function for any element changes since you can't change a tag
name in place.
@param {Function} fn
@param {Function} cb
@return {Element}
|
[
"Create",
"an",
"element",
"and",
"subscribe",
"to",
"any",
"changes",
".",
"This",
"method",
"requires",
"a",
"callback",
"function",
"for",
"any",
"element",
"changes",
"since",
"you",
"can",
"t",
"change",
"a",
"tag",
"name",
"in",
"place",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L396-L402
|
|
37,735 |
blakeembrey/dombars
|
lib/runtime.js
|
function (currentEl, nameFn, valueFn) {
var attrName = subscribe.call(this, nameFn, null, function (value) {
VM.removeAttribute(currentEl(), this.value);
VM.setAttribute(currentEl(), this.value = value, attrValue.value);
});
var attrValue = subscribe.call(this, valueFn, null, function (value) {
VM.setAttribute(currentEl(), attrName.value, this.value = value);
});
return VM.setAttribute(currentEl(), attrName.value, attrValue.value);
}
|
javascript
|
function (currentEl, nameFn, valueFn) {
var attrName = subscribe.call(this, nameFn, null, function (value) {
VM.removeAttribute(currentEl(), this.value);
VM.setAttribute(currentEl(), this.value = value, attrValue.value);
});
var attrValue = subscribe.call(this, valueFn, null, function (value) {
VM.setAttribute(currentEl(), attrName.value, this.value = value);
});
return VM.setAttribute(currentEl(), attrName.value, attrValue.value);
}
|
[
"function",
"(",
"currentEl",
",",
"nameFn",
",",
"valueFn",
")",
"{",
"var",
"attrName",
"=",
"subscribe",
".",
"call",
"(",
"this",
",",
"nameFn",
",",
"null",
",",
"function",
"(",
"value",
")",
"{",
"VM",
".",
"removeAttribute",
"(",
"currentEl",
"(",
")",
",",
"this",
".",
"value",
")",
";",
"VM",
".",
"setAttribute",
"(",
"currentEl",
"(",
")",
",",
"this",
".",
"value",
"=",
"value",
",",
"attrValue",
".",
"value",
")",
";",
"}",
")",
";",
"var",
"attrValue",
"=",
"subscribe",
".",
"call",
"(",
"this",
",",
"valueFn",
",",
"null",
",",
"function",
"(",
"value",
")",
"{",
"VM",
".",
"setAttribute",
"(",
"currentEl",
"(",
")",
",",
"attrName",
".",
"value",
",",
"this",
".",
"value",
"=",
"value",
")",
";",
"}",
")",
";",
"return",
"VM",
".",
"setAttribute",
"(",
"currentEl",
"(",
")",
",",
"attrName",
".",
"value",
",",
"attrValue",
".",
"value",
")",
";",
"}"
] |
Set an elements attribute. We accept the current element a function
because when a tag name changes we will lose reference to the actively
rendered element.
@param {Function} currentEl
@param {Function} nameFn
@param {Function} valueFn
|
[
"Set",
"an",
"elements",
"attribute",
".",
"We",
"accept",
"the",
"current",
"element",
"a",
"function",
"because",
"when",
"a",
"tag",
"name",
"changes",
"we",
"will",
"lose",
"reference",
"to",
"the",
"actively",
"rendered",
"element",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L426-L437
|
|
37,736 |
blakeembrey/dombars
|
lib/runtime.js
|
function (fn) {
return subscribe.call(this, fn, function (value) {
return VM.createComment(value);
}, function (value) {
this.value.textContent = value;
}).value;
}
|
javascript
|
function (fn) {
return subscribe.call(this, fn, function (value) {
return VM.createComment(value);
}, function (value) {
this.value.textContent = value;
}).value;
}
|
[
"function",
"(",
"fn",
")",
"{",
"return",
"subscribe",
".",
"call",
"(",
"this",
",",
"fn",
",",
"function",
"(",
"value",
")",
"{",
"return",
"VM",
".",
"createComment",
"(",
"value",
")",
";",
"}",
",",
"function",
"(",
"value",
")",
"{",
"this",
".",
"value",
".",
"textContent",
"=",
"value",
";",
"}",
")",
".",
"value",
";",
"}"
] |
Create a comment node and subscribe to any changes.
@param {Function} fn
@return {Comment}
|
[
"Create",
"a",
"comment",
"node",
"and",
"subscribe",
"to",
"any",
"changes",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/runtime.js#L465-L471
|
|
37,737 |
openbiz/openbiz
|
lib/services/ObjectService.js
|
function(objectName)
{
var app = this;
var objectName = objectName.split(".");
var obj = {};
try
{
switch(objectName.length){
case 1:
for(var module in app.modules)
{
if(app.modules[module].models.hasOwnProperty(objectName[0]))
{
objectName[1]=objectName[0];
objectName[0]=module;
break;
}
}
break;
}
if(app.modules[objectName[0]].models.hasOwnProperty(objectName[1])){
obj = app.modules[objectName[0]].models[objectName[1]];
}else{
throw "not found";
}
}
catch(e)
{
switch(objectName.length){
case 1:
var modulePath = path.join(app._path,"modules");
fs.readdirSync(modulePath).forEach(function(moduleName){
var objFilePath = path.join(app._path,"modules",moduleName,"models",objectName[0]);
if(fs.existsSync(objFilePath+".js"))
{
if( app.modules.hasOwnProperty(moduleName) &&
app.modules[moduleName].hasOwnProperty('models') &&
app.modules[moduleName].models.hasOwnProperty(objectName[0])){
var obj = app.modules[moduleName].models[objectName[0]];
return obj;
}else{
var obj = require(objFilePath)(app);
if(typeof app.modules[moduleName] != "object") app.modules[moduleName]={};
if(typeof app.modules[moduleName].models != "object") app.modules[moduleName].models={};
}
app.modules[moduleName].models[objectName[0]] = obj;
}
});
break;
case 2:
var objFilePath = path.join(app._path,"modules",objectName[0],"models",objectName[1]);
if(fs.existsSync(objFilePath+".js"))
{
var obj = require(objFilePath)(app);
if(typeof app.modules[objectName[0]] != "object") app.modules[objectName[0]]={};
if(typeof app.modules[objectName[0]].models != "object") app.modules[objectName[0]].models={};
app.modules[objectName[0]].models[objectName[1]] = obj;
}
break;
}
}
return obj;
}
|
javascript
|
function(objectName)
{
var app = this;
var objectName = objectName.split(".");
var obj = {};
try
{
switch(objectName.length){
case 1:
for(var module in app.modules)
{
if(app.modules[module].models.hasOwnProperty(objectName[0]))
{
objectName[1]=objectName[0];
objectName[0]=module;
break;
}
}
break;
}
if(app.modules[objectName[0]].models.hasOwnProperty(objectName[1])){
obj = app.modules[objectName[0]].models[objectName[1]];
}else{
throw "not found";
}
}
catch(e)
{
switch(objectName.length){
case 1:
var modulePath = path.join(app._path,"modules");
fs.readdirSync(modulePath).forEach(function(moduleName){
var objFilePath = path.join(app._path,"modules",moduleName,"models",objectName[0]);
if(fs.existsSync(objFilePath+".js"))
{
if( app.modules.hasOwnProperty(moduleName) &&
app.modules[moduleName].hasOwnProperty('models') &&
app.modules[moduleName].models.hasOwnProperty(objectName[0])){
var obj = app.modules[moduleName].models[objectName[0]];
return obj;
}else{
var obj = require(objFilePath)(app);
if(typeof app.modules[moduleName] != "object") app.modules[moduleName]={};
if(typeof app.modules[moduleName].models != "object") app.modules[moduleName].models={};
}
app.modules[moduleName].models[objectName[0]] = obj;
}
});
break;
case 2:
var objFilePath = path.join(app._path,"modules",objectName[0],"models",objectName[1]);
if(fs.existsSync(objFilePath+".js"))
{
var obj = require(objFilePath)(app);
if(typeof app.modules[objectName[0]] != "object") app.modules[objectName[0]]={};
if(typeof app.modules[objectName[0]].models != "object") app.modules[objectName[0]].models={};
app.modules[objectName[0]].models[objectName[1]] = obj;
}
break;
}
}
return obj;
}
|
[
"function",
"(",
"objectName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"objectName",
"=",
"objectName",
".",
"split",
"(",
"\".\"",
")",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"try",
"{",
"switch",
"(",
"objectName",
".",
"length",
")",
"{",
"case",
"1",
":",
"for",
"(",
"var",
"module",
"in",
"app",
".",
"modules",
")",
"{",
"if",
"(",
"app",
".",
"modules",
"[",
"module",
"]",
".",
"models",
".",
"hasOwnProperty",
"(",
"objectName",
"[",
"0",
"]",
")",
")",
"{",
"objectName",
"[",
"1",
"]",
"=",
"objectName",
"[",
"0",
"]",
";",
"objectName",
"[",
"0",
"]",
"=",
"module",
";",
"break",
";",
"}",
"}",
"break",
";",
"}",
"if",
"(",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
".",
"hasOwnProperty",
"(",
"objectName",
"[",
"1",
"]",
")",
")",
"{",
"obj",
"=",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"[",
"objectName",
"[",
"1",
"]",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"switch",
"(",
"objectName",
".",
"length",
")",
"{",
"case",
"1",
":",
"var",
"modulePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"modules\"",
")",
";",
"fs",
".",
"readdirSync",
"(",
"modulePath",
")",
".",
"forEach",
"(",
"function",
"(",
"moduleName",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"modules\"",
",",
"moduleName",
",",
"\"models\"",
",",
"objectName",
"[",
"0",
"]",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"if",
"(",
"app",
".",
"modules",
".",
"hasOwnProperty",
"(",
"moduleName",
")",
"&&",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"hasOwnProperty",
"(",
"'models'",
")",
"&&",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
".",
"hasOwnProperty",
"(",
"objectName",
"[",
"0",
"]",
")",
")",
"{",
"var",
"obj",
"=",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"[",
"objectName",
"[",
"0",
"]",
"]",
";",
"return",
"obj",
";",
"}",
"else",
"{",
"var",
"obj",
"=",
"require",
"(",
"objFilePath",
")",
"(",
"app",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"moduleName",
"]",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"moduleName",
"]",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"=",
"{",
"}",
";",
"}",
"app",
".",
"modules",
"[",
"moduleName",
"]",
".",
"models",
"[",
"objectName",
"[",
"0",
"]",
"]",
"=",
"obj",
";",
"}",
"}",
")",
";",
"break",
";",
"case",
"2",
":",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"modules\"",
",",
"objectName",
"[",
"0",
"]",
",",
"\"models\"",
",",
"objectName",
"[",
"1",
"]",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"var",
"obj",
"=",
"require",
"(",
"objFilePath",
")",
"(",
"app",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
"=",
"{",
"}",
";",
"if",
"(",
"typeof",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"!=",
"\"object\"",
")",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"=",
"{",
"}",
";",
"app",
".",
"modules",
"[",
"objectName",
"[",
"0",
"]",
"]",
".",
"models",
"[",
"objectName",
"[",
"1",
"]",
"]",
"=",
"obj",
";",
"}",
"break",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] |
Get specified openbiz data model class
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} objectName - The specified openbiz controller name
@returns {openbiz.objects.Controller}
@example
//below code is how to get a instance of "openbiz-cubi.user.User" class
//cubiApp is instance of openbiz.objects.Application
var myModel = cubiApp.getModel("User");
//then you can access methods of this model like 'hasPermission()'
if(myModel.hasPermission('some-permission')){
...
}
@example
//if you want to call this method directly , please try this way
require('openbiz/services/ObjectService').getController.apply(applicationPointer,objectName)
|
[
"Get",
"specified",
"openbiz",
"data",
"model",
"class"
] |
997f1398396683d7ad667b1b360ce74c7c7fcf6f
|
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L56-L118
|
|
37,738 |
openbiz/openbiz
|
lib/services/ObjectService.js
|
function(policyName)
{
var app = this;
var objectName = policyName;
var obj = {};
try
{
if(app.policies.hasOwnProperty(policyName)){
obj = app.policies[policyName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"policies",policyName);
if(fs.existsSync(objFilePath+".js"))
{
obj = require(objFilePath);
if(typeof app.policies != "object") app.policies={};
app.policies[policyName] = obj;
}
}
return obj;
}
|
javascript
|
function(policyName)
{
var app = this;
var objectName = policyName;
var obj = {};
try
{
if(app.policies.hasOwnProperty(policyName)){
obj = app.policies[policyName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"policies",policyName);
if(fs.existsSync(objFilePath+".js"))
{
obj = require(objFilePath);
if(typeof app.policies != "object") app.policies={};
app.policies[policyName] = obj;
}
}
return obj;
}
|
[
"function",
"(",
"policyName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"objectName",
"=",
"policyName",
";",
"var",
"obj",
"=",
"{",
"}",
";",
"try",
"{",
"if",
"(",
"app",
".",
"policies",
".",
"hasOwnProperty",
"(",
"policyName",
")",
")",
"{",
"obj",
"=",
"app",
".",
"policies",
"[",
"policyName",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"policies\"",
",",
"policyName",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"obj",
"=",
"require",
"(",
"objFilePath",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"policies",
"!=",
"\"object\"",
")",
"app",
".",
"policies",
"=",
"{",
"}",
";",
"app",
".",
"policies",
"[",
"policyName",
"]",
"=",
"obj",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] |
Get specified openbiz policy middle-ware function.
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService.
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} policyName - The specified policy middle-ware name
@returns {function}
@example
//below code is how to get the middle-ware of "cubi.user.ensureSomething" function
//cubiApp is instance of openbiz.objects.Application
var something = cubiApp.getPolicy("ensureSomething");
@example
//if you want to call this method directly , please try this way
require('openbiz/services/ObjectService').getPolicy.apply(applicationPointer,policyName)
|
[
"Get",
"specified",
"openbiz",
"policy",
"middle",
"-",
"ware",
"function",
"."
] |
997f1398396683d7ad667b1b360ce74c7c7fcf6f
|
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L223-L247
|
|
37,739 |
openbiz/openbiz
|
lib/services/ObjectService.js
|
function(roleName)
{
var app = this;
var role = {permissions:[]};
try
{
if(app.roles.hasOwnProperty(roleName)){
role = app.roles[roleName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"roles",roleName);
if(fs.existsSync(objFilePath+".js"))
{
var roleConfig = require(objFilePath);
if(typeof app.roles != "object") app.roles={};
app.roles[roleName]= roleConfig.permissions;
if(roleConfig.hasOwnProperty('isDefault') && roleConfig.isDefault == true){
app.defaultRoles.push(roleName);
}
role = roleConfig.permissions;
}
}
return role;
}
|
javascript
|
function(roleName)
{
var app = this;
var role = {permissions:[]};
try
{
if(app.roles.hasOwnProperty(roleName)){
role = app.roles[roleName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"roles",roleName);
if(fs.existsSync(objFilePath+".js"))
{
var roleConfig = require(objFilePath);
if(typeof app.roles != "object") app.roles={};
app.roles[roleName]= roleConfig.permissions;
if(roleConfig.hasOwnProperty('isDefault') && roleConfig.isDefault == true){
app.defaultRoles.push(roleName);
}
role = roleConfig.permissions;
}
}
return role;
}
|
[
"function",
"(",
"roleName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"role",
"=",
"{",
"permissions",
":",
"[",
"]",
"}",
";",
"try",
"{",
"if",
"(",
"app",
".",
"roles",
".",
"hasOwnProperty",
"(",
"roleName",
")",
")",
"{",
"role",
"=",
"app",
".",
"roles",
"[",
"roleName",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"roles\"",
",",
"roleName",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"var",
"roleConfig",
"=",
"require",
"(",
"objFilePath",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"roles",
"!=",
"\"object\"",
")",
"app",
".",
"roles",
"=",
"{",
"}",
";",
"app",
".",
"roles",
"[",
"roleName",
"]",
"=",
"roleConfig",
".",
"permissions",
";",
"if",
"(",
"roleConfig",
".",
"hasOwnProperty",
"(",
"'isDefault'",
")",
"&&",
"roleConfig",
".",
"isDefault",
"==",
"true",
")",
"{",
"app",
".",
"defaultRoles",
".",
"push",
"(",
"roleName",
")",
";",
"}",
"role",
"=",
"roleConfig",
".",
"permissions",
";",
"}",
"}",
"return",
"role",
";",
"}"
] |
Get specified openbiz pre-defined system role.
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService.
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} roleName - The specified system role name
@returns {array.<string>} Array of permission names,
the permission could be used by {@link openbiz.policies.ensurePermission} middle-ware for protect resource access
@example
//below code is how to get the role named "cubi-admin"
//cubiApp is instance of openbiz.objects.Application
var cubiAdmin = app.getRole("cubi-admin");
//cubiAdmin will looks like below
// [
// "cubi-user-manage",
// "cubi-contact-manage",
// "cubi-account-manage"
// ]
@example
//if you want to call this method directly , please try this way
require('openbiz/services/ObjectService').getRole.apply(applicationPointer,roleName)
|
[
"Get",
"specified",
"openbiz",
"pre",
"-",
"defined",
"system",
"role",
"."
] |
997f1398396683d7ad667b1b360ce74c7c7fcf6f
|
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L276-L303
|
|
37,740 |
openbiz/openbiz
|
lib/services/ObjectService.js
|
function(exceptionName)
{
var app = this;
var exception = {};
try
{
if(app.exceptions.hasOwnProperty(exceptionName)){
exception = app.exceptions[exceptionName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"exceptions",exceptionName);
if(fs.existsSync(objFilePath+".js"))
{
var exceptionConfig = require(objFilePath);
if(typeof app.exceptions != "object") app.exceptions={};
app.exceptions[exceptionName]= exceptionConfig;
exception = exceptionConfig;
}
}
return exception;
}
|
javascript
|
function(exceptionName)
{
var app = this;
var exception = {};
try
{
if(app.exceptions.hasOwnProperty(exceptionName)){
exception = app.exceptions[exceptionName];
}else{
throw "not found";
}
}
catch(e)
{
var objFilePath = path.join(app._path,"exceptions",exceptionName);
if(fs.existsSync(objFilePath+".js"))
{
var exceptionConfig = require(objFilePath);
if(typeof app.exceptions != "object") app.exceptions={};
app.exceptions[exceptionName]= exceptionConfig;
exception = exceptionConfig;
}
}
return exception;
}
|
[
"function",
"(",
"exceptionName",
")",
"{",
"var",
"app",
"=",
"this",
";",
"var",
"exception",
"=",
"{",
"}",
";",
"try",
"{",
"if",
"(",
"app",
".",
"exceptions",
".",
"hasOwnProperty",
"(",
"exceptionName",
")",
")",
"{",
"exception",
"=",
"app",
".",
"exceptions",
"[",
"exceptionName",
"]",
";",
"}",
"else",
"{",
"throw",
"\"not found\"",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"objFilePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"_path",
",",
"\"exceptions\"",
",",
"exceptionName",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"objFilePath",
"+",
"\".js\"",
")",
")",
"{",
"var",
"exceptionConfig",
"=",
"require",
"(",
"objFilePath",
")",
";",
"if",
"(",
"typeof",
"app",
".",
"exceptions",
"!=",
"\"object\"",
")",
"app",
".",
"exceptions",
"=",
"{",
"}",
";",
"app",
".",
"exceptions",
"[",
"exceptionName",
"]",
"=",
"exceptionConfig",
";",
"exception",
"=",
"exceptionConfig",
";",
"}",
"}",
"return",
"exception",
";",
"}"
] |
Get specified openbiz pre-defined system exception.
This method it part of {@link openbiz.objects.Application},
please never call this directly by ObjectService.
if need to call this method, you have to use javascript's function.apply(applicationPointer,params)
please see sample
@memberof openbiz.services.ObjectService
@param {string} exceptionName
@returns object Exception object
@example
var Exception = app.openbiz.apps.xxxx.getExecption("Exception");
throw new Exception(exceptionCode, error);
|
[
"Get",
"specified",
"openbiz",
"pre",
"-",
"defined",
"system",
"exception",
"."
] |
997f1398396683d7ad667b1b360ce74c7c7fcf6f
|
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/services/ObjectService.js#L322-L346
|
|
37,741 |
arobson/consequent
|
src/loader.js
|
loadModule
|
function loadModule (actorPath) {
try {
let key = path.resolve(actorPath)
delete require.cache[ key ]
return require(actorPath)
} catch (err) {
log.error(`Error loading actor module at ${actorPath} with ${err.stack}`)
return undefined
}
}
|
javascript
|
function loadModule (actorPath) {
try {
let key = path.resolve(actorPath)
delete require.cache[ key ]
return require(actorPath)
} catch (err) {
log.error(`Error loading actor module at ${actorPath} with ${err.stack}`)
return undefined
}
}
|
[
"function",
"loadModule",
"(",
"actorPath",
")",
"{",
"try",
"{",
"let",
"key",
"=",
"path",
".",
"resolve",
"(",
"actorPath",
")",
"delete",
"require",
".",
"cache",
"[",
"key",
"]",
"return",
"require",
"(",
"actorPath",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"`",
"${",
"actorPath",
"}",
"${",
"err",
".",
"stack",
"}",
"`",
")",
"return",
"undefined",
"}",
"}"
] |
loads a module based on the file path
|
[
"loads",
"a",
"module",
"based",
"on",
"the",
"file",
"path"
] |
70cf5c7cd07ae530ca1b5996b53211c520908b4f
|
https://github.com/arobson/consequent/blob/70cf5c7cd07ae530ca1b5996b53211c520908b4f/src/loader.js#L19-L28
|
37,742 |
arobson/consequent
|
src/loader.js
|
loadActors
|
function loadActors (fount, actors) {
let result
function addActor (acc, instance) {
let factory = isFunction(instance.state)
? instance.state : () => clone(instance.state)
processHandles(instance)
acc[ instance.actor.type ] = {
factory: factory,
metadata: instance
}
return acc
}
function onActors (list) {
function onInstances (instances) {
return instances.reduce(addActor, {})
}
let modules = filter(list)
let promises = modules.map((modulePath) => {
let actorFn = loadModule(modulePath)
return fount.inject(actorFn)
})
return Promise
.all(promises)
.then(onInstances)
}
if (isString(actors)) {
let filePath = actors
if (!fs.existsSync(filePath)) {
filePath = path.resolve(process.cwd(), filePath)
}
return getActors(filePath)
.then(onActors)
} else if (Array.isArray(actors)) {
result = actors.reduce((acc, instance) => {
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isObject(actors)) {
let keys = Object.keys(actors)
result = keys.reduce((acc, key) => {
let instance = actors[ key ]
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isFunction(actors)) {
result = actors()
if (!result.then) {
result = Promise.resolve(result)
}
return result.then(function (list) {
return list.reduce((acc, instance) => {
addActor(acc, instance)
return Promise.resolve(acc)
}, {})
})
}
}
|
javascript
|
function loadActors (fount, actors) {
let result
function addActor (acc, instance) {
let factory = isFunction(instance.state)
? instance.state : () => clone(instance.state)
processHandles(instance)
acc[ instance.actor.type ] = {
factory: factory,
metadata: instance
}
return acc
}
function onActors (list) {
function onInstances (instances) {
return instances.reduce(addActor, {})
}
let modules = filter(list)
let promises = modules.map((modulePath) => {
let actorFn = loadModule(modulePath)
return fount.inject(actorFn)
})
return Promise
.all(promises)
.then(onInstances)
}
if (isString(actors)) {
let filePath = actors
if (!fs.existsSync(filePath)) {
filePath = path.resolve(process.cwd(), filePath)
}
return getActors(filePath)
.then(onActors)
} else if (Array.isArray(actors)) {
result = actors.reduce((acc, instance) => {
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isObject(actors)) {
let keys = Object.keys(actors)
result = keys.reduce((acc, key) => {
let instance = actors[ key ]
addActor(acc, instance)
return acc
}, {})
return Promise.resolve(result)
} else if (isFunction(actors)) {
result = actors()
if (!result.then) {
result = Promise.resolve(result)
}
return result.then(function (list) {
return list.reduce((acc, instance) => {
addActor(acc, instance)
return Promise.resolve(acc)
}, {})
})
}
}
|
[
"function",
"loadActors",
"(",
"fount",
",",
"actors",
")",
"{",
"let",
"result",
"function",
"addActor",
"(",
"acc",
",",
"instance",
")",
"{",
"let",
"factory",
"=",
"isFunction",
"(",
"instance",
".",
"state",
")",
"?",
"instance",
".",
"state",
":",
"(",
")",
"=>",
"clone",
"(",
"instance",
".",
"state",
")",
"processHandles",
"(",
"instance",
")",
"acc",
"[",
"instance",
".",
"actor",
".",
"type",
"]",
"=",
"{",
"factory",
":",
"factory",
",",
"metadata",
":",
"instance",
"}",
"return",
"acc",
"}",
"function",
"onActors",
"(",
"list",
")",
"{",
"function",
"onInstances",
"(",
"instances",
")",
"{",
"return",
"instances",
".",
"reduce",
"(",
"addActor",
",",
"{",
"}",
")",
"}",
"let",
"modules",
"=",
"filter",
"(",
"list",
")",
"let",
"promises",
"=",
"modules",
".",
"map",
"(",
"(",
"modulePath",
")",
"=>",
"{",
"let",
"actorFn",
"=",
"loadModule",
"(",
"modulePath",
")",
"return",
"fount",
".",
"inject",
"(",
"actorFn",
")",
"}",
")",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"onInstances",
")",
"}",
"if",
"(",
"isString",
"(",
"actors",
")",
")",
"{",
"let",
"filePath",
"=",
"actors",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"filePath",
")",
"}",
"return",
"getActors",
"(",
"filePath",
")",
".",
"then",
"(",
"onActors",
")",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"actors",
")",
")",
"{",
"result",
"=",
"actors",
".",
"reduce",
"(",
"(",
"acc",
",",
"instance",
")",
"=>",
"{",
"addActor",
"(",
"acc",
",",
"instance",
")",
"return",
"acc",
"}",
",",
"{",
"}",
")",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
"else",
"if",
"(",
"isObject",
"(",
"actors",
")",
")",
"{",
"let",
"keys",
"=",
"Object",
".",
"keys",
"(",
"actors",
")",
"result",
"=",
"keys",
".",
"reduce",
"(",
"(",
"acc",
",",
"key",
")",
"=>",
"{",
"let",
"instance",
"=",
"actors",
"[",
"key",
"]",
"addActor",
"(",
"acc",
",",
"instance",
")",
"return",
"acc",
"}",
",",
"{",
"}",
")",
"return",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
"else",
"if",
"(",
"isFunction",
"(",
"actors",
")",
")",
"{",
"result",
"=",
"actors",
"(",
")",
"if",
"(",
"!",
"result",
".",
"then",
")",
"{",
"result",
"=",
"Promise",
".",
"resolve",
"(",
"result",
")",
"}",
"return",
"result",
".",
"then",
"(",
"function",
"(",
"list",
")",
"{",
"return",
"list",
".",
"reduce",
"(",
"(",
"acc",
",",
"instance",
")",
"=>",
"{",
"addActor",
"(",
"acc",
",",
"instance",
")",
"return",
"Promise",
".",
"resolve",
"(",
"acc",
")",
"}",
",",
"{",
"}",
")",
"}",
")",
"}",
"}"
] |
load actors from path and returns the modules once they're loaded
|
[
"load",
"actors",
"from",
"path",
"and",
"returns",
"the",
"modules",
"once",
"they",
"re",
"loaded"
] |
70cf5c7cd07ae530ca1b5996b53211c520908b4f
|
https://github.com/arobson/consequent/blob/70cf5c7cd07ae530ca1b5996b53211c520908b4f/src/loader.js#L31-L94
|
37,743 |
mlewand-org/vscode-test-set-content
|
src/index.js
|
setContent
|
function setContent( content, options ) {
options = getOptions( options );
return vscode.workspace.openTextDocument( {
language: options.language
} )
.then( doc => vscode.window.showTextDocument( doc ) )
.then( editor => {
let editBuilder = textEdit => {
textEdit.insert( new vscode.Position( 0, 0 ), String( content ) );
};
return editor.edit( editBuilder, {
undoStopBefore: true,
undoStopAfter: false
} )
.then( () => editor );
} );
}
|
javascript
|
function setContent( content, options ) {
options = getOptions( options );
return vscode.workspace.openTextDocument( {
language: options.language
} )
.then( doc => vscode.window.showTextDocument( doc ) )
.then( editor => {
let editBuilder = textEdit => {
textEdit.insert( new vscode.Position( 0, 0 ), String( content ) );
};
return editor.edit( editBuilder, {
undoStopBefore: true,
undoStopAfter: false
} )
.then( () => editor );
} );
}
|
[
"function",
"setContent",
"(",
"content",
",",
"options",
")",
"{",
"options",
"=",
"getOptions",
"(",
"options",
")",
";",
"return",
"vscode",
".",
"workspace",
".",
"openTextDocument",
"(",
"{",
"language",
":",
"options",
".",
"language",
"}",
")",
".",
"then",
"(",
"doc",
"=>",
"vscode",
".",
"window",
".",
"showTextDocument",
"(",
"doc",
")",
")",
".",
"then",
"(",
"editor",
"=>",
"{",
"let",
"editBuilder",
"=",
"textEdit",
"=>",
"{",
"textEdit",
".",
"insert",
"(",
"new",
"vscode",
".",
"Position",
"(",
"0",
",",
"0",
")",
",",
"String",
"(",
"content",
")",
")",
";",
"}",
";",
"return",
"editor",
".",
"edit",
"(",
"editBuilder",
",",
"{",
"undoStopBefore",
":",
"true",
",",
"undoStopAfter",
":",
"false",
"}",
")",
".",
"then",
"(",
"(",
")",
"=>",
"editor",
")",
";",
"}",
")",
";",
"}"
] |
Returns a promise that will provide a tet editor with given `content`.
@param {String} content
@param {Object} [options] Config object.
@param {String} [options.language='text'] Indicates what language should the editor use.
@param {String} [options.caret='^'] Character used to represent caret (collapsed selection).
@param {Object} [options.anchor]
@param {String} [options.anchor.start='['] Selection anchor open character.
@param {String} [options.anchor.end=']'] Selection anchor close character.
@param {Object} [options.active]
@param {String} [options.active.start='{'] Selection active part open character.
@param {String} [options.active.end='}'] Selection active part close character.
@returns {Promise<TextEditor>}
|
[
"Returns",
"a",
"promise",
"that",
"will",
"provide",
"a",
"tet",
"editor",
"with",
"given",
"content",
"."
] |
6ac90d0dfa943602d1a6c8f209f794649cfd2275
|
https://github.com/mlewand-org/vscode-test-set-content/blob/6ac90d0dfa943602d1a6c8f209f794649cfd2275/src/index.js#L20-L38
|
37,744 |
freshout-dev/fluorine
|
fluorine.js
|
init
|
function init(config) {
Object.keys(config).forEach(function (property) {
this[property] = config[property];
}, this);
}
|
javascript
|
function init(config) {
Object.keys(config).forEach(function (property) {
this[property] = config[property];
}, this);
}
|
[
"function",
"init",
"(",
"config",
")",
"{",
"Object",
".",
"keys",
"(",
"config",
")",
".",
"forEach",
"(",
"function",
"(",
"property",
")",
"{",
"this",
"[",
"property",
"]",
"=",
"config",
"[",
"property",
"]",
";",
"}",
",",
"this",
")",
";",
"}"
] |
initializer for the class
@property init <public> [Function]
@argument config <optional> [Object]
|
[
"initializer",
"for",
"the",
"class"
] |
deccd2e0d003678c035a91dffdc6873d9eba8d50
|
https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L22-L26
|
37,745 |
freshout-dev/fluorine
|
fluorine.js
|
toDot
|
function toDot() {
var dotGraph = [];
dotGraph.push("digraph " + this.name + " {");
this.children.forEach(function (step) {
dotGraph.push(step.name);
step.dependencies.forEach(function (dependencyName) {
dotGraph.push(dependencyName + " -> " + step.name);
});
});
dotGraph.push("}");
console.debug("Put this in a file and run this in a terminal: dot -Tsvg yourDotFile > graph.svg");
return dotGraph.join("\n");
}
|
javascript
|
function toDot() {
var dotGraph = [];
dotGraph.push("digraph " + this.name + " {");
this.children.forEach(function (step) {
dotGraph.push(step.name);
step.dependencies.forEach(function (dependencyName) {
dotGraph.push(dependencyName + " -> " + step.name);
});
});
dotGraph.push("}");
console.debug("Put this in a file and run this in a terminal: dot -Tsvg yourDotFile > graph.svg");
return dotGraph.join("\n");
}
|
[
"function",
"toDot",
"(",
")",
"{",
"var",
"dotGraph",
"=",
"[",
"]",
";",
"dotGraph",
".",
"push",
"(",
"\"digraph \"",
"+",
"this",
".",
"name",
"+",
"\" {\"",
")",
";",
"this",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"step",
")",
"{",
"dotGraph",
".",
"push",
"(",
"step",
".",
"name",
")",
";",
"step",
".",
"dependencies",
".",
"forEach",
"(",
"function",
"(",
"dependencyName",
")",
"{",
"dotGraph",
".",
"push",
"(",
"dependencyName",
"+",
"\" -> \"",
"+",
"step",
".",
"name",
")",
";",
"}",
")",
";",
"}",
")",
";",
"dotGraph",
".",
"push",
"(",
"\"}\"",
")",
";",
"console",
".",
"debug",
"(",
"\"Put this in a file and run this in a terminal: dot -Tsvg yourDotFile > graph.svg\"",
")",
";",
"return",
"dotGraph",
".",
"join",
"(",
"\"\\n\"",
")",
";",
"}"
] |
This is a utility method to introspect a flow. flow use case is for when a complex sequence
needs to be solved and its very hard to solve it by simpler programming constructs, so mapping
this sequences is hard, this method dumps the flow into a dot directed graph to be visualized.
@property toDot <public> [Function]
@return string The actual dot string that represents this flow graph.
|
[
"This",
"is",
"a",
"utility",
"method",
"to",
"introspect",
"a",
"flow",
".",
"flow",
"use",
"case",
"is",
"for",
"when",
"a",
"complex",
"sequence",
"needs",
"to",
"be",
"solved",
"and",
"its",
"very",
"hard",
"to",
"solve",
"it",
"by",
"simpler",
"programming",
"constructs",
"so",
"mapping",
"this",
"sequences",
"is",
"hard",
"this",
"method",
"dumps",
"the",
"flow",
"into",
"a",
"dot",
"directed",
"graph",
"to",
"be",
"visualized",
"."
] |
deccd2e0d003678c035a91dffdc6873d9eba8d50
|
https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L146-L161
|
37,746 |
freshout-dev/fluorine
|
fluorine.js
|
function (nodeLikeObject) {
var node = this;
if (nodeLikeObject.hasOwnProperty('data') === true) {
setTimeout(function runFlowNode() {
node.code(nodeLikeObject);
}, 0);
}
else if (typeof this.errorCode !== 'undefined') {
setTimeout(function runFlowNodeError() {
node.errorCode(nodeLikeObject);
}, 0);
}
}
|
javascript
|
function (nodeLikeObject) {
var node = this;
if (nodeLikeObject.hasOwnProperty('data') === true) {
setTimeout(function runFlowNode() {
node.code(nodeLikeObject);
}, 0);
}
else if (typeof this.errorCode !== 'undefined') {
setTimeout(function runFlowNodeError() {
node.errorCode(nodeLikeObject);
}, 0);
}
}
|
[
"function",
"(",
"nodeLikeObject",
")",
"{",
"var",
"node",
"=",
"this",
";",
"if",
"(",
"nodeLikeObject",
".",
"hasOwnProperty",
"(",
"'data'",
")",
"===",
"true",
")",
"{",
"setTimeout",
"(",
"function",
"runFlowNode",
"(",
")",
"{",
"node",
".",
"code",
"(",
"nodeLikeObject",
")",
";",
"}",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"this",
".",
"errorCode",
"!==",
"'undefined'",
")",
"{",
"setTimeout",
"(",
"function",
"runFlowNodeError",
"(",
")",
"{",
"node",
".",
"errorCode",
"(",
"nodeLikeObject",
")",
";",
"}",
",",
"0",
")",
";",
"}",
"}"
] |
Executes the node. This is done via a setTimeout to release the stack depth.
Even thought it is required for events to be synchronous, a flow step does
not represent a safe data signal propagation, instead is a pass to other process
like behavior.
@property run <public> [Function]
@argument FlowNode <required> [Object]
@return Undefined
|
[
"Executes",
"the",
"node",
".",
"This",
"is",
"done",
"via",
"a",
"setTimeout",
"to",
"release",
"the",
"stack",
"depth",
".",
"Even",
"thought",
"it",
"is",
"required",
"for",
"events",
"to",
"be",
"synchronous",
"a",
"flow",
"step",
"does",
"not",
"represent",
"a",
"safe",
"data",
"signal",
"propagation",
"instead",
"is",
"a",
"pass",
"to",
"other",
"process",
"like",
"behavior",
"."
] |
deccd2e0d003678c035a91dffdc6873d9eba8d50
|
https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L240-L252
|
|
37,747 |
freshout-dev/fluorine
|
fluorine.js
|
function (data) {
this.data = data;
this.isFulfilled = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
}
|
javascript
|
function (data) {
this.data = data;
this.isFulfilled = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
}
|
[
"function",
"(",
"data",
")",
"{",
"this",
".",
"data",
"=",
"data",
";",
"this",
".",
"isFulfilled",
"=",
"true",
";",
"if",
"(",
"this",
".",
"parent",
"===",
"null",
")",
"{",
"return",
";",
"}",
"this",
".",
"parent",
".",
"dispatch",
"(",
"this",
".",
"name",
")",
";",
"}"
] |
method to notify that the step executed succesfully.
@property fulfill <public> [Function]
|
[
"method",
"to",
"notify",
"that",
"the",
"step",
"executed",
"succesfully",
"."
] |
deccd2e0d003678c035a91dffdc6873d9eba8d50
|
https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L258-L267
|
|
37,748 |
freshout-dev/fluorine
|
fluorine.js
|
function (error) {
this.error = error;
this.isRejected = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
this.parent.dispatch('reject', {
data : { node : this, error: error }
});
}
|
javascript
|
function (error) {
this.error = error;
this.isRejected = true;
if (this.parent === null) {
return;
}
this.parent.dispatch(this.name);
this.parent.dispatch('reject', {
data : { node : this, error: error }
});
}
|
[
"function",
"(",
"error",
")",
"{",
"this",
".",
"error",
"=",
"error",
";",
"this",
".",
"isRejected",
"=",
"true",
";",
"if",
"(",
"this",
".",
"parent",
"===",
"null",
")",
"{",
"return",
";",
"}",
"this",
".",
"parent",
".",
"dispatch",
"(",
"this",
".",
"name",
")",
";",
"this",
".",
"parent",
".",
"dispatch",
"(",
"'reject'",
",",
"{",
"data",
":",
"{",
"node",
":",
"this",
",",
"error",
":",
"error",
"}",
"}",
")",
";",
"}"
] |
method to notify that the step executed wrong.
@property reject <public> [Function]
|
[
"method",
"to",
"notify",
"that",
"the",
"step",
"executed",
"wrong",
"."
] |
deccd2e0d003678c035a91dffdc6873d9eba8d50
|
https://github.com/freshout-dev/fluorine/blob/deccd2e0d003678c035a91dffdc6873d9eba8d50/fluorine.js#L273-L285
|
|
37,749 |
novemberborn/cloudflare-origin-pull
|
src/index.js
|
tryVerify
|
function tryVerify (rawBytes) {
const {
tbsCertificate,
tbsCertificate: {
validity: {
notBefore: { value: notBefore },
notAfter: { value: notAfter }
}
},
signatureAlgorithm: { algorithm },
signature: { data: signature }
} = Certificate.decode(rawBytes, 'der')
// Require sha512WithRSAEncryption.
if (algorithm.join('.') !== '1.2.840.113549.1.1.13') {
return false
}
// Check if certificate is still valid.–
const now = Date.now()
if (now < notBefore || now > notAfter) {
return false
}
// Make sure the certificate was signed by CloudFlare's origin pull
// certificate authority.
const verifier = createVerify('RSA-SHA512')
verifier.update(TBSCertificate.encode(tbsCertificate, 'der'))
return verifier.verify(originPullCa, signature)
}
|
javascript
|
function tryVerify (rawBytes) {
const {
tbsCertificate,
tbsCertificate: {
validity: {
notBefore: { value: notBefore },
notAfter: { value: notAfter }
}
},
signatureAlgorithm: { algorithm },
signature: { data: signature }
} = Certificate.decode(rawBytes, 'der')
// Require sha512WithRSAEncryption.
if (algorithm.join('.') !== '1.2.840.113549.1.1.13') {
return false
}
// Check if certificate is still valid.–
const now = Date.now()
if (now < notBefore || now > notAfter) {
return false
}
// Make sure the certificate was signed by CloudFlare's origin pull
// certificate authority.
const verifier = createVerify('RSA-SHA512')
verifier.update(TBSCertificate.encode(tbsCertificate, 'der'))
return verifier.verify(originPullCa, signature)
}
|
[
"function",
"tryVerify",
"(",
"rawBytes",
")",
"{",
"const",
"{",
"tbsCertificate",
",",
"tbsCertificate",
":",
"{",
"validity",
":",
"{",
"notBefore",
":",
"{",
"value",
":",
"notBefore",
"}",
",",
"notAfter",
":",
"{",
"value",
":",
"notAfter",
"}",
"}",
"}",
",",
"signatureAlgorithm",
":",
"{",
"algorithm",
"}",
",",
"signature",
":",
"{",
"data",
":",
"signature",
"}",
"}",
"=",
"Certificate",
".",
"decode",
"(",
"rawBytes",
",",
"'der'",
")",
"// Require sha512WithRSAEncryption.",
"if",
"(",
"algorithm",
".",
"join",
"(",
"'.'",
")",
"!==",
"'1.2.840.113549.1.1.13'",
")",
"{",
"return",
"false",
"}",
"// Check if certificate is still valid.–",
"const",
"now",
"=",
"Date",
".",
"now",
"(",
")",
"if",
"(",
"now",
"<",
"notBefore",
"||",
"now",
">",
"notAfter",
")",
"{",
"return",
"false",
"}",
"// Make sure the certificate was signed by CloudFlare's origin pull",
"// certificate authority.",
"const",
"verifier",
"=",
"createVerify",
"(",
"'RSA-SHA512'",
")",
"verifier",
".",
"update",
"(",
"TBSCertificate",
".",
"encode",
"(",
"tbsCertificate",
",",
"'der'",
")",
")",
"return",
"verifier",
".",
"verify",
"(",
"originPullCa",
",",
"signature",
")",
"}"
] |
N.B. This only checks if the timestamps are valid and if the signature matches. Proper certificate validation requires more checks but that seems unnecessary in this case.
|
[
"N",
".",
"B",
".",
"This",
"only",
"checks",
"if",
"the",
"timestamps",
"are",
"valid",
"and",
"if",
"the",
"signature",
"matches",
".",
"Proper",
"certificate",
"validation",
"requires",
"more",
"checks",
"but",
"that",
"seems",
"unnecessary",
"in",
"this",
"case",
"."
] |
01fa94b020e67ca54bef99175e1ece22e0c2eb08
|
https://github.com/novemberborn/cloudflare-origin-pull/blob/01fa94b020e67ca54bef99175e1ece22e0c2eb08/src/index.js#L60-L88
|
37,750 |
fergaldoyle/gulp-require-angular
|
parseNg.js
|
parse
|
function parse(source) {
var moduleDefinitions = {},
moduleReferences = [];
estraverse.traverse(esprima.parse(source), {
leave: function (node, parent) {
if(!isAngular(node)) {
return;
}
//console.log('node:', JSON.stringify(node, null, 3));
//console.log('parent:', JSON.stringify(parent, null, 3));
var moduleName = parent.arguments[0].value;
// if a second argument exists
// this is a module definition
if(parent.arguments[1]) {
if(parent.arguments[1].type === 'ArrayExpression') {
moduleDefinitions[moduleName] = parent.arguments[1].elements.map(function(item){
return item['value'];
});
} else {
throw 'Argument must be an ArrayExpression, not a variable';
}
} else {
// is a module reference
pushDistinct(moduleReferences, moduleName);
}
}
});
return {
modules: moduleDefinitions,
references: moduleReferences
}
}
|
javascript
|
function parse(source) {
var moduleDefinitions = {},
moduleReferences = [];
estraverse.traverse(esprima.parse(source), {
leave: function (node, parent) {
if(!isAngular(node)) {
return;
}
//console.log('node:', JSON.stringify(node, null, 3));
//console.log('parent:', JSON.stringify(parent, null, 3));
var moduleName = parent.arguments[0].value;
// if a second argument exists
// this is a module definition
if(parent.arguments[1]) {
if(parent.arguments[1].type === 'ArrayExpression') {
moduleDefinitions[moduleName] = parent.arguments[1].elements.map(function(item){
return item['value'];
});
} else {
throw 'Argument must be an ArrayExpression, not a variable';
}
} else {
// is a module reference
pushDistinct(moduleReferences, moduleName);
}
}
});
return {
modules: moduleDefinitions,
references: moduleReferences
}
}
|
[
"function",
"parse",
"(",
"source",
")",
"{",
"var",
"moduleDefinitions",
"=",
"{",
"}",
",",
"moduleReferences",
"=",
"[",
"]",
";",
"estraverse",
".",
"traverse",
"(",
"esprima",
".",
"parse",
"(",
"source",
")",
",",
"{",
"leave",
":",
"function",
"(",
"node",
",",
"parent",
")",
"{",
"if",
"(",
"!",
"isAngular",
"(",
"node",
")",
")",
"{",
"return",
";",
"}",
"//console.log('node:', JSON.stringify(node, null, 3));",
"//console.log('parent:', JSON.stringify(parent, null, 3));",
"var",
"moduleName",
"=",
"parent",
".",
"arguments",
"[",
"0",
"]",
".",
"value",
";",
"// if a second argument exists",
"// this is a module definition",
"if",
"(",
"parent",
".",
"arguments",
"[",
"1",
"]",
")",
"{",
"if",
"(",
"parent",
".",
"arguments",
"[",
"1",
"]",
".",
"type",
"===",
"'ArrayExpression'",
")",
"{",
"moduleDefinitions",
"[",
"moduleName",
"]",
"=",
"parent",
".",
"arguments",
"[",
"1",
"]",
".",
"elements",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
"[",
"'value'",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"'Argument must be an ArrayExpression, not a variable'",
";",
"}",
"}",
"else",
"{",
"// is a module reference",
"pushDistinct",
"(",
"moduleReferences",
",",
"moduleName",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"{",
"modules",
":",
"moduleDefinitions",
",",
"references",
":",
"moduleReferences",
"}",
"}"
] |
Find module definitions and the dependencies of those modules Find module references
|
[
"Find",
"module",
"definitions",
"and",
"the",
"dependencies",
"of",
"those",
"modules",
"Find",
"module",
"references"
] |
9b6250dada310590b4575e030a1e03293454b98f
|
https://github.com/fergaldoyle/gulp-require-angular/blob/9b6250dada310590b4575e030a1e03293454b98f/parseNg.js#L18-L57
|
37,751 |
oskargustafsson/BFF
|
src/view.js
|
View
|
function View() {
Object.defineProperty(this, '__private', { writable: true, value: {}, });
this.__private.isRenderRequested = false;
var delegates = this.__private.eventDelegates = {};
this.__private.onDelegatedEvent = function onDelegatedEvent(ev) {
var delegatesForEvent = delegates[ev.type];
var el = ev.target;
for (var selectorStr in delegatesForEvent) {
if (!elMatchesSelector(el, selectorStr)) { continue; }
var delegatesForEventAndSelector = delegatesForEvent[selectorStr];
for (var i = 0, n = delegatesForEventAndSelector.length; i < n; ++i) {
delegatesForEventAndSelector[i](ev);
}
}
};
/**
* The root DOM element of the view. The default implementation of {@link module:bff/view#render} assigns to and updates this element. Delegated event listeners, created by calling {@link module:bff/view#listenTo} are attached to this element.
* Replacing the current element with another will clear all currently delegated event listeners - it is usually a better approach update the element (using e.g. {@link module:bff/patch-dom}) instead of replacing it.
* @instance
* @member {HTMLElement|undefined} el
*/
Object.defineProperty(this, 'el', {
enumerable: true,
get: function () { return this.__private.el; },
set: function (el) {
this.stopListening('*');
this.__private.el = el;
}
});
this.__private.childViews = new List();
this.listenTo(this.__private.childViews, 'item:destroyed', function (childView) {
this.__private.childViews.remove(childView);
});
/**
* A list of this view's child views. Initially empty.
* @instance
* @member {module:bff/list} children
*/
Object.defineProperty(this, 'children', {
enumerable: true,
get: function () { return this.__private.childViews; },
});
}
|
javascript
|
function View() {
Object.defineProperty(this, '__private', { writable: true, value: {}, });
this.__private.isRenderRequested = false;
var delegates = this.__private.eventDelegates = {};
this.__private.onDelegatedEvent = function onDelegatedEvent(ev) {
var delegatesForEvent = delegates[ev.type];
var el = ev.target;
for (var selectorStr in delegatesForEvent) {
if (!elMatchesSelector(el, selectorStr)) { continue; }
var delegatesForEventAndSelector = delegatesForEvent[selectorStr];
for (var i = 0, n = delegatesForEventAndSelector.length; i < n; ++i) {
delegatesForEventAndSelector[i](ev);
}
}
};
/**
* The root DOM element of the view. The default implementation of {@link module:bff/view#render} assigns to and updates this element. Delegated event listeners, created by calling {@link module:bff/view#listenTo} are attached to this element.
* Replacing the current element with another will clear all currently delegated event listeners - it is usually a better approach update the element (using e.g. {@link module:bff/patch-dom}) instead of replacing it.
* @instance
* @member {HTMLElement|undefined} el
*/
Object.defineProperty(this, 'el', {
enumerable: true,
get: function () { return this.__private.el; },
set: function (el) {
this.stopListening('*');
this.__private.el = el;
}
});
this.__private.childViews = new List();
this.listenTo(this.__private.childViews, 'item:destroyed', function (childView) {
this.__private.childViews.remove(childView);
});
/**
* A list of this view's child views. Initially empty.
* @instance
* @member {module:bff/list} children
*/
Object.defineProperty(this, 'children', {
enumerable: true,
get: function () { return this.__private.childViews; },
});
}
|
[
"function",
"View",
"(",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'__private'",
",",
"{",
"writable",
":",
"true",
",",
"value",
":",
"{",
"}",
",",
"}",
")",
";",
"this",
".",
"__private",
".",
"isRenderRequested",
"=",
"false",
";",
"var",
"delegates",
"=",
"this",
".",
"__private",
".",
"eventDelegates",
"=",
"{",
"}",
";",
"this",
".",
"__private",
".",
"onDelegatedEvent",
"=",
"function",
"onDelegatedEvent",
"(",
"ev",
")",
"{",
"var",
"delegatesForEvent",
"=",
"delegates",
"[",
"ev",
".",
"type",
"]",
";",
"var",
"el",
"=",
"ev",
".",
"target",
";",
"for",
"(",
"var",
"selectorStr",
"in",
"delegatesForEvent",
")",
"{",
"if",
"(",
"!",
"elMatchesSelector",
"(",
"el",
",",
"selectorStr",
")",
")",
"{",
"continue",
";",
"}",
"var",
"delegatesForEventAndSelector",
"=",
"delegatesForEvent",
"[",
"selectorStr",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"delegatesForEventAndSelector",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"delegatesForEventAndSelector",
"[",
"i",
"]",
"(",
"ev",
")",
";",
"}",
"}",
"}",
";",
"/**\n\t\t\t * The root DOM element of the view. The default implementation of {@link module:bff/view#render} assigns to and updates this element. Delegated event listeners, created by calling {@link module:bff/view#listenTo} are attached to this element.\n\t\t\t * Replacing the current element with another will clear all currently delegated event listeners - it is usually a better approach update the element (using e.g. {@link module:bff/patch-dom}) instead of replacing it.\n\t\t\t * @instance\n\t\t\t * @member {HTMLElement|undefined} el\n\t\t\t */",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'el'",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"__private",
".",
"el",
";",
"}",
",",
"set",
":",
"function",
"(",
"el",
")",
"{",
"this",
".",
"stopListening",
"(",
"'*'",
")",
";",
"this",
".",
"__private",
".",
"el",
"=",
"el",
";",
"}",
"}",
")",
";",
"this",
".",
"__private",
".",
"childViews",
"=",
"new",
"List",
"(",
")",
";",
"this",
".",
"listenTo",
"(",
"this",
".",
"__private",
".",
"childViews",
",",
"'item:destroyed'",
",",
"function",
"(",
"childView",
")",
"{",
"this",
".",
"__private",
".",
"childViews",
".",
"remove",
"(",
"childView",
")",
";",
"}",
")",
";",
"/**\n\t\t\t * A list of this view's child views. Initially empty.\n\t\t\t * @instance\n\t\t\t * @member {module:bff/list} children\n\t\t\t */",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'children'",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
".",
"__private",
".",
"childViews",
";",
"}",
",",
"}",
")",
";",
"}"
] |
Creates a new View instance.
@constructor
@mixes module:bff/event-emitter
@mixes module:bff/event-listener
@alias module:bff/view
|
[
"Creates",
"a",
"new",
"View",
"instance",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L39-L86
|
37,752 |
oskargustafsson/BFF
|
src/view.js
|
function (htmlString, returnAll) {
if (RUNTIME_CHECKS) {
if (typeof htmlString !== 'string') {
throw '"htmlString" argument must be a string';
}
if (arguments.length > 1 && typeof returnAll !== 'boolean') {
throw '"returnAll" argument must be a boolean value';
}
}
HTML_PARSER_EL.innerHTML = htmlString;
if (RUNTIME_CHECKS && !returnAll && HTML_PARSER_EL.children.length > 1) {
throw 'The parsed HTML contains more than one root element.' +
'Specify returnAll = true to return all of them';
}
var ret = returnAll ? HTML_PARSER_EL.children : HTML_PARSER_EL.firstChild;
while (HTML_PARSER_EL.firstChild) {
HTML_PARSER_EL.removeChild(HTML_PARSER_EL.firstChild);
}
return ret;
}
|
javascript
|
function (htmlString, returnAll) {
if (RUNTIME_CHECKS) {
if (typeof htmlString !== 'string') {
throw '"htmlString" argument must be a string';
}
if (arguments.length > 1 && typeof returnAll !== 'boolean') {
throw '"returnAll" argument must be a boolean value';
}
}
HTML_PARSER_EL.innerHTML = htmlString;
if (RUNTIME_CHECKS && !returnAll && HTML_PARSER_EL.children.length > 1) {
throw 'The parsed HTML contains more than one root element.' +
'Specify returnAll = true to return all of them';
}
var ret = returnAll ? HTML_PARSER_EL.children : HTML_PARSER_EL.firstChild;
while (HTML_PARSER_EL.firstChild) {
HTML_PARSER_EL.removeChild(HTML_PARSER_EL.firstChild);
}
return ret;
}
|
[
"function",
"(",
"htmlString",
",",
"returnAll",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"typeof",
"htmlString",
"!==",
"'string'",
")",
"{",
"throw",
"'\"htmlString\" argument must be a string'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"typeof",
"returnAll",
"!==",
"'boolean'",
")",
"{",
"throw",
"'\"returnAll\" argument must be a boolean value'",
";",
"}",
"}",
"HTML_PARSER_EL",
".",
"innerHTML",
"=",
"htmlString",
";",
"if",
"(",
"RUNTIME_CHECKS",
"&&",
"!",
"returnAll",
"&&",
"HTML_PARSER_EL",
".",
"children",
".",
"length",
">",
"1",
")",
"{",
"throw",
"'The parsed HTML contains more than one root element.'",
"+",
"'Specify returnAll = true to return all of them'",
";",
"}",
"var",
"ret",
"=",
"returnAll",
"?",
"HTML_PARSER_EL",
".",
"children",
":",
"HTML_PARSER_EL",
".",
"firstChild",
";",
"while",
"(",
"HTML_PARSER_EL",
".",
"firstChild",
")",
"{",
"HTML_PARSER_EL",
".",
"removeChild",
"(",
"HTML_PARSER_EL",
".",
"firstChild",
")",
";",
"}",
"return",
"ret",
";",
"}"
] |
Helper function that parses an HTML string into an HTMLElement hierarchy and returns the first element in the NodeList, unless the returnAll flag is true, in which case the whole node list is returned.
@instance
@arg {string} htmlString - The string to be parsed
@arg {boolean} returnAll - If true will return all top level elements
|
[
"Helper",
"function",
"that",
"parses",
"an",
"HTML",
"string",
"into",
"an",
"HTMLElement",
"hierarchy",
"and",
"returns",
"the",
"first",
"element",
"in",
"the",
"NodeList",
"unless",
"the",
"returnAll",
"flag",
"is",
"true",
"in",
"which",
"case",
"the",
"whole",
"node",
"list",
"is",
"returned",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L160-L182
|
|
37,753 |
oskargustafsson/BFF
|
src/view.js
|
function (childView, el) {
if (RUNTIME_CHECKS) {
if (!(childView instanceof View)) {
throw '"childView" argument must be a BFF View';
}
if (arguments.length > 1 && !(el === false || el instanceof HTMLElement)) {
throw '"el" argument must be an HTMLElement or the boolean value false';
}
}
this.__private.childViews.push(childView);
el !== false && (el || this.el).appendChild(childView.el);
return childView;
}
|
javascript
|
function (childView, el) {
if (RUNTIME_CHECKS) {
if (!(childView instanceof View)) {
throw '"childView" argument must be a BFF View';
}
if (arguments.length > 1 && !(el === false || el instanceof HTMLElement)) {
throw '"el" argument must be an HTMLElement or the boolean value false';
}
}
this.__private.childViews.push(childView);
el !== false && (el || this.el).appendChild(childView.el);
return childView;
}
|
[
"function",
"(",
"childView",
",",
"el",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"!",
"(",
"childView",
"instanceof",
"View",
")",
")",
"{",
"throw",
"'\"childView\" argument must be a BFF View'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"!",
"(",
"el",
"===",
"false",
"||",
"el",
"instanceof",
"HTMLElement",
")",
")",
"{",
"throw",
"'\"el\" argument must be an HTMLElement or the boolean value false'",
";",
"}",
"}",
"this",
".",
"__private",
".",
"childViews",
".",
"push",
"(",
"childView",
")",
";",
"el",
"!==",
"false",
"&&",
"(",
"el",
"||",
"this",
".",
"el",
")",
".",
"appendChild",
"(",
"childView",
".",
"el",
")",
";",
"return",
"childView",
";",
"}"
] |
Adds another view as a child to the view. A child view will be automatically added to this view's root element and destroyed whenever its parent view is destroyed.
@instance
@arg {module:bff/view} childView - The view that will be added to the list of this view's children.
@arg {HTMLElement|boolean} [optional] - An element to which the child view's root element will be appended. If not specified, it will be appended to this view's root element. Can also be `false`, in which case the child view will not be appended to anything.
|
[
"Adds",
"another",
"view",
"as",
"a",
"child",
"to",
"the",
"view",
".",
"A",
"child",
"view",
"will",
"be",
"automatically",
"added",
"to",
"this",
"view",
"s",
"root",
"element",
"and",
"destroyed",
"whenever",
"its",
"parent",
"view",
"is",
"destroyed",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L216-L229
|
|
37,754 |
oskargustafsson/BFF
|
src/view.js
|
function () {
// Iterate backwards because the list might shrink while being iterated
for (var i = this.__private.childViews.length - 1; i >= 0; --i) {
this.__private.childViews[i].destroy();
}
}
|
javascript
|
function () {
// Iterate backwards because the list might shrink while being iterated
for (var i = this.__private.childViews.length - 1; i >= 0; --i) {
this.__private.childViews[i].destroy();
}
}
|
[
"function",
"(",
")",
"{",
"// Iterate backwards because the list might shrink while being iterated",
"for",
"(",
"var",
"i",
"=",
"this",
".",
"__private",
".",
"childViews",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"this",
".",
"__private",
".",
"childViews",
"[",
"i",
"]",
".",
"destroy",
"(",
")",
";",
"}",
"}"
] |
Destroy all child views of this view.
@instance
|
[
"Destroy",
"all",
"child",
"views",
"of",
"this",
"view",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/view.js#L235-L240
|
|
37,755 |
TorchlightSoftware/particle
|
dist/lodash.js
|
createCache
|
function createCache(array) {
var index = -1,
length = array.length;
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return cache.object === false
? (releaseObject(result), null)
: result;
}
|
javascript
|
function createCache(array) {
var index = -1,
length = array.length;
var cache = getObject();
cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return cache.object === false
? (releaseObject(result), null)
: result;
}
|
[
"function",
"createCache",
"(",
"array",
")",
"{",
"var",
"index",
"=",
"-",
"1",
",",
"length",
"=",
"array",
".",
"length",
";",
"var",
"cache",
"=",
"getObject",
"(",
")",
";",
"cache",
"[",
"'false'",
"]",
"=",
"cache",
"[",
"'null'",
"]",
"=",
"cache",
"[",
"'true'",
"]",
"=",
"cache",
"[",
"'undefined'",
"]",
"=",
"false",
";",
"var",
"result",
"=",
"getObject",
"(",
")",
";",
"result",
".",
"array",
"=",
"array",
";",
"result",
".",
"cache",
"=",
"cache",
";",
"result",
".",
"push",
"=",
"cachePush",
";",
"while",
"(",
"++",
"index",
"<",
"length",
")",
"{",
"result",
".",
"push",
"(",
"array",
"[",
"index",
"]",
")",
";",
"}",
"return",
"cache",
".",
"object",
"===",
"false",
"?",
"(",
"releaseObject",
"(",
"result",
")",
",",
"null",
")",
":",
"result",
";",
"}"
] |
Creates a cache object to optimize linear searches of large arrays.
@private
@param {Array} [array=[]] The array to search.
@returns {Null|Object} Returns the cache object or `null` if caching should not be used.
|
[
"Creates",
"a",
"cache",
"object",
"to",
"optimize",
"linear",
"searches",
"of",
"large",
"arrays",
"."
] |
1312f00d04477c46325420329012681bda152c71
|
https://github.com/TorchlightSoftware/particle/blob/1312f00d04477c46325420329012681bda152c71/dist/lodash.js#L212-L230
|
37,756 |
TorchlightSoftware/particle
|
dist/lodash.js
|
getIndexOf
|
function getIndexOf(array, value, fromIndex) {
var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result;
return result;
}
|
javascript
|
function getIndexOf(array, value, fromIndex) {
var result = (result = lodash.indexOf) === indexOf ? basicIndexOf : result;
return result;
}
|
[
"function",
"getIndexOf",
"(",
"array",
",",
"value",
",",
"fromIndex",
")",
"{",
"var",
"result",
"=",
"(",
"result",
"=",
"lodash",
".",
"indexOf",
")",
"===",
"indexOf",
"?",
"basicIndexOf",
":",
"result",
";",
"return",
"result",
";",
"}"
] |
Gets the appropriate "indexOf" function. If the `_.indexOf` method is
customized, this method returns the custom method, otherwise it returns
the `basicIndexOf` function.
@private
@returns {Function} Returns the "indexOf" function.
|
[
"Gets",
"the",
"appropriate",
"indexOf",
"function",
".",
"If",
"the",
"_",
".",
"indexOf",
"method",
"is",
"customized",
"this",
"method",
"returns",
"the",
"custom",
"method",
"otherwise",
"it",
"returns",
"the",
"basicIndexOf",
"function",
"."
] |
1312f00d04477c46325420329012681bda152c71
|
https://github.com/TorchlightSoftware/particle/blob/1312f00d04477c46325420329012681bda152c71/dist/lodash.js#L801-L804
|
37,757 |
axke/rs-api
|
lib/apis/distraction/spotlight.js
|
function () {
return new Promise(function (resolve, reject) {
var rotations = [];
for (var i = 0; i < spotlightRotations.length; i++) {
var now = new Date();
var daysToAdd = 3 * i;
now.setDate(now.getDate() + daysToAdd);
var currentSpotlight = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length)) / 3);
var daysUntilNext = (3 - ((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length) % 3) + daysToAdd;
var start = new Date();
start.setDate(start.getDate() + (daysUntilNext - 3));
var obj = {
rotation: spotlightRotations[currentSpotlight],
daysUntilNext: daysUntilNext,
startDate: start
};
rotations.push(obj);
}
resolve(rotations);
});
}
|
javascript
|
function () {
return new Promise(function (resolve, reject) {
var rotations = [];
for (var i = 0; i < spotlightRotations.length; i++) {
var now = new Date();
var daysToAdd = 3 * i;
now.setDate(now.getDate() + daysToAdd);
var currentSpotlight = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length)) / 3);
var daysUntilNext = (3 - ((Math.floor((now / 1000) / (24 * 60 * 60))) - 49) % (3 * spotlightRotations.length) % 3) + daysToAdd;
var start = new Date();
start.setDate(start.getDate() + (daysUntilNext - 3));
var obj = {
rotation: spotlightRotations[currentSpotlight],
daysUntilNext: daysUntilNext,
startDate: start
};
rotations.push(obj);
}
resolve(rotations);
});
}
|
[
"function",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"rotations",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"spotlightRotations",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"daysToAdd",
"=",
"3",
"*",
"i",
";",
"now",
".",
"setDate",
"(",
"now",
".",
"getDate",
"(",
")",
"+",
"daysToAdd",
")",
";",
"var",
"currentSpotlight",
"=",
"Math",
".",
"floor",
"(",
"(",
"(",
"(",
"Math",
".",
"floor",
"(",
"(",
"now",
"/",
"1000",
")",
"/",
"(",
"24",
"*",
"60",
"*",
"60",
")",
")",
")",
"-",
"49",
")",
"%",
"(",
"3",
"*",
"spotlightRotations",
".",
"length",
")",
")",
"/",
"3",
")",
";",
"var",
"daysUntilNext",
"=",
"(",
"3",
"-",
"(",
"(",
"Math",
".",
"floor",
"(",
"(",
"now",
"/",
"1000",
")",
"/",
"(",
"24",
"*",
"60",
"*",
"60",
")",
")",
")",
"-",
"49",
")",
"%",
"(",
"3",
"*",
"spotlightRotations",
".",
"length",
")",
"%",
"3",
")",
"+",
"daysToAdd",
";",
"var",
"start",
"=",
"new",
"Date",
"(",
")",
";",
"start",
".",
"setDate",
"(",
"start",
".",
"getDate",
"(",
")",
"+",
"(",
"daysUntilNext",
"-",
"3",
")",
")",
";",
"var",
"obj",
"=",
"{",
"rotation",
":",
"spotlightRotations",
"[",
"currentSpotlight",
"]",
",",
"daysUntilNext",
":",
"daysUntilNext",
",",
"startDate",
":",
"start",
"}",
";",
"rotations",
".",
"push",
"(",
"obj",
")",
";",
"}",
"resolve",
"(",
"rotations",
")",
";",
"}",
")",
";",
"}"
] |
Gets upcoming rotations
|
[
"Gets",
"upcoming",
"rotations"
] |
71af4973e1d079f09b7d888b6d24735784185942
|
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/distraction/spotlight.js#L122-L144
|
|
37,758 |
primus/deumdify
|
index.js
|
prune
|
function prune(code) {
var ast = esprima.parse(code);
estraverse.replace(ast, {
leave: function leave(node, parent) {
var ret;
if ('IfStatement' === node.type) {
if ('BinaryExpression' !== node.test.type) return;
if ('self' === node.test.left.argument.name) {
node.alternate = null;
} else if ('global' === node.test.left.argument.name) {
ret = node.alternate;
}
return ret;
}
if (
'BlockStatement' === node.type
&& 'FunctionExpression' === parent.type
) {
return node.body[0].alternate.alternate;
}
}
});
return escodegen.generate(ast, {
format: {
indent: { style: ' ' },
semicolons: false,
compact: true
}
});
}
|
javascript
|
function prune(code) {
var ast = esprima.parse(code);
estraverse.replace(ast, {
leave: function leave(node, parent) {
var ret;
if ('IfStatement' === node.type) {
if ('BinaryExpression' !== node.test.type) return;
if ('self' === node.test.left.argument.name) {
node.alternate = null;
} else if ('global' === node.test.left.argument.name) {
ret = node.alternate;
}
return ret;
}
if (
'BlockStatement' === node.type
&& 'FunctionExpression' === parent.type
) {
return node.body[0].alternate.alternate;
}
}
});
return escodegen.generate(ast, {
format: {
indent: { style: ' ' },
semicolons: false,
compact: true
}
});
}
|
[
"function",
"prune",
"(",
"code",
")",
"{",
"var",
"ast",
"=",
"esprima",
".",
"parse",
"(",
"code",
")",
";",
"estraverse",
".",
"replace",
"(",
"ast",
",",
"{",
"leave",
":",
"function",
"leave",
"(",
"node",
",",
"parent",
")",
"{",
"var",
"ret",
";",
"if",
"(",
"'IfStatement'",
"===",
"node",
".",
"type",
")",
"{",
"if",
"(",
"'BinaryExpression'",
"!==",
"node",
".",
"test",
".",
"type",
")",
"return",
";",
"if",
"(",
"'self'",
"===",
"node",
".",
"test",
".",
"left",
".",
"argument",
".",
"name",
")",
"{",
"node",
".",
"alternate",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"'global'",
"===",
"node",
".",
"test",
".",
"left",
".",
"argument",
".",
"name",
")",
"{",
"ret",
"=",
"node",
".",
"alternate",
";",
"}",
"return",
"ret",
";",
"}",
"if",
"(",
"'BlockStatement'",
"===",
"node",
".",
"type",
"&&",
"'FunctionExpression'",
"===",
"parent",
".",
"type",
")",
"{",
"return",
"node",
".",
"body",
"[",
"0",
"]",
".",
"alternate",
".",
"alternate",
";",
"}",
"}",
"}",
")",
";",
"return",
"escodegen",
".",
"generate",
"(",
"ast",
",",
"{",
"format",
":",
"{",
"indent",
":",
"{",
"style",
":",
"' '",
"}",
",",
"semicolons",
":",
"false",
",",
"compact",
":",
"true",
"}",
"}",
")",
";",
"}"
] |
Prune unwanted branches from the given source code.
@param {String} code Source code to prune
@returns {String} Pruned source code
@api private
|
[
"Prune",
"unwanted",
"branches",
"from",
"the",
"given",
"source",
"code",
"."
] |
3a6ca83742a0d984ed9c5ca0d992366fa19805f6
|
https://github.com/primus/deumdify/blob/3a6ca83742a0d984ed9c5ca0d992366fa19805f6/index.js#L20-L55
|
37,759 |
primus/deumdify
|
index.js
|
createStream
|
function createStream() {
var firstChunk = true;
var stream = through(function transform(chunk, encoding, next) {
if (!firstChunk) return next(null, chunk);
firstChunk = false;
var regex = /^(.+?)(\(function\(\)\{)/
, pattern;
chunk = chunk.toString().replace(regex, function replacer(match, p1, p2) {
pattern = p1;
return p2;
});
this.push(prune(pattern) + chunk);
next();
});
stream.label = 'prune-umd';
return stream;
}
|
javascript
|
function createStream() {
var firstChunk = true;
var stream = through(function transform(chunk, encoding, next) {
if (!firstChunk) return next(null, chunk);
firstChunk = false;
var regex = /^(.+?)(\(function\(\)\{)/
, pattern;
chunk = chunk.toString().replace(regex, function replacer(match, p1, p2) {
pattern = p1;
return p2;
});
this.push(prune(pattern) + chunk);
next();
});
stream.label = 'prune-umd';
return stream;
}
|
[
"function",
"createStream",
"(",
")",
"{",
"var",
"firstChunk",
"=",
"true",
";",
"var",
"stream",
"=",
"through",
"(",
"function",
"transform",
"(",
"chunk",
",",
"encoding",
",",
"next",
")",
"{",
"if",
"(",
"!",
"firstChunk",
")",
"return",
"next",
"(",
"null",
",",
"chunk",
")",
";",
"firstChunk",
"=",
"false",
";",
"var",
"regex",
"=",
"/",
"^(.+?)(\\(function\\(\\)\\{)",
"/",
",",
"pattern",
";",
"chunk",
"=",
"chunk",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"regex",
",",
"function",
"replacer",
"(",
"match",
",",
"p1",
",",
"p2",
")",
"{",
"pattern",
"=",
"p1",
";",
"return",
"p2",
";",
"}",
")",
";",
"this",
".",
"push",
"(",
"prune",
"(",
"pattern",
")",
"+",
"chunk",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"stream",
".",
"label",
"=",
"'prune-umd'",
";",
"return",
"stream",
";",
"}"
] |
Create a transform stream.
@returns {Stream} Transform stream
@api private
|
[
"Create",
"a",
"transform",
"stream",
"."
] |
3a6ca83742a0d984ed9c5ca0d992366fa19805f6
|
https://github.com/primus/deumdify/blob/3a6ca83742a0d984ed9c5ca0d992366fa19805f6/index.js#L63-L85
|
37,760 |
primus/deumdify
|
index.js
|
deumdify
|
function deumdify(browserify) {
//
// Bail out if there is no UMD wrapper.
//
if (!browserify._options.standalone) return;
browserify.pipeline.push(createStream());
browserify.on('reset', function reset() {
browserify.pipeline.push(createStream());
});
}
|
javascript
|
function deumdify(browserify) {
//
// Bail out if there is no UMD wrapper.
//
if (!browserify._options.standalone) return;
browserify.pipeline.push(createStream());
browserify.on('reset', function reset() {
browserify.pipeline.push(createStream());
});
}
|
[
"function",
"deumdify",
"(",
"browserify",
")",
"{",
"//",
"// Bail out if there is no UMD wrapper.",
"//",
"if",
"(",
"!",
"browserify",
".",
"_options",
".",
"standalone",
")",
"return",
";",
"browserify",
".",
"pipeline",
".",
"push",
"(",
"createStream",
"(",
")",
")",
";",
"browserify",
".",
"on",
"(",
"'reset'",
",",
"function",
"reset",
"(",
")",
"{",
"browserify",
".",
"pipeline",
".",
"push",
"(",
"createStream",
"(",
")",
")",
";",
"}",
")",
";",
"}"
] |
Prune the UMD pattern from a Browserify bundle stream.
@param {Browserify} browserify Browserify instance
@api public
|
[
"Prune",
"the",
"UMD",
"pattern",
"from",
"a",
"Browserify",
"bundle",
"stream",
"."
] |
3a6ca83742a0d984ed9c5ca0d992366fa19805f6
|
https://github.com/primus/deumdify/blob/3a6ca83742a0d984ed9c5ca0d992366fa19805f6/index.js#L93-L103
|
37,761 |
axke/rs-api
|
lib/apis/distraction/raven.js
|
Raven
|
function Raven() {
/**
* Pull from the rs forums...this can easily break if they stop using the version 4 of the thread
* http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383
* @returns {Promise} current viswax
* @example
* rsapi.rs.distraction.viswax.getCurrent().then(function(vis) {
* console.log(vis);
* }).catch(console.error);
*/
this.getCurrent = function() {
return new Promise(function (resolve, reject) {
let spawned = false;
let daysUntilNext = 0;
let found = (((Math.floor((Date.now() / 1000) / (24 * 60 * 60))) + 7) % 13);
if (found < 1) {
daysUntilNext = 1 - found;
spawned = true;
}
else {
daysUntilNext = 13 - found;
spawned = false;
}
resolve({
isSpawned: spawned,
daysUntilNext: daysUntilNext
});
});
}
}
|
javascript
|
function Raven() {
/**
* Pull from the rs forums...this can easily break if they stop using the version 4 of the thread
* http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383
* @returns {Promise} current viswax
* @example
* rsapi.rs.distraction.viswax.getCurrent().then(function(vis) {
* console.log(vis);
* }).catch(console.error);
*/
this.getCurrent = function() {
return new Promise(function (resolve, reject) {
let spawned = false;
let daysUntilNext = 0;
let found = (((Math.floor((Date.now() / 1000) / (24 * 60 * 60))) + 7) % 13);
if (found < 1) {
daysUntilNext = 1 - found;
spawned = true;
}
else {
daysUntilNext = 13 - found;
spawned = false;
}
resolve({
isSpawned: spawned,
daysUntilNext: daysUntilNext
});
});
}
}
|
[
"function",
"Raven",
"(",
")",
"{",
"/**\n * Pull from the rs forums...this can easily break if they stop using the version 4 of the thread\n * http://services.runescape.com/m=forum/forums.ws?75,76,387,65763383\n * @returns {Promise} current viswax\n * @example\n * rsapi.rs.distraction.viswax.getCurrent().then(function(vis) {\n * console.log(vis);\n * }).catch(console.error);\n */",
"this",
".",
"getCurrent",
"=",
"function",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"let",
"spawned",
"=",
"false",
";",
"let",
"daysUntilNext",
"=",
"0",
";",
"let",
"found",
"=",
"(",
"(",
"(",
"Math",
".",
"floor",
"(",
"(",
"Date",
".",
"now",
"(",
")",
"/",
"1000",
")",
"/",
"(",
"24",
"*",
"60",
"*",
"60",
")",
")",
")",
"+",
"7",
")",
"%",
"13",
")",
";",
"if",
"(",
"found",
"<",
"1",
")",
"{",
"daysUntilNext",
"=",
"1",
"-",
"found",
";",
"spawned",
"=",
"true",
";",
"}",
"else",
"{",
"daysUntilNext",
"=",
"13",
"-",
"found",
";",
"spawned",
"=",
"false",
";",
"}",
"resolve",
"(",
"{",
"isSpawned",
":",
"spawned",
",",
"daysUntilNext",
":",
"daysUntilNext",
"}",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Module containing Raven functions
@module Raven
|
[
"Module",
"containing",
"Raven",
"functions"
] |
71af4973e1d079f09b7d888b6d24735784185942
|
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/distraction/raven.js#L10-L43
|
37,762 |
LaunchPadLab/lp-redux-api
|
src/handlers/handle-failure.js
|
handleFailure
|
function handleFailure (handler) {
return (state, action) => isFailureAction(action) ? handler(state, action, getDataFromAction(action)) : state
}
|
javascript
|
function handleFailure (handler) {
return (state, action) => isFailureAction(action) ? handler(state, action, getDataFromAction(action)) : state
}
|
[
"function",
"handleFailure",
"(",
"handler",
")",
"{",
"return",
"(",
"state",
",",
"action",
")",
"=>",
"isFailureAction",
"(",
"action",
")",
"?",
"handler",
"(",
"state",
",",
"action",
",",
"getDataFromAction",
"(",
"action",
")",
")",
":",
"state",
"}"
] |
A function that takes an API action handler and only applies that handler when the request fails.
@name handleFailure
@param {Function} handler - An action handler that is passed `state`, `action` and `data` params
@returns {Function} An action handler that runs when a request is unsuccessful
@example
handleActions({
[apiActions.fetchUser]: handleFailure((state, action) => {
// This code only runs when the call was unsuccessful
return set('userFetchError', action.payload.data, state)
})
})
|
[
"A",
"function",
"that",
"takes",
"an",
"API",
"action",
"handler",
"and",
"only",
"applies",
"that",
"handler",
"when",
"the",
"request",
"fails",
"."
] |
73eee231067365326780ddc1dbbfa50d3e65defc
|
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/handle-failure.js#L20-L22
|
37,763 |
simonepri/phc-scrypt
|
index.js
|
hash
|
function hash(password, options) {
options = options || {};
const blocksize = options.blocksize || defaults.blocksize;
const cost = options.cost || defaults.cost;
const parallelism = options.parallelism || defaults.parallelism;
const saltSize = options.saltSize || defaults.saltSize;
// Blocksize Validation
if (typeof blocksize !== 'number' || !Number.isInteger(blocksize)) {
return Promise.reject(
new TypeError("The 'blocksize' option must be an integer")
);
}
if (blocksize < 1 || blocksize > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'blocksize' option must be in the range (1 <= blocksize <= ${MAX_UINT32})`
)
);
}
// Cost Validation
if (typeof cost !== 'number' || !Number.isInteger(cost)) {
return Promise.reject(
new TypeError("The 'cost' option must be an integer")
);
}
const maxcost = (128 * blocksize) / 8 - 1;
if (cost < 2 || cost > maxcost) {
return Promise.reject(
new TypeError(
`The 'cost' option must be in the range (1 <= cost <= ${maxcost})`
)
);
}
// Parallelism Validation
if (typeof parallelism !== 'number' || !Number.isInteger(parallelism)) {
return Promise.reject(
new TypeError("The 'parallelism' option must be an integer")
);
}
const maxpar = Math.floor(((Math.pow(2, 32) - 1) * 32) / (128 * blocksize));
if (parallelism < 1 || parallelism > maxpar) {
return Promise.reject(
new TypeError(
`The 'parallelism' option must be in the range (1 <= parallelism <= ${maxpar})`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)"
)
);
}
const params = {
N: Math.pow(2, cost),
r: blocksize,
p: parallelism
};
const keylen = 32;
return gensalt(saltSize).then(salt => {
return scrypt.hash(password, params, keylen, salt).then(hash => {
const phcstr = phc.serialize({
id: 'scrypt',
params: {
ln: cost,
r: blocksize,
p: parallelism
},
salt,
hash
});
return phcstr;
});
});
}
|
javascript
|
function hash(password, options) {
options = options || {};
const blocksize = options.blocksize || defaults.blocksize;
const cost = options.cost || defaults.cost;
const parallelism = options.parallelism || defaults.parallelism;
const saltSize = options.saltSize || defaults.saltSize;
// Blocksize Validation
if (typeof blocksize !== 'number' || !Number.isInteger(blocksize)) {
return Promise.reject(
new TypeError("The 'blocksize' option must be an integer")
);
}
if (blocksize < 1 || blocksize > MAX_UINT32) {
return Promise.reject(
new TypeError(
`The 'blocksize' option must be in the range (1 <= blocksize <= ${MAX_UINT32})`
)
);
}
// Cost Validation
if (typeof cost !== 'number' || !Number.isInteger(cost)) {
return Promise.reject(
new TypeError("The 'cost' option must be an integer")
);
}
const maxcost = (128 * blocksize) / 8 - 1;
if (cost < 2 || cost > maxcost) {
return Promise.reject(
new TypeError(
`The 'cost' option must be in the range (1 <= cost <= ${maxcost})`
)
);
}
// Parallelism Validation
if (typeof parallelism !== 'number' || !Number.isInteger(parallelism)) {
return Promise.reject(
new TypeError("The 'parallelism' option must be an integer")
);
}
const maxpar = Math.floor(((Math.pow(2, 32) - 1) * 32) / (128 * blocksize));
if (parallelism < 1 || parallelism > maxpar) {
return Promise.reject(
new TypeError(
`The 'parallelism' option must be in the range (1 <= parallelism <= ${maxpar})`
)
);
}
// Salt Size Validation
if (saltSize < 8 || saltSize > 1024) {
return Promise.reject(
new TypeError(
"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)"
)
);
}
const params = {
N: Math.pow(2, cost),
r: blocksize,
p: parallelism
};
const keylen = 32;
return gensalt(saltSize).then(salt => {
return scrypt.hash(password, params, keylen, salt).then(hash => {
const phcstr = phc.serialize({
id: 'scrypt',
params: {
ln: cost,
r: blocksize,
p: parallelism
},
salt,
hash
});
return phcstr;
});
});
}
|
[
"function",
"hash",
"(",
"password",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"const",
"blocksize",
"=",
"options",
".",
"blocksize",
"||",
"defaults",
".",
"blocksize",
";",
"const",
"cost",
"=",
"options",
".",
"cost",
"||",
"defaults",
".",
"cost",
";",
"const",
"parallelism",
"=",
"options",
".",
"parallelism",
"||",
"defaults",
".",
"parallelism",
";",
"const",
"saltSize",
"=",
"options",
".",
"saltSize",
"||",
"defaults",
".",
"saltSize",
";",
"// Blocksize Validation",
"if",
"(",
"typeof",
"blocksize",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"blocksize",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'blocksize' option must be an integer\"",
")",
")",
";",
"}",
"if",
"(",
"blocksize",
"<",
"1",
"||",
"blocksize",
">",
"MAX_UINT32",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"MAX_UINT32",
"}",
"`",
")",
")",
";",
"}",
"// Cost Validation",
"if",
"(",
"typeof",
"cost",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"cost",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'cost' option must be an integer\"",
")",
")",
";",
"}",
"const",
"maxcost",
"=",
"(",
"128",
"*",
"blocksize",
")",
"/",
"8",
"-",
"1",
";",
"if",
"(",
"cost",
"<",
"2",
"||",
"cost",
">",
"maxcost",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"maxcost",
"}",
"`",
")",
")",
";",
"}",
"// Parallelism Validation",
"if",
"(",
"typeof",
"parallelism",
"!==",
"'number'",
"||",
"!",
"Number",
".",
"isInteger",
"(",
"parallelism",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'parallelism' option must be an integer\"",
")",
")",
";",
"}",
"const",
"maxpar",
"=",
"Math",
".",
"floor",
"(",
"(",
"(",
"Math",
".",
"pow",
"(",
"2",
",",
"32",
")",
"-",
"1",
")",
"*",
"32",
")",
"/",
"(",
"128",
"*",
"blocksize",
")",
")",
";",
"if",
"(",
"parallelism",
"<",
"1",
"||",
"parallelism",
">",
"maxpar",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"`",
"${",
"maxpar",
"}",
"`",
")",
")",
";",
"}",
"// Salt Size Validation",
"if",
"(",
"saltSize",
"<",
"8",
"||",
"saltSize",
">",
"1024",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"\"The 'saltSize' option must be in the range (8 <= saltSize <= 1023)\"",
")",
")",
";",
"}",
"const",
"params",
"=",
"{",
"N",
":",
"Math",
".",
"pow",
"(",
"2",
",",
"cost",
")",
",",
"r",
":",
"blocksize",
",",
"p",
":",
"parallelism",
"}",
";",
"const",
"keylen",
"=",
"32",
";",
"return",
"gensalt",
"(",
"saltSize",
")",
".",
"then",
"(",
"salt",
"=>",
"{",
"return",
"scrypt",
".",
"hash",
"(",
"password",
",",
"params",
",",
"keylen",
",",
"salt",
")",
".",
"then",
"(",
"hash",
"=>",
"{",
"const",
"phcstr",
"=",
"phc",
".",
"serialize",
"(",
"{",
"id",
":",
"'scrypt'",
",",
"params",
":",
"{",
"ln",
":",
"cost",
",",
"r",
":",
"blocksize",
",",
"p",
":",
"parallelism",
"}",
",",
"salt",
",",
"hash",
"}",
")",
";",
"return",
"phcstr",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Computes the hash string of the given password in the PHC format using scrypt
package.
@public
@param {string} password The password to hash.
@param {Object} [options] Optional configurations related to the hashing
function.
@param {number} [options.blocksize=8] Optional amount of memory to use in
kibibytes.
Must be an integer within the range (`8` <= `memory` <= `2^32-1`).
@param {number} [options.cost=15] Optional CPU/memory cost parameter.
Must be an integer power of 2 within the range
(`2` <= `cost` <= `2^((128 * blocksize) / 8) - 1`).
@param {number} [options.parallelism=1] Optional degree of parallelism to
use.
Must be an integer within the range
(`1` <= `parallelism` <= `((2^32-1) * 32) / (128 * blocksize)`).
@return {Promise.<string>} The generated secure hash string in the PHC
format.
|
[
"Computes",
"the",
"hash",
"string",
"of",
"the",
"given",
"password",
"in",
"the",
"PHC",
"format",
"using",
"scrypt",
"package",
"."
] |
c3fa7b360864135af4075fa448de3ed07be5a5a1
|
https://github.com/simonepri/phc-scrypt/blob/c3fa7b360864135af4075fa448de3ed07be5a5a1/index.js#L47-L129
|
37,764 |
bholloway/persistent-cache-webpack-plugin
|
lib/application-classes.js
|
getName
|
function getName(candidate) {
var proto = getProto(candidate),
isValid = !!proto && !isPlainObject(candidate) && !Array.isArray(candidate);
if (isValid) {
for (var key in require.cache) {
var exports = require.cache[key].exports,
result = isPlainObject(exports) ? Object.keys(exports).reduce(test.bind(null, key), null) : test(key);
if (result) {
return result;
}
}
}
return null;
function test(filename, result, field) {
if (result) {
return result;
} else {
var candidate = field ? exports[field] : exports,
qualified = [filename, field].filter(Boolean).join('::'),
isDefinition = (typeof candidate === 'function') && !!candidate.prototype &&
(typeof candidate.prototype === 'object') && (candidate.prototype === proto);
return isDefinition && qualified || null;
}
}
}
|
javascript
|
function getName(candidate) {
var proto = getProto(candidate),
isValid = !!proto && !isPlainObject(candidate) && !Array.isArray(candidate);
if (isValid) {
for (var key in require.cache) {
var exports = require.cache[key].exports,
result = isPlainObject(exports) ? Object.keys(exports).reduce(test.bind(null, key), null) : test(key);
if (result) {
return result;
}
}
}
return null;
function test(filename, result, field) {
if (result) {
return result;
} else {
var candidate = field ? exports[field] : exports,
qualified = [filename, field].filter(Boolean).join('::'),
isDefinition = (typeof candidate === 'function') && !!candidate.prototype &&
(typeof candidate.prototype === 'object') && (candidate.prototype === proto);
return isDefinition && qualified || null;
}
}
}
|
[
"function",
"getName",
"(",
"candidate",
")",
"{",
"var",
"proto",
"=",
"getProto",
"(",
"candidate",
")",
",",
"isValid",
"=",
"!",
"!",
"proto",
"&&",
"!",
"isPlainObject",
"(",
"candidate",
")",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"candidate",
")",
";",
"if",
"(",
"isValid",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"require",
".",
"cache",
")",
"{",
"var",
"exports",
"=",
"require",
".",
"cache",
"[",
"key",
"]",
".",
"exports",
",",
"result",
"=",
"isPlainObject",
"(",
"exports",
")",
"?",
"Object",
".",
"keys",
"(",
"exports",
")",
".",
"reduce",
"(",
"test",
".",
"bind",
"(",
"null",
",",
"key",
")",
",",
"null",
")",
":",
"test",
"(",
"key",
")",
";",
"if",
"(",
"result",
")",
"{",
"return",
"result",
";",
"}",
"}",
"}",
"return",
"null",
";",
"function",
"test",
"(",
"filename",
",",
"result",
",",
"field",
")",
"{",
"if",
"(",
"result",
")",
"{",
"return",
"result",
";",
"}",
"else",
"{",
"var",
"candidate",
"=",
"field",
"?",
"exports",
"[",
"field",
"]",
":",
"exports",
",",
"qualified",
"=",
"[",
"filename",
",",
"field",
"]",
".",
"filter",
"(",
"Boolean",
")",
".",
"join",
"(",
"'::'",
")",
",",
"isDefinition",
"=",
"(",
"typeof",
"candidate",
"===",
"'function'",
")",
"&&",
"!",
"!",
"candidate",
".",
"prototype",
"&&",
"(",
"typeof",
"candidate",
".",
"prototype",
"===",
"'object'",
")",
"&&",
"(",
"candidate",
".",
"prototype",
"===",
"proto",
")",
";",
"return",
"isDefinition",
"&&",
"qualified",
"||",
"null",
";",
"}",
"}",
"}"
] |
Find the class name of the given instance.
@param {object} candidate A possible instance to name
@returns {string} The absolute path to the candidate definition where it is an instance or null otherwise
|
[
"Find",
"the",
"class",
"name",
"of",
"the",
"given",
"instance",
"."
] |
bd5aec58b1b38477218dcdc0fb144c6981604fa8
|
https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/application-classes.js#L15-L40
|
37,765 |
bholloway/persistent-cache-webpack-plugin
|
lib/application-classes.js
|
getDefinition
|
function getDefinition(name) {
var split = name.split('::'),
path = split[0],
field = split[1],
exported = (path in require.cache) && require.cache[path].exports,
definition = !!exported && (field ? exported[field] : exported);
return !!definition && !!getProto(definition) && definition || null;
}
|
javascript
|
function getDefinition(name) {
var split = name.split('::'),
path = split[0],
field = split[1],
exported = (path in require.cache) && require.cache[path].exports,
definition = !!exported && (field ? exported[field] : exported);
return !!definition && !!getProto(definition) && definition || null;
}
|
[
"function",
"getDefinition",
"(",
"name",
")",
"{",
"var",
"split",
"=",
"name",
".",
"split",
"(",
"'::'",
")",
",",
"path",
"=",
"split",
"[",
"0",
"]",
",",
"field",
"=",
"split",
"[",
"1",
"]",
",",
"exported",
"=",
"(",
"path",
"in",
"require",
".",
"cache",
")",
"&&",
"require",
".",
"cache",
"[",
"path",
"]",
".",
"exports",
",",
"definition",
"=",
"!",
"!",
"exported",
"&&",
"(",
"field",
"?",
"exported",
"[",
"field",
"]",
":",
"exported",
")",
";",
"return",
"!",
"!",
"definition",
"&&",
"!",
"!",
"getProto",
"(",
"definition",
")",
"&&",
"definition",
"||",
"null",
";",
"}"
] |
Get the class definition by explicit path where already in the require cache.
@param {string} name The absolute path to the file containing the class
@returns {null}
|
[
"Get",
"the",
"class",
"definition",
"by",
"explicit",
"path",
"where",
"already",
"in",
"the",
"require",
"cache",
"."
] |
bd5aec58b1b38477218dcdc0fb144c6981604fa8
|
https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/application-classes.js#L47-L54
|
37,766 |
axke/rs-api
|
lib/apis/player.js
|
Player
|
function Player(config) {
/**
* Gets a users hiscores and activities (available for `rs` / `osrs`)
* @param username {String} Display name of the user
* @param type {String} [Optional] normal, ironman, hardcore/ultimate
* @returns {Promise} Object of the users hiscores and activities
* @example
* // returns Sync's RS stats and activities
* rsapi.rs.player.hiscores('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the ironman game type
* api.rs.hiscores.player('sausage', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the hardcore ironman game type
* api.rs.hiscores.player('sausage', 'hardcore').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns hey jase's Old School RS stats and activities
* api.osrs.hiscores.player('hey jase').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns lezley's Old School RS stats and activities from the ironman game type
* api.osrs.hiscores.player('lezley', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns perm iron's Old School RS stats and activities from the ultimate ironman game type
* api.osrs.hiscores.player('perm iron', 'ultimate').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*/
this.hiscores = function (username, type) {
return new Hiscores(username, config.hiscores).lookup(type);
};
/**
* Gets a users events log (aka adventure log) (available for `rs`)
* @param username {String} Display name of the user
* @returns {Promise} Object of the users events log
* @example
* // returns Sync's events / adventure log
* rsapi.rs.player.events('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*/
this.events = function (username) {
return new Events(username, config.events).lookup();
}
/**
* Returns the input user(s) clan, title, if the clan is recruiting, if the title is a suffix, as well as online status
* if process.env.username and process.env.password are configured to a valid RS sign-in
* @param usernames {string|array} String of a single username or array of multiple to lookup
* @returns {Promise} Object of the users player details
* @example
* rsapi.rs.player.details(['sync','xredfoxx']).then(function(details) {
* console.log(details);
* }).catch(console.error);
*/
this.details = function (usernames) {
return new Promise(function (resolve, reject) {
var names = [];
if (typeof usernames === 'string') {
names.push(usernames);
}
else if (typeof usernames === 'object') {
names = usernames;
}
else {
var jsonError = new Error('Unrecognized input for usernames. Should be a string or array.');
reject(jsonError);
}
request.createSession().then( function(session) {
request.jsonp(config.urls.playerDetails + JSON.stringify(names), session).then(resolve).catch(reject);
}
).catch(console.error);
});
}
/**
* Return RuneMetrics profile for user
* @param usernames
* @returns {Promise} Object of the users player profile
* @example
* rsapi.rs.player.profile('sync').then(function(profile) {
* console.log(profile);
* }).catch(console.error);
*/
this.profile = function(usernames) {
return new Profile(usernames, config).lookup();
}
}
|
javascript
|
function Player(config) {
/**
* Gets a users hiscores and activities (available for `rs` / `osrs`)
* @param username {String} Display name of the user
* @param type {String} [Optional] normal, ironman, hardcore/ultimate
* @returns {Promise} Object of the users hiscores and activities
* @example
* // returns Sync's RS stats and activities
* rsapi.rs.player.hiscores('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the ironman game type
* api.rs.hiscores.player('sausage', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns Sausage's RS stats and activities from the hardcore ironman game type
* api.rs.hiscores.player('sausage', 'hardcore').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns hey jase's Old School RS stats and activities
* api.osrs.hiscores.player('hey jase').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns lezley's Old School RS stats and activities from the ironman game type
* api.osrs.hiscores.player('lezley', 'ironman').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*
* // returns perm iron's Old School RS stats and activities from the ultimate ironman game type
* api.osrs.hiscores.player('perm iron', 'ultimate').then(function(stats) {
* console.log(stats)
* }).catch(console.error);
*/
this.hiscores = function (username, type) {
return new Hiscores(username, config.hiscores).lookup(type);
};
/**
* Gets a users events log (aka adventure log) (available for `rs`)
* @param username {String} Display name of the user
* @returns {Promise} Object of the users events log
* @example
* // returns Sync's events / adventure log
* rsapi.rs.player.events('sync').then(function(stats) {
* console.log(stats);
* }).catch(console.error);
*/
this.events = function (username) {
return new Events(username, config.events).lookup();
}
/**
* Returns the input user(s) clan, title, if the clan is recruiting, if the title is a suffix, as well as online status
* if process.env.username and process.env.password are configured to a valid RS sign-in
* @param usernames {string|array} String of a single username or array of multiple to lookup
* @returns {Promise} Object of the users player details
* @example
* rsapi.rs.player.details(['sync','xredfoxx']).then(function(details) {
* console.log(details);
* }).catch(console.error);
*/
this.details = function (usernames) {
return new Promise(function (resolve, reject) {
var names = [];
if (typeof usernames === 'string') {
names.push(usernames);
}
else if (typeof usernames === 'object') {
names = usernames;
}
else {
var jsonError = new Error('Unrecognized input for usernames. Should be a string or array.');
reject(jsonError);
}
request.createSession().then( function(session) {
request.jsonp(config.urls.playerDetails + JSON.stringify(names), session).then(resolve).catch(reject);
}
).catch(console.error);
});
}
/**
* Return RuneMetrics profile for user
* @param usernames
* @returns {Promise} Object of the users player profile
* @example
* rsapi.rs.player.profile('sync').then(function(profile) {
* console.log(profile);
* }).catch(console.error);
*/
this.profile = function(usernames) {
return new Profile(usernames, config).lookup();
}
}
|
[
"function",
"Player",
"(",
"config",
")",
"{",
"/**\n * Gets a users hiscores and activities (available for `rs` / `osrs`)\n * @param username {String} Display name of the user\n * @param type {String} [Optional] normal, ironman, hardcore/ultimate\n * @returns {Promise} Object of the users hiscores and activities\n * @example\n * // returns Sync's RS stats and activities\n * rsapi.rs.player.hiscores('sync').then(function(stats) {\n * console.log(stats);\n * }).catch(console.error);\n *\n * // returns Sausage's RS stats and activities from the ironman game type\n * api.rs.hiscores.player('sausage', 'ironman').then(function(stats) {\n * console.log(stats)\n * }).catch(console.error);\n *\n * // returns Sausage's RS stats and activities from the hardcore ironman game type\n * api.rs.hiscores.player('sausage', 'hardcore').then(function(stats) {\n * console.log(stats)\n * }).catch(console.error);\n *\n * // returns hey jase's Old School RS stats and activities\n * api.osrs.hiscores.player('hey jase').then(function(stats) {\n * console.log(stats)\n * }).catch(console.error);\n *\n * // returns lezley's Old School RS stats and activities from the ironman game type\n * api.osrs.hiscores.player('lezley', 'ironman').then(function(stats) {\n * console.log(stats)\n * }).catch(console.error);\n *\n * // returns perm iron's Old School RS stats and activities from the ultimate ironman game type\n * api.osrs.hiscores.player('perm iron', 'ultimate').then(function(stats) {\n * console.log(stats)\n * }).catch(console.error);\n */",
"this",
".",
"hiscores",
"=",
"function",
"(",
"username",
",",
"type",
")",
"{",
"return",
"new",
"Hiscores",
"(",
"username",
",",
"config",
".",
"hiscores",
")",
".",
"lookup",
"(",
"type",
")",
";",
"}",
";",
"/**\n * Gets a users events log (aka adventure log) (available for `rs`)\n * @param username {String} Display name of the user\n * @returns {Promise} Object of the users events log\n * @example\n * // returns Sync's events / adventure log\n * rsapi.rs.player.events('sync').then(function(stats) {\n * console.log(stats);\n * }).catch(console.error);\n */",
"this",
".",
"events",
"=",
"function",
"(",
"username",
")",
"{",
"return",
"new",
"Events",
"(",
"username",
",",
"config",
".",
"events",
")",
".",
"lookup",
"(",
")",
";",
"}",
"/**\n * Returns the input user(s) clan, title, if the clan is recruiting, if the title is a suffix, as well as online status\n * if process.env.username and process.env.password are configured to a valid RS sign-in\n * @param usernames {string|array} String of a single username or array of multiple to lookup\n * @returns {Promise} Object of the users player details\n * @example\n * rsapi.rs.player.details(['sync','xredfoxx']).then(function(details) {\n * console.log(details);\n * }).catch(console.error);\n */",
"this",
".",
"details",
"=",
"function",
"(",
"usernames",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"names",
"=",
"[",
"]",
";",
"if",
"(",
"typeof",
"usernames",
"===",
"'string'",
")",
"{",
"names",
".",
"push",
"(",
"usernames",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"usernames",
"===",
"'object'",
")",
"{",
"names",
"=",
"usernames",
";",
"}",
"else",
"{",
"var",
"jsonError",
"=",
"new",
"Error",
"(",
"'Unrecognized input for usernames. Should be a string or array.'",
")",
";",
"reject",
"(",
"jsonError",
")",
";",
"}",
"request",
".",
"createSession",
"(",
")",
".",
"then",
"(",
"function",
"(",
"session",
")",
"{",
"request",
".",
"jsonp",
"(",
"config",
".",
"urls",
".",
"playerDetails",
"+",
"JSON",
".",
"stringify",
"(",
"names",
")",
",",
"session",
")",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
")",
".",
"catch",
"(",
"console",
".",
"error",
")",
";",
"}",
")",
";",
"}",
"/**\n * Return RuneMetrics profile for user\n * @param usernames\n * @returns {Promise} Object of the users player profile\n * @example\n * rsapi.rs.player.profile('sync').then(function(profile) {\n * console.log(profile);\n * }).catch(console.error);\n */",
"this",
".",
"profile",
"=",
"function",
"(",
"usernames",
")",
"{",
"return",
"new",
"Profile",
"(",
"usernames",
",",
"config",
")",
".",
"lookup",
"(",
")",
";",
"}",
"}"
] |
Module containing Player functions
@module Player
|
[
"Module",
"containing",
"Player",
"functions"
] |
71af4973e1d079f09b7d888b6d24735784185942
|
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/player.js#L13-L112
|
37,767 |
mysticatea/eslint4b
|
scripts/rollup-plugin/replace.js
|
toAbsolute
|
function toAbsolute(id) {
return id.startsWith("./") ? path.resolve(id) : require.resolve(id)
}
|
javascript
|
function toAbsolute(id) {
return id.startsWith("./") ? path.resolve(id) : require.resolve(id)
}
|
[
"function",
"toAbsolute",
"(",
"id",
")",
"{",
"return",
"id",
".",
"startsWith",
"(",
"\"./\"",
")",
"?",
"path",
".",
"resolve",
"(",
"id",
")",
":",
"require",
".",
"resolve",
"(",
"id",
")",
"}"
] |
Convert a given moduleId to an absolute path.
@param {string} id The moduleId to normalize.
@returns {string} The normalized path.
|
[
"Convert",
"a",
"given",
"moduleId",
"to",
"an",
"absolute",
"path",
"."
] |
e0ecf68565c252210131c2418437765bc2d8b641
|
https://github.com/mysticatea/eslint4b/blob/e0ecf68565c252210131c2418437765bc2d8b641/scripts/rollup-plugin/replace.js#L12-L14
|
37,768 |
LaunchPadLab/lp-redux-api
|
src/selectors.js
|
stripNamespace
|
function stripNamespace (requestKey) {
return requestKey.startsWith(LP_API_ACTION_NAMESPACE)
? requestKey.slice(LP_API_ACTION_NAMESPACE.length)
: requestKey
}
|
javascript
|
function stripNamespace (requestKey) {
return requestKey.startsWith(LP_API_ACTION_NAMESPACE)
? requestKey.slice(LP_API_ACTION_NAMESPACE.length)
: requestKey
}
|
[
"function",
"stripNamespace",
"(",
"requestKey",
")",
"{",
"return",
"requestKey",
".",
"startsWith",
"(",
"LP_API_ACTION_NAMESPACE",
")",
"?",
"requestKey",
".",
"slice",
"(",
"LP_API_ACTION_NAMESPACE",
".",
"length",
")",
":",
"requestKey",
"}"
] |
Remove action namespace if it's at the beginning
|
[
"Remove",
"action",
"namespace",
"if",
"it",
"s",
"at",
"the",
"beginning"
] |
73eee231067365326780ddc1dbbfa50d3e65defc
|
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/selectors.js#L54-L58
|
37,769 |
jonschlinkert/deep-bind
|
index.js
|
deepBind
|
function deepBind(target, thisArg, options) {
if (!isObject(target)) {
throw new TypeError('expected an object');
}
options = options || {};
for (var key in target) {
var fn = target[key];
if (typeof fn === 'object') {
target[key] = deepBind(fn, thisArg);
} else if (typeof fn === 'function') {
target[key] = bind(thisArg, key, fn, options);
// copy function keys
for (var k in fn) {
target[key][k] = fn[k];
}
} else {
target[key] = fn;
}
}
return target;
}
|
javascript
|
function deepBind(target, thisArg, options) {
if (!isObject(target)) {
throw new TypeError('expected an object');
}
options = options || {};
for (var key in target) {
var fn = target[key];
if (typeof fn === 'object') {
target[key] = deepBind(fn, thisArg);
} else if (typeof fn === 'function') {
target[key] = bind(thisArg, key, fn, options);
// copy function keys
for (var k in fn) {
target[key][k] = fn[k];
}
} else {
target[key] = fn;
}
}
return target;
}
|
[
"function",
"deepBind",
"(",
"target",
",",
"thisArg",
",",
"options",
")",
"{",
"if",
"(",
"!",
"isObject",
"(",
"target",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected an object'",
")",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"target",
")",
"{",
"var",
"fn",
"=",
"target",
"[",
"key",
"]",
";",
"if",
"(",
"typeof",
"fn",
"===",
"'object'",
")",
"{",
"target",
"[",
"key",
"]",
"=",
"deepBind",
"(",
"fn",
",",
"thisArg",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"fn",
"===",
"'function'",
")",
"{",
"target",
"[",
"key",
"]",
"=",
"bind",
"(",
"thisArg",
",",
"key",
",",
"fn",
",",
"options",
")",
";",
"// copy function keys",
"for",
"(",
"var",
"k",
"in",
"fn",
")",
"{",
"target",
"[",
"key",
"]",
"[",
"k",
"]",
"=",
"fn",
"[",
"k",
"]",
";",
"}",
"}",
"else",
"{",
"target",
"[",
"key",
"]",
"=",
"fn",
";",
"}",
"}",
"return",
"target",
";",
"}"
] |
Bind a `thisArg` to all the functions on the target
@param {Object|Array} `target` Object or Array with functions as values that will be bound.
@param {Object} `thisArg` Object to bind to the functions
@return {Object|Array} Object or Array with bound functions.
@api public
|
[
"Bind",
"a",
"thisArg",
"to",
"all",
"the",
"functions",
"on",
"the",
"target"
] |
c654562afd3712add9d41ec02cabdb5c45e99a0b
|
https://github.com/jonschlinkert/deep-bind/blob/c654562afd3712add9d41ec02cabdb5c45e99a0b/index.js#L14-L38
|
37,770 |
LaunchPadLab/lp-redux-api
|
src/handlers/handle-response.js
|
handleResponse
|
function handleResponse (successHandler, failureHandler) {
if (!(successHandler && failureHandler)) throw new Error('handleResponse requires both a success handler and failure handler.')
return (state, action) => {
if (isSuccessAction(action)) return successHandler(state, action, getDataFromAction(action))
if (isFailureAction(action)) return failureHandler(state, action, getDataFromAction(action))
return state
}
}
|
javascript
|
function handleResponse (successHandler, failureHandler) {
if (!(successHandler && failureHandler)) throw new Error('handleResponse requires both a success handler and failure handler.')
return (state, action) => {
if (isSuccessAction(action)) return successHandler(state, action, getDataFromAction(action))
if (isFailureAction(action)) return failureHandler(state, action, getDataFromAction(action))
return state
}
}
|
[
"function",
"handleResponse",
"(",
"successHandler",
",",
"failureHandler",
")",
"{",
"if",
"(",
"!",
"(",
"successHandler",
"&&",
"failureHandler",
")",
")",
"throw",
"new",
"Error",
"(",
"'handleResponse requires both a success handler and failure handler.'",
")",
"return",
"(",
"state",
",",
"action",
")",
"=>",
"{",
"if",
"(",
"isSuccessAction",
"(",
"action",
")",
")",
"return",
"successHandler",
"(",
"state",
",",
"action",
",",
"getDataFromAction",
"(",
"action",
")",
")",
"if",
"(",
"isFailureAction",
"(",
"action",
")",
")",
"return",
"failureHandler",
"(",
"state",
",",
"action",
",",
"getDataFromAction",
"(",
"action",
")",
")",
"return",
"state",
"}",
"}"
] |
A function that takes two API action handlers, one for successful requests and one for failed requests,
and applies the handlers when the responses have the correct status.
@name handleResponse
@param {Function} successHandler - An action handler that is passed `state`, `action` and `data` params
@param {Function} failureHandler - An action handler that is passed `state`, `action` and `data` params
@returns {Function} An action handler runs the handler that corresponds to the request status
@example
handleActions({
[apiActions.fetchUser]: handleResponse(
(state, action) => {
// This code runs if the call is successful
return set('currentUser', action.payload.data, state)
},
(state, action) => {
// This code runs if the call is unsuccessful
return set('userFetchError', action.payload.data, state)
},
)
})
|
[
"A",
"function",
"that",
"takes",
"two",
"API",
"action",
"handlers",
"one",
"for",
"successful",
"requests",
"and",
"one",
"for",
"failed",
"requests",
"and",
"applies",
"the",
"handlers",
"when",
"the",
"responses",
"have",
"the",
"correct",
"status",
"."
] |
73eee231067365326780ddc1dbbfa50d3e65defc
|
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/handle-response.js#L28-L35
|
37,771 |
almost/string-replace-stream
|
string-replace-stream.js
|
buildTable
|
function buildTable(search) {
// Based on https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm
var table = Array(search.length), pos = 2, cnd = 0, searchLen = search.length;
table[0] = -1;
table[1] = 0;
while (pos < searchLen) {
if (search[pos-1] === search[cnd]) {
// the substring continues
cnd++;
table[pos] = cnd;
pos++;
} else if (cnd > 0) {
// it doesn't, but we can fall back
cnd = table[cnd];
} else {
// we have run part of candidates. Note cnd = 0
table[pos] = 0;
pos++;
}
}
return table;
}
|
javascript
|
function buildTable(search) {
// Based on https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm
var table = Array(search.length), pos = 2, cnd = 0, searchLen = search.length;
table[0] = -1;
table[1] = 0;
while (pos < searchLen) {
if (search[pos-1] === search[cnd]) {
// the substring continues
cnd++;
table[pos] = cnd;
pos++;
} else if (cnd > 0) {
// it doesn't, but we can fall back
cnd = table[cnd];
} else {
// we have run part of candidates. Note cnd = 0
table[pos] = 0;
pos++;
}
}
return table;
}
|
[
"function",
"buildTable",
"(",
"search",
")",
"{",
"// Based on https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm",
"var",
"table",
"=",
"Array",
"(",
"search",
".",
"length",
")",
",",
"pos",
"=",
"2",
",",
"cnd",
"=",
"0",
",",
"searchLen",
"=",
"search",
".",
"length",
";",
"table",
"[",
"0",
"]",
"=",
"-",
"1",
";",
"table",
"[",
"1",
"]",
"=",
"0",
";",
"while",
"(",
"pos",
"<",
"searchLen",
")",
"{",
"if",
"(",
"search",
"[",
"pos",
"-",
"1",
"]",
"===",
"search",
"[",
"cnd",
"]",
")",
"{",
"// the substring continues",
"cnd",
"++",
";",
"table",
"[",
"pos",
"]",
"=",
"cnd",
";",
"pos",
"++",
";",
"}",
"else",
"if",
"(",
"cnd",
">",
"0",
")",
"{",
"// it doesn't, but we can fall back",
"cnd",
"=",
"table",
"[",
"cnd",
"]",
";",
"}",
"else",
"{",
"// we have run part of candidates. Note cnd = 0",
"table",
"[",
"pos",
"]",
"=",
"0",
";",
"pos",
"++",
";",
"}",
"}",
"return",
"table",
";",
"}"
] |
Build the Knuth-Morris-Pratt table
|
[
"Build",
"the",
"Knuth",
"-",
"Morris",
"-",
"Pratt",
"table"
] |
f47cdfa8b0acbe27cf82685c0a4343df7a47bd73
|
https://github.com/almost/string-replace-stream/blob/f47cdfa8b0acbe27cf82685c0a4343df7a47bd73/string-replace-stream.js#L8-L29
|
37,772 |
lvhaohua/react-candee
|
src/actions.js
|
actionCreator
|
function actionCreator(modelName, actionName) {
return data => (
dispatch({
type: getFullTypeName(modelName, actionName),
data
})
)
}
|
javascript
|
function actionCreator(modelName, actionName) {
return data => (
dispatch({
type: getFullTypeName(modelName, actionName),
data
})
)
}
|
[
"function",
"actionCreator",
"(",
"modelName",
",",
"actionName",
")",
"{",
"return",
"data",
"=>",
"(",
"dispatch",
"(",
"{",
"type",
":",
"getFullTypeName",
"(",
"modelName",
",",
"actionName",
")",
",",
"data",
"}",
")",
")",
"}"
] |
auto dispatch action
|
[
"auto",
"dispatch",
"action"
] |
d93d05e5dee580a547d9732c7f8157dace0b4eb6
|
https://github.com/lvhaohua/react-candee/blob/d93d05e5dee580a547d9732c7f8157dace0b4eb6/src/actions.js#L8-L15
|
37,773 |
oskargustafsson/BFF
|
src/event-listener.js
|
function (eventEmitters, eventNames, callback, context, useCapture) {
if (RUNTIME_CHECKS) {
if (!eventEmitters || !(eventEmitters.addEventListener || eventEmitters instanceof Array)) {
throw '"eventEmitters" argument must be an event emitter or an array of event emitters';
}
if (typeof eventNames !== 'string' && !(eventNames instanceof Array)) {
throw '"eventNames" argument must be a string or an array of strings';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
if (arguments.length > 4 && typeof useCapture !== 'boolean') {
throw '"useCapture" argument must be a boolean value';
}
}
// Convenience functionality that allows you to listen to all items in an Array or NodeList
// BFF Lists have this kind of functionality built it, so don't handle that case here
eventEmitters = eventEmitters instanceof Array ||
(typeof NodeList !== 'undefined' && eventEmitters instanceof NodeList) ? eventEmitters : [ eventEmitters ];
eventNames = eventNames instanceof Array ? eventNames : [ eventNames ];
for (var i = 0; i < eventEmitters.length; ++i) {
for (var j = 0; j < eventNames.length; ++j) {
setupListeners(this, eventEmitters[i], eventNames[j], callback, context, !!useCapture);
}
}
}
|
javascript
|
function (eventEmitters, eventNames, callback, context, useCapture) {
if (RUNTIME_CHECKS) {
if (!eventEmitters || !(eventEmitters.addEventListener || eventEmitters instanceof Array)) {
throw '"eventEmitters" argument must be an event emitter or an array of event emitters';
}
if (typeof eventNames !== 'string' && !(eventNames instanceof Array)) {
throw '"eventNames" argument must be a string or an array of strings';
}
if (typeof callback !== 'function') {
throw '"callback" argument must be a function';
}
if (arguments.length > 4 && typeof useCapture !== 'boolean') {
throw '"useCapture" argument must be a boolean value';
}
}
// Convenience functionality that allows you to listen to all items in an Array or NodeList
// BFF Lists have this kind of functionality built it, so don't handle that case here
eventEmitters = eventEmitters instanceof Array ||
(typeof NodeList !== 'undefined' && eventEmitters instanceof NodeList) ? eventEmitters : [ eventEmitters ];
eventNames = eventNames instanceof Array ? eventNames : [ eventNames ];
for (var i = 0; i < eventEmitters.length; ++i) {
for (var j = 0; j < eventNames.length; ++j) {
setupListeners(this, eventEmitters[i], eventNames[j], callback, context, !!useCapture);
}
}
}
|
[
"function",
"(",
"eventEmitters",
",",
"eventNames",
",",
"callback",
",",
"context",
",",
"useCapture",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"!",
"eventEmitters",
"||",
"!",
"(",
"eventEmitters",
".",
"addEventListener",
"||",
"eventEmitters",
"instanceof",
"Array",
")",
")",
"{",
"throw",
"'\"eventEmitters\" argument must be an event emitter or an array of event emitters'",
";",
"}",
"if",
"(",
"typeof",
"eventNames",
"!==",
"'string'",
"&&",
"!",
"(",
"eventNames",
"instanceof",
"Array",
")",
")",
"{",
"throw",
"'\"eventNames\" argument must be a string or an array of strings'",
";",
"}",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"throw",
"'\"callback\" argument must be a function'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"4",
"&&",
"typeof",
"useCapture",
"!==",
"'boolean'",
")",
"{",
"throw",
"'\"useCapture\" argument must be a boolean value'",
";",
"}",
"}",
"// Convenience functionality that allows you to listen to all items in an Array or NodeList",
"// BFF Lists have this kind of functionality built it, so don't handle that case here",
"eventEmitters",
"=",
"eventEmitters",
"instanceof",
"Array",
"||",
"(",
"typeof",
"NodeList",
"!==",
"'undefined'",
"&&",
"eventEmitters",
"instanceof",
"NodeList",
")",
"?",
"eventEmitters",
":",
"[",
"eventEmitters",
"]",
";",
"eventNames",
"=",
"eventNames",
"instanceof",
"Array",
"?",
"eventNames",
":",
"[",
"eventNames",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"eventEmitters",
".",
"length",
";",
"++",
"i",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"eventNames",
".",
"length",
";",
"++",
"j",
")",
"{",
"setupListeners",
"(",
"this",
",",
"eventEmitters",
"[",
"i",
"]",
",",
"eventNames",
"[",
"j",
"]",
",",
"callback",
",",
"context",
",",
"!",
"!",
"useCapture",
")",
";",
"}",
"}",
"}"
] |
Start listening to an event on a specified event emitting object. Both eventEmitters and eventNames arguments can be arrays. The total amount of listeners added will be the Cartesian product of the two lists.
@instance
@arg {Object|Array|NodeList} eventEmitters - One or more event emitters that will be listened to.
@arg {string|Array} eventNames - One or more string identifiers for events that will be listented to.
@arg {function} callback - The function that will be called when the event is emitted.
@arg {any} [context] - The context with which the callback will be called (i.e. what "this" will be).
Will default to the caller of .listenTo, if not provided.
|
[
"Start",
"listening",
"to",
"an",
"event",
"on",
"a",
"specified",
"event",
"emitting",
"object",
".",
"Both",
"eventEmitters",
"and",
"eventNames",
"arguments",
"can",
"be",
"arrays",
".",
"The",
"total",
"amount",
"of",
"listeners",
"added",
"will",
"be",
"the",
"Cartesian",
"product",
"of",
"the",
"two",
"lists",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-listener.js#L55-L83
|
|
37,774 |
oskargustafsson/BFF
|
src/event-listener.js
|
function (eventEmitter, eventName) {
if (RUNTIME_CHECKS) {
if (!!eventEmitter && !eventEmitter.addEventListener) {
throw '"eventEmitter" argument must be an event emitter';
}
if (arguments.length > 1 && typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
}
if (!this.__private || !this.__private.listeningTo) { return; } // Not listening to anything? We are done.
var eventNames = eventName ? {} : this.__private.listeningTo;
eventName && (eventNames[eventName] = true);
for (eventName in eventNames) {
var listeningToList = this.__private.listeningTo[eventName];
if (!listeningToList) { continue; }
filterList(listeningToList, eventName, eventEmitter);
listeningToList.length || (delete this.__private.listeningTo[eventName]);
}
}
|
javascript
|
function (eventEmitter, eventName) {
if (RUNTIME_CHECKS) {
if (!!eventEmitter && !eventEmitter.addEventListener) {
throw '"eventEmitter" argument must be an event emitter';
}
if (arguments.length > 1 && typeof eventName !== 'string') {
throw '"eventName" argument must be a string';
}
}
if (!this.__private || !this.__private.listeningTo) { return; } // Not listening to anything? We are done.
var eventNames = eventName ? {} : this.__private.listeningTo;
eventName && (eventNames[eventName] = true);
for (eventName in eventNames) {
var listeningToList = this.__private.listeningTo[eventName];
if (!listeningToList) { continue; }
filterList(listeningToList, eventName, eventEmitter);
listeningToList.length || (delete this.__private.listeningTo[eventName]);
}
}
|
[
"function",
"(",
"eventEmitter",
",",
"eventName",
")",
"{",
"if",
"(",
"RUNTIME_CHECKS",
")",
"{",
"if",
"(",
"!",
"!",
"eventEmitter",
"&&",
"!",
"eventEmitter",
".",
"addEventListener",
")",
"{",
"throw",
"'\"eventEmitter\" argument must be an event emitter'",
";",
"}",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
"&&",
"typeof",
"eventName",
"!==",
"'string'",
")",
"{",
"throw",
"'\"eventName\" argument must be a string'",
";",
"}",
"}",
"if",
"(",
"!",
"this",
".",
"__private",
"||",
"!",
"this",
".",
"__private",
".",
"listeningTo",
")",
"{",
"return",
";",
"}",
"// Not listening to anything? We are done.",
"var",
"eventNames",
"=",
"eventName",
"?",
"{",
"}",
":",
"this",
".",
"__private",
".",
"listeningTo",
";",
"eventName",
"&&",
"(",
"eventNames",
"[",
"eventName",
"]",
"=",
"true",
")",
";",
"for",
"(",
"eventName",
"in",
"eventNames",
")",
"{",
"var",
"listeningToList",
"=",
"this",
".",
"__private",
".",
"listeningTo",
"[",
"eventName",
"]",
";",
"if",
"(",
"!",
"listeningToList",
")",
"{",
"continue",
";",
"}",
"filterList",
"(",
"listeningToList",
",",
"eventName",
",",
"eventEmitter",
")",
";",
"listeningToList",
".",
"length",
"||",
"(",
"delete",
"this",
".",
"__private",
".",
"listeningTo",
"[",
"eventName",
"]",
")",
";",
"}",
"}"
] |
Stop listening to events. If no arguments are provided, the listener removes all its event listeners. Providing any or both of the optional arguments will filter the list of event listeners removed.
@instance
@arg {Object} [eventEmitter] - If provided, only callbacks attached to the given event emitter will be removed.
@arg {string} [eventName] - If provided, only callbacks attached to the given event name will be removed.
|
[
"Stop",
"listening",
"to",
"events",
".",
"If",
"no",
"arguments",
"are",
"provided",
"the",
"listener",
"removes",
"all",
"its",
"event",
"listeners",
".",
"Providing",
"any",
"or",
"both",
"of",
"the",
"optional",
"arguments",
"will",
"filter",
"the",
"list",
"of",
"event",
"listeners",
"removed",
"."
] |
38ebebf3b69f758da78ffb50a97742d33d6d5931
|
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-listener.js#L91-L112
|
|
37,775 |
axke/rs-api
|
lib/apis/grandexchange.js
|
function (data) {
var items = [];
data.forEach(function (d, i) {
if (d.includes('ITEM:') && d.length > 3) {
var iid = data[i + 1];
var item = {
item: {
id: Number(iid[1].trim()),
name: d[2].replace(/_/g, ' '),
price: d[3],
change: d[4]
}
};
items.push(item);
}
});
return items;
}
|
javascript
|
function (data) {
var items = [];
data.forEach(function (d, i) {
if (d.includes('ITEM:') && d.length > 3) {
var iid = data[i + 1];
var item = {
item: {
id: Number(iid[1].trim()),
name: d[2].replace(/_/g, ' '),
price: d[3],
change: d[4]
}
};
items.push(item);
}
});
return items;
}
|
[
"function",
"(",
"data",
")",
"{",
"var",
"items",
"=",
"[",
"]",
";",
"data",
".",
"forEach",
"(",
"function",
"(",
"d",
",",
"i",
")",
"{",
"if",
"(",
"d",
".",
"includes",
"(",
"'ITEM:'",
")",
"&&",
"d",
".",
"length",
">",
"3",
")",
"{",
"var",
"iid",
"=",
"data",
"[",
"i",
"+",
"1",
"]",
";",
"var",
"item",
"=",
"{",
"item",
":",
"{",
"id",
":",
"Number",
"(",
"iid",
"[",
"1",
"]",
".",
"trim",
"(",
")",
")",
",",
"name",
":",
"d",
"[",
"2",
"]",
".",
"replace",
"(",
"/",
"_",
"/",
"g",
",",
"' '",
")",
",",
"price",
":",
"d",
"[",
"3",
"]",
",",
"change",
":",
"d",
"[",
"4",
"]",
"}",
"}",
";",
"items",
".",
"push",
"(",
"item",
")",
";",
"}",
"}",
")",
";",
"return",
"items",
";",
"}"
] |
Read the RScript data and put it into an item array
|
[
"Read",
"the",
"RScript",
"data",
"and",
"put",
"it",
"into",
"an",
"item",
"array"
] |
71af4973e1d079f09b7d888b6d24735784185942
|
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/grandexchange.js#L13-L30
|
|
37,776 |
skuid/skuid-grunt
|
tasks/lib/helpers.js
|
function(pagedef, pagedir){
var filenameBase = pagedir + pagedef.uniqueId;
var xmlDef = {ext: '.xml', contents: pd.xml(pagedef.body)};
var metaDef = {
ext: '.json',
contents: JSON.stringify(_.omit(pagedef, 'body'), null, 3)
};
_.each([xmlDef, metaDef], function(item){
var filename = filenameBase + item.ext;
grunt.file.write(filenameBase + item.ext, item.contents);
if(grunt.option('verbose')){
grunt.log.ok(filename + ' written to ' + pagedir);
}
});
}
|
javascript
|
function(pagedef, pagedir){
var filenameBase = pagedir + pagedef.uniqueId;
var xmlDef = {ext: '.xml', contents: pd.xml(pagedef.body)};
var metaDef = {
ext: '.json',
contents: JSON.stringify(_.omit(pagedef, 'body'), null, 3)
};
_.each([xmlDef, metaDef], function(item){
var filename = filenameBase + item.ext;
grunt.file.write(filenameBase + item.ext, item.contents);
if(grunt.option('verbose')){
grunt.log.ok(filename + ' written to ' + pagedir);
}
});
}
|
[
"function",
"(",
"pagedef",
",",
"pagedir",
")",
"{",
"var",
"filenameBase",
"=",
"pagedir",
"+",
"pagedef",
".",
"uniqueId",
";",
"var",
"xmlDef",
"=",
"{",
"ext",
":",
"'.xml'",
",",
"contents",
":",
"pd",
".",
"xml",
"(",
"pagedef",
".",
"body",
")",
"}",
";",
"var",
"metaDef",
"=",
"{",
"ext",
":",
"'.json'",
",",
"contents",
":",
"JSON",
".",
"stringify",
"(",
"_",
".",
"omit",
"(",
"pagedef",
",",
"'body'",
")",
",",
"null",
",",
"3",
")",
"}",
";",
"_",
".",
"each",
"(",
"[",
"xmlDef",
",",
"metaDef",
"]",
",",
"function",
"(",
"item",
")",
"{",
"var",
"filename",
"=",
"filenameBase",
"+",
"item",
".",
"ext",
";",
"grunt",
".",
"file",
".",
"write",
"(",
"filenameBase",
"+",
"item",
".",
"ext",
",",
"item",
".",
"contents",
")",
";",
"if",
"(",
"grunt",
".",
"option",
"(",
"'verbose'",
")",
")",
"{",
"grunt",
".",
"log",
".",
"ok",
"(",
"filename",
"+",
"' written to '",
"+",
"pagedir",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Prepare the xml and json meta files for the specified Skuid page
@param {[type]} pagedef [description]
@param {[type]} pagedir [description]
@return {[type]} [description]
|
[
"Prepare",
"the",
"xml",
"and",
"json",
"meta",
"files",
"for",
"the",
"specified",
"Skuid",
"page"
] |
e714b0181ab2674f889b5e2571fd88e0802fbdf1
|
https://github.com/skuid/skuid-grunt/blob/e714b0181ab2674f889b5e2571fd88e0802fbdf1/tasks/lib/helpers.js#L12-L26
|
|
37,777 |
junghans-schneider/extjs-dependencies
|
lib/parser.js
|
parseAlternateMappingsCall
|
function parseAlternateMappingsCall(node, output) {
var firstArgument = node.expression.arguments[0];
if (firstArgument && firstArgument.type === 'ObjectExpression') {
firstArgument.properties.forEach(function(prop) {
var aliasClassNames = getPropertyValue(prop); // Could be a string or an array of strings
if (aliasClassNames && aliasClassNames.length > 0) {
var className = prop.key.value;
if (! output.aliasNames) {
output.aliasNames = {};
}
if (typeof aliasClassNames === 'string') {
aliasClassNames = [ aliasClassNames ];
}
var existingAliasClassNames = output.aliasNames[className];
if (existingAliasClassNames) {
aliasClassNames = existingAliasClassNames.concat(aliasClassNames);
}
output.aliasNames[className] = unique(aliasClassNames);
}
});
if (options.optimizeSource) {
// Remove `uses` from parsed file
node.update('/* call to Ext.ClassManager.addNameAlternateMappings removed */');
}
}
}
|
javascript
|
function parseAlternateMappingsCall(node, output) {
var firstArgument = node.expression.arguments[0];
if (firstArgument && firstArgument.type === 'ObjectExpression') {
firstArgument.properties.forEach(function(prop) {
var aliasClassNames = getPropertyValue(prop); // Could be a string or an array of strings
if (aliasClassNames && aliasClassNames.length > 0) {
var className = prop.key.value;
if (! output.aliasNames) {
output.aliasNames = {};
}
if (typeof aliasClassNames === 'string') {
aliasClassNames = [ aliasClassNames ];
}
var existingAliasClassNames = output.aliasNames[className];
if (existingAliasClassNames) {
aliasClassNames = existingAliasClassNames.concat(aliasClassNames);
}
output.aliasNames[className] = unique(aliasClassNames);
}
});
if (options.optimizeSource) {
// Remove `uses` from parsed file
node.update('/* call to Ext.ClassManager.addNameAlternateMappings removed */');
}
}
}
|
[
"function",
"parseAlternateMappingsCall",
"(",
"node",
",",
"output",
")",
"{",
"var",
"firstArgument",
"=",
"node",
".",
"expression",
".",
"arguments",
"[",
"0",
"]",
";",
"if",
"(",
"firstArgument",
"&&",
"firstArgument",
".",
"type",
"===",
"'ObjectExpression'",
")",
"{",
"firstArgument",
".",
"properties",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"var",
"aliasClassNames",
"=",
"getPropertyValue",
"(",
"prop",
")",
";",
"// Could be a string or an array of strings",
"if",
"(",
"aliasClassNames",
"&&",
"aliasClassNames",
".",
"length",
">",
"0",
")",
"{",
"var",
"className",
"=",
"prop",
".",
"key",
".",
"value",
";",
"if",
"(",
"!",
"output",
".",
"aliasNames",
")",
"{",
"output",
".",
"aliasNames",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"aliasClassNames",
"===",
"'string'",
")",
"{",
"aliasClassNames",
"=",
"[",
"aliasClassNames",
"]",
";",
"}",
"var",
"existingAliasClassNames",
"=",
"output",
".",
"aliasNames",
"[",
"className",
"]",
";",
"if",
"(",
"existingAliasClassNames",
")",
"{",
"aliasClassNames",
"=",
"existingAliasClassNames",
".",
"concat",
"(",
"aliasClassNames",
")",
";",
"}",
"output",
".",
"aliasNames",
"[",
"className",
"]",
"=",
"unique",
"(",
"aliasClassNames",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"options",
".",
"optimizeSource",
")",
"{",
"// Remove `uses` from parsed file",
"node",
".",
"update",
"(",
"'/* call to Ext.ClassManager.addNameAlternateMappings removed */'",
")",
";",
"}",
"}",
"}"
] |
Parses a call to Ext.ClassManager.addNameAlternateMappings
|
[
"Parses",
"a",
"call",
"to",
"Ext",
".",
"ClassManager",
".",
"addNameAlternateMappings"
] |
be36e87339b0973883c490fe2535414e74b1413b
|
https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/parser.js#L297-L328
|
37,778 |
junghans-schneider/extjs-dependencies
|
lib/parser.js
|
parseLoaderSetPathCall
|
function parseLoaderSetPathCall(node, output) {
// Example: `Ext.Loader.setPath('Ext.ux', 'lib/extjs-ux/src');`
var classPrefixArg = node.expression.arguments[0];
var pathArg = node.expression.arguments[1];
if (classPrefixArg && pathArg) {
addResolvePath(classPrefixArg.value, pathArg.value, output);
}
}
|
javascript
|
function parseLoaderSetPathCall(node, output) {
// Example: `Ext.Loader.setPath('Ext.ux', 'lib/extjs-ux/src');`
var classPrefixArg = node.expression.arguments[0];
var pathArg = node.expression.arguments[1];
if (classPrefixArg && pathArg) {
addResolvePath(classPrefixArg.value, pathArg.value, output);
}
}
|
[
"function",
"parseLoaderSetPathCall",
"(",
"node",
",",
"output",
")",
"{",
"// Example: `Ext.Loader.setPath('Ext.ux', 'lib/extjs-ux/src');`",
"var",
"classPrefixArg",
"=",
"node",
".",
"expression",
".",
"arguments",
"[",
"0",
"]",
";",
"var",
"pathArg",
"=",
"node",
".",
"expression",
".",
"arguments",
"[",
"1",
"]",
";",
"if",
"(",
"classPrefixArg",
"&&",
"pathArg",
")",
"{",
"addResolvePath",
"(",
"classPrefixArg",
".",
"value",
",",
"pathArg",
".",
"value",
",",
"output",
")",
";",
"}",
"}"
] |
Parses call to Ext.Loader.setPath
|
[
"Parses",
"call",
"to",
"Ext",
".",
"Loader",
".",
"setPath"
] |
be36e87339b0973883c490fe2535414e74b1413b
|
https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/parser.js#L331-L338
|
37,779 |
twolfson/fontsmith
|
lib/fontsmith.js
|
fontsmith
|
function fontsmith(params, cb) {
// Collect paths
var files = params.src,
retObj = {};
// TODO: Allow specification of engine when we have more
// TODO: By default, use an `auto` engine which falls back through engines until it finds one.
// Load in our engine and assert it exists
var engine = engines['icomoon-phantomjs'];
assert(engine, 'fontsmith engine "icomoon-phantomjs" could not be loaded. Please verify its dependencies are satisfied.');
// In series
var palette;
async.waterfall([
// Create an engine to work with
function createEngine (cb) {
// TODO; Figure out what the options will be / where they come from
engine.create({}, cb);
},
// Save the palette for external reference
function savePalette (_palette, cb) {
palette = _palette;
cb();
},
// TODO: Each SVG might have a specified character
// TODO: This is the equivalent of a custom `layout` as defined in spritesmith
// Add in our svgs
function addSvgs (cb) {
// DEV: If we ever run into perf issue regarding this, we should make this a batch function as in spritesmith
async.forEach(files, palette.addSvg.bind(palette), cb);
},
// Export the resulting fonts/map
function exportFn (cb) {
// Format should be {map:{'absolute/path':'\unicode'}, fonts: {svg:'binary', ttf:'binary'}}
palette['export'](params.exportOptions || {}, cb);
}
], cb);
}
|
javascript
|
function fontsmith(params, cb) {
// Collect paths
var files = params.src,
retObj = {};
// TODO: Allow specification of engine when we have more
// TODO: By default, use an `auto` engine which falls back through engines until it finds one.
// Load in our engine and assert it exists
var engine = engines['icomoon-phantomjs'];
assert(engine, 'fontsmith engine "icomoon-phantomjs" could not be loaded. Please verify its dependencies are satisfied.');
// In series
var palette;
async.waterfall([
// Create an engine to work with
function createEngine (cb) {
// TODO; Figure out what the options will be / where they come from
engine.create({}, cb);
},
// Save the palette for external reference
function savePalette (_palette, cb) {
palette = _palette;
cb();
},
// TODO: Each SVG might have a specified character
// TODO: This is the equivalent of a custom `layout` as defined in spritesmith
// Add in our svgs
function addSvgs (cb) {
// DEV: If we ever run into perf issue regarding this, we should make this a batch function as in spritesmith
async.forEach(files, palette.addSvg.bind(palette), cb);
},
// Export the resulting fonts/map
function exportFn (cb) {
// Format should be {map:{'absolute/path':'\unicode'}, fonts: {svg:'binary', ttf:'binary'}}
palette['export'](params.exportOptions || {}, cb);
}
], cb);
}
|
[
"function",
"fontsmith",
"(",
"params",
",",
"cb",
")",
"{",
"// Collect paths",
"var",
"files",
"=",
"params",
".",
"src",
",",
"retObj",
"=",
"{",
"}",
";",
"// TODO: Allow specification of engine when we have more",
"// TODO: By default, use an `auto` engine which falls back through engines until it finds one.",
"// Load in our engine and assert it exists",
"var",
"engine",
"=",
"engines",
"[",
"'icomoon-phantomjs'",
"]",
";",
"assert",
"(",
"engine",
",",
"'fontsmith engine \"icomoon-phantomjs\" could not be loaded. Please verify its dependencies are satisfied.'",
")",
";",
"// In series",
"var",
"palette",
";",
"async",
".",
"waterfall",
"(",
"[",
"// Create an engine to work with",
"function",
"createEngine",
"(",
"cb",
")",
"{",
"// TODO; Figure out what the options will be / where they come from",
"engine",
".",
"create",
"(",
"{",
"}",
",",
"cb",
")",
";",
"}",
",",
"// Save the palette for external reference",
"function",
"savePalette",
"(",
"_palette",
",",
"cb",
")",
"{",
"palette",
"=",
"_palette",
";",
"cb",
"(",
")",
";",
"}",
",",
"// TODO: Each SVG might have a specified character",
"// TODO: This is the equivalent of a custom `layout` as defined in spritesmith",
"// Add in our svgs",
"function",
"addSvgs",
"(",
"cb",
")",
"{",
"// DEV: If we ever run into perf issue regarding this, we should make this a batch function as in spritesmith",
"async",
".",
"forEach",
"(",
"files",
",",
"palette",
".",
"addSvg",
".",
"bind",
"(",
"palette",
")",
",",
"cb",
")",
";",
"}",
",",
"// Export the resulting fonts/map",
"function",
"exportFn",
"(",
"cb",
")",
"{",
"// Format should be {map:{'absolute/path':'\\unicode'}, fonts: {svg:'binary', ttf:'binary'}}",
"palette",
"[",
"'export'",
"]",
"(",
"params",
".",
"exportOptions",
"||",
"{",
"}",
",",
"cb",
")",
";",
"}",
"]",
",",
"cb",
")",
";",
"}"
] |
Function which eats SVGs and outputs fonts and a mapping from file names to unicode values
@param {Object} params Object containing all parameters for fontsmith
@param {String[]} params.src Array of paths to SVGs to compile
@param {Function} cb Error-first function to callback with composition results
|
[
"Function",
"which",
"eats",
"SVGs",
"and",
"outputs",
"fonts",
"and",
"a",
"mapping",
"from",
"file",
"names",
"to",
"unicode",
"values"
] |
c5b1e24f4bb06fdefba57b0b73af8971024d9216
|
https://github.com/twolfson/fontsmith/blob/c5b1e24f4bb06fdefba57b0b73af8971024d9216/lib/fontsmith.js#L12-L49
|
37,780 |
blakeembrey/dombars
|
lib/raf.js
|
function () {
/**
* Return the current timestamp integer.
*/
var now = Date.now || function () {
return new Date().getTime();
};
// Keep track of the previous "animation frame" manually.
var prev = now();
return function (fn) {
var curr = now();
var ms = Math.max(0, 16 - (curr - prev));
var req = setTimeout(fn, ms);
prev = curr;
return req;
};
}
|
javascript
|
function () {
/**
* Return the current timestamp integer.
*/
var now = Date.now || function () {
return new Date().getTime();
};
// Keep track of the previous "animation frame" manually.
var prev = now();
return function (fn) {
var curr = now();
var ms = Math.max(0, 16 - (curr - prev));
var req = setTimeout(fn, ms);
prev = curr;
return req;
};
}
|
[
"function",
"(",
")",
"{",
"/**\n * Return the current timestamp integer.\n */",
"var",
"now",
"=",
"Date",
".",
"now",
"||",
"function",
"(",
")",
"{",
"return",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"}",
";",
"// Keep track of the previous \"animation frame\" manually.",
"var",
"prev",
"=",
"now",
"(",
")",
";",
"return",
"function",
"(",
"fn",
")",
"{",
"var",
"curr",
"=",
"now",
"(",
")",
";",
"var",
"ms",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"16",
"-",
"(",
"curr",
"-",
"prev",
")",
")",
";",
"var",
"req",
"=",
"setTimeout",
"(",
"fn",
",",
"ms",
")",
";",
"prev",
"=",
"curr",
";",
"return",
"req",
";",
"}",
";",
"}"
] |
Fallback animation frame implementation.
@return {Function}
|
[
"Fallback",
"animation",
"frame",
"implementation",
"."
] |
2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed
|
https://github.com/blakeembrey/dombars/blob/2b8fc7b462bbab3aee9addbc24c2dbd59a5613ed/lib/raf.js#L10-L30
|
|
37,781 |
enquirer/prompt-question
|
index.js
|
Question
|
function Question(name, message, options) {
debug('initializing from <%s>', __filename);
if (arguments.length === 0) {
throw new TypeError('expected a string or object');
}
if (Question.isQuestion(name)) {
return name;
}
this.type = 'input';
this.options = {};
this.getDefault();
if (Array.isArray(message)) {
options = { choices: message };
message = name;
}
if (Array.isArray(options)) {
options = { choices: options };
}
define(this, 'Choices', Choices);
define(this, 'isQuestion', true);
utils.assign(this, {
name: name,
message: message,
options: options
});
}
|
javascript
|
function Question(name, message, options) {
debug('initializing from <%s>', __filename);
if (arguments.length === 0) {
throw new TypeError('expected a string or object');
}
if (Question.isQuestion(name)) {
return name;
}
this.type = 'input';
this.options = {};
this.getDefault();
if (Array.isArray(message)) {
options = { choices: message };
message = name;
}
if (Array.isArray(options)) {
options = { choices: options };
}
define(this, 'Choices', Choices);
define(this, 'isQuestion', true);
utils.assign(this, {
name: name,
message: message,
options: options
});
}
|
[
"function",
"Question",
"(",
"name",
",",
"message",
",",
"options",
")",
"{",
"debug",
"(",
"'initializing from <%s>'",
",",
"__filename",
")",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected a string or object'",
")",
";",
"}",
"if",
"(",
"Question",
".",
"isQuestion",
"(",
"name",
")",
")",
"{",
"return",
"name",
";",
"}",
"this",
".",
"type",
"=",
"'input'",
";",
"this",
".",
"options",
"=",
"{",
"}",
";",
"this",
".",
"getDefault",
"(",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"message",
")",
")",
"{",
"options",
"=",
"{",
"choices",
":",
"message",
"}",
";",
"message",
"=",
"name",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
")",
")",
"{",
"options",
"=",
"{",
"choices",
":",
"options",
"}",
";",
"}",
"define",
"(",
"this",
",",
"'Choices'",
",",
"Choices",
")",
";",
"define",
"(",
"this",
",",
"'isQuestion'",
",",
"true",
")",
";",
"utils",
".",
"assign",
"(",
"this",
",",
"{",
"name",
":",
"name",
",",
"message",
":",
"message",
",",
"options",
":",
"options",
"}",
")",
";",
"}"
] |
Create a new question with the given `name`, `message` and `options`.
```js
var question = new Question('first', 'What is your first name?');
console.log(question);
// {
// type: 'input',
// name: 'color',
// message: 'What is your favorite color?'
// }
```
@param {String|Object} `name` Question name or options.
@param {String|Object} `message` Question message or options.
@param {String|Object} `options` Question options.
@api public
|
[
"Create",
"a",
"new",
"question",
"with",
"the",
"given",
"name",
"message",
"and",
"options",
"."
] |
8261c899a3ff0a4f76f7e39851538c6374991ddb
|
https://github.com/enquirer/prompt-question/blob/8261c899a3ff0a4f76f7e39851538c6374991ddb/index.js#L29-L59
|
37,782 |
zynga/gravity
|
gravity.js
|
addLineHints
|
function addLineHints(name, content) {
var
i = -1,
lines = content.split('\n'),
len = lines.length,
out = []
;
while (++i < len) {
out.push(lines[i] +
((i % 10 === 9) ? ' //' + name + ':' + (i + 1) + '//' : ''));
}
return out.join('\n');
}
|
javascript
|
function addLineHints(name, content) {
var
i = -1,
lines = content.split('\n'),
len = lines.length,
out = []
;
while (++i < len) {
out.push(lines[i] +
((i % 10 === 9) ? ' //' + name + ':' + (i + 1) + '//' : ''));
}
return out.join('\n');
}
|
[
"function",
"addLineHints",
"(",
"name",
",",
"content",
")",
"{",
"var",
"i",
"=",
"-",
"1",
",",
"lines",
"=",
"content",
".",
"split",
"(",
"'\\n'",
")",
",",
"len",
"=",
"lines",
".",
"length",
",",
"out",
"=",
"[",
"]",
";",
"while",
"(",
"++",
"i",
"<",
"len",
")",
"{",
"out",
".",
"push",
"(",
"lines",
"[",
"i",
"]",
"+",
"(",
"(",
"i",
"%",
"10",
"===",
"9",
")",
"?",
"' //'",
"+",
"name",
"+",
"':'",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"'//'",
":",
"''",
")",
")",
";",
"}",
"return",
"out",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] |
Add JavaScript line-hint comments to every 10th line of a file.
|
[
"Add",
"JavaScript",
"line",
"-",
"hint",
"comments",
"to",
"every",
"10th",
"line",
"of",
"a",
"file",
"."
] |
79916523c2c0733be80c21354e5a2aa0ea4cf2c7
|
https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L65-L77
|
37,783 |
zynga/gravity
|
gravity.js
|
joinBuffers
|
function joinBuffers(buffers) {
var
i = -1, j = -1,
num = buffers.length,
totalBytes = 0,
bytesWritten = 0,
buff,
superBuff
;
while (++i < num) {
totalBytes += buffers[i].length;
}
superBuff = new Buffer(totalBytes);
while (++j < num) {
buff = buffers[j];
buff.copy(superBuff, bytesWritten, 0);
bytesWritten += buff.length;
}
return superBuff;
}
|
javascript
|
function joinBuffers(buffers) {
var
i = -1, j = -1,
num = buffers.length,
totalBytes = 0,
bytesWritten = 0,
buff,
superBuff
;
while (++i < num) {
totalBytes += buffers[i].length;
}
superBuff = new Buffer(totalBytes);
while (++j < num) {
buff = buffers[j];
buff.copy(superBuff, bytesWritten, 0);
bytesWritten += buff.length;
}
return superBuff;
}
|
[
"function",
"joinBuffers",
"(",
"buffers",
")",
"{",
"var",
"i",
"=",
"-",
"1",
",",
"j",
"=",
"-",
"1",
",",
"num",
"=",
"buffers",
".",
"length",
",",
"totalBytes",
"=",
"0",
",",
"bytesWritten",
"=",
"0",
",",
"buff",
",",
"superBuff",
";",
"while",
"(",
"++",
"i",
"<",
"num",
")",
"{",
"totalBytes",
"+=",
"buffers",
"[",
"i",
"]",
".",
"length",
";",
"}",
"superBuff",
"=",
"new",
"Buffer",
"(",
"totalBytes",
")",
";",
"while",
"(",
"++",
"j",
"<",
"num",
")",
"{",
"buff",
"=",
"buffers",
"[",
"j",
"]",
";",
"buff",
".",
"copy",
"(",
"superBuff",
",",
"bytesWritten",
",",
"0",
")",
";",
"bytesWritten",
"+=",
"buff",
".",
"length",
";",
"}",
"return",
"superBuff",
";",
"}"
] |
Concatentate an array of Buffers into a single one.
|
[
"Concatentate",
"an",
"array",
"of",
"Buffers",
"into",
"a",
"single",
"one",
"."
] |
79916523c2c0733be80c21354e5a2aa0ea4cf2c7
|
https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L81-L100
|
37,784 |
zynga/gravity
|
gravity.js
|
wget
|
function wget(fileURL, callback) {
var
chunks = [],
isHTTPS = fileURL.indexOf('https') === 0,
client = isHTTPS ? https : http,
options = fileURL
;
if (isHTTPS) {
options = url.parse(fileURL);
options.rejectUnauthorized = false;
options.agent = new https.Agent(options);
}
client.get(options, function (res) {
res.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function () {
callback(null, joinBuffers(chunks));
});
});
}
|
javascript
|
function wget(fileURL, callback) {
var
chunks = [],
isHTTPS = fileURL.indexOf('https') === 0,
client = isHTTPS ? https : http,
options = fileURL
;
if (isHTTPS) {
options = url.parse(fileURL);
options.rejectUnauthorized = false;
options.agent = new https.Agent(options);
}
client.get(options, function (res) {
res.on('data', function (chunk) {
chunks.push(chunk);
}).on('end', function () {
callback(null, joinBuffers(chunks));
});
});
}
|
[
"function",
"wget",
"(",
"fileURL",
",",
"callback",
")",
"{",
"var",
"chunks",
"=",
"[",
"]",
",",
"isHTTPS",
"=",
"fileURL",
".",
"indexOf",
"(",
"'https'",
")",
"===",
"0",
",",
"client",
"=",
"isHTTPS",
"?",
"https",
":",
"http",
",",
"options",
"=",
"fileURL",
";",
"if",
"(",
"isHTTPS",
")",
"{",
"options",
"=",
"url",
".",
"parse",
"(",
"fileURL",
")",
";",
"options",
".",
"rejectUnauthorized",
"=",
"false",
";",
"options",
".",
"agent",
"=",
"new",
"https",
".",
"Agent",
"(",
"options",
")",
";",
"}",
"client",
".",
"get",
"(",
"options",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"chunks",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"callback",
"(",
"null",
",",
"joinBuffers",
"(",
"chunks",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Given a web URL, fetch the file contents.
|
[
"Given",
"a",
"web",
"URL",
"fetch",
"the",
"file",
"contents",
"."
] |
79916523c2c0733be80c21354e5a2aa0ea4cf2c7
|
https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L104-L123
|
37,785 |
zynga/gravity
|
gravity.js
|
reduce
|
function reduce(map, path) {
var mapNode, prefix, split, splits = getResourcePathSplits(path),
subValue, suffix;
while (splits.length) {
split = splits.shift();
suffix = split[1];
prefix = suffix ? split[0] + '/' : split[0];
mapNode = map[prefix];
if (mapNode) {
if (!suffix || typeof mapNode === 'string') {
return { map: mapNode, prefix: prefix, suffix: suffix };
}
if (typeof mapNode === 'object') {
subValue = reduce(mapNode, suffix);
if (subValue) {
subValue.prefix = prefix + '/' + subValue.prefix;
return subValue;
}
}
}
}
return { map: map, prefix: '', suffix: path };
}
|
javascript
|
function reduce(map, path) {
var mapNode, prefix, split, splits = getResourcePathSplits(path),
subValue, suffix;
while (splits.length) {
split = splits.shift();
suffix = split[1];
prefix = suffix ? split[0] + '/' : split[0];
mapNode = map[prefix];
if (mapNode) {
if (!suffix || typeof mapNode === 'string') {
return { map: mapNode, prefix: prefix, suffix: suffix };
}
if (typeof mapNode === 'object') {
subValue = reduce(mapNode, suffix);
if (subValue) {
subValue.prefix = prefix + '/' + subValue.prefix;
return subValue;
}
}
}
}
return { map: map, prefix: '', suffix: path };
}
|
[
"function",
"reduce",
"(",
"map",
",",
"path",
")",
"{",
"var",
"mapNode",
",",
"prefix",
",",
"split",
",",
"splits",
"=",
"getResourcePathSplits",
"(",
"path",
")",
",",
"subValue",
",",
"suffix",
";",
"while",
"(",
"splits",
".",
"length",
")",
"{",
"split",
"=",
"splits",
".",
"shift",
"(",
")",
";",
"suffix",
"=",
"split",
"[",
"1",
"]",
";",
"prefix",
"=",
"suffix",
"?",
"split",
"[",
"0",
"]",
"+",
"'/'",
":",
"split",
"[",
"0",
"]",
";",
"mapNode",
"=",
"map",
"[",
"prefix",
"]",
";",
"if",
"(",
"mapNode",
")",
"{",
"if",
"(",
"!",
"suffix",
"||",
"typeof",
"mapNode",
"===",
"'string'",
")",
"{",
"return",
"{",
"map",
":",
"mapNode",
",",
"prefix",
":",
"prefix",
",",
"suffix",
":",
"suffix",
"}",
";",
"}",
"if",
"(",
"typeof",
"mapNode",
"===",
"'object'",
")",
"{",
"subValue",
"=",
"reduce",
"(",
"mapNode",
",",
"suffix",
")",
";",
"if",
"(",
"subValue",
")",
"{",
"subValue",
".",
"prefix",
"=",
"prefix",
"+",
"'/'",
"+",
"subValue",
".",
"prefix",
";",
"return",
"subValue",
";",
"}",
"}",
"}",
"}",
"return",
"{",
"map",
":",
"map",
",",
"prefix",
":",
"''",
",",
"suffix",
":",
"path",
"}",
";",
"}"
] |
Given a map and a resource path, drill down in the map to find the most specific map node that matches the path. Return the map node, the matched path prefix, and the unmatched path suffix.
|
[
"Given",
"a",
"map",
"and",
"a",
"resource",
"path",
"drill",
"down",
"in",
"the",
"map",
"to",
"find",
"the",
"most",
"specific",
"map",
"node",
"that",
"matches",
"the",
"path",
".",
"Return",
"the",
"map",
"node",
"the",
"matched",
"path",
"prefix",
"and",
"the",
"unmatched",
"path",
"suffix",
"."
] |
79916523c2c0733be80c21354e5a2aa0ea4cf2c7
|
https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L154-L176
|
37,786 |
zynga/gravity
|
gravity.js
|
getResource
|
function getResource(map, base, internal, path, callback, addLineHints) {
var
reduced = reduce(map, path),
reducedMap = reduced.map,
reducedMapType = nodeType(reducedMap),
reducedPrefix = reduced.prefix,
reducedSuffix = reduced.suffix,
firstChar = path.charAt(0),
temporary = firstChar === '~',
literal = firstChar === '='
;
if (isURL(path)) {
wget(path, callback);
} else if (literal) {
callback(null, new Buffer(path.substr(1) + '\n'));
} else if (temporary && !internal) {
// External request for a temporary resource.
callback({ code: 403, message: 'Forbidden' });
} else if (reducedSuffix) {
// We did NOT find an exact match in the map.
if (!reducedPrefix && internal) {
getFile(base, path, callback, addLineHints);
} else if (reducedMapType === 'string') {
getFile(base, reducedMap + '/' + reducedSuffix, callback, addLineHints);
} else {
callback({ code: 404, message: 'Not Found' });
}
} else {
// We found an exact match in the map.
if (reducedMap === reducedPrefix) {
// This is just a local file/dir to expose.
getFile(base, reducedPrefix, callback, addLineHints);
} else if (reducedMapType === 'string') {
// A string value may be a web URL.
if (isURL(reducedMap)) {
wget(reducedMap, callback);
} else {
// Otherwise, it's another resource path.
getResource(map, base, true, reducedMap, callback, addLineHints);
}
} else if (reducedMapType === 'array') {
// An array is a list of resources to get packed together.
packResources(map, base, reducedMap, callback);
//} else if (reducedMapType === 'object') {
// An object is a directory. We could return a listing...
// TODO: Do we really want to support listings?
} else {
callback({ code: 500, message: 'Unable to read gravity.map.' });
}
}
}
|
javascript
|
function getResource(map, base, internal, path, callback, addLineHints) {
var
reduced = reduce(map, path),
reducedMap = reduced.map,
reducedMapType = nodeType(reducedMap),
reducedPrefix = reduced.prefix,
reducedSuffix = reduced.suffix,
firstChar = path.charAt(0),
temporary = firstChar === '~',
literal = firstChar === '='
;
if (isURL(path)) {
wget(path, callback);
} else if (literal) {
callback(null, new Buffer(path.substr(1) + '\n'));
} else if (temporary && !internal) {
// External request for a temporary resource.
callback({ code: 403, message: 'Forbidden' });
} else if (reducedSuffix) {
// We did NOT find an exact match in the map.
if (!reducedPrefix && internal) {
getFile(base, path, callback, addLineHints);
} else if (reducedMapType === 'string') {
getFile(base, reducedMap + '/' + reducedSuffix, callback, addLineHints);
} else {
callback({ code: 404, message: 'Not Found' });
}
} else {
// We found an exact match in the map.
if (reducedMap === reducedPrefix) {
// This is just a local file/dir to expose.
getFile(base, reducedPrefix, callback, addLineHints);
} else if (reducedMapType === 'string') {
// A string value may be a web URL.
if (isURL(reducedMap)) {
wget(reducedMap, callback);
} else {
// Otherwise, it's another resource path.
getResource(map, base, true, reducedMap, callback, addLineHints);
}
} else if (reducedMapType === 'array') {
// An array is a list of resources to get packed together.
packResources(map, base, reducedMap, callback);
//} else if (reducedMapType === 'object') {
// An object is a directory. We could return a listing...
// TODO: Do we really want to support listings?
} else {
callback({ code: 500, message: 'Unable to read gravity.map.' });
}
}
}
|
[
"function",
"getResource",
"(",
"map",
",",
"base",
",",
"internal",
",",
"path",
",",
"callback",
",",
"addLineHints",
")",
"{",
"var",
"reduced",
"=",
"reduce",
"(",
"map",
",",
"path",
")",
",",
"reducedMap",
"=",
"reduced",
".",
"map",
",",
"reducedMapType",
"=",
"nodeType",
"(",
"reducedMap",
")",
",",
"reducedPrefix",
"=",
"reduced",
".",
"prefix",
",",
"reducedSuffix",
"=",
"reduced",
".",
"suffix",
",",
"firstChar",
"=",
"path",
".",
"charAt",
"(",
"0",
")",
",",
"temporary",
"=",
"firstChar",
"===",
"'~'",
",",
"literal",
"=",
"firstChar",
"===",
"'='",
";",
"if",
"(",
"isURL",
"(",
"path",
")",
")",
"{",
"wget",
"(",
"path",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"literal",
")",
"{",
"callback",
"(",
"null",
",",
"new",
"Buffer",
"(",
"path",
".",
"substr",
"(",
"1",
")",
"+",
"'\\n'",
")",
")",
";",
"}",
"else",
"if",
"(",
"temporary",
"&&",
"!",
"internal",
")",
"{",
"// External request for a temporary resource.",
"callback",
"(",
"{",
"code",
":",
"403",
",",
"message",
":",
"'Forbidden'",
"}",
")",
";",
"}",
"else",
"if",
"(",
"reducedSuffix",
")",
"{",
"// We did NOT find an exact match in the map.",
"if",
"(",
"!",
"reducedPrefix",
"&&",
"internal",
")",
"{",
"getFile",
"(",
"base",
",",
"path",
",",
"callback",
",",
"addLineHints",
")",
";",
"}",
"else",
"if",
"(",
"reducedMapType",
"===",
"'string'",
")",
"{",
"getFile",
"(",
"base",
",",
"reducedMap",
"+",
"'/'",
"+",
"reducedSuffix",
",",
"callback",
",",
"addLineHints",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"{",
"code",
":",
"404",
",",
"message",
":",
"'Not Found'",
"}",
")",
";",
"}",
"}",
"else",
"{",
"// We found an exact match in the map.",
"if",
"(",
"reducedMap",
"===",
"reducedPrefix",
")",
"{",
"// This is just a local file/dir to expose.",
"getFile",
"(",
"base",
",",
"reducedPrefix",
",",
"callback",
",",
"addLineHints",
")",
";",
"}",
"else",
"if",
"(",
"reducedMapType",
"===",
"'string'",
")",
"{",
"// A string value may be a web URL.",
"if",
"(",
"isURL",
"(",
"reducedMap",
")",
")",
"{",
"wget",
"(",
"reducedMap",
",",
"callback",
")",
";",
"}",
"else",
"{",
"// Otherwise, it's another resource path.",
"getResource",
"(",
"map",
",",
"base",
",",
"true",
",",
"reducedMap",
",",
"callback",
",",
"addLineHints",
")",
";",
"}",
"}",
"else",
"if",
"(",
"reducedMapType",
"===",
"'array'",
")",
"{",
"// An array is a list of resources to get packed together.",
"packResources",
"(",
"map",
",",
"base",
",",
"reducedMap",
",",
"callback",
")",
";",
"//} else if (reducedMapType === 'object') {",
"// An object is a directory. We could return a listing...",
"// TODO: Do we really want to support listings?",
"}",
"else",
"{",
"callback",
"(",
"{",
"code",
":",
"500",
",",
"message",
":",
"'Unable to read gravity.map.'",
"}",
")",
";",
"}",
"}",
"}"
] |
Given a resource path, retrieve the associated content. Internal requests are always allowed, whereas external requests will only have access to resources explicitly exposed by the gravity map.
|
[
"Given",
"a",
"resource",
"path",
"retrieve",
"the",
"associated",
"content",
".",
"Internal",
"requests",
"are",
"always",
"allowed",
"whereas",
"external",
"requests",
"will",
"only",
"have",
"access",
"to",
"resources",
"explicitly",
"exposed",
"by",
"the",
"gravity",
"map",
"."
] |
79916523c2c0733be80c21354e5a2aa0ea4cf2c7
|
https://github.com/zynga/gravity/blob/79916523c2c0733be80c21354e5a2aa0ea4cf2c7/gravity.js#L210-L271
|
37,787 |
arschmitz/ember-cli-standard
|
blueprints/ember-cli-standard/index.js
|
synchronize
|
function synchronize (items, cb) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return cb.call(this, item)
})
}, RSVP.resolve())
}
|
javascript
|
function synchronize (items, cb) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return cb.call(this, item)
})
}, RSVP.resolve())
}
|
[
"function",
"synchronize",
"(",
"items",
",",
"cb",
")",
"{",
"return",
"items",
".",
"reduce",
"(",
"function",
"(",
"promise",
",",
"item",
")",
"{",
"return",
"promise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"cb",
".",
"call",
"(",
"this",
",",
"item",
")",
"}",
")",
"}",
",",
"RSVP",
".",
"resolve",
"(",
")",
")",
"}"
] |
For each item in the array, call the callback, passing the item as the argument.
However, only call the next callback after the promise returned by the previous
one has resolved.
@param {*[]} items the elements to iterate over
@param {Function} cb called for each item, with the item as the parameter. Should return a promise
@return {Promise}
|
[
"For",
"each",
"item",
"in",
"the",
"array",
"call",
"the",
"callback",
"passing",
"the",
"item",
"as",
"the",
"argument",
".",
"However",
"only",
"call",
"the",
"next",
"callback",
"after",
"the",
"promise",
"returned",
"by",
"the",
"previous",
"one",
"has",
"resolved",
"."
] |
2395264c329fffd97f2581b8cb739185bfc615b3
|
https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L17-L23
|
37,788 |
arschmitz/ember-cli-standard
|
blueprints/ember-cli-standard/index.js
|
function () {
var promptRemove = this._promptRemove.bind(this)
var removeFile = this._removeFile.bind(this)
var ui = this.ui
return this._findConfigFiles()
.then(function (files) {
if (files.length === 0) {
ui.writeLine('No JSHint or ESLint config files found.')
return RSVP.resolve({
result: {
deleteFiles: 'none'
}
})
}
ui.writeLine('\nI found the following JSHint and ESLint config files:')
files.forEach(function (file) {
ui.writeLine(' ' + file)
})
var promptPromise = ui.prompt({
type: 'list',
name: 'deleteFiles',
message: 'What would you like to do?',
choices: [
{ name: 'Remove them all', value: 'all' },
{ name: 'Remove individually', value: 'each' },
{ name: 'Nothing', value: 'none' }
]
})
return RSVP.hash({
result: promptPromise,
files: files
})
}).then(function (data) {
var value = data.result.deleteFiles
var files = data.files
// Noop if we're not deleting any files
if (value === 'none') {
return RSVP.resolve()
}
if (value === 'all') {
return RSVP.all(files.map(function (fileName) {
return removeFile(fileName)
}))
}
if (value === 'each') {
return synchronize(files, function (fileName) {
return promptRemove(fileName)
})
}
})
}
|
javascript
|
function () {
var promptRemove = this._promptRemove.bind(this)
var removeFile = this._removeFile.bind(this)
var ui = this.ui
return this._findConfigFiles()
.then(function (files) {
if (files.length === 0) {
ui.writeLine('No JSHint or ESLint config files found.')
return RSVP.resolve({
result: {
deleteFiles: 'none'
}
})
}
ui.writeLine('\nI found the following JSHint and ESLint config files:')
files.forEach(function (file) {
ui.writeLine(' ' + file)
})
var promptPromise = ui.prompt({
type: 'list',
name: 'deleteFiles',
message: 'What would you like to do?',
choices: [
{ name: 'Remove them all', value: 'all' },
{ name: 'Remove individually', value: 'each' },
{ name: 'Nothing', value: 'none' }
]
})
return RSVP.hash({
result: promptPromise,
files: files
})
}).then(function (data) {
var value = data.result.deleteFiles
var files = data.files
// Noop if we're not deleting any files
if (value === 'none') {
return RSVP.resolve()
}
if (value === 'all') {
return RSVP.all(files.map(function (fileName) {
return removeFile(fileName)
}))
}
if (value === 'each') {
return synchronize(files, function (fileName) {
return promptRemove(fileName)
})
}
})
}
|
[
"function",
"(",
")",
"{",
"var",
"promptRemove",
"=",
"this",
".",
"_promptRemove",
".",
"bind",
"(",
"this",
")",
"var",
"removeFile",
"=",
"this",
".",
"_removeFile",
".",
"bind",
"(",
"this",
")",
"var",
"ui",
"=",
"this",
".",
"ui",
"return",
"this",
".",
"_findConfigFiles",
"(",
")",
".",
"then",
"(",
"function",
"(",
"files",
")",
"{",
"if",
"(",
"files",
".",
"length",
"===",
"0",
")",
"{",
"ui",
".",
"writeLine",
"(",
"'No JSHint or ESLint config files found.'",
")",
"return",
"RSVP",
".",
"resolve",
"(",
"{",
"result",
":",
"{",
"deleteFiles",
":",
"'none'",
"}",
"}",
")",
"}",
"ui",
".",
"writeLine",
"(",
"'\\nI found the following JSHint and ESLint config files:'",
")",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"ui",
".",
"writeLine",
"(",
"' '",
"+",
"file",
")",
"}",
")",
"var",
"promptPromise",
"=",
"ui",
".",
"prompt",
"(",
"{",
"type",
":",
"'list'",
",",
"name",
":",
"'deleteFiles'",
",",
"message",
":",
"'What would you like to do?'",
",",
"choices",
":",
"[",
"{",
"name",
":",
"'Remove them all'",
",",
"value",
":",
"'all'",
"}",
",",
"{",
"name",
":",
"'Remove individually'",
",",
"value",
":",
"'each'",
"}",
",",
"{",
"name",
":",
"'Nothing'",
",",
"value",
":",
"'none'",
"}",
"]",
"}",
")",
"return",
"RSVP",
".",
"hash",
"(",
"{",
"result",
":",
"promptPromise",
",",
"files",
":",
"files",
"}",
")",
"}",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"var",
"value",
"=",
"data",
".",
"result",
".",
"deleteFiles",
"var",
"files",
"=",
"data",
".",
"files",
"// Noop if we're not deleting any files",
"if",
"(",
"value",
"===",
"'none'",
")",
"{",
"return",
"RSVP",
".",
"resolve",
"(",
")",
"}",
"if",
"(",
"value",
"===",
"'all'",
")",
"{",
"return",
"RSVP",
".",
"all",
"(",
"files",
".",
"map",
"(",
"function",
"(",
"fileName",
")",
"{",
"return",
"removeFile",
"(",
"fileName",
")",
"}",
")",
")",
"}",
"if",
"(",
"value",
"===",
"'each'",
")",
"{",
"return",
"synchronize",
"(",
"files",
",",
"function",
"(",
"fileName",
")",
"{",
"return",
"promptRemove",
"(",
"fileName",
")",
"}",
")",
"}",
"}",
")",
"}"
] |
Find JSHint and ESLint configuration files and offer to remove them
@return {RSVP.Promise}
|
[
"Find",
"JSHint",
"and",
"ESLint",
"configuration",
"files",
"and",
"offer",
"to",
"remove",
"them"
] |
2395264c329fffd97f2581b8cb739185bfc615b3
|
https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L54-L111
|
|
37,789 |
arschmitz/ember-cli-standard
|
blueprints/ember-cli-standard/index.js
|
function () {
var projectRoot = this.project.root
var ui = this.ui
ui.startProgress('Searching for JSHint and ESLint config files')
return new RSVP.Promise(function (resolve) {
var files = walkSync(projectRoot, {
globs: ['**/.jshintrc', '**/.eslintrc.js'],
ignore: [
'**/bower_components',
'**/dist',
'**/node_modules',
'**/tmp'
]
})
ui.stopProgress()
resolve(files)
})
}
|
javascript
|
function () {
var projectRoot = this.project.root
var ui = this.ui
ui.startProgress('Searching for JSHint and ESLint config files')
return new RSVP.Promise(function (resolve) {
var files = walkSync(projectRoot, {
globs: ['**/.jshintrc', '**/.eslintrc.js'],
ignore: [
'**/bower_components',
'**/dist',
'**/node_modules',
'**/tmp'
]
})
ui.stopProgress()
resolve(files)
})
}
|
[
"function",
"(",
")",
"{",
"var",
"projectRoot",
"=",
"this",
".",
"project",
".",
"root",
"var",
"ui",
"=",
"this",
".",
"ui",
"ui",
".",
"startProgress",
"(",
"'Searching for JSHint and ESLint config files'",
")",
"return",
"new",
"RSVP",
".",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"var",
"files",
"=",
"walkSync",
"(",
"projectRoot",
",",
"{",
"globs",
":",
"[",
"'**/.jshintrc'",
",",
"'**/.eslintrc.js'",
"]",
",",
"ignore",
":",
"[",
"'**/bower_components'",
",",
"'**/dist'",
",",
"'**/node_modules'",
",",
"'**/tmp'",
"]",
"}",
")",
"ui",
".",
"stopProgress",
"(",
")",
"resolve",
"(",
"files",
")",
"}",
")",
"}"
] |
Find JSHint and ESLint configuration files
@return {Promise->string[]} found file names
|
[
"Find",
"JSHint",
"and",
"ESLint",
"configuration",
"files"
] |
2395264c329fffd97f2581b8cb739185bfc615b3
|
https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L144-L163
|
|
37,790 |
arschmitz/ember-cli-standard
|
blueprints/ember-cli-standard/index.js
|
function (filePath) {
var removeFile = this._removeFile.bind(this)
var message = 'Should I remove `' + filePath + '`?'
var promptPromise = this.ui.prompt({
type: 'confirm',
name: 'answer',
message: message,
choices: [
{ key: 'y', name: 'Yes, remove it', value: 'yes' },
{ key: 'n', name: 'No, leave it there', value: 'no' }
]
})
return promptPromise.then(function (response) {
if (response.answer) {
return removeFile(filePath)
} else {
return RSVP.resolve()
}
})
}
|
javascript
|
function (filePath) {
var removeFile = this._removeFile.bind(this)
var message = 'Should I remove `' + filePath + '`?'
var promptPromise = this.ui.prompt({
type: 'confirm',
name: 'answer',
message: message,
choices: [
{ key: 'y', name: 'Yes, remove it', value: 'yes' },
{ key: 'n', name: 'No, leave it there', value: 'no' }
]
})
return promptPromise.then(function (response) {
if (response.answer) {
return removeFile(filePath)
} else {
return RSVP.resolve()
}
})
}
|
[
"function",
"(",
"filePath",
")",
"{",
"var",
"removeFile",
"=",
"this",
".",
"_removeFile",
".",
"bind",
"(",
"this",
")",
"var",
"message",
"=",
"'Should I remove `'",
"+",
"filePath",
"+",
"'`?'",
"var",
"promptPromise",
"=",
"this",
".",
"ui",
".",
"prompt",
"(",
"{",
"type",
":",
"'confirm'",
",",
"name",
":",
"'answer'",
",",
"message",
":",
"message",
",",
"choices",
":",
"[",
"{",
"key",
":",
"'y'",
",",
"name",
":",
"'Yes, remove it'",
",",
"value",
":",
"'yes'",
"}",
",",
"{",
"key",
":",
"'n'",
",",
"name",
":",
"'No, leave it there'",
",",
"value",
":",
"'no'",
"}",
"]",
"}",
")",
"return",
"promptPromise",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"answer",
")",
"{",
"return",
"removeFile",
"(",
"filePath",
")",
"}",
"else",
"{",
"return",
"RSVP",
".",
"resolve",
"(",
")",
"}",
"}",
")",
"}"
] |
Prompt the user about whether or not they want to remove the given file
@param {string} filePath the path to the file
@return {RSVP.Promise}
|
[
"Prompt",
"the",
"user",
"about",
"whether",
"or",
"not",
"they",
"want",
"to",
"remove",
"the",
"given",
"file"
] |
2395264c329fffd97f2581b8cb739185bfc615b3
|
https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L171-L192
|
|
37,791 |
arschmitz/ember-cli-standard
|
blueprints/ember-cli-standard/index.js
|
function (filePath) {
var projectRoot = this.project.root
var fullPath = resolve(projectRoot, filePath)
return RSVP.denodeify(unlink)(fullPath)
}
|
javascript
|
function (filePath) {
var projectRoot = this.project.root
var fullPath = resolve(projectRoot, filePath)
return RSVP.denodeify(unlink)(fullPath)
}
|
[
"function",
"(",
"filePath",
")",
"{",
"var",
"projectRoot",
"=",
"this",
".",
"project",
".",
"root",
"var",
"fullPath",
"=",
"resolve",
"(",
"projectRoot",
",",
"filePath",
")",
"return",
"RSVP",
".",
"denodeify",
"(",
"unlink",
")",
"(",
"fullPath",
")",
"}"
] |
Remove the specified file
@param {string} filePath the relative path (from the project root) to remove
@return {RSVP.Promise}
|
[
"Remove",
"the",
"specified",
"file"
] |
2395264c329fffd97f2581b8cb739185bfc615b3
|
https://github.com/arschmitz/ember-cli-standard/blob/2395264c329fffd97f2581b8cb739185bfc615b3/blueprints/ember-cli-standard/index.js#L200-L205
|
|
37,792 |
LaunchPadLab/lp-redux-api
|
src/middleware/parse-options.js
|
parseOptions
|
function parseOptions ({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
...requestOptions
}) {
return {
configOptions: omitUndefined({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
}),
requestOptions,
}
}
|
javascript
|
function parseOptions ({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
...requestOptions
}) {
return {
configOptions: omitUndefined({
type,
onUnauthorized,
actions,
types,
requestAction,
successAction,
failureAction,
isStub,
stubData,
adapter,
}),
requestOptions,
}
}
|
[
"function",
"parseOptions",
"(",
"{",
"type",
",",
"onUnauthorized",
",",
"actions",
",",
"types",
",",
"requestAction",
",",
"successAction",
",",
"failureAction",
",",
"isStub",
",",
"stubData",
",",
"adapter",
",",
"...",
"requestOptions",
"}",
")",
"{",
"return",
"{",
"configOptions",
":",
"omitUndefined",
"(",
"{",
"type",
",",
"onUnauthorized",
",",
"actions",
",",
"types",
",",
"requestAction",
",",
"successAction",
",",
"failureAction",
",",
"isStub",
",",
"stubData",
",",
"adapter",
",",
"}",
")",
",",
"requestOptions",
",",
"}",
"}"
] |
Separate middleware options into config options and request options
|
[
"Separate",
"middleware",
"options",
"into",
"config",
"options",
"and",
"request",
"options"
] |
73eee231067365326780ddc1dbbfa50d3e65defc
|
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/middleware/parse-options.js#L5-L33
|
37,793 |
fergaldoyle/gulp-require-angular
|
index.js
|
dive
|
function dive(name) {
// check if this module has already been
// processed in case of circular dependency
if (dive[name]) {
return;
}
dive[name] = true;
dive.required.push(name);
var deps = allModules[name] || [];
deps.forEach(function (item) {
dive(item);
});
}
|
javascript
|
function dive(name) {
// check if this module has already been
// processed in case of circular dependency
if (dive[name]) {
return;
}
dive[name] = true;
dive.required.push(name);
var deps = allModules[name] || [];
deps.forEach(function (item) {
dive(item);
});
}
|
[
"function",
"dive",
"(",
"name",
")",
"{",
"// check if this module has already been ",
"// processed in case of circular dependency",
"if",
"(",
"dive",
"[",
"name",
"]",
")",
"{",
"return",
";",
"}",
"dive",
"[",
"name",
"]",
"=",
"true",
";",
"dive",
".",
"required",
".",
"push",
"(",
"name",
")",
";",
"var",
"deps",
"=",
"allModules",
"[",
"name",
"]",
"||",
"[",
"]",
";",
"deps",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"dive",
"(",
"item",
")",
";",
"}",
")",
";",
"}"
] |
recursive function, dive into the dependencies
|
[
"recursive",
"function",
"dive",
"into",
"the",
"dependencies"
] |
9b6250dada310590b4575e030a1e03293454b98f
|
https://github.com/fergaldoyle/gulp-require-angular/blob/9b6250dada310590b4575e030a1e03293454b98f/index.js#L25-L38
|
37,794 |
mikl/node-drupal
|
lib/db.js
|
getClient
|
function getClient(callback) {
if (!connectionOptions) {
callback('Connection options missing. Please call db.connect before any other database functions to configure the database configuration');
}
if (activeBackend === 'mysql') {
if (activeDb) {
return callback(null, activeDb);
}
else {
connect(connectionOptions);
return callback(null, activeDb);
}
}
else if (activeBackend === 'pgsql') {
return pg.connect(connectionOptions, callback);
}
}
|
javascript
|
function getClient(callback) {
if (!connectionOptions) {
callback('Connection options missing. Please call db.connect before any other database functions to configure the database configuration');
}
if (activeBackend === 'mysql') {
if (activeDb) {
return callback(null, activeDb);
}
else {
connect(connectionOptions);
return callback(null, activeDb);
}
}
else if (activeBackend === 'pgsql') {
return pg.connect(connectionOptions, callback);
}
}
|
[
"function",
"getClient",
"(",
"callback",
")",
"{",
"if",
"(",
"!",
"connectionOptions",
")",
"{",
"callback",
"(",
"'Connection options missing. Please call db.connect before any other database functions to configure the database configuration'",
")",
";",
"}",
"if",
"(",
"activeBackend",
"===",
"'mysql'",
")",
"{",
"if",
"(",
"activeDb",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"activeDb",
")",
";",
"}",
"else",
"{",
"connect",
"(",
"connectionOptions",
")",
";",
"return",
"callback",
"(",
"null",
",",
"activeDb",
")",
";",
"}",
"}",
"else",
"if",
"(",
"activeBackend",
"===",
"'pgsql'",
")",
"{",
"return",
"pg",
".",
"connect",
"(",
"connectionOptions",
",",
"callback",
")",
";",
"}",
"}"
] |
Get the client object for the current database connection.
|
[
"Get",
"the",
"client",
"object",
"for",
"the",
"current",
"database",
"connection",
"."
] |
0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd
|
https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/db.js#L44-L61
|
37,795 |
mikl/node-drupal
|
lib/db.js
|
runQuery
|
function runQuery(client, queryString, args, callback) {
if (activeBackend === 'mysql') {
queryString = queryString.replace(/\$\d+/, '?');
}
client.query(queryString, args, function (err, result) {
if (err) {
callback(err, null);
return;
}
if (activeBackend === 'mysql') {
callback(err, result);
}
else if (activeBackend === 'pgsql') {
var rows = [];
if (result.rows) {
rows = result.rows;
}
callback(err, rows);
}
});
}
|
javascript
|
function runQuery(client, queryString, args, callback) {
if (activeBackend === 'mysql') {
queryString = queryString.replace(/\$\d+/, '?');
}
client.query(queryString, args, function (err, result) {
if (err) {
callback(err, null);
return;
}
if (activeBackend === 'mysql') {
callback(err, result);
}
else if (activeBackend === 'pgsql') {
var rows = [];
if (result.rows) {
rows = result.rows;
}
callback(err, rows);
}
});
}
|
[
"function",
"runQuery",
"(",
"client",
",",
"queryString",
",",
"args",
",",
"callback",
")",
"{",
"if",
"(",
"activeBackend",
"===",
"'mysql'",
")",
"{",
"queryString",
"=",
"queryString",
".",
"replace",
"(",
"/",
"\\$\\d+",
"/",
",",
"'?'",
")",
";",
"}",
"client",
".",
"query",
"(",
"queryString",
",",
"args",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"null",
")",
";",
"return",
";",
"}",
"if",
"(",
"activeBackend",
"===",
"'mysql'",
")",
"{",
"callback",
"(",
"err",
",",
"result",
")",
";",
"}",
"else",
"if",
"(",
"activeBackend",
"===",
"'pgsql'",
")",
"{",
"var",
"rows",
"=",
"[",
"]",
";",
"if",
"(",
"result",
".",
"rows",
")",
"{",
"rows",
"=",
"result",
".",
"rows",
";",
"}",
"callback",
"(",
"err",
",",
"rows",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Do the actual work of running the query.
|
[
"Do",
"the",
"actual",
"work",
"of",
"running",
"the",
"query",
"."
] |
0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd
|
https://github.com/mikl/node-drupal/blob/0bf8926d69c1c960c26c6e8808d9c7e7e26f78bd/lib/db.js#L82-L103
|
37,796 |
kt3k/kocha
|
packages/kocha/src/reporters/json.js
|
errorJSON
|
function errorJSON (err) {
var res = {}
Object.getOwnPropertyNames(err).forEach(function (key) {
res[key] = err[key]
}, err)
return res
}
|
javascript
|
function errorJSON (err) {
var res = {}
Object.getOwnPropertyNames(err).forEach(function (key) {
res[key] = err[key]
}, err)
return res
}
|
[
"function",
"errorJSON",
"(",
"err",
")",
"{",
"var",
"res",
"=",
"{",
"}",
"Object",
".",
"getOwnPropertyNames",
"(",
"err",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"res",
"[",
"key",
"]",
"=",
"err",
"[",
"key",
"]",
"}",
",",
"err",
")",
"return",
"res",
"}"
] |
Transform `error` into a JSON object.
@api private
@param {Error} err
@return {Object}
|
[
"Transform",
"error",
"into",
"a",
"JSON",
"object",
"."
] |
3dab0d0a0aaaf152e4a71fa2a68f3835dcdbf68d
|
https://github.com/kt3k/kocha/blob/3dab0d0a0aaaf152e4a71fa2a68f3835dcdbf68d/packages/kocha/src/reporters/json.js#L80-L86
|
37,797 |
lludol/clf-date
|
src/main.js
|
getCLFOffset
|
function getCLFOffset(date) {
const offset = date.getTimezoneOffset().toString();
const op = offset[0] === '-' ? '-' : '+';
let number = offset.replace(op, '');
while (number.length < 4) {
number = `0${number}`;
}
return `${op}${number}`;
}
|
javascript
|
function getCLFOffset(date) {
const offset = date.getTimezoneOffset().toString();
const op = offset[0] === '-' ? '-' : '+';
let number = offset.replace(op, '');
while (number.length < 4) {
number = `0${number}`;
}
return `${op}${number}`;
}
|
[
"function",
"getCLFOffset",
"(",
"date",
")",
"{",
"const",
"offset",
"=",
"date",
".",
"getTimezoneOffset",
"(",
")",
".",
"toString",
"(",
")",
";",
"const",
"op",
"=",
"offset",
"[",
"0",
"]",
"===",
"'-'",
"?",
"'-'",
":",
"'+'",
";",
"let",
"number",
"=",
"offset",
".",
"replace",
"(",
"op",
",",
"''",
")",
";",
"while",
"(",
"number",
".",
"length",
"<",
"4",
")",
"{",
"number",
"=",
"`",
"${",
"number",
"}",
"`",
";",
"}",
"return",
"`",
"${",
"op",
"}",
"${",
"number",
"}",
"`",
";",
"}"
] |
Return the offset from UTC in CLF format.
@param {Date} date - The date
@return {String} The offset.
|
[
"Return",
"the",
"offset",
"from",
"UTC",
"in",
"CLF",
"format",
"."
] |
3c5ee7ac4dc4f034a46b83d910ef328e81257d19
|
https://github.com/lludol/clf-date/blob/3c5ee7ac4dc4f034a46b83d910ef328e81257d19/src/main.js#L16-L26
|
37,798 |
lammas/tree-traversal
|
tree-traversal.js
|
traverseBreadthFirst
|
function traverseBreadthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
(function next() {
if (queue.length == 0) {
options.onComplete(rootNode);
return;
}
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
queue.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
},
data);
})();
}
|
javascript
|
function traverseBreadthFirst(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, callback, userdata) { callback(); },
onComplete: function(rootNode) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
(function next() {
if (queue.length == 0) {
options.onComplete(rootNode);
return;
}
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, function() {
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
async.eachSeries(subnodes,
function(subnode, nextNode) {
queue.push([subnode, subnodeData]);
async.setImmediate(nextNode);
},
function() {
async.setImmediate(next);
}
);
},
data);
})();
}
|
[
"function",
"traverseBreadthFirst",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"userdataAccessor",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"return",
"userdata",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"callback",
",",
"userdata",
")",
"{",
"callback",
"(",
")",
";",
"}",
",",
"onComplete",
":",
"function",
"(",
"rootNode",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"var",
"queue",
"=",
"[",
"]",
";",
"queue",
".",
"push",
"(",
"[",
"rootNode",
",",
"options",
".",
"userdata",
"]",
")",
";",
"(",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"queue",
".",
"length",
"==",
"0",
")",
"{",
"options",
".",
"onComplete",
"(",
"rootNode",
")",
";",
"return",
";",
"}",
"var",
"front",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"var",
"node",
"=",
"front",
"[",
"0",
"]",
";",
"var",
"data",
"=",
"front",
"[",
"1",
"]",
";",
"options",
".",
"onNode",
"(",
"node",
",",
"function",
"(",
")",
"{",
"var",
"subnodeData",
"=",
"options",
".",
"userdataAccessor",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"async",
".",
"eachSeries",
"(",
"subnodes",
",",
"function",
"(",
"subnode",
",",
"nextNode",
")",
"{",
"queue",
".",
"push",
"(",
"[",
"subnode",
",",
"subnodeData",
"]",
")",
";",
"async",
".",
"setImmediate",
"(",
"nextNode",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"async",
".",
"setImmediate",
"(",
"next",
")",
";",
"}",
")",
";",
"}",
",",
"data",
")",
";",
"}",
")",
"(",
")",
";",
"}"
] |
Asynchronously traverses the tree breadth first.
|
[
"Asynchronously",
"traverses",
"the",
"tree",
"breadth",
"first",
"."
] |
ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47
|
https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L17-L54
|
37,799 |
lammas/tree-traversal
|
tree-traversal.js
|
traverseBreadthFirstSync
|
function traverseBreadthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
while (queue.length>0) {
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
queue.push([subnodes[i], subnodeData]);
}
}
return rootNode;
}
|
javascript
|
function traverseBreadthFirstSync(rootNode, options) {
options = extend({
subnodesAccessor: function(node) { return node.subnodes; },
userdataAccessor: function(node, userdata) { return userdata; },
onNode: function(node, userdata) {},
userdata: null
}, options);
var queue = [];
queue.push([rootNode, options.userdata]);
while (queue.length>0) {
var front = queue.shift();
var node = front[0];
var data = front[1];
options.onNode(node, data);
var subnodeData = options.userdataAccessor(node, data);
var subnodes = options.subnodesAccessor(node);
for (var i=0; i<subnodes.length; i++) {
queue.push([subnodes[i], subnodeData]);
}
}
return rootNode;
}
|
[
"function",
"traverseBreadthFirstSync",
"(",
"rootNode",
",",
"options",
")",
"{",
"options",
"=",
"extend",
"(",
"{",
"subnodesAccessor",
":",
"function",
"(",
"node",
")",
"{",
"return",
"node",
".",
"subnodes",
";",
"}",
",",
"userdataAccessor",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"return",
"userdata",
";",
"}",
",",
"onNode",
":",
"function",
"(",
"node",
",",
"userdata",
")",
"{",
"}",
",",
"userdata",
":",
"null",
"}",
",",
"options",
")",
";",
"var",
"queue",
"=",
"[",
"]",
";",
"queue",
".",
"push",
"(",
"[",
"rootNode",
",",
"options",
".",
"userdata",
"]",
")",
";",
"while",
"(",
"queue",
".",
"length",
">",
"0",
")",
"{",
"var",
"front",
"=",
"queue",
".",
"shift",
"(",
")",
";",
"var",
"node",
"=",
"front",
"[",
"0",
"]",
";",
"var",
"data",
"=",
"front",
"[",
"1",
"]",
";",
"options",
".",
"onNode",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodeData",
"=",
"options",
".",
"userdataAccessor",
"(",
"node",
",",
"data",
")",
";",
"var",
"subnodes",
"=",
"options",
".",
"subnodesAccessor",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"subnodes",
".",
"length",
";",
"i",
"++",
")",
"{",
"queue",
".",
"push",
"(",
"[",
"subnodes",
"[",
"i",
"]",
",",
"subnodeData",
"]",
")",
";",
"}",
"}",
"return",
"rootNode",
";",
"}"
] |
Synchronously traverses the tree breadth first.
|
[
"Synchronously",
"traverses",
"the",
"tree",
"breadth",
"first",
"."
] |
ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47
|
https://github.com/lammas/tree-traversal/blob/ca02a2a4308eb6cff27b0dd030fd8ccfb36b6e47/tree-traversal.js#L59-L84
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.