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
|
---|---|---|---|---|---|---|---|---|---|---|---|
41,300 | rorymadden/neoprene | lib/errors/cast.js | CastError | function CastError (type, value) {
NeopreneError.call(this, 'Cast to ' + type + ' failed for value "' + value + '"');
Error.captureStackTrace(this, arguments.callee);
this.name = 'CastError';
this.type = type;
this.value = value;
} | javascript | function CastError (type, value) {
NeopreneError.call(this, 'Cast to ' + type + ' failed for value "' + value + '"');
Error.captureStackTrace(this, arguments.callee);
this.name = 'CastError';
this.type = type;
this.value = value;
} | [
"function",
"CastError",
"(",
"type",
",",
"value",
")",
"{",
"NeopreneError",
".",
"call",
"(",
"this",
",",
"'Cast to '",
"+",
"type",
"+",
"' failed for value \"'",
"+",
"value",
"+",
"'\"'",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"arguments",
".",
"callee",
")",
";",
"this",
".",
"name",
"=",
"'CastError'",
";",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"value",
"=",
"value",
";",
"}"
]
| Casting Error constructor.
@param {String} type
@param {String} value
@inherits NeopreneError
@api private | [
"Casting",
"Error",
"constructor",
"."
]
| 11f22f65a006c25b779b2add9058e9b00b053466 | https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/errors/cast.js#L16-L22 |
41,301 | crudlio/crudl-connectors-base | lib/createFrontendConnector.js | fc | function fc() {
for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
return createFrontendConnector(parametrize(c, params), debug);
} | javascript | function fc() {
for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
return createFrontendConnector(parametrize(c, params), debug);
} | [
"function",
"fc",
"(",
")",
"{",
"for",
"(",
"var",
"_len",
"=",
"arguments",
".",
"length",
",",
"params",
"=",
"Array",
"(",
"_len",
")",
",",
"_key",
"=",
"0",
";",
"_key",
"<",
"_len",
";",
"_key",
"++",
")",
"{",
"params",
"[",
"_key",
"]",
"=",
"arguments",
"[",
"_key",
"]",
";",
"}",
"return",
"createFrontendConnector",
"(",
"parametrize",
"(",
"c",
",",
"params",
")",
",",
"debug",
")",
";",
"}"
]
| Frontend connector is a function that returns a parametrized connector | [
"Frontend",
"connector",
"is",
"a",
"function",
"that",
"returns",
"a",
"parametrized",
"connector"
]
| 454d541b3b3cf7eef5edf4fa84923458052c733a | https://github.com/crudlio/crudl-connectors-base/blob/454d541b3b3cf7eef5edf4fa84923458052c733a/lib/createFrontendConnector.js#L110-L116 |
41,302 | rorymadden/neoprene | lib/errors/validation.js | ValidationError | function ValidationError (instance) {
NeopreneError.call(this, "Validation failed");
Error.captureStackTrace(this, arguments.callee);
this.name = 'ValidationError';
this.errors = instance.errors = {};
} | javascript | function ValidationError (instance) {
NeopreneError.call(this, "Validation failed");
Error.captureStackTrace(this, arguments.callee);
this.name = 'ValidationError';
this.errors = instance.errors = {};
} | [
"function",
"ValidationError",
"(",
"instance",
")",
"{",
"NeopreneError",
".",
"call",
"(",
"this",
",",
"\"Validation failed\"",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"arguments",
".",
"callee",
")",
";",
"this",
".",
"name",
"=",
"'ValidationError'",
";",
"this",
".",
"errors",
"=",
"instance",
".",
"errors",
"=",
"{",
"}",
";",
"}"
]
| Document Validation Error
@api private
@param {Document} instance
@inherits NeopreneError | [
"Document",
"Validation",
"Error"
]
| 11f22f65a006c25b779b2add9058e9b00b053466 | https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/errors/validation.js#L16-L21 |
41,303 | mattdesl/gl-sprite-batch | demo/dynamic.js | render | function render(gl, width, height, dt, batch, shader) {
time+=dt
var anim = Math.sin(time/1000)/2+0.5
//clear the batch to zero
batch.clear()
//bind before drawing
batch.bind(shader)
//push our sprites which may have a variety
//of textures
batch.push({
position: [anim*100, anim*50],
shape: [128, 128],
texture: tex2
})
batch.push({
position: [100, 100],
shape: [128, 128],
color: [1, 1, 1, 0.5],
texture: tex
})
batch.push({
position: [300, 100],
shape: [128, 128],
color: [1, 1, 1, 0.5],
texcoord: [0, 0, 2.5, 2.5],
texture: tex
})
batch.push({
texture: null,
position: [100+100*Math.sin(time/2000), 100],
shape: [63, 63],
color: [anim, 0, 0, 1.0]
})
//we need to flush any outstanding sprites
batch.draw()
//and unbind it...
batch.unbind()
} | javascript | function render(gl, width, height, dt, batch, shader) {
time+=dt
var anim = Math.sin(time/1000)/2+0.5
//clear the batch to zero
batch.clear()
//bind before drawing
batch.bind(shader)
//push our sprites which may have a variety
//of textures
batch.push({
position: [anim*100, anim*50],
shape: [128, 128],
texture: tex2
})
batch.push({
position: [100, 100],
shape: [128, 128],
color: [1, 1, 1, 0.5],
texture: tex
})
batch.push({
position: [300, 100],
shape: [128, 128],
color: [1, 1, 1, 0.5],
texcoord: [0, 0, 2.5, 2.5],
texture: tex
})
batch.push({
texture: null,
position: [100+100*Math.sin(time/2000), 100],
shape: [63, 63],
color: [anim, 0, 0, 1.0]
})
//we need to flush any outstanding sprites
batch.draw()
//and unbind it...
batch.unbind()
} | [
"function",
"render",
"(",
"gl",
",",
"width",
",",
"height",
",",
"dt",
",",
"batch",
",",
"shader",
")",
"{",
"time",
"+=",
"dt",
"var",
"anim",
"=",
"Math",
".",
"sin",
"(",
"time",
"/",
"1000",
")",
"/",
"2",
"+",
"0.5",
"//clear the batch to zero",
"batch",
".",
"clear",
"(",
")",
"//bind before drawing",
"batch",
".",
"bind",
"(",
"shader",
")",
"//push our sprites which may have a variety",
"//of textures",
"batch",
".",
"push",
"(",
"{",
"position",
":",
"[",
"anim",
"*",
"100",
",",
"anim",
"*",
"50",
"]",
",",
"shape",
":",
"[",
"128",
",",
"128",
"]",
",",
"texture",
":",
"tex2",
"}",
")",
"batch",
".",
"push",
"(",
"{",
"position",
":",
"[",
"100",
",",
"100",
"]",
",",
"shape",
":",
"[",
"128",
",",
"128",
"]",
",",
"color",
":",
"[",
"1",
",",
"1",
",",
"1",
",",
"0.5",
"]",
",",
"texture",
":",
"tex",
"}",
")",
"batch",
".",
"push",
"(",
"{",
"position",
":",
"[",
"300",
",",
"100",
"]",
",",
"shape",
":",
"[",
"128",
",",
"128",
"]",
",",
"color",
":",
"[",
"1",
",",
"1",
",",
"1",
",",
"0.5",
"]",
",",
"texcoord",
":",
"[",
"0",
",",
"0",
",",
"2.5",
",",
"2.5",
"]",
",",
"texture",
":",
"tex",
"}",
")",
"batch",
".",
"push",
"(",
"{",
"texture",
":",
"null",
",",
"position",
":",
"[",
"100",
"+",
"100",
"*",
"Math",
".",
"sin",
"(",
"time",
"/",
"2000",
")",
",",
"100",
"]",
",",
"shape",
":",
"[",
"63",
",",
"63",
"]",
",",
"color",
":",
"[",
"anim",
",",
"0",
",",
"0",
",",
"1.0",
"]",
"}",
")",
"//we need to flush any outstanding sprites",
"batch",
".",
"draw",
"(",
")",
"//and unbind it...",
"batch",
".",
"unbind",
"(",
")",
"}"
]
| The "dynamic" flag to the Batch constructor is an optional hint for how the buffer will be stored on the GPU. | [
"The",
"dynamic",
"flag",
"to",
"the",
"Batch",
"constructor",
"is",
"an",
"optional",
"hint",
"for",
"how",
"the",
"buffer",
"will",
"be",
"stored",
"on",
"the",
"GPU",
"."
]
| 664a6dc437bab3916968015b4580574335422243 | https://github.com/mattdesl/gl-sprite-batch/blob/664a6dc437bab3916968015b4580574335422243/demo/dynamic.js#L21-L67 |
41,304 | rorymadden/neoprene | lib/schema/mixed.js | Mixed | function Mixed (path, options) {
// make sure empty array defaults are handled
if (options &&
options.default &&
Array.isArray(options.default) &&
0 === options.default.length) {
options.default = Array;
}
SchemaType.call(this, path, options);
} | javascript | function Mixed (path, options) {
// make sure empty array defaults are handled
if (options &&
options.default &&
Array.isArray(options.default) &&
0 === options.default.length) {
options.default = Array;
}
SchemaType.call(this, path, options);
} | [
"function",
"Mixed",
"(",
"path",
",",
"options",
")",
"{",
"// make sure empty array defaults are handled",
"if",
"(",
"options",
"&&",
"options",
".",
"default",
"&&",
"Array",
".",
"isArray",
"(",
"options",
".",
"default",
")",
"&&",
"0",
"===",
"options",
".",
"default",
".",
"length",
")",
"{",
"options",
".",
"default",
"=",
"Array",
";",
"}",
"SchemaType",
".",
"call",
"(",
"this",
",",
"path",
",",
"options",
")",
";",
"}"
]
| Mixed SchemaType constructor.
@param {String} path
@param {Object} options
@inherits SchemaType
@api private | [
"Mixed",
"SchemaType",
"constructor",
"."
]
| 11f22f65a006c25b779b2add9058e9b00b053466 | https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/schema/mixed.js#L17-L27 |
41,305 | 3rd-Eden/node-bisection | index.js | bisection | function bisection(array, x, low, high){
// The low and high bounds the inital slice of the array that needs to be searched
// this is optional
low = low || 0;
high = high || array.length;
var mid;
while (low < high) {
mid = (low + high) >> 1;
if (x < array[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
} | javascript | function bisection(array, x, low, high){
// The low and high bounds the inital slice of the array that needs to be searched
// this is optional
low = low || 0;
high = high || array.length;
var mid;
while (low < high) {
mid = (low + high) >> 1;
if (x < array[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
} | [
"function",
"bisection",
"(",
"array",
",",
"x",
",",
"low",
",",
"high",
")",
"{",
"// The low and high bounds the inital slice of the array that needs to be searched",
"// this is optional",
"low",
"=",
"low",
"||",
"0",
";",
"high",
"=",
"high",
"||",
"array",
".",
"length",
";",
"var",
"mid",
";",
"while",
"(",
"low",
"<",
"high",
")",
"{",
"mid",
"=",
"(",
"low",
"+",
"high",
")",
">>",
"1",
";",
"if",
"(",
"x",
"<",
"array",
"[",
"mid",
"]",
")",
"{",
"high",
"=",
"mid",
";",
"}",
"else",
"{",
"low",
"=",
"mid",
"+",
"1",
";",
"}",
"}",
"return",
"low",
";",
"}"
]
| Calculates the index of the Array where item X should be placed, assuming the Array is sorted.
@param {Array} array The array containing the items.
@param {Number} x The item that needs to be added to the array.
@param {Number} low Inital Index that is used to start searching, optional.
@param {Number} high The maximum Index that is used to stop searching, optional.
@returns {Number} the index where item X should be placed | [
"Calculates",
"the",
"index",
"of",
"the",
"Array",
"where",
"item",
"X",
"should",
"be",
"placed",
"assuming",
"the",
"Array",
"is",
"sorted",
"."
]
| d90998fa1ebc059e9707b68094eb38a99eaf406a | https://github.com/3rd-Eden/node-bisection/blob/d90998fa1ebc059e9707b68094eb38a99eaf406a/index.js#L12-L31 |
41,306 | rorymadden/neoprene | lib/model.js | model | function model (doc, fields) {
if (!(this instanceof model))
return new model(doc, fields);
Model.call(this, doc, fields);
} | javascript | function model (doc, fields) {
if (!(this instanceof model))
return new model(doc, fields);
Model.call(this, doc, fields);
} | [
"function",
"model",
"(",
"doc",
",",
"fields",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"model",
")",
")",
"return",
"new",
"model",
"(",
"doc",
",",
"fields",
")",
";",
"Model",
".",
"call",
"(",
"this",
",",
"doc",
",",
"fields",
")",
";",
"}"
]
| generate new class | [
"generate",
"new",
"class"
]
| 11f22f65a006c25b779b2add9058e9b00b053466 | https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/model.js#L50-L54 |
41,307 | rorymadden/neoprene | lib/graphObject.js | GraphObject | function GraphObject(obj, fields) {
this.isNew = true;
this.errors = undefined;
this._saveError = undefined;
this._validationError = undefined;
// this._adhocPaths = undefined;
// this._removing = undefined;
// this._inserting = undefined;
// this.__version = undefined;
this.__getters = {};
// this.__id = undefined;
// the type of container - node or relationship
this._activePaths = new ActiveRoster();
var required = this.schema.requiredPaths();
for (var i = 0; i < required.length; ++i) {
this._activePaths.require(required[i]);
}
this._doc = this._buildDoc(obj, fields);
if (obj) this.set(obj, undefined, true);
this._registerHooks();
} | javascript | function GraphObject(obj, fields) {
this.isNew = true;
this.errors = undefined;
this._saveError = undefined;
this._validationError = undefined;
// this._adhocPaths = undefined;
// this._removing = undefined;
// this._inserting = undefined;
// this.__version = undefined;
this.__getters = {};
// this.__id = undefined;
// the type of container - node or relationship
this._activePaths = new ActiveRoster();
var required = this.schema.requiredPaths();
for (var i = 0; i < required.length; ++i) {
this._activePaths.require(required[i]);
}
this._doc = this._buildDoc(obj, fields);
if (obj) this.set(obj, undefined, true);
this._registerHooks();
} | [
"function",
"GraphObject",
"(",
"obj",
",",
"fields",
")",
"{",
"this",
".",
"isNew",
"=",
"true",
";",
"this",
".",
"errors",
"=",
"undefined",
";",
"this",
".",
"_saveError",
"=",
"undefined",
";",
"this",
".",
"_validationError",
"=",
"undefined",
";",
"// this._adhocPaths = undefined;",
"// this._removing = undefined;",
"// this._inserting = undefined;",
"// this.__version = undefined;",
"this",
".",
"__getters",
"=",
"{",
"}",
";",
"// this.__id = undefined;",
"// the type of container - node or relationship",
"this",
".",
"_activePaths",
"=",
"new",
"ActiveRoster",
"(",
")",
";",
"var",
"required",
"=",
"this",
".",
"schema",
".",
"requiredPaths",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"required",
".",
"length",
";",
"++",
"i",
")",
"{",
"this",
".",
"_activePaths",
".",
"require",
"(",
"required",
"[",
"i",
"]",
")",
";",
"}",
"this",
".",
"_doc",
"=",
"this",
".",
"_buildDoc",
"(",
"obj",
",",
"fields",
")",
";",
"if",
"(",
"obj",
")",
"this",
".",
"set",
"(",
"obj",
",",
"undefined",
",",
"true",
")",
";",
"this",
".",
"_registerHooks",
"(",
")",
";",
"}"
]
| A wrapper object for a neo4j node or relationship
@param {String} url Url for the neo4j database.
@param {Object} data The properties of the neo4j object.
@param {String} objectType node or relationship.
@return {Object} The GraphObject object.
@api private | [
"A",
"wrapper",
"object",
"for",
"a",
"neo4j",
"node",
"or",
"relationship"
]
| 11f22f65a006c25b779b2add9058e9b00b053466 | https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/graphObject.js#L35-L58 |
41,308 | rorymadden/neoprene | lib/index.js | function(row, callback) {
var map = {}, value;
for (var i = 0, j = row.length; i < j; i++) {
value = row[i];
// transform the value to either Node, Relationship or Path
map[resColumns[i]] = utils.transform(value, self);
}
return callback(null, map);
} | javascript | function(row, callback) {
var map = {}, value;
for (var i = 0, j = row.length; i < j; i++) {
value = row[i];
// transform the value to either Node, Relationship or Path
map[resColumns[i]] = utils.transform(value, self);
}
return callback(null, map);
} | [
"function",
"(",
"row",
",",
"callback",
")",
"{",
"var",
"map",
"=",
"{",
"}",
",",
"value",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"row",
".",
"length",
";",
"i",
"<",
"j",
";",
"i",
"++",
")",
"{",
"value",
"=",
"row",
"[",
"i",
"]",
";",
"// transform the value to either Node, Relationship or Path",
"map",
"[",
"resColumns",
"[",
"i",
"]",
"]",
"=",
"utils",
".",
"transform",
"(",
"value",
",",
"self",
")",
";",
"}",
"return",
"callback",
"(",
"null",
",",
"map",
")",
";",
"}"
]
| each row returned could represent a node, relationship or path | [
"each",
"row",
"returned",
"could",
"represent",
"a",
"node",
"relationship",
"or",
"path"
]
| 11f22f65a006c25b779b2add9058e9b00b053466 | https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/index.js#L248-L256 |
|
41,309 | crudlio/crudl-connectors-base | lib/middleware/transformData.js | transformData | function transformData(methodRegExp) {
var transform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (data) {
return data;
};
var re = new RegExp(methodRegExp || '.*');
// The middleware function
return function transformDataMiddleware(next) {
// Checks if the call should be transformed. If yes, it applies the transform function
function checkAndTransform(method) {
return re.test(method) ? function (req) {
return next[method](req).then(function (res) {
return Object.assign(res, { data: transform(res.data) });
});
} : function (req) {
return next[method](req);
};
}
// The middleware connector:
return {
create: checkAndTransform('create'),
read: checkAndTransform('read'),
update: checkAndTransform('update'),
delete: checkAndTransform('delete')
};
};
} | javascript | function transformData(methodRegExp) {
var transform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (data) {
return data;
};
var re = new RegExp(methodRegExp || '.*');
// The middleware function
return function transformDataMiddleware(next) {
// Checks if the call should be transformed. If yes, it applies the transform function
function checkAndTransform(method) {
return re.test(method) ? function (req) {
return next[method](req).then(function (res) {
return Object.assign(res, { data: transform(res.data) });
});
} : function (req) {
return next[method](req);
};
}
// The middleware connector:
return {
create: checkAndTransform('create'),
read: checkAndTransform('read'),
update: checkAndTransform('update'),
delete: checkAndTransform('delete')
};
};
} | [
"function",
"transformData",
"(",
"methodRegExp",
")",
"{",
"var",
"transform",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"function",
"(",
"data",
")",
"{",
"return",
"data",
";",
"}",
";",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"methodRegExp",
"||",
"'.*'",
")",
";",
"// The middleware function",
"return",
"function",
"transformDataMiddleware",
"(",
"next",
")",
"{",
"// Checks if the call should be transformed. If yes, it applies the transform function",
"function",
"checkAndTransform",
"(",
"method",
")",
"{",
"return",
"re",
".",
"test",
"(",
"method",
")",
"?",
"function",
"(",
"req",
")",
"{",
"return",
"next",
"[",
"method",
"]",
"(",
"req",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"res",
",",
"{",
"data",
":",
"transform",
"(",
"res",
".",
"data",
")",
"}",
")",
";",
"}",
")",
";",
"}",
":",
"function",
"(",
"req",
")",
"{",
"return",
"next",
"[",
"method",
"]",
"(",
"req",
")",
";",
"}",
";",
"}",
"// The middleware connector:",
"return",
"{",
"create",
":",
"checkAndTransform",
"(",
"'create'",
")",
",",
"read",
":",
"checkAndTransform",
"(",
"'read'",
")",
",",
"update",
":",
"checkAndTransform",
"(",
"'update'",
")",
",",
"delete",
":",
"checkAndTransform",
"(",
"'delete'",
")",
"}",
";",
"}",
";",
"}"
]
| Creates a transformData middleware
@methodRegExp Which methods should be transformed e.g. 'create|update'
@transform The transform function | [
"Creates",
"a",
"transformData",
"middleware"
]
| 454d541b3b3cf7eef5edf4fa84923458052c733a | https://github.com/crudlio/crudl-connectors-base/blob/454d541b3b3cf7eef5edf4fa84923458052c733a/lib/middleware/transformData.js#L12-L40 |
41,310 | crudlio/crudl-connectors-base | lib/middleware/transformData.js | checkAndTransform | function checkAndTransform(method) {
return re.test(method) ? function (req) {
return next[method](req).then(function (res) {
return Object.assign(res, { data: transform(res.data) });
});
} : function (req) {
return next[method](req);
};
} | javascript | function checkAndTransform(method) {
return re.test(method) ? function (req) {
return next[method](req).then(function (res) {
return Object.assign(res, { data: transform(res.data) });
});
} : function (req) {
return next[method](req);
};
} | [
"function",
"checkAndTransform",
"(",
"method",
")",
"{",
"return",
"re",
".",
"test",
"(",
"method",
")",
"?",
"function",
"(",
"req",
")",
"{",
"return",
"next",
"[",
"method",
"]",
"(",
"req",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"res",
",",
"{",
"data",
":",
"transform",
"(",
"res",
".",
"data",
")",
"}",
")",
";",
"}",
")",
";",
"}",
":",
"function",
"(",
"req",
")",
"{",
"return",
"next",
"[",
"method",
"]",
"(",
"req",
")",
";",
"}",
";",
"}"
]
| Checks if the call should be transformed. If yes, it applies the transform function | [
"Checks",
"if",
"the",
"call",
"should",
"be",
"transformed",
".",
"If",
"yes",
"it",
"applies",
"the",
"transform",
"function"
]
| 454d541b3b3cf7eef5edf4fa84923458052c733a | https://github.com/crudlio/crudl-connectors-base/blob/454d541b3b3cf7eef5edf4fa84923458052c733a/lib/middleware/transformData.js#L22-L30 |
41,311 | rorymadden/neoprene | lib/schema.js | Schema | function Schema (obj, options) {
if (!(this instanceof Schema))
return new Schema(obj, options);
this.paths = {};
this.virtuals = {};
this.callQueue = [];
this._indexes = [];
this.methods = {};
this.statics = {};
this.tree = {};
this._requiredpaths = undefined;
// set options
this.options = utils.options({
// safe: true
strict: true
, versionKey: '__v'
, minimize: true
, autoIndex: true
// the following are only applied at construction time
// , _id: true
// , id: true
}, options);
// build paths
if (obj) {
this.add(obj);
}
} | javascript | function Schema (obj, options) {
if (!(this instanceof Schema))
return new Schema(obj, options);
this.paths = {};
this.virtuals = {};
this.callQueue = [];
this._indexes = [];
this.methods = {};
this.statics = {};
this.tree = {};
this._requiredpaths = undefined;
// set options
this.options = utils.options({
// safe: true
strict: true
, versionKey: '__v'
, minimize: true
, autoIndex: true
// the following are only applied at construction time
// , _id: true
// , id: true
}, options);
// build paths
if (obj) {
this.add(obj);
}
} | [
"function",
"Schema",
"(",
"obj",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Schema",
")",
")",
"return",
"new",
"Schema",
"(",
"obj",
",",
"options",
")",
";",
"this",
".",
"paths",
"=",
"{",
"}",
";",
"this",
".",
"virtuals",
"=",
"{",
"}",
";",
"this",
".",
"callQueue",
"=",
"[",
"]",
";",
"this",
".",
"_indexes",
"=",
"[",
"]",
";",
"this",
".",
"methods",
"=",
"{",
"}",
";",
"this",
".",
"statics",
"=",
"{",
"}",
";",
"this",
".",
"tree",
"=",
"{",
"}",
";",
"this",
".",
"_requiredpaths",
"=",
"undefined",
";",
"// set options",
"this",
".",
"options",
"=",
"utils",
".",
"options",
"(",
"{",
"// safe: true",
"strict",
":",
"true",
",",
"versionKey",
":",
"'__v'",
",",
"minimize",
":",
"true",
",",
"autoIndex",
":",
"true",
"// the following are only applied at construction time",
"// , _id: true",
"// , id: true",
"}",
",",
"options",
")",
";",
"// build paths",
"if",
"(",
"obj",
")",
"{",
"this",
".",
"add",
"(",
"obj",
")",
";",
"}",
"}"
]
| Schema constructor.
####Example:
var child = new Schema({ name: String });
var schema = new Schema({ name: String, age: Number });
var Tree = mongoose.model('node', Tree', schema);
####Options:
- [safe](/docs/guide.html#safe): bool - defaults to true NOT IMPLEMENTED
- [strict](/docs/guide.html#strict): bool - defaults to true
- [capped](/docs/guide.html#capped): bool - defaults to false
- [versionKey](/docs/guide.html#versionKey): bool - defaults to "__v"
- [autoIndex](/docs/guide.html#autoIndex): bool - defaults to true
- `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
@param {Object} definition
@inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
@api public | [
"Schema",
"constructor",
"."
]
| 11f22f65a006c25b779b2add9058e9b00b053466 | https://github.com/rorymadden/neoprene/blob/11f22f65a006c25b779b2add9058e9b00b053466/lib/schema.js#L34-L63 |
41,312 | joshmarinacci/aminogfx | src/widgets.js | function() {
this.comps.base.add(this.comps.background);
this.comps.base.add(this.comps.label);
var self = this;
this.setFill(amino.colortheme.button.fill.normal);
amino.getCore().on('press', this, function(e) {
self.setFill(amino.colortheme.button.fill.pressed);
});
amino.getCore().on("release",this,function(e) {
self.setFill(amino.colortheme.button.fill.normal);
});
amino.getCore().on("click",this,function(e) {
var event = {type:'action',source:self};
amino.getCore().fireEvent(event);
if(self.actioncb) self.actioncb(event);
});
this.setFontSize(15);
/** @func onAction(cb) a function to call when this button fires an action. You can also listen for the 'action' event. */
this.onAction = function(cb) {
this.actioncb = cb;
return this;
}
this.markDirty = function() {
this.dirty = true;
amino.dirtylist.push(this);
}
this.doLayout = function() {
var textw = this.comps.label.font.calcStringWidth(this.getText(),this.getFontSize(),this.getFontWeight(),this.getFontStyle());
this.comps.label.setTx(Math.round((this.getW()-textw)/2));
var texth = this.comps.label.font.getHeight(this.getFontSize(),this.getFontWeight(),this.getFontStyle());
this.comps.label.setTy(Math.round(this.getH()/2 + texth/2));
}
this.validate = function() {
this.doLayout();
this.dirty = false;
}
} | javascript | function() {
this.comps.base.add(this.comps.background);
this.comps.base.add(this.comps.label);
var self = this;
this.setFill(amino.colortheme.button.fill.normal);
amino.getCore().on('press', this, function(e) {
self.setFill(amino.colortheme.button.fill.pressed);
});
amino.getCore().on("release",this,function(e) {
self.setFill(amino.colortheme.button.fill.normal);
});
amino.getCore().on("click",this,function(e) {
var event = {type:'action',source:self};
amino.getCore().fireEvent(event);
if(self.actioncb) self.actioncb(event);
});
this.setFontSize(15);
/** @func onAction(cb) a function to call when this button fires an action. You can also listen for the 'action' event. */
this.onAction = function(cb) {
this.actioncb = cb;
return this;
}
this.markDirty = function() {
this.dirty = true;
amino.dirtylist.push(this);
}
this.doLayout = function() {
var textw = this.comps.label.font.calcStringWidth(this.getText(),this.getFontSize(),this.getFontWeight(),this.getFontStyle());
this.comps.label.setTx(Math.round((this.getW()-textw)/2));
var texth = this.comps.label.font.getHeight(this.getFontSize(),this.getFontWeight(),this.getFontStyle());
this.comps.label.setTy(Math.round(this.getH()/2 + texth/2));
}
this.validate = function() {
this.doLayout();
this.dirty = false;
}
} | [
"function",
"(",
")",
"{",
"this",
".",
"comps",
".",
"base",
".",
"add",
"(",
"this",
".",
"comps",
".",
"background",
")",
";",
"this",
".",
"comps",
".",
"base",
".",
"add",
"(",
"this",
".",
"comps",
".",
"label",
")",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"setFill",
"(",
"amino",
".",
"colortheme",
".",
"button",
".",
"fill",
".",
"normal",
")",
";",
"amino",
".",
"getCore",
"(",
")",
".",
"on",
"(",
"'press'",
",",
"this",
",",
"function",
"(",
"e",
")",
"{",
"self",
".",
"setFill",
"(",
"amino",
".",
"colortheme",
".",
"button",
".",
"fill",
".",
"pressed",
")",
";",
"}",
")",
";",
"amino",
".",
"getCore",
"(",
")",
".",
"on",
"(",
"\"release\"",
",",
"this",
",",
"function",
"(",
"e",
")",
"{",
"self",
".",
"setFill",
"(",
"amino",
".",
"colortheme",
".",
"button",
".",
"fill",
".",
"normal",
")",
";",
"}",
")",
";",
"amino",
".",
"getCore",
"(",
")",
".",
"on",
"(",
"\"click\"",
",",
"this",
",",
"function",
"(",
"e",
")",
"{",
"var",
"event",
"=",
"{",
"type",
":",
"'action'",
",",
"source",
":",
"self",
"}",
";",
"amino",
".",
"getCore",
"(",
")",
".",
"fireEvent",
"(",
"event",
")",
";",
"if",
"(",
"self",
".",
"actioncb",
")",
"self",
".",
"actioncb",
"(",
"event",
")",
";",
"}",
")",
";",
"this",
".",
"setFontSize",
"(",
"15",
")",
";",
"/** @func onAction(cb) a function to call when this button fires an action. You can also listen for the 'action' event. */",
"this",
".",
"onAction",
"=",
"function",
"(",
"cb",
")",
"{",
"this",
".",
"actioncb",
"=",
"cb",
";",
"return",
"this",
";",
"}",
"this",
".",
"markDirty",
"=",
"function",
"(",
")",
"{",
"this",
".",
"dirty",
"=",
"true",
";",
"amino",
".",
"dirtylist",
".",
"push",
"(",
"this",
")",
";",
"}",
"this",
".",
"doLayout",
"=",
"function",
"(",
")",
"{",
"var",
"textw",
"=",
"this",
".",
"comps",
".",
"label",
".",
"font",
".",
"calcStringWidth",
"(",
"this",
".",
"getText",
"(",
")",
",",
"this",
".",
"getFontSize",
"(",
")",
",",
"this",
".",
"getFontWeight",
"(",
")",
",",
"this",
".",
"getFontStyle",
"(",
")",
")",
";",
"this",
".",
"comps",
".",
"label",
".",
"setTx",
"(",
"Math",
".",
"round",
"(",
"(",
"this",
".",
"getW",
"(",
")",
"-",
"textw",
")",
"/",
"2",
")",
")",
";",
"var",
"texth",
"=",
"this",
".",
"comps",
".",
"label",
".",
"font",
".",
"getHeight",
"(",
"this",
".",
"getFontSize",
"(",
")",
",",
"this",
".",
"getFontWeight",
"(",
")",
",",
"this",
".",
"getFontStyle",
"(",
")",
")",
";",
"this",
".",
"comps",
".",
"label",
".",
"setTy",
"(",
"Math",
".",
"round",
"(",
"this",
".",
"getH",
"(",
")",
"/",
"2",
"+",
"texth",
"/",
"2",
")",
")",
";",
"}",
"this",
".",
"validate",
"=",
"function",
"(",
")",
"{",
"this",
".",
"doLayout",
"(",
")",
";",
"this",
".",
"dirty",
"=",
"false",
";",
"}",
"}"
]
| replaces all setters | [
"replaces",
"all",
"setters"
]
| bafc6567f3fc3f244d7bff3d6c980fd69750b663 | https://github.com/joshmarinacci/aminogfx/blob/bafc6567f3fc3f244d7bff3d6c980fd69750b663/src/widgets.js#L87-L124 |
|
41,313 | eivindfjeldstad/textarea-editor | src/editor.js | hasPrefix | function hasPrefix(text, prefix) {
let exp = new RegExp(`^${prefix.pattern}`);
let result = exp.test(text);
if (prefix.antipattern) {
let exp = new RegExp(`^${prefix.antipattern}`);
result = result && !exp.test(text);
}
return result;
} | javascript | function hasPrefix(text, prefix) {
let exp = new RegExp(`^${prefix.pattern}`);
let result = exp.test(text);
if (prefix.antipattern) {
let exp = new RegExp(`^${prefix.antipattern}`);
result = result && !exp.test(text);
}
return result;
} | [
"function",
"hasPrefix",
"(",
"text",
",",
"prefix",
")",
"{",
"let",
"exp",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
".",
"pattern",
"}",
"`",
")",
";",
"let",
"result",
"=",
"exp",
".",
"test",
"(",
"text",
")",
";",
"if",
"(",
"prefix",
".",
"antipattern",
")",
"{",
"let",
"exp",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
".",
"antipattern",
"}",
"`",
")",
";",
"result",
"=",
"result",
"&&",
"!",
"exp",
".",
"test",
"(",
"text",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Check if given prefix is present.
@private | [
"Check",
"if",
"given",
"prefix",
"is",
"present",
"."
]
| f3c0183291a014a82b5c7657c282bce727323da7 | https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L279-L289 |
41,314 | eivindfjeldstad/textarea-editor | src/editor.js | hasSuffix | function hasSuffix(text, suffix) {
let exp = new RegExp(`${suffix.pattern}$`);
let result = exp.test(text);
if (suffix.antipattern) {
let exp = new RegExp(`${suffix.antipattern}$`);
result = result && !exp.test(text);
}
return result;
} | javascript | function hasSuffix(text, suffix) {
let exp = new RegExp(`${suffix.pattern}$`);
let result = exp.test(text);
if (suffix.antipattern) {
let exp = new RegExp(`${suffix.antipattern}$`);
result = result && !exp.test(text);
}
return result;
} | [
"function",
"hasSuffix",
"(",
"text",
",",
"suffix",
")",
"{",
"let",
"exp",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"suffix",
".",
"pattern",
"}",
"`",
")",
";",
"let",
"result",
"=",
"exp",
".",
"test",
"(",
"text",
")",
";",
"if",
"(",
"suffix",
".",
"antipattern",
")",
"{",
"let",
"exp",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"suffix",
".",
"antipattern",
"}",
"`",
")",
";",
"result",
"=",
"result",
"&&",
"!",
"exp",
".",
"test",
"(",
"text",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Check if given suffix is present.
@private | [
"Check",
"if",
"given",
"suffix",
"is",
"present",
"."
]
| f3c0183291a014a82b5c7657c282bce727323da7 | https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L296-L306 |
41,315 | eivindfjeldstad/textarea-editor | src/editor.js | matchLength | function matchLength(text, exp) {
const match = text.match(exp);
return match ? match[0].length : 0;
} | javascript | function matchLength(text, exp) {
const match = text.match(exp);
return match ? match[0].length : 0;
} | [
"function",
"matchLength",
"(",
"text",
",",
"exp",
")",
"{",
"const",
"match",
"=",
"text",
".",
"match",
"(",
"exp",
")",
";",
"return",
"match",
"?",
"match",
"[",
"0",
"]",
".",
"length",
":",
"0",
";",
"}"
]
| Get length of match.
@private | [
"Get",
"length",
"of",
"match",
"."
]
| f3c0183291a014a82b5c7657c282bce727323da7 | https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L313-L316 |
41,316 | eivindfjeldstad/textarea-editor | src/editor.js | prefixLength | function prefixLength(text, prefix) {
const exp = new RegExp(`^${prefix.pattern}`);
return matchLength(text, exp);
} | javascript | function prefixLength(text, prefix) {
const exp = new RegExp(`^${prefix.pattern}`);
return matchLength(text, exp);
} | [
"function",
"prefixLength",
"(",
"text",
",",
"prefix",
")",
"{",
"const",
"exp",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"prefix",
".",
"pattern",
"}",
"`",
")",
";",
"return",
"matchLength",
"(",
"text",
",",
"exp",
")",
";",
"}"
]
| Get prefix length.
@private | [
"Get",
"prefix",
"length",
"."
]
| f3c0183291a014a82b5c7657c282bce727323da7 | https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L323-L326 |
41,317 | eivindfjeldstad/textarea-editor | src/editor.js | suffixLength | function suffixLength(text, suffix) {
let exp = new RegExp(`${suffix.pattern}$`);
return matchLength(text, exp);
} | javascript | function suffixLength(text, suffix) {
let exp = new RegExp(`${suffix.pattern}$`);
return matchLength(text, exp);
} | [
"function",
"suffixLength",
"(",
"text",
",",
"suffix",
")",
"{",
"let",
"exp",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"suffix",
".",
"pattern",
"}",
"`",
")",
";",
"return",
"matchLength",
"(",
"text",
",",
"exp",
")",
";",
"}"
]
| Get suffix length.
@private | [
"Get",
"suffix",
"length",
"."
]
| f3c0183291a014a82b5c7657c282bce727323da7 | https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L333-L336 |
41,318 | eivindfjeldstad/textarea-editor | src/editor.js | normalizeFormat | function normalizeFormat(format) {
const clone = Object.assign({}, format);
clone.prefix = normalizePrefixSuffix(format.prefix);
clone.suffix = normalizePrefixSuffix(format.suffix);
return clone;
} | javascript | function normalizeFormat(format) {
const clone = Object.assign({}, format);
clone.prefix = normalizePrefixSuffix(format.prefix);
clone.suffix = normalizePrefixSuffix(format.suffix);
return clone;
} | [
"function",
"normalizeFormat",
"(",
"format",
")",
"{",
"const",
"clone",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"format",
")",
";",
"clone",
".",
"prefix",
"=",
"normalizePrefixSuffix",
"(",
"format",
".",
"prefix",
")",
";",
"clone",
".",
"suffix",
"=",
"normalizePrefixSuffix",
"(",
"format",
".",
"suffix",
")",
";",
"return",
"clone",
";",
"}"
]
| Normalize format.
@private | [
"Normalize",
"format",
"."
]
| f3c0183291a014a82b5c7657c282bce727323da7 | https://github.com/eivindfjeldstad/textarea-editor/blob/f3c0183291a014a82b5c7657c282bce727323da7/src/editor.js#L352-L357 |
41,319 | joshmarinacci/aminogfx | demos/slideshow/slideshow.js | scaleImage | function scaleImage(img,prop,obj) {
var scale = Math.min(sw/img.w,sh/img.h);
obj.sx(scale).sy(scale);
} | javascript | function scaleImage(img,prop,obj) {
var scale = Math.min(sw/img.w,sh/img.h);
obj.sx(scale).sy(scale);
} | [
"function",
"scaleImage",
"(",
"img",
",",
"prop",
",",
"obj",
")",
"{",
"var",
"scale",
"=",
"Math",
".",
"min",
"(",
"sw",
"/",
"img",
".",
"w",
",",
"sh",
"/",
"img",
".",
"h",
")",
";",
"obj",
".",
"sx",
"(",
"scale",
")",
".",
"sy",
"(",
"scale",
")",
";",
"}"
]
| auto scale them | [
"auto",
"scale",
"them"
]
| bafc6567f3fc3f244d7bff3d6c980fd69750b663 | https://github.com/joshmarinacci/aminogfx/blob/bafc6567f3fc3f244d7bff3d6c980fd69750b663/demos/slideshow/slideshow.js#L50-L53 |
41,320 | joshmarinacci/aminogfx | demos/slideshow/slideshow.js | swap | function swap() {
iv1.x.anim().delay(1000).from(0).to(-sw).dur(3000).start();
iv2.x.anim().delay(1000).from(sw).to(0).dur(3000)
.then(afterAnim).start();
} | javascript | function swap() {
iv1.x.anim().delay(1000).from(0).to(-sw).dur(3000).start();
iv2.x.anim().delay(1000).from(sw).to(0).dur(3000)
.then(afterAnim).start();
} | [
"function",
"swap",
"(",
")",
"{",
"iv1",
".",
"x",
".",
"anim",
"(",
")",
".",
"delay",
"(",
"1000",
")",
".",
"from",
"(",
"0",
")",
".",
"to",
"(",
"-",
"sw",
")",
".",
"dur",
"(",
"3000",
")",
".",
"start",
"(",
")",
";",
"iv2",
".",
"x",
".",
"anim",
"(",
")",
".",
"delay",
"(",
"1000",
")",
".",
"from",
"(",
"sw",
")",
".",
"to",
"(",
"0",
")",
".",
"dur",
"(",
"3000",
")",
".",
"then",
"(",
"afterAnim",
")",
".",
"start",
"(",
")",
";",
"}"
]
| animate out and in | [
"animate",
"out",
"and",
"in"
]
| bafc6567f3fc3f244d7bff3d6c980fd69750b663 | https://github.com/joshmarinacci/aminogfx/blob/bafc6567f3fc3f244d7bff3d6c980fd69750b663/demos/slideshow/slideshow.js#L64-L68 |
41,321 | joshmarinacci/aminogfx | demos/adsr/adsr.js | updatePolys | function updatePolys() {
border.geometry([0,200,
adsr.a(),50,
adsr.d(),adsr.s(),
adsr.r(),adsr.s(),
300,200]);
aPoly.geometry([
0,200,
adsr.a(),50,
adsr.a(),200
]);
dPoly.geometry([
adsr.a(),200,
adsr.a(),50,
adsr.d(),adsr.s(),
adsr.d(),200,
]);
sPoly.geometry([
adsr.d(),200,
adsr.d(),adsr.s(),
adsr.r(),adsr.s(),
adsr.r(),200,
])
rPoly.geometry([
adsr.r(),200,
adsr.r(),adsr.s(),
300,200
]);
} | javascript | function updatePolys() {
border.geometry([0,200,
adsr.a(),50,
adsr.d(),adsr.s(),
adsr.r(),adsr.s(),
300,200]);
aPoly.geometry([
0,200,
adsr.a(),50,
adsr.a(),200
]);
dPoly.geometry([
adsr.a(),200,
adsr.a(),50,
adsr.d(),adsr.s(),
adsr.d(),200,
]);
sPoly.geometry([
adsr.d(),200,
adsr.d(),adsr.s(),
adsr.r(),adsr.s(),
adsr.r(),200,
])
rPoly.geometry([
adsr.r(),200,
adsr.r(),adsr.s(),
300,200
]);
} | [
"function",
"updatePolys",
"(",
")",
"{",
"border",
".",
"geometry",
"(",
"[",
"0",
",",
"200",
",",
"adsr",
".",
"a",
"(",
")",
",",
"50",
",",
"adsr",
".",
"d",
"(",
")",
",",
"adsr",
".",
"s",
"(",
")",
",",
"adsr",
".",
"r",
"(",
")",
",",
"adsr",
".",
"s",
"(",
")",
",",
"300",
",",
"200",
"]",
")",
";",
"aPoly",
".",
"geometry",
"(",
"[",
"0",
",",
"200",
",",
"adsr",
".",
"a",
"(",
")",
",",
"50",
",",
"adsr",
".",
"a",
"(",
")",
",",
"200",
"]",
")",
";",
"dPoly",
".",
"geometry",
"(",
"[",
"adsr",
".",
"a",
"(",
")",
",",
"200",
",",
"adsr",
".",
"a",
"(",
")",
",",
"50",
",",
"adsr",
".",
"d",
"(",
")",
",",
"adsr",
".",
"s",
"(",
")",
",",
"adsr",
".",
"d",
"(",
")",
",",
"200",
",",
"]",
")",
";",
"sPoly",
".",
"geometry",
"(",
"[",
"adsr",
".",
"d",
"(",
")",
",",
"200",
",",
"adsr",
".",
"d",
"(",
")",
",",
"adsr",
".",
"s",
"(",
")",
",",
"adsr",
".",
"r",
"(",
")",
",",
"adsr",
".",
"s",
"(",
")",
",",
"adsr",
".",
"r",
"(",
")",
",",
"200",
",",
"]",
")",
"rPoly",
".",
"geometry",
"(",
"[",
"adsr",
".",
"r",
"(",
")",
",",
"200",
",",
"adsr",
".",
"r",
"(",
")",
",",
"adsr",
".",
"s",
"(",
")",
",",
"300",
",",
"200",
"]",
")",
";",
"}"
]
| update the polygons when the model changes | [
"update",
"the",
"polygons",
"when",
"the",
"model",
"changes"
]
| bafc6567f3fc3f244d7bff3d6c980fd69750b663 | https://github.com/joshmarinacci/aminogfx/blob/bafc6567f3fc3f244d7bff3d6c980fd69750b663/demos/adsr/adsr.js#L48-L77 |
41,322 | nathanboktae/q-xhr | q-xhr.js | extend | function extend(dst) {
Array.prototype.forEach.call(arguments, function(obj) {
if (obj && obj !== dst) {
Object.keys(obj).forEach(function(key) {
dst[key] = obj[key]
})
}
})
return dst
} | javascript | function extend(dst) {
Array.prototype.forEach.call(arguments, function(obj) {
if (obj && obj !== dst) {
Object.keys(obj).forEach(function(key) {
dst[key] = obj[key]
})
}
})
return dst
} | [
"function",
"extend",
"(",
"dst",
")",
"{",
"Array",
".",
"prototype",
".",
"forEach",
".",
"call",
"(",
"arguments",
",",
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
"&&",
"obj",
"!==",
"dst",
")",
"{",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"dst",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
"}",
")",
"}",
"}",
")",
"return",
"dst",
"}"
]
| shallow extend with varargs | [
"shallow",
"extend",
"with",
"varargs"
]
| 40525e1871b8eec8a9ffaf8e222ede6ec5f389bd | https://github.com/nathanboktae/q-xhr/blob/40525e1871b8eec8a9ffaf8e222ede6ec5f389bd/q-xhr.js#L21-L31 |
41,323 | herrstucki/sprout | src/hasIn.js | hasIn | function hasIn(obj, keys) {
var k = keys[0],
ks = keys.slice(1);
if (ks.length) return !(k in obj) ? false : hasIn(obj[k], ks);
return (k in obj);
} | javascript | function hasIn(obj, keys) {
var k = keys[0],
ks = keys.slice(1);
if (ks.length) return !(k in obj) ? false : hasIn(obj[k], ks);
return (k in obj);
} | [
"function",
"hasIn",
"(",
"obj",
",",
"keys",
")",
"{",
"var",
"k",
"=",
"keys",
"[",
"0",
"]",
",",
"ks",
"=",
"keys",
".",
"slice",
"(",
"1",
")",
";",
"if",
"(",
"ks",
".",
"length",
")",
"return",
"!",
"(",
"k",
"in",
"obj",
")",
"?",
"false",
":",
"hasIn",
"(",
"obj",
"[",
"k",
"]",
",",
"ks",
")",
";",
"return",
"(",
"k",
"in",
"obj",
")",
";",
"}"
]
| Check if a nested property is present. Currently only used internally | [
"Check",
"if",
"a",
"nested",
"property",
"is",
"present",
".",
"Currently",
"only",
"used",
"internally"
]
| 9bb4697cdf6b84411e0e727683e032ee44b5dd83 | https://github.com/herrstucki/sprout/blob/9bb4697cdf6b84411e0e727683e032ee44b5dd83/src/hasIn.js#L3-L8 |
41,324 | herrstucki/sprout | src/getIn.js | getIn | function getIn(obj, keys, orValue) {
var k = keys[0],
ks = keys.slice(1);
return get(obj, k) && ks.length ? getIn(obj[k], ks, orValue) : get(obj, k, orValue);
} | javascript | function getIn(obj, keys, orValue) {
var k = keys[0],
ks = keys.slice(1);
return get(obj, k) && ks.length ? getIn(obj[k], ks, orValue) : get(obj, k, orValue);
} | [
"function",
"getIn",
"(",
"obj",
",",
"keys",
",",
"orValue",
")",
"{",
"var",
"k",
"=",
"keys",
"[",
"0",
"]",
",",
"ks",
"=",
"keys",
".",
"slice",
"(",
"1",
")",
";",
"return",
"get",
"(",
"obj",
",",
"k",
")",
"&&",
"ks",
".",
"length",
"?",
"getIn",
"(",
"obj",
"[",
"k",
"]",
",",
"ks",
",",
"orValue",
")",
":",
"get",
"(",
"obj",
",",
"k",
",",
"orValue",
")",
";",
"}"
]
| Get value from a nested structure or null. | [
"Get",
"value",
"from",
"a",
"nested",
"structure",
"or",
"null",
"."
]
| 9bb4697cdf6b84411e0e727683e032ee44b5dd83 | https://github.com/herrstucki/sprout/blob/9bb4697cdf6b84411e0e727683e032ee44b5dd83/src/getIn.js#L4-L8 |
41,325 | 75lb/array-tools | lib/array-tools.js | pluck | function pluck (recordset, property) {
recordset = arrayify(recordset)
var properties = arrayify(property)
return recordset
.map(function (record) {
for (var i = 0; i < properties.length; i++) {
var propValue = objectGet(record, properties[i])
if (propValue) return propValue
}
})
.filter(function (record) {
return typeof record !== 'undefined'
})
} | javascript | function pluck (recordset, property) {
recordset = arrayify(recordset)
var properties = arrayify(property)
return recordset
.map(function (record) {
for (var i = 0; i < properties.length; i++) {
var propValue = objectGet(record, properties[i])
if (propValue) return propValue
}
})
.filter(function (record) {
return typeof record !== 'undefined'
})
} | [
"function",
"pluck",
"(",
"recordset",
",",
"property",
")",
"{",
"recordset",
"=",
"arrayify",
"(",
"recordset",
")",
"var",
"properties",
"=",
"arrayify",
"(",
"property",
")",
"return",
"recordset",
".",
"map",
"(",
"function",
"(",
"record",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"properties",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"propValue",
"=",
"objectGet",
"(",
"record",
",",
"properties",
"[",
"i",
"]",
")",
"if",
"(",
"propValue",
")",
"return",
"propValue",
"}",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"record",
")",
"{",
"return",
"typeof",
"record",
"!==",
"'undefined'",
"}",
")",
"}"
]
| Returns an array containing each value plucked from the specified property of each object in the input array.
@param recordset {object[]} - The input recordset
@param property {string|string[]} - Property name, or an array of property names. If an array is supplied, the first existing property will be returned.
@returns {Array}
@category chainable
@static
@example
with this data..
```js
> var data = [
{ name: "Pavel", nick: "Pasha" },
{ name: "Richard", nick: "Dick" },
{ name: "Trevor" },
]
```
pluck all the nicknames
```js
> a.pluck(data, "nick")
[ 'Pasha', 'Dick' ]
```
in the case no nickname exists, take the name instead:
```js
> a.pluck(data, [ "nick", "name" ])
[ 'Pasha', 'Dick', 'Trevor' ]
```
the values being plucked can be at any depth:
```js
> var data = [
{ leeds: { leeds: { leeds: "we" } } },
{ leeds: { leeds: { leeds: "are" } } },
{ leeds: { leeds: { leeds: "Leeds" } } }
]
> a.pluck(data, "leeds.leeds.leeds")
[ 'we', 'are', 'Leeds' ]
``` | [
"Returns",
"an",
"array",
"containing",
"each",
"value",
"plucked",
"from",
"the",
"specified",
"property",
"of",
"each",
"object",
"in",
"the",
"input",
"array",
"."
]
| 0b0bc3db025ada4cc58c182b40a45ee641d27a87 | https://github.com/75lb/array-tools/blob/0b0bc3db025ada4cc58c182b40a45ee641d27a87/lib/array-tools.js#L289-L303 |
41,326 | 75lb/array-tools | lib/array-tools.js | spliceWhile | function spliceWhile (array, index, test) {
for (var i = 0; i < array.length; i++) {
if (!testValue(array[i], test)) break
}
var spliceArgs = [ index, i ]
spliceArgs = spliceArgs.concat(arrayify(arguments).slice(3))
return array.splice.apply(array, spliceArgs)
} | javascript | function spliceWhile (array, index, test) {
for (var i = 0; i < array.length; i++) {
if (!testValue(array[i], test)) break
}
var spliceArgs = [ index, i ]
spliceArgs = spliceArgs.concat(arrayify(arguments).slice(3))
return array.splice.apply(array, spliceArgs)
} | [
"function",
"spliceWhile",
"(",
"array",
",",
"index",
",",
"test",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"testValue",
"(",
"array",
"[",
"i",
"]",
",",
"test",
")",
")",
"break",
"}",
"var",
"spliceArgs",
"=",
"[",
"index",
",",
"i",
"]",
"spliceArgs",
"=",
"spliceArgs",
".",
"concat",
"(",
"arrayify",
"(",
"arguments",
")",
".",
"slice",
"(",
"3",
")",
")",
"return",
"array",
".",
"splice",
".",
"apply",
"(",
"array",
",",
"spliceArgs",
")",
"}"
]
| Splice items from the input array until the matching test fails. Returns an array containing the items removed.
@param array {Array} - the input array
@param index {number} - the position to begin splicing from
@param test {any} - the sequence of items passing this test will be removed
@param [elementN] {...*} - elements to add to the array in place
@returns {Array}
@category chainable
@static
@example
> function under10(n){ return n < 10; }
> numbers = [ 1, 2, 4, 6, 12 ]
> a.spliceWhile(numbers, 0, under10)
[ 1, 2, 4, 6 ]
> numbers
[ 12 ]
> countries = [ "Egypt", "Ethiopia", "France", "Argentina" ]
> a.spliceWhile(countries, 0, /^e/i)
[ 'Egypt', 'Ethiopia' ]
> countries
[ 'France', 'Argentina' ] | [
"Splice",
"items",
"from",
"the",
"input",
"array",
"until",
"the",
"matching",
"test",
"fails",
".",
"Returns",
"an",
"array",
"containing",
"the",
"items",
"removed",
"."
]
| 0b0bc3db025ada4cc58c182b40a45ee641d27a87 | https://github.com/75lb/array-tools/blob/0b0bc3db025ada4cc58c182b40a45ee641d27a87/lib/array-tools.js#L434-L441 |
41,327 | sazze/node-pm | lib/clusterEvents.js | forkTimeoutHandler | function forkTimeoutHandler(worker, cluster) {
verbose('worker %d is stuck in fork', worker.process.pid);
if (!cluster.workers[worker.id]) {
return;
}
// something is wrong with this worker. Kill it!
master.suicideOverrides[worker.id] = worker.id;
master.isRunning(worker, function(running) {
if (!running) {
return;
}
try {
debug('sending SIGKILL to worker %d', worker.process.pid);
process.kill(worker.process.pid, 'SIGKILL');
} catch (e) {
// this can happen. don't crash!!
}
});
} | javascript | function forkTimeoutHandler(worker, cluster) {
verbose('worker %d is stuck in fork', worker.process.pid);
if (!cluster.workers[worker.id]) {
return;
}
// something is wrong with this worker. Kill it!
master.suicideOverrides[worker.id] = worker.id;
master.isRunning(worker, function(running) {
if (!running) {
return;
}
try {
debug('sending SIGKILL to worker %d', worker.process.pid);
process.kill(worker.process.pid, 'SIGKILL');
} catch (e) {
// this can happen. don't crash!!
}
});
} | [
"function",
"forkTimeoutHandler",
"(",
"worker",
",",
"cluster",
")",
"{",
"verbose",
"(",
"'worker %d is stuck in fork'",
",",
"worker",
".",
"process",
".",
"pid",
")",
";",
"if",
"(",
"!",
"cluster",
".",
"workers",
"[",
"worker",
".",
"id",
"]",
")",
"{",
"return",
";",
"}",
"// something is wrong with this worker. Kill it!",
"master",
".",
"suicideOverrides",
"[",
"worker",
".",
"id",
"]",
"=",
"worker",
".",
"id",
";",
"master",
".",
"isRunning",
"(",
"worker",
",",
"function",
"(",
"running",
")",
"{",
"if",
"(",
"!",
"running",
")",
"{",
"return",
";",
"}",
"try",
"{",
"debug",
"(",
"'sending SIGKILL to worker %d'",
",",
"worker",
".",
"process",
".",
"pid",
")",
";",
"process",
".",
"kill",
"(",
"worker",
".",
"process",
".",
"pid",
",",
"'SIGKILL'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// this can happen. don't crash!!",
"}",
"}",
")",
";",
"}"
]
| Called when worker takes too long to fork
@private
@param worker
@param cluster | [
"Called",
"when",
"worker",
"takes",
"too",
"long",
"to",
"fork"
]
| d2f1348cb0446e98dcf873e319b55ce89f79b386 | https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/clusterEvents.js#L155-L177 |
41,328 | sazze/node-pm | lib/clusterEvents.js | disconnectTimeoutHandler | function disconnectTimeoutHandler(worker, cluster) {
verbose('worker %d is stuck in disconnect', worker.process.pid);
// if this is not a suicide we need to preserve that as worker.kill() will make this a suicide
if (!worker.suicide) {
master.suicideOverrides[worker.id] = worker.id;
}
master.isRunning(worker, function(running) {
if (!running) {
return;
}
try {
debug('sending SIGKILL to worker %d', worker.process.pid);
process.kill(worker.process.pid, 'SIGKILL');
} catch (e) {
// this can happen. don't crash!!
}
});
} | javascript | function disconnectTimeoutHandler(worker, cluster) {
verbose('worker %d is stuck in disconnect', worker.process.pid);
// if this is not a suicide we need to preserve that as worker.kill() will make this a suicide
if (!worker.suicide) {
master.suicideOverrides[worker.id] = worker.id;
}
master.isRunning(worker, function(running) {
if (!running) {
return;
}
try {
debug('sending SIGKILL to worker %d', worker.process.pid);
process.kill(worker.process.pid, 'SIGKILL');
} catch (e) {
// this can happen. don't crash!!
}
});
} | [
"function",
"disconnectTimeoutHandler",
"(",
"worker",
",",
"cluster",
")",
"{",
"verbose",
"(",
"'worker %d is stuck in disconnect'",
",",
"worker",
".",
"process",
".",
"pid",
")",
";",
"// if this is not a suicide we need to preserve that as worker.kill() will make this a suicide",
"if",
"(",
"!",
"worker",
".",
"suicide",
")",
"{",
"master",
".",
"suicideOverrides",
"[",
"worker",
".",
"id",
"]",
"=",
"worker",
".",
"id",
";",
"}",
"master",
".",
"isRunning",
"(",
"worker",
",",
"function",
"(",
"running",
")",
"{",
"if",
"(",
"!",
"running",
")",
"{",
"return",
";",
"}",
"try",
"{",
"debug",
"(",
"'sending SIGKILL to worker %d'",
",",
"worker",
".",
"process",
".",
"pid",
")",
";",
"process",
".",
"kill",
"(",
"worker",
".",
"process",
".",
"pid",
",",
"'SIGKILL'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// this can happen. don't crash!!",
"}",
"}",
")",
";",
"}"
]
| Called when worker is taking too long to disconnect
@private
@param worker
@param cluster | [
"Called",
"when",
"worker",
"is",
"taking",
"too",
"long",
"to",
"disconnect"
]
| d2f1348cb0446e98dcf873e319b55ce89f79b386 | https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/clusterEvents.js#L186-L206 |
41,329 | hapticdata/animitter | index.js | makeThrottle | function makeThrottle(fps){
var delay = 1000/fps;
var lastTime = Date.now();
if( fps<=0 || fps === Infinity ){
return returnTrue;
}
//if an fps throttle has been set then we'll assume
//it natively runs at 60fps,
var half = Math.ceil(1000 / 60) / 2;
return function(){
//if a custom fps is requested
var now = Date.now();
//is this frame within 8.5ms of the target?
//if so then next frame is gonna be too late
if(now - lastTime < delay - half){
return false;
}
lastTime = now;
return true;
};
} | javascript | function makeThrottle(fps){
var delay = 1000/fps;
var lastTime = Date.now();
if( fps<=0 || fps === Infinity ){
return returnTrue;
}
//if an fps throttle has been set then we'll assume
//it natively runs at 60fps,
var half = Math.ceil(1000 / 60) / 2;
return function(){
//if a custom fps is requested
var now = Date.now();
//is this frame within 8.5ms of the target?
//if so then next frame is gonna be too late
if(now - lastTime < delay - half){
return false;
}
lastTime = now;
return true;
};
} | [
"function",
"makeThrottle",
"(",
"fps",
")",
"{",
"var",
"delay",
"=",
"1000",
"/",
"fps",
";",
"var",
"lastTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"if",
"(",
"fps",
"<=",
"0",
"||",
"fps",
"===",
"Infinity",
")",
"{",
"return",
"returnTrue",
";",
"}",
"//if an fps throttle has been set then we'll assume",
"//it natively runs at 60fps,",
"var",
"half",
"=",
"Math",
".",
"ceil",
"(",
"1000",
"/",
"60",
")",
"/",
"2",
";",
"return",
"function",
"(",
")",
"{",
"//if a custom fps is requested",
"var",
"now",
"=",
"Date",
".",
"now",
"(",
")",
";",
"//is this frame within 8.5ms of the target?",
"//if so then next frame is gonna be too late",
"if",
"(",
"now",
"-",
"lastTime",
"<",
"delay",
"-",
"half",
")",
"{",
"return",
"false",
";",
"}",
"lastTime",
"=",
"now",
";",
"return",
"true",
";",
"}",
";",
"}"
]
| manage FPS if < 60, else return true; | [
"manage",
"FPS",
"if",
"<",
"60",
"else",
"return",
"true",
";"
]
| 4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e | https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L16-L40 |
41,330 | hapticdata/animitter | index.js | Animitter | function Animitter( opts ){
opts = opts || {};
this.__delay = opts.delay || 0;
/** @expose */
this.fixedDelta = !!opts.fixedDelta;
/** @expose */
this.frameCount = 0;
/** @expose */
this.deltaTime = 0;
/** @expose */
this.elapsedTime = 0;
/** @private */
this.__running = false;
/** @private */
this.__completed = false;
this.setFPS(opts.fps || Infinity);
this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject);
} | javascript | function Animitter( opts ){
opts = opts || {};
this.__delay = opts.delay || 0;
/** @expose */
this.fixedDelta = !!opts.fixedDelta;
/** @expose */
this.frameCount = 0;
/** @expose */
this.deltaTime = 0;
/** @expose */
this.elapsedTime = 0;
/** @private */
this.__running = false;
/** @private */
this.__completed = false;
this.setFPS(opts.fps || Infinity);
this.setRequestAnimationFrameObject(opts.requestAnimationFrameObject || defaultRAFObject);
} | [
"function",
"Animitter",
"(",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"__delay",
"=",
"opts",
".",
"delay",
"||",
"0",
";",
"/** @expose */",
"this",
".",
"fixedDelta",
"=",
"!",
"!",
"opts",
".",
"fixedDelta",
";",
"/** @expose */",
"this",
".",
"frameCount",
"=",
"0",
";",
"/** @expose */",
"this",
".",
"deltaTime",
"=",
"0",
";",
"/** @expose */",
"this",
".",
"elapsedTime",
"=",
"0",
";",
"/** @private */",
"this",
".",
"__running",
"=",
"false",
";",
"/** @private */",
"this",
".",
"__completed",
"=",
"false",
";",
"this",
".",
"setFPS",
"(",
"opts",
".",
"fps",
"||",
"Infinity",
")",
";",
"this",
".",
"setRequestAnimationFrameObject",
"(",
"opts",
".",
"requestAnimationFrameObject",
"||",
"defaultRAFObject",
")",
";",
"}"
]
| Animitter provides event-based loops for the browser and node,
using `requestAnimationFrame`
@param {Object} [opts]
@param {Number} [opts.fps=Infinity] the framerate requested, defaults to as fast as it can (60fps on window)
@param {Number} [opts.delay=0] milliseconds delay between invoking `start` and initializing the loop
@param {Object} [opts.requestAnimationFrameObject=global] the object on which to find `requestAnimationFrame` and `cancelAnimationFrame` methods
@param {Boolean} [opts.fixedDelta=false] if true, timestamps will pretend to be executed at fixed intervals always
@constructor | [
"Animitter",
"provides",
"event",
"-",
"based",
"loops",
"for",
"the",
"browser",
"and",
"node",
"using",
"requestAnimationFrame"
]
| 4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e | https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L53-L75 |
41,331 | hapticdata/animitter | index.js | function(){
this.frameCount++;
/** @private */
var now = Date.now();
this.__lastTime = this.__lastTime || now;
this.deltaTime = (this.fixedDelta || exports.globalFixedDelta) ? 1000/Math.min(60, this.__fps) : now - this.__lastTime;
this.elapsedTime += this.deltaTime;
this.__lastTime = now;
this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount);
return this;
} | javascript | function(){
this.frameCount++;
/** @private */
var now = Date.now();
this.__lastTime = this.__lastTime || now;
this.deltaTime = (this.fixedDelta || exports.globalFixedDelta) ? 1000/Math.min(60, this.__fps) : now - this.__lastTime;
this.elapsedTime += this.deltaTime;
this.__lastTime = now;
this.emit('update', this.deltaTime, this.elapsedTime, this.frameCount);
return this;
} | [
"function",
"(",
")",
"{",
"this",
".",
"frameCount",
"++",
";",
"/** @private */",
"var",
"now",
"=",
"Date",
".",
"now",
"(",
")",
";",
"this",
".",
"__lastTime",
"=",
"this",
".",
"__lastTime",
"||",
"now",
";",
"this",
".",
"deltaTime",
"=",
"(",
"this",
".",
"fixedDelta",
"||",
"exports",
".",
"globalFixedDelta",
")",
"?",
"1000",
"/",
"Math",
".",
"min",
"(",
"60",
",",
"this",
".",
"__fps",
")",
":",
"now",
"-",
"this",
".",
"__lastTime",
";",
"this",
".",
"elapsedTime",
"+=",
"this",
".",
"deltaTime",
";",
"this",
".",
"__lastTime",
"=",
"now",
";",
"this",
".",
"emit",
"(",
"'update'",
",",
"this",
".",
"deltaTime",
",",
"this",
".",
"elapsedTime",
",",
"this",
".",
"frameCount",
")",
";",
"return",
"this",
";",
"}"
]
| update the animation loop once
@emit Animitter#update
@return {Animitter} | [
"update",
"the",
"animation",
"loop",
"once"
]
| 4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e | https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L311-L322 |
|
41,332 | hapticdata/animitter | index.js | createAnimitter | function createAnimitter(options, fn){
if( arguments.length === 1 && typeof options === 'function'){
fn = options;
options = {};
}
var _instance = new Animitter( options );
if( fn ){
_instance.on('update', fn);
}
return _instance;
} | javascript | function createAnimitter(options, fn){
if( arguments.length === 1 && typeof options === 'function'){
fn = options;
options = {};
}
var _instance = new Animitter( options );
if( fn ){
_instance.on('update', fn);
}
return _instance;
} | [
"function",
"createAnimitter",
"(",
"options",
",",
"fn",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
"&&",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"fn",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"var",
"_instance",
"=",
"new",
"Animitter",
"(",
"options",
")",
";",
"if",
"(",
"fn",
")",
"{",
"_instance",
".",
"on",
"(",
"'update'",
",",
"fn",
")",
";",
"}",
"return",
"_instance",
";",
"}"
]
| create an animitter instance,
@param {Object} [options]
@param {Function} fn( deltaTime:Number, elapsedTime:Number, frameCount:Number )
@returns {Animitter} | [
"create",
"an",
"animitter",
"instance"
]
| 4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e | https://github.com/hapticdata/animitter/blob/4488a9e3ac8e3bf04ea09f6b253b00c3f8701d6e/index.js#L338-L352 |
41,333 | sazze/node-pm | lib/master.js | fork | function fork(number) {
var numProc = number || require('os').cpus().length;
config.n = numProc;
debug('forking %d workers', numProc);
forkLoopProtect();
for (var i = 0; i < numProc; i++) {
cluster.fork({PWD: config.CWD});
}
} | javascript | function fork(number) {
var numProc = number || require('os').cpus().length;
config.n = numProc;
debug('forking %d workers', numProc);
forkLoopProtect();
for (var i = 0; i < numProc; i++) {
cluster.fork({PWD: config.CWD});
}
} | [
"function",
"fork",
"(",
"number",
")",
"{",
"var",
"numProc",
"=",
"number",
"||",
"require",
"(",
"'os'",
")",
".",
"cpus",
"(",
")",
".",
"length",
";",
"config",
".",
"n",
"=",
"numProc",
";",
"debug",
"(",
"'forking %d workers'",
",",
"numProc",
")",
";",
"forkLoopProtect",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numProc",
";",
"i",
"++",
")",
"{",
"cluster",
".",
"fork",
"(",
"{",
"PWD",
":",
"config",
".",
"CWD",
"}",
")",
";",
"}",
"}"
]
| Fork Workers N times
@private
@param {int} [number=cpus.length] the number of processes to start | [
"Fork",
"Workers",
"N",
"times"
]
| d2f1348cb0446e98dcf873e319b55ce89f79b386 | https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/master.js#L339-L351 |
41,334 | sazze/node-pm | lib/master.js | lifecycleTimeoutHandler | function lifecycleTimeoutHandler() {
if (shutdownCalled) {
return;
}
verbose('workers have reached the end of their life');
master.restart(function () {
if (!shutdownCalled) {
lifecycleTimer = setTimeout(lifecycleTimeoutHandler.bind(master), config.timeouts.maxAge);
}
});
} | javascript | function lifecycleTimeoutHandler() {
if (shutdownCalled) {
return;
}
verbose('workers have reached the end of their life');
master.restart(function () {
if (!shutdownCalled) {
lifecycleTimer = setTimeout(lifecycleTimeoutHandler.bind(master), config.timeouts.maxAge);
}
});
} | [
"function",
"lifecycleTimeoutHandler",
"(",
")",
"{",
"if",
"(",
"shutdownCalled",
")",
"{",
"return",
";",
"}",
"verbose",
"(",
"'workers have reached the end of their life'",
")",
";",
"master",
".",
"restart",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"shutdownCalled",
")",
"{",
"lifecycleTimer",
"=",
"setTimeout",
"(",
"lifecycleTimeoutHandler",
".",
"bind",
"(",
"master",
")",
",",
"config",
".",
"timeouts",
".",
"maxAge",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Called when workers have reached the end of their lifespan
@private | [
"Called",
"when",
"workers",
"have",
"reached",
"the",
"end",
"of",
"their",
"lifespan"
]
| d2f1348cb0446e98dcf873e319b55ce89f79b386 | https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/master.js#L358-L370 |
41,335 | snatalenko/node-cqrs | src/Observer.js | subscribe | function subscribe(observable, observer, options) {
if (typeof observable !== 'object' || !observable)
throw new TypeError('observable argument must be an Object');
if (typeof observable.on !== 'function')
throw new TypeError('observable.on must be a Function');
if (typeof observer !== 'object' || !observer)
throw new TypeError('observer argument must be an Object');
const { masterHandler, messageTypes, queueName } = options;
if (masterHandler && typeof masterHandler !== 'function')
throw new TypeError('masterHandler parameter, when provided, must be a Function');
if (queueName && typeof observable.queue !== 'function')
throw new TypeError('observable.queue, when queueName is specified, must be a Function');
const subscribeTo = messageTypes
|| observer.handles
|| Object.getPrototypeOf(observer).constructor.handles;
if (!Array.isArray(subscribeTo))
throw new TypeError('either options.messageTypes, observer.handles or ObserverType.handles is required');
unique(subscribeTo).forEach(messageType => {
const handler = masterHandler || getHandler(observer, messageType);
if (!handler)
throw new Error(`'${messageType}' handler is not defined or not a function`);
if (queueName)
observable.queue(queueName).on(messageType, handler.bind(observer));
else
observable.on(messageType, handler.bind(observer));
});
} | javascript | function subscribe(observable, observer, options) {
if (typeof observable !== 'object' || !observable)
throw new TypeError('observable argument must be an Object');
if (typeof observable.on !== 'function')
throw new TypeError('observable.on must be a Function');
if (typeof observer !== 'object' || !observer)
throw new TypeError('observer argument must be an Object');
const { masterHandler, messageTypes, queueName } = options;
if (masterHandler && typeof masterHandler !== 'function')
throw new TypeError('masterHandler parameter, when provided, must be a Function');
if (queueName && typeof observable.queue !== 'function')
throw new TypeError('observable.queue, when queueName is specified, must be a Function');
const subscribeTo = messageTypes
|| observer.handles
|| Object.getPrototypeOf(observer).constructor.handles;
if (!Array.isArray(subscribeTo))
throw new TypeError('either options.messageTypes, observer.handles or ObserverType.handles is required');
unique(subscribeTo).forEach(messageType => {
const handler = masterHandler || getHandler(observer, messageType);
if (!handler)
throw new Error(`'${messageType}' handler is not defined or not a function`);
if (queueName)
observable.queue(queueName).on(messageType, handler.bind(observer));
else
observable.on(messageType, handler.bind(observer));
});
} | [
"function",
"subscribe",
"(",
"observable",
",",
"observer",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"observable",
"!==",
"'object'",
"||",
"!",
"observable",
")",
"throw",
"new",
"TypeError",
"(",
"'observable argument must be an Object'",
")",
";",
"if",
"(",
"typeof",
"observable",
".",
"on",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'observable.on must be a Function'",
")",
";",
"if",
"(",
"typeof",
"observer",
"!==",
"'object'",
"||",
"!",
"observer",
")",
"throw",
"new",
"TypeError",
"(",
"'observer argument must be an Object'",
")",
";",
"const",
"{",
"masterHandler",
",",
"messageTypes",
",",
"queueName",
"}",
"=",
"options",
";",
"if",
"(",
"masterHandler",
"&&",
"typeof",
"masterHandler",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'masterHandler parameter, when provided, must be a Function'",
")",
";",
"if",
"(",
"queueName",
"&&",
"typeof",
"observable",
".",
"queue",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'observable.queue, when queueName is specified, must be a Function'",
")",
";",
"const",
"subscribeTo",
"=",
"messageTypes",
"||",
"observer",
".",
"handles",
"||",
"Object",
".",
"getPrototypeOf",
"(",
"observer",
")",
".",
"constructor",
".",
"handles",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"subscribeTo",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'either options.messageTypes, observer.handles or ObserverType.handles is required'",
")",
";",
"unique",
"(",
"subscribeTo",
")",
".",
"forEach",
"(",
"messageType",
"=>",
"{",
"const",
"handler",
"=",
"masterHandler",
"||",
"getHandler",
"(",
"observer",
",",
"messageType",
")",
";",
"if",
"(",
"!",
"handler",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"messageType",
"}",
"`",
")",
";",
"if",
"(",
"queueName",
")",
"observable",
".",
"queue",
"(",
"queueName",
")",
".",
"on",
"(",
"messageType",
",",
"handler",
".",
"bind",
"(",
"observer",
")",
")",
";",
"else",
"observable",
".",
"on",
"(",
"messageType",
",",
"handler",
".",
"bind",
"(",
"observer",
")",
")",
";",
"}",
")",
";",
"}"
]
| Subscribe observer to observable
@param {IObservable} observable
@param {IObserver} observer
@param {TSubscribeOptions} [options] | [
"Subscribe",
"observer",
"to",
"observable"
]
| 32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c | https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/Observer.js#L14-L44 |
41,336 | battlejj/recursive-readdir-sync | index.js | recursiveReaddirSync | function recursiveReaddirSync(path) {
var list = []
, files = fs.readdirSync(path)
, stats
;
files.forEach(function (file) {
stats = fs.lstatSync(p.join(path, file));
if(stats.isDirectory()) {
list = list.concat(recursiveReaddirSync(p.join(path, file)));
} else {
list.push(p.join(path, file));
}
});
return list;
} | javascript | function recursiveReaddirSync(path) {
var list = []
, files = fs.readdirSync(path)
, stats
;
files.forEach(function (file) {
stats = fs.lstatSync(p.join(path, file));
if(stats.isDirectory()) {
list = list.concat(recursiveReaddirSync(p.join(path, file)));
} else {
list.push(p.join(path, file));
}
});
return list;
} | [
"function",
"recursiveReaddirSync",
"(",
"path",
")",
"{",
"var",
"list",
"=",
"[",
"]",
",",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"path",
")",
",",
"stats",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"stats",
"=",
"fs",
".",
"lstatSync",
"(",
"p",
".",
"join",
"(",
"path",
",",
"file",
")",
")",
";",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"list",
"=",
"list",
".",
"concat",
"(",
"recursiveReaddirSync",
"(",
"p",
".",
"join",
"(",
"path",
",",
"file",
")",
")",
")",
";",
"}",
"else",
"{",
"list",
".",
"push",
"(",
"p",
".",
"join",
"(",
"path",
",",
"file",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"list",
";",
"}"
]
| how to know when you are done? | [
"how",
"to",
"know",
"when",
"you",
"are",
"done?"
]
| 77b9b005c95128252f9f4a8a17a8318c0219e7c3 | https://github.com/battlejj/recursive-readdir-sync/blob/77b9b005c95128252f9f4a8a17a8318c0219e7c3/index.js#L6-L22 |
41,337 | snatalenko/node-cqrs | src/EventStore.js | validateEvent | function validateEvent(event) {
if (typeof event !== 'object' || !event) throw new TypeError('event must be an Object');
if (typeof event.type !== 'string' || !event.type.length) throw new TypeError('event.type must be a non-empty String');
if (!event.aggregateId && !event.sagaId) throw new TypeError('either event.aggregateId or event.sagaId is required');
if (event.sagaId && typeof event.sagaVersion === 'undefined') throw new TypeError('event.sagaVersion is required, when event.sagaId is defined');
} | javascript | function validateEvent(event) {
if (typeof event !== 'object' || !event) throw new TypeError('event must be an Object');
if (typeof event.type !== 'string' || !event.type.length) throw new TypeError('event.type must be a non-empty String');
if (!event.aggregateId && !event.sagaId) throw new TypeError('either event.aggregateId or event.sagaId is required');
if (event.sagaId && typeof event.sagaVersion === 'undefined') throw new TypeError('event.sagaVersion is required, when event.sagaId is defined');
} | [
"function",
"validateEvent",
"(",
"event",
")",
"{",
"if",
"(",
"typeof",
"event",
"!==",
"'object'",
"||",
"!",
"event",
")",
"throw",
"new",
"TypeError",
"(",
"'event must be an Object'",
")",
";",
"if",
"(",
"typeof",
"event",
".",
"type",
"!==",
"'string'",
"||",
"!",
"event",
".",
"type",
".",
"length",
")",
"throw",
"new",
"TypeError",
"(",
"'event.type must be a non-empty String'",
")",
";",
"if",
"(",
"!",
"event",
".",
"aggregateId",
"&&",
"!",
"event",
".",
"sagaId",
")",
"throw",
"new",
"TypeError",
"(",
"'either event.aggregateId or event.sagaId is required'",
")",
";",
"if",
"(",
"event",
".",
"sagaId",
"&&",
"typeof",
"event",
".",
"sagaVersion",
"===",
"'undefined'",
")",
"throw",
"new",
"TypeError",
"(",
"'event.sagaVersion is required, when event.sagaId is defined'",
")",
";",
"}"
]
| Validate event structure
@param {IEvent} event | [
"Validate",
"event",
"structure"
]
| 32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c | https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L19-L24 |
41,338 | snatalenko/node-cqrs | src/EventStore.js | validateEventStorage | function validateEventStorage(storage) {
if (!storage) throw new TypeError('storage argument required');
if (typeof storage !== 'object') throw new TypeError('storage argument must be an Object');
if (typeof storage.commitEvents !== 'function') throw new TypeError('storage.commitEvents must be a Function');
if (typeof storage.getEvents !== 'function') throw new TypeError('storage.getEvents must be a Function');
if (typeof storage.getAggregateEvents !== 'function') throw new TypeError('storage.getAggregateEvents must be a Function');
if (typeof storage.getSagaEvents !== 'function') throw new TypeError('storage.getSagaEvents must be a Function');
if (typeof storage.getNewId !== 'function') throw new TypeError('storage.getNewId must be a Function');
} | javascript | function validateEventStorage(storage) {
if (!storage) throw new TypeError('storage argument required');
if (typeof storage !== 'object') throw new TypeError('storage argument must be an Object');
if (typeof storage.commitEvents !== 'function') throw new TypeError('storage.commitEvents must be a Function');
if (typeof storage.getEvents !== 'function') throw new TypeError('storage.getEvents must be a Function');
if (typeof storage.getAggregateEvents !== 'function') throw new TypeError('storage.getAggregateEvents must be a Function');
if (typeof storage.getSagaEvents !== 'function') throw new TypeError('storage.getSagaEvents must be a Function');
if (typeof storage.getNewId !== 'function') throw new TypeError('storage.getNewId must be a Function');
} | [
"function",
"validateEventStorage",
"(",
"storage",
")",
"{",
"if",
"(",
"!",
"storage",
")",
"throw",
"new",
"TypeError",
"(",
"'storage argument required'",
")",
";",
"if",
"(",
"typeof",
"storage",
"!==",
"'object'",
")",
"throw",
"new",
"TypeError",
"(",
"'storage argument must be an Object'",
")",
";",
"if",
"(",
"typeof",
"storage",
".",
"commitEvents",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'storage.commitEvents must be a Function'",
")",
";",
"if",
"(",
"typeof",
"storage",
".",
"getEvents",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'storage.getEvents must be a Function'",
")",
";",
"if",
"(",
"typeof",
"storage",
".",
"getAggregateEvents",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'storage.getAggregateEvents must be a Function'",
")",
";",
"if",
"(",
"typeof",
"storage",
".",
"getSagaEvents",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'storage.getSagaEvents must be a Function'",
")",
";",
"if",
"(",
"typeof",
"storage",
".",
"getNewId",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'storage.getNewId must be a Function'",
")",
";",
"}"
]
| Ensure provided eventStorage matches the expected format
@param {IEventStorage} storage | [
"Ensure",
"provided",
"eventStorage",
"matches",
"the",
"expected",
"format"
]
| 32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c | https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L30-L38 |
41,339 | snatalenko/node-cqrs | src/EventStore.js | validateSnapshotStorage | function validateSnapshotStorage(snapshotStorage) {
if (typeof snapshotStorage !== 'object' || !snapshotStorage)
throw new TypeError('snapshotStorage argument must be an Object');
if (typeof snapshotStorage.getAggregateSnapshot !== 'function')
throw new TypeError('snapshotStorage.getAggregateSnapshot argument must be a Function');
if (typeof snapshotStorage.saveAggregateSnapshot !== 'function')
throw new TypeError('snapshotStorage.saveAggregateSnapshot argument must be a Function');
} | javascript | function validateSnapshotStorage(snapshotStorage) {
if (typeof snapshotStorage !== 'object' || !snapshotStorage)
throw new TypeError('snapshotStorage argument must be an Object');
if (typeof snapshotStorage.getAggregateSnapshot !== 'function')
throw new TypeError('snapshotStorage.getAggregateSnapshot argument must be a Function');
if (typeof snapshotStorage.saveAggregateSnapshot !== 'function')
throw new TypeError('snapshotStorage.saveAggregateSnapshot argument must be a Function');
} | [
"function",
"validateSnapshotStorage",
"(",
"snapshotStorage",
")",
"{",
"if",
"(",
"typeof",
"snapshotStorage",
"!==",
"'object'",
"||",
"!",
"snapshotStorage",
")",
"throw",
"new",
"TypeError",
"(",
"'snapshotStorage argument must be an Object'",
")",
";",
"if",
"(",
"typeof",
"snapshotStorage",
".",
"getAggregateSnapshot",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'snapshotStorage.getAggregateSnapshot argument must be a Function'",
")",
";",
"if",
"(",
"typeof",
"snapshotStorage",
".",
"saveAggregateSnapshot",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'snapshotStorage.saveAggregateSnapshot argument must be a Function'",
")",
";",
"}"
]
| Ensure snapshotStorage matches the expected format
@param {IAggregateSnapshotStorage} snapshotStorage | [
"Ensure",
"snapshotStorage",
"matches",
"the",
"expected",
"format"
]
| 32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c | https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L54-L61 |
41,340 | snatalenko/node-cqrs | src/EventStore.js | validateMessageBus | function validateMessageBus(messageBus) {
if (typeof messageBus !== 'object' || !messageBus)
throw new TypeError('messageBus argument must be an Object');
if (typeof messageBus.on !== 'function')
throw new TypeError('messageBus.on argument must be a Function');
if (typeof messageBus.publish !== 'function')
throw new TypeError('messageBus.publish argument must be a Function');
} | javascript | function validateMessageBus(messageBus) {
if (typeof messageBus !== 'object' || !messageBus)
throw new TypeError('messageBus argument must be an Object');
if (typeof messageBus.on !== 'function')
throw new TypeError('messageBus.on argument must be a Function');
if (typeof messageBus.publish !== 'function')
throw new TypeError('messageBus.publish argument must be a Function');
} | [
"function",
"validateMessageBus",
"(",
"messageBus",
")",
"{",
"if",
"(",
"typeof",
"messageBus",
"!==",
"'object'",
"||",
"!",
"messageBus",
")",
"throw",
"new",
"TypeError",
"(",
"'messageBus argument must be an Object'",
")",
";",
"if",
"(",
"typeof",
"messageBus",
".",
"on",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'messageBus.on argument must be a Function'",
")",
";",
"if",
"(",
"typeof",
"messageBus",
".",
"publish",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'messageBus.publish argument must be a Function'",
")",
";",
"}"
]
| Ensure messageBus matches the expected format
@param {IMessageBus} messageBus | [
"Ensure",
"messageBus",
"matches",
"the",
"expected",
"format"
]
| 32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c | https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L67-L74 |
41,341 | snatalenko/node-cqrs | src/EventStore.js | setupOneTimeEmitterSubscription | function setupOneTimeEmitterSubscription(emitter, messageTypes, filter, handler) {
if (typeof emitter !== 'object' || !emitter)
throw new TypeError('emitter argument must be an Object');
if (!Array.isArray(messageTypes) || messageTypes.some(m => !m || typeof m !== 'string'))
throw new TypeError('messageTypes argument must be an Array of non-empty Strings');
if (handler && typeof handler !== 'function')
throw new TypeError('handler argument, when specified, must be a Function');
if (filter && typeof filter !== 'function')
throw new TypeError('filter argument, when specified, must be a Function');
return new Promise(resolve => {
// handler will be invoked only once,
// even if multiple events have been emitted before subscription was destroyed
// https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener
let handled = false;
function filteredHandler(event) {
if (filter && !filter(event)) return;
if (handled) return;
handled = true;
for (const messageType of messageTypes)
emitter.off(messageType, filteredHandler);
debug('\'%s\' received, one-time subscription to \'%s\' removed', event.type, messageTypes.join(','));
if (handler)
handler(event);
resolve(event);
}
for (const messageType of messageTypes)
emitter.on(messageType, filteredHandler);
debug('set up one-time %s to \'%s\'', filter ? 'filtered subscription' : 'subscription', messageTypes.join(','));
});
} | javascript | function setupOneTimeEmitterSubscription(emitter, messageTypes, filter, handler) {
if (typeof emitter !== 'object' || !emitter)
throw new TypeError('emitter argument must be an Object');
if (!Array.isArray(messageTypes) || messageTypes.some(m => !m || typeof m !== 'string'))
throw new TypeError('messageTypes argument must be an Array of non-empty Strings');
if (handler && typeof handler !== 'function')
throw new TypeError('handler argument, when specified, must be a Function');
if (filter && typeof filter !== 'function')
throw new TypeError('filter argument, when specified, must be a Function');
return new Promise(resolve => {
// handler will be invoked only once,
// even if multiple events have been emitted before subscription was destroyed
// https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener
let handled = false;
function filteredHandler(event) {
if (filter && !filter(event)) return;
if (handled) return;
handled = true;
for (const messageType of messageTypes)
emitter.off(messageType, filteredHandler);
debug('\'%s\' received, one-time subscription to \'%s\' removed', event.type, messageTypes.join(','));
if (handler)
handler(event);
resolve(event);
}
for (const messageType of messageTypes)
emitter.on(messageType, filteredHandler);
debug('set up one-time %s to \'%s\'', filter ? 'filtered subscription' : 'subscription', messageTypes.join(','));
});
} | [
"function",
"setupOneTimeEmitterSubscription",
"(",
"emitter",
",",
"messageTypes",
",",
"filter",
",",
"handler",
")",
"{",
"if",
"(",
"typeof",
"emitter",
"!==",
"'object'",
"||",
"!",
"emitter",
")",
"throw",
"new",
"TypeError",
"(",
"'emitter argument must be an Object'",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"messageTypes",
")",
"||",
"messageTypes",
".",
"some",
"(",
"m",
"=>",
"!",
"m",
"||",
"typeof",
"m",
"!==",
"'string'",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'messageTypes argument must be an Array of non-empty Strings'",
")",
";",
"if",
"(",
"handler",
"&&",
"typeof",
"handler",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'handler argument, when specified, must be a Function'",
")",
";",
"if",
"(",
"filter",
"&&",
"typeof",
"filter",
"!==",
"'function'",
")",
"throw",
"new",
"TypeError",
"(",
"'filter argument, when specified, must be a Function'",
")",
";",
"return",
"new",
"Promise",
"(",
"resolve",
"=>",
"{",
"// handler will be invoked only once,",
"// even if multiple events have been emitted before subscription was destroyed",
"// https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener",
"let",
"handled",
"=",
"false",
";",
"function",
"filteredHandler",
"(",
"event",
")",
"{",
"if",
"(",
"filter",
"&&",
"!",
"filter",
"(",
"event",
")",
")",
"return",
";",
"if",
"(",
"handled",
")",
"return",
";",
"handled",
"=",
"true",
";",
"for",
"(",
"const",
"messageType",
"of",
"messageTypes",
")",
"emitter",
".",
"off",
"(",
"messageType",
",",
"filteredHandler",
")",
";",
"debug",
"(",
"'\\'%s\\' received, one-time subscription to \\'%s\\' removed'",
",",
"event",
".",
"type",
",",
"messageTypes",
".",
"join",
"(",
"','",
")",
")",
";",
"if",
"(",
"handler",
")",
"handler",
"(",
"event",
")",
";",
"resolve",
"(",
"event",
")",
";",
"}",
"for",
"(",
"const",
"messageType",
"of",
"messageTypes",
")",
"emitter",
".",
"on",
"(",
"messageType",
",",
"filteredHandler",
")",
";",
"debug",
"(",
"'set up one-time %s to \\'%s\\''",
",",
"filter",
"?",
"'filtered subscription'",
":",
"'subscription'",
",",
"messageTypes",
".",
"join",
"(",
"','",
")",
")",
";",
"}",
")",
";",
"}"
]
| Create one-time eventEmitter subscription for one or multiple events that match a filter
@param {IEventEmitter} emitter
@param {string[]} messageTypes Array of event type to subscribe to
@param {function(IEvent):any} [handler] Optional handler to execute for a first event received
@param {function(IEvent):boolean} [filter] Optional filter to apply before executing a handler
@return {Promise<IEvent>} Resolves to first event that passes filter | [
"Create",
"one",
"-",
"time",
"eventEmitter",
"subscription",
"for",
"one",
"or",
"multiple",
"events",
"that",
"match",
"a",
"filter"
]
| 32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c | https://github.com/snatalenko/node-cqrs/blob/32e2a8ff8bbb70e199e60cd44fd2f4ee19ee5a5c/src/EventStore.js#L86-L124 |
41,342 | sazze/node-pm | lib/main.js | function(settings, callback) {
"use strict";
if (typeof settings === 'function') {
callback = settings;
settings = {};
}
if (typeof settings === 'undefined') {
settings = {};
}
if (typeof callback !== 'function') {
callback = function () {};
}
getLogFiles(function () {
parseOptions(settings, function () {
setupLogger();
require('./Logger').verbose('Starting worker manager');
// Start the Master
master = require('./master');
registerListeners(master);
master.start();
callback();
});
});
} | javascript | function(settings, callback) {
"use strict";
if (typeof settings === 'function') {
callback = settings;
settings = {};
}
if (typeof settings === 'undefined') {
settings = {};
}
if (typeof callback !== 'function') {
callback = function () {};
}
getLogFiles(function () {
parseOptions(settings, function () {
setupLogger();
require('./Logger').verbose('Starting worker manager');
// Start the Master
master = require('./master');
registerListeners(master);
master.start();
callback();
});
});
} | [
"function",
"(",
"settings",
",",
"callback",
")",
"{",
"\"use strict\"",
";",
"if",
"(",
"typeof",
"settings",
"===",
"'function'",
")",
"{",
"callback",
"=",
"settings",
";",
"settings",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"settings",
"===",
"'undefined'",
")",
"{",
"settings",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"callback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"}",
"getLogFiles",
"(",
"function",
"(",
")",
"{",
"parseOptions",
"(",
"settings",
",",
"function",
"(",
")",
"{",
"setupLogger",
"(",
")",
";",
"require",
"(",
"'./Logger'",
")",
".",
"verbose",
"(",
"'Starting worker manager'",
")",
";",
"// Start the Master",
"master",
"=",
"require",
"(",
"'./master'",
")",
";",
"registerListeners",
"(",
"master",
")",
";",
"master",
".",
"start",
"(",
")",
";",
"callback",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Start the Worker Manager
@param [settings={}]
@param [callback=function] | [
"Start",
"the",
"Worker",
"Manager"
]
| d2f1348cb0446e98dcf873e319b55ce89f79b386 | https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/main.js#L28-L60 |
|
41,343 | sazze/node-pm | lib/Logger.js | log | function log(logLevel, prefix, args) {
"use strict";
if (logLevel > level) {
return;
}
args = Array.prototype.slice.call(args);
if (typeof args[0] === 'undefined') {
return;
}
var message = args[0];
args.splice(0, 1, prefix + message);
console.log.apply(this, args);
} | javascript | function log(logLevel, prefix, args) {
"use strict";
if (logLevel > level) {
return;
}
args = Array.prototype.slice.call(args);
if (typeof args[0] === 'undefined') {
return;
}
var message = args[0];
args.splice(0, 1, prefix + message);
console.log.apply(this, args);
} | [
"function",
"log",
"(",
"logLevel",
",",
"prefix",
",",
"args",
")",
"{",
"\"use strict\"",
";",
"if",
"(",
"logLevel",
">",
"level",
")",
"{",
"return",
";",
"}",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"args",
")",
";",
"if",
"(",
"typeof",
"args",
"[",
"0",
"]",
"===",
"'undefined'",
")",
"{",
"return",
";",
"}",
"var",
"message",
"=",
"args",
"[",
"0",
"]",
";",
"args",
".",
"splice",
"(",
"0",
",",
"1",
",",
"prefix",
"+",
"message",
")",
";",
"console",
".",
"log",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}"
]
| The internal log function
@private
@param {int} logLevel the log level that is allowed
@param prefix the prefix that gets prepended to the message
@param args and object of arguments, usually from global [arguments] | [
"The",
"internal",
"log",
"function"
]
| d2f1348cb0446e98dcf873e319b55ce89f79b386 | https://github.com/sazze/node-pm/blob/d2f1348cb0446e98dcf873e319b55ce89f79b386/lib/Logger.js#L95-L111 |
41,344 | dpw/promisify | promisify.js | append | function append(arrlike /* , items... */) {
return Array.prototype.slice.call(arrlike, 0).concat(Array.prototype.slice.call(arguments, 1));
} | javascript | function append(arrlike /* , items... */) {
return Array.prototype.slice.call(arrlike, 0).concat(Array.prototype.slice.call(arguments, 1));
} | [
"function",
"append",
"(",
"arrlike",
"/* , items... */",
")",
"{",
"return",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arrlike",
",",
"0",
")",
".",
"concat",
"(",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
")",
";",
"}"
]
| Append items to an array-like object | [
"Append",
"items",
"to",
"an",
"array",
"-",
"like",
"object"
]
| 23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc | https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L11-L13 |
41,345 | dpw/promisify | promisify.js | promisify_value | function promisify_value(result_transformer) {
result_transformer = result_transformer || identity;
var transformer = function (promise) {
result_transformer(promise);
};
transformer.for_property = function (obj_promise, prop) {
return when(obj_promise, function (obj) {
result_transformer(obj[prop]);
});
};
return transformer;
} | javascript | function promisify_value(result_transformer) {
result_transformer = result_transformer || identity;
var transformer = function (promise) {
result_transformer(promise);
};
transformer.for_property = function (obj_promise, prop) {
return when(obj_promise, function (obj) {
result_transformer(obj[prop]);
});
};
return transformer;
} | [
"function",
"promisify_value",
"(",
"result_transformer",
")",
"{",
"result_transformer",
"=",
"result_transformer",
"||",
"identity",
";",
"var",
"transformer",
"=",
"function",
"(",
"promise",
")",
"{",
"result_transformer",
"(",
"promise",
")",
";",
"}",
";",
"transformer",
".",
"for_property",
"=",
"function",
"(",
"obj_promise",
",",
"prop",
")",
"{",
"return",
"when",
"(",
"obj_promise",
",",
"function",
"(",
"obj",
")",
"{",
"result_transformer",
"(",
"obj",
"[",
"prop",
"]",
")",
";",
"}",
")",
";",
"}",
";",
"return",
"transformer",
";",
"}"
]
| Produces a transformer that takes a value and simply returns it. | [
"Produces",
"a",
"transformer",
"that",
"takes",
"a",
"value",
"and",
"simply",
"returns",
"it",
"."
]
| 23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc | https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L19-L33 |
41,346 | dpw/promisify | promisify.js | promisify_func | function promisify_func(result_transformer) {
result_transformer = result_transformer || identity;
var transformer = function (func_promise) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(func_promise, function (func) {
return func.apply(null, args);
}));
};
};
transformer.for_property = function (obj_promise, prop) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(obj_promise, function (obj) {
return obj[prop].apply(obj, args);
}));
};
};
return transformer;
} | javascript | function promisify_func(result_transformer) {
result_transformer = result_transformer || identity;
var transformer = function (func_promise) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(func_promise, function (func) {
return func.apply(null, args);
}));
};
};
transformer.for_property = function (obj_promise, prop) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(obj_promise, function (obj) {
return obj[prop].apply(obj, args);
}));
};
};
return transformer;
} | [
"function",
"promisify_func",
"(",
"result_transformer",
")",
"{",
"result_transformer",
"=",
"result_transformer",
"||",
"identity",
";",
"var",
"transformer",
"=",
"function",
"(",
"func_promise",
")",
"{",
"return",
"function",
"(",
"/* ... */",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"return",
"result_transformer",
"(",
"when",
"(",
"func_promise",
",",
"function",
"(",
"func",
")",
"{",
"return",
"func",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}",
")",
")",
";",
"}",
";",
"}",
";",
"transformer",
".",
"for_property",
"=",
"function",
"(",
"obj_promise",
",",
"prop",
")",
"{",
"return",
"function",
"(",
"/* ... */",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"return",
"result_transformer",
"(",
"when",
"(",
"obj_promise",
",",
"function",
"(",
"obj",
")",
"{",
"return",
"obj",
"[",
"prop",
"]",
".",
"apply",
"(",
"obj",
",",
"args",
")",
";",
"}",
")",
")",
";",
"}",
";",
"}",
";",
"return",
"transformer",
";",
"}"
]
| Produces a transformer that takes a promised function, and returns a function returning a promise, optionally transforming that promise. | [
"Produces",
"a",
"transformer",
"that",
"takes",
"a",
"promised",
"function",
"and",
"returns",
"a",
"function",
"returning",
"a",
"promise",
"optionally",
"transforming",
"that",
"promise",
"."
]
| 23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc | https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L38-L60 |
41,347 | dpw/promisify | promisify.js | promisify_cb_func_generic | function promisify_cb_func_generic(result_transformer, cb_generator) {
result_transformer = result_transformer || identity;
var transformer = function (func_promise) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(func_promise, function (func) {
var d = when.defer();
func.apply(null, append(args, cb_generator(d)));
return d.promise;
}));
};
};
transformer.for_property = function (obj_promise, prop) {
return function(/* ... */) {
var args = arguments;
return result_transformer(when(obj_promise, function (obj) {
var d = when.defer();
obj[prop].apply(obj, append(args, cb_generator(d)));
return d.promise;
}));
};
};
return transformer;
} | javascript | function promisify_cb_func_generic(result_transformer, cb_generator) {
result_transformer = result_transformer || identity;
var transformer = function (func_promise) {
return function (/* ... */) {
var args = arguments;
return result_transformer(when(func_promise, function (func) {
var d = when.defer();
func.apply(null, append(args, cb_generator(d)));
return d.promise;
}));
};
};
transformer.for_property = function (obj_promise, prop) {
return function(/* ... */) {
var args = arguments;
return result_transformer(when(obj_promise, function (obj) {
var d = when.defer();
obj[prop].apply(obj, append(args, cb_generator(d)));
return d.promise;
}));
};
};
return transformer;
} | [
"function",
"promisify_cb_func_generic",
"(",
"result_transformer",
",",
"cb_generator",
")",
"{",
"result_transformer",
"=",
"result_transformer",
"||",
"identity",
";",
"var",
"transformer",
"=",
"function",
"(",
"func_promise",
")",
"{",
"return",
"function",
"(",
"/* ... */",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"return",
"result_transformer",
"(",
"when",
"(",
"func_promise",
",",
"function",
"(",
"func",
")",
"{",
"var",
"d",
"=",
"when",
".",
"defer",
"(",
")",
";",
"func",
".",
"apply",
"(",
"null",
",",
"append",
"(",
"args",
",",
"cb_generator",
"(",
"d",
")",
")",
")",
";",
"return",
"d",
".",
"promise",
";",
"}",
")",
")",
";",
"}",
";",
"}",
";",
"transformer",
".",
"for_property",
"=",
"function",
"(",
"obj_promise",
",",
"prop",
")",
"{",
"return",
"function",
"(",
"/* ... */",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"return",
"result_transformer",
"(",
"when",
"(",
"obj_promise",
",",
"function",
"(",
"obj",
")",
"{",
"var",
"d",
"=",
"when",
".",
"defer",
"(",
")",
";",
"obj",
"[",
"prop",
"]",
".",
"apply",
"(",
"obj",
",",
"append",
"(",
"args",
",",
"cb_generator",
"(",
"d",
")",
")",
")",
";",
"return",
"d",
".",
"promise",
";",
"}",
")",
")",
";",
"}",
";",
"}",
";",
"return",
"transformer",
";",
"}"
]
| Produces a transformer that takes a promised function taking a callback, and returns a function returning a promise, optionally transforming that promise. | [
"Produces",
"a",
"transformer",
"that",
"takes",
"a",
"promised",
"function",
"taking",
"a",
"callback",
"and",
"returns",
"a",
"function",
"returning",
"a",
"promise",
"optionally",
"transforming",
"that",
"promise",
"."
]
| 23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc | https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L65-L91 |
41,348 | dpw/promisify | promisify.js | promisify_object | function promisify_object(template, object_creator) {
object_creator = object_creator || new_object;
var transformer = function (obj_promise) {
var res = object_creator(obj_promise);
for (var prop in template) {
res[prop] = template[prop].for_property(obj_promise, prop);
}
return res;
};
transformer.for_property = function (parent_promise, prop) {
return transformer(when(parent_promise, function (obj) {
return obj[prop];
}));
};
return transformer;
} | javascript | function promisify_object(template, object_creator) {
object_creator = object_creator || new_object;
var transformer = function (obj_promise) {
var res = object_creator(obj_promise);
for (var prop in template) {
res[prop] = template[prop].for_property(obj_promise, prop);
}
return res;
};
transformer.for_property = function (parent_promise, prop) {
return transformer(when(parent_promise, function (obj) {
return obj[prop];
}));
};
return transformer;
} | [
"function",
"promisify_object",
"(",
"template",
",",
"object_creator",
")",
"{",
"object_creator",
"=",
"object_creator",
"||",
"new_object",
";",
"var",
"transformer",
"=",
"function",
"(",
"obj_promise",
")",
"{",
"var",
"res",
"=",
"object_creator",
"(",
"obj_promise",
")",
";",
"for",
"(",
"var",
"prop",
"in",
"template",
")",
"{",
"res",
"[",
"prop",
"]",
"=",
"template",
"[",
"prop",
"]",
".",
"for_property",
"(",
"obj_promise",
",",
"prop",
")",
";",
"}",
"return",
"res",
";",
"}",
";",
"transformer",
".",
"for_property",
"=",
"function",
"(",
"parent_promise",
",",
"prop",
")",
"{",
"return",
"transformer",
"(",
"when",
"(",
"parent_promise",
",",
"function",
"(",
"obj",
")",
"{",
"return",
"obj",
"[",
"prop",
"]",
";",
"}",
")",
")",
";",
"}",
";",
"return",
"transformer",
";",
"}"
]
| Produces a transformer that takes a promised object, and returns an object with the properties transformed according to the template. | [
"Produces",
"a",
"transformer",
"that",
"takes",
"a",
"promised",
"object",
"and",
"returns",
"an",
"object",
"with",
"the",
"properties",
"transformed",
"according",
"to",
"the",
"template",
"."
]
| 23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc | https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L115-L132 |
41,349 | dpw/promisify | promisify.js | promisify_read_stream | function promisify_read_stream() {
var transformer = function (stream_promise) {
var res = new PStream();
res.to = function (dest) {
when(stream_promise, function (stream) {
PStream.wrap_read_stream(stream).to(dest);
}, function (err) {
dest.error(err);
});
};
return res.sanitize();
};
transformer.for_property = function (obj_promise, prop) {
return transformer(when(obj_promise, function (obj) {
return obj[prop];
}));
};
return transformer;
} | javascript | function promisify_read_stream() {
var transformer = function (stream_promise) {
var res = new PStream();
res.to = function (dest) {
when(stream_promise, function (stream) {
PStream.wrap_read_stream(stream).to(dest);
}, function (err) {
dest.error(err);
});
};
return res.sanitize();
};
transformer.for_property = function (obj_promise, prop) {
return transformer(when(obj_promise, function (obj) {
return obj[prop];
}));
};
return transformer;
} | [
"function",
"promisify_read_stream",
"(",
")",
"{",
"var",
"transformer",
"=",
"function",
"(",
"stream_promise",
")",
"{",
"var",
"res",
"=",
"new",
"PStream",
"(",
")",
";",
"res",
".",
"to",
"=",
"function",
"(",
"dest",
")",
"{",
"when",
"(",
"stream_promise",
",",
"function",
"(",
"stream",
")",
"{",
"PStream",
".",
"wrap_read_stream",
"(",
"stream",
")",
".",
"to",
"(",
"dest",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"dest",
".",
"error",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
";",
"return",
"res",
".",
"sanitize",
"(",
")",
";",
"}",
";",
"transformer",
".",
"for_property",
"=",
"function",
"(",
"obj_promise",
",",
"prop",
")",
"{",
"return",
"transformer",
"(",
"when",
"(",
"obj_promise",
",",
"function",
"(",
"obj",
")",
"{",
"return",
"obj",
"[",
"prop",
"]",
";",
"}",
")",
")",
";",
"}",
";",
"return",
"transformer",
";",
"}"
]
| Takes a promised read stream and returns a PStream | [
"Takes",
"a",
"promised",
"read",
"stream",
"and",
"returns",
"a",
"PStream"
]
| 23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc | https://github.com/dpw/promisify/blob/23e1e783fb22b6b4bca86f53ec3cbb7bc864a4cc/promisify.js#L135-L155 |
41,350 | mattrayner/cordova-plugin-vuforia-sdk | hooks/AfterPluginInstall.js | function() {
let xcConfigBuildFilePath = path.join(cwd, 'platforms', 'ios', 'cordova', 'build.xcconfig');
try {
let xcConfigBuildFileExists = fs.accessSync(xcConfigBuildFilePath);
}
catch(e) {
console.log('Could not locate build.xcconfig, you will need to set HEADER_SEARCH_PATHS manually');
return;
}
console.log(`xcConfigBuildFilePath: ${xcConfigBuildFilePath}`);
addHeaderSearchPaths(xcConfigBuildFilePath);
} | javascript | function() {
let xcConfigBuildFilePath = path.join(cwd, 'platforms', 'ios', 'cordova', 'build.xcconfig');
try {
let xcConfigBuildFileExists = fs.accessSync(xcConfigBuildFilePath);
}
catch(e) {
console.log('Could not locate build.xcconfig, you will need to set HEADER_SEARCH_PATHS manually');
return;
}
console.log(`xcConfigBuildFilePath: ${xcConfigBuildFilePath}`);
addHeaderSearchPaths(xcConfigBuildFilePath);
} | [
"function",
"(",
")",
"{",
"let",
"xcConfigBuildFilePath",
"=",
"path",
".",
"join",
"(",
"cwd",
",",
"'platforms'",
",",
"'ios'",
",",
"'cordova'",
",",
"'build.xcconfig'",
")",
";",
"try",
"{",
"let",
"xcConfigBuildFileExists",
"=",
"fs",
".",
"accessSync",
"(",
"xcConfigBuildFilePath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"'Could not locate build.xcconfig, you will need to set HEADER_SEARCH_PATHS manually'",
")",
";",
"return",
";",
"}",
"console",
".",
"log",
"(",
"`",
"${",
"xcConfigBuildFilePath",
"}",
"`",
")",
";",
"addHeaderSearchPaths",
"(",
"xcConfigBuildFilePath",
")",
";",
"}"
]
| Modify the xcconfig build path and pass the resulting file path to the addHeaderSearchPaths function. | [
"Modify",
"the",
"xcconfig",
"build",
"path",
"and",
"pass",
"the",
"resulting",
"file",
"path",
"to",
"the",
"addHeaderSearchPaths",
"function",
"."
]
| d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6 | https://github.com/mattrayner/cordova-plugin-vuforia-sdk/blob/d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6/hooks/AfterPluginInstall.js#L12-L26 |
|
41,351 | mattrayner/cordova-plugin-vuforia-sdk | hooks/AfterPluginInstall.js | function(xcConfigBuildFilePath) {
let lines = fs.readFileSync(xcConfigBuildFilePath, 'utf8').split('\n');
let paths = hookData.headerPaths;
let headerSearchPathLineNumber;
lines.forEach((l, i) => {
if (l.indexOf('HEADER_SEARCH_PATHS') > -1) {
headerSearchPathLineNumber = i;
}
});
if (headerSearchPathLineNumber) {
for(let actualPath of paths) {
if (lines[headerSearchPathLineNumber].indexOf(actualPath) == -1) {
lines[headerSearchPathLineNumber] += ` ${actualPath}`;
console.log(`${actualPath} was added to the search paths`);
}
else {
console.log(`${actualPath} was already setup in build.xcconfig`);
}
}
}
else {
lines[lines.length - 1] = 'HEADER_SEARCH_PATHS = ';
for(let actualPath of paths) {
lines[lines.length - 1] += actualPath;
}
}
let newConfig = lines.join('\n');
fs.writeFile(xcConfigBuildFilePath, newConfig, function (err) {
if (err) {
console.log(`Error updating build.xcconfig: ${err}`);
return;
}
console.log('Successfully updated HEADER_SEARCH_PATHS in build.xcconfig');
});
} | javascript | function(xcConfigBuildFilePath) {
let lines = fs.readFileSync(xcConfigBuildFilePath, 'utf8').split('\n');
let paths = hookData.headerPaths;
let headerSearchPathLineNumber;
lines.forEach((l, i) => {
if (l.indexOf('HEADER_SEARCH_PATHS') > -1) {
headerSearchPathLineNumber = i;
}
});
if (headerSearchPathLineNumber) {
for(let actualPath of paths) {
if (lines[headerSearchPathLineNumber].indexOf(actualPath) == -1) {
lines[headerSearchPathLineNumber] += ` ${actualPath}`;
console.log(`${actualPath} was added to the search paths`);
}
else {
console.log(`${actualPath} was already setup in build.xcconfig`);
}
}
}
else {
lines[lines.length - 1] = 'HEADER_SEARCH_PATHS = ';
for(let actualPath of paths) {
lines[lines.length - 1] += actualPath;
}
}
let newConfig = lines.join('\n');
fs.writeFile(xcConfigBuildFilePath, newConfig, function (err) {
if (err) {
console.log(`Error updating build.xcconfig: ${err}`);
return;
}
console.log('Successfully updated HEADER_SEARCH_PATHS in build.xcconfig');
});
} | [
"function",
"(",
"xcConfigBuildFilePath",
")",
"{",
"let",
"lines",
"=",
"fs",
".",
"readFileSync",
"(",
"xcConfigBuildFilePath",
",",
"'utf8'",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"let",
"paths",
"=",
"hookData",
".",
"headerPaths",
";",
"let",
"headerSearchPathLineNumber",
";",
"lines",
".",
"forEach",
"(",
"(",
"l",
",",
"i",
")",
"=>",
"{",
"if",
"(",
"l",
".",
"indexOf",
"(",
"'HEADER_SEARCH_PATHS'",
")",
">",
"-",
"1",
")",
"{",
"headerSearchPathLineNumber",
"=",
"i",
";",
"}",
"}",
")",
";",
"if",
"(",
"headerSearchPathLineNumber",
")",
"{",
"for",
"(",
"let",
"actualPath",
"of",
"paths",
")",
"{",
"if",
"(",
"lines",
"[",
"headerSearchPathLineNumber",
"]",
".",
"indexOf",
"(",
"actualPath",
")",
"==",
"-",
"1",
")",
"{",
"lines",
"[",
"headerSearchPathLineNumber",
"]",
"+=",
"`",
"${",
"actualPath",
"}",
"`",
";",
"console",
".",
"log",
"(",
"`",
"${",
"actualPath",
"}",
"`",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"actualPath",
"}",
"`",
")",
";",
"}",
"}",
"}",
"else",
"{",
"lines",
"[",
"lines",
".",
"length",
"-",
"1",
"]",
"=",
"'HEADER_SEARCH_PATHS = '",
";",
"for",
"(",
"let",
"actualPath",
"of",
"paths",
")",
"{",
"lines",
"[",
"lines",
".",
"length",
"-",
"1",
"]",
"+=",
"actualPath",
";",
"}",
"}",
"let",
"newConfig",
"=",
"lines",
".",
"join",
"(",
"'\\n'",
")",
";",
"fs",
".",
"writeFile",
"(",
"xcConfigBuildFilePath",
",",
"newConfig",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"err",
"}",
"`",
")",
";",
"return",
";",
"}",
"console",
".",
"log",
"(",
"'Successfully updated HEADER_SEARCH_PATHS in build.xcconfig'",
")",
";",
"}",
")",
";",
"}"
]
| Read the build config, add the correct Header Search Paths to the config before calling modifyAppDelegate. | [
"Read",
"the",
"build",
"config",
"add",
"the",
"correct",
"Header",
"Search",
"Paths",
"to",
"the",
"config",
"before",
"calling",
"modifyAppDelegate",
"."
]
| d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6 | https://github.com/mattrayner/cordova-plugin-vuforia-sdk/blob/d75349a1c4e5a4d6d6890c52fba9602df2ea6bc6/hooks/AfterPluginInstall.js#L29-L69 |
|
41,352 | MattL922/implied-volatility | implied-volatility.js | getImpliedVolatility | function getImpliedVolatility(expectedCost, s, k, t, r, callPut, estimate)
{
estimate = estimate || .1;
var low = 0;
var high = Infinity;
// perform 100 iterations max
for(var i = 0; i < 100; i++)
{
var actualCost = bs.blackScholes(s, k, t, estimate, r, callPut);
// compare the price down to the cent
if(expectedCost * 100 == Math.floor(actualCost * 100))
{
break;
}
else if(actualCost > expectedCost)
{
high = estimate;
estimate = (estimate - low) / 2 + low
}
else
{
low = estimate;
estimate = (high - estimate) / 2 + estimate;
if(!isFinite(estimate)) estimate = low * 2;
}
}
return estimate;
} | javascript | function getImpliedVolatility(expectedCost, s, k, t, r, callPut, estimate)
{
estimate = estimate || .1;
var low = 0;
var high = Infinity;
// perform 100 iterations max
for(var i = 0; i < 100; i++)
{
var actualCost = bs.blackScholes(s, k, t, estimate, r, callPut);
// compare the price down to the cent
if(expectedCost * 100 == Math.floor(actualCost * 100))
{
break;
}
else if(actualCost > expectedCost)
{
high = estimate;
estimate = (estimate - low) / 2 + low
}
else
{
low = estimate;
estimate = (high - estimate) / 2 + estimate;
if(!isFinite(estimate)) estimate = low * 2;
}
}
return estimate;
} | [
"function",
"getImpliedVolatility",
"(",
"expectedCost",
",",
"s",
",",
"k",
",",
"t",
",",
"r",
",",
"callPut",
",",
"estimate",
")",
"{",
"estimate",
"=",
"estimate",
"||",
".1",
";",
"var",
"low",
"=",
"0",
";",
"var",
"high",
"=",
"Infinity",
";",
"// perform 100 iterations max",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"100",
";",
"i",
"++",
")",
"{",
"var",
"actualCost",
"=",
"bs",
".",
"blackScholes",
"(",
"s",
",",
"k",
",",
"t",
",",
"estimate",
",",
"r",
",",
"callPut",
")",
";",
"// compare the price down to the cent",
"if",
"(",
"expectedCost",
"*",
"100",
"==",
"Math",
".",
"floor",
"(",
"actualCost",
"*",
"100",
")",
")",
"{",
"break",
";",
"}",
"else",
"if",
"(",
"actualCost",
">",
"expectedCost",
")",
"{",
"high",
"=",
"estimate",
";",
"estimate",
"=",
"(",
"estimate",
"-",
"low",
")",
"/",
"2",
"+",
"low",
"}",
"else",
"{",
"low",
"=",
"estimate",
";",
"estimate",
"=",
"(",
"high",
"-",
"estimate",
")",
"/",
"2",
"+",
"estimate",
";",
"if",
"(",
"!",
"isFinite",
"(",
"estimate",
")",
")",
"estimate",
"=",
"low",
"*",
"2",
";",
"}",
"}",
"return",
"estimate",
";",
"}"
]
| Calculate a close estimate of implied volatility given an option price. A
binary search type approach is used to determine the implied volatility.
@param {Number} expectedCost The market price of the option
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} r Anual risk-free interest rate as a decimal
@param {String} callPut The type of option priced - "call" or "put"
@param {Number} [estimate=.1] An initial estimate of implied volatility
@returns {Number} The implied volatility estimate | [
"Calculate",
"a",
"close",
"estimate",
"of",
"implied",
"volatility",
"given",
"an",
"option",
"price",
".",
"A",
"binary",
"search",
"type",
"approach",
"is",
"used",
"to",
"determine",
"the",
"implied",
"volatility",
"."
]
| 7b9a5e957d895645a46fd910769fe5243ed0d504 | https://github.com/MattL922/implied-volatility/blob/7b9a5e957d895645a46fd910769fe5243ed0d504/implied-volatility.js#L23-L50 |
41,353 | alexeykuzmin/jsonpointer.js | src/jsonpointer.js | getPointedValue | function getPointedValue(target, opt_pointer) {
// .get() method implementation.
// First argument must be either string or object.
if (isString(target)) {
// If string it must be valid JSON document.
try {
// Let's try to parse it as JSON.
target = JSON.parse(target);
}
catch (e) {
// If parsing failed, an exception will be thrown.
throw getError(ErrorMessage.INVALID_DOCUMENT);
}
}
else if (!isObject(target)) {
// If not object or string, an exception will be thrown.
throw getError(ErrorMessage.INVALID_DOCUMENT_TYPE);
}
// |target| is already parsed, let's create evaluator function for it.
var evaluator = createPointerEvaluator(target);
if (isUndefined(opt_pointer)) {
// If pointer was not provided, return evaluator function.
return evaluator;
}
else {
// If pointer is provided, return evaluation result.
return evaluator(opt_pointer);
}
} | javascript | function getPointedValue(target, opt_pointer) {
// .get() method implementation.
// First argument must be either string or object.
if (isString(target)) {
// If string it must be valid JSON document.
try {
// Let's try to parse it as JSON.
target = JSON.parse(target);
}
catch (e) {
// If parsing failed, an exception will be thrown.
throw getError(ErrorMessage.INVALID_DOCUMENT);
}
}
else if (!isObject(target)) {
// If not object or string, an exception will be thrown.
throw getError(ErrorMessage.INVALID_DOCUMENT_TYPE);
}
// |target| is already parsed, let's create evaluator function for it.
var evaluator = createPointerEvaluator(target);
if (isUndefined(opt_pointer)) {
// If pointer was not provided, return evaluator function.
return evaluator;
}
else {
// If pointer is provided, return evaluation result.
return evaluator(opt_pointer);
}
} | [
"function",
"getPointedValue",
"(",
"target",
",",
"opt_pointer",
")",
"{",
"// .get() method implementation.",
"// First argument must be either string or object.",
"if",
"(",
"isString",
"(",
"target",
")",
")",
"{",
"// If string it must be valid JSON document.",
"try",
"{",
"// Let's try to parse it as JSON.",
"target",
"=",
"JSON",
".",
"parse",
"(",
"target",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// If parsing failed, an exception will be thrown.",
"throw",
"getError",
"(",
"ErrorMessage",
".",
"INVALID_DOCUMENT",
")",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"isObject",
"(",
"target",
")",
")",
"{",
"// If not object or string, an exception will be thrown.",
"throw",
"getError",
"(",
"ErrorMessage",
".",
"INVALID_DOCUMENT_TYPE",
")",
";",
"}",
"// |target| is already parsed, let's create evaluator function for it.",
"var",
"evaluator",
"=",
"createPointerEvaluator",
"(",
"target",
")",
";",
"if",
"(",
"isUndefined",
"(",
"opt_pointer",
")",
")",
"{",
"// If pointer was not provided, return evaluator function.",
"return",
"evaluator",
";",
"}",
"else",
"{",
"// If pointer is provided, return evaluation result.",
"return",
"evaluator",
"(",
"opt_pointer",
")",
";",
"}",
"}"
]
| Returns |target| object's value pointed by |opt_pointer|, returns undefined
if |opt_pointer| points to non-existing value.
If pointer is not provided, validates first argument and returns
evaluator function that takes pointer as argument.
@param {(string|Object|Array)} target Evaluation target.
@param {string=} opt_pointer JSON Pointer string.
@returns {*} Some value. | [
"Returns",
"|target|",
"object",
"s",
"value",
"pointed",
"by",
"|opt_pointer|",
"returns",
"undefined",
"if",
"|opt_pointer|",
"points",
"to",
"non",
"-",
"existing",
"value",
".",
"If",
"pointer",
"is",
"not",
"provided",
"validates",
"first",
"argument",
"and",
"returns",
"evaluator",
"function",
"that",
"takes",
"pointer",
"as",
"argument",
"."
]
| 57d7cf484d906792255a7c30cbb6c2d90d4ab152 | https://github.com/alexeykuzmin/jsonpointer.js/blob/57d7cf484d906792255a7c30cbb6c2d90d4ab152/src/jsonpointer.js#L77-L109 |
41,354 | alexeykuzmin/jsonpointer.js | src/jsonpointer.js | isValidJSONPointer | function isValidJSONPointer(pointer) {
// Validates JSON pointer string.
if (!isString(pointer)) {
// If it's not a string, it obviously is not valid.
return false;
}
if ('' === pointer) {
// If it is string and is an empty string, it's valid.
return true;
}
// If it is non-empty string, it must match spec defined format.
// Check Section 3 of specification for concrete syntax.
return NON_EMPTY_POINTER_REGEXP.test(pointer);
} | javascript | function isValidJSONPointer(pointer) {
// Validates JSON pointer string.
if (!isString(pointer)) {
// If it's not a string, it obviously is not valid.
return false;
}
if ('' === pointer) {
// If it is string and is an empty string, it's valid.
return true;
}
// If it is non-empty string, it must match spec defined format.
// Check Section 3 of specification for concrete syntax.
return NON_EMPTY_POINTER_REGEXP.test(pointer);
} | [
"function",
"isValidJSONPointer",
"(",
"pointer",
")",
"{",
"// Validates JSON pointer string.",
"if",
"(",
"!",
"isString",
"(",
"pointer",
")",
")",
"{",
"// If it's not a string, it obviously is not valid.",
"return",
"false",
";",
"}",
"if",
"(",
"''",
"===",
"pointer",
")",
"{",
"// If it is string and is an empty string, it's valid.",
"return",
"true",
";",
"}",
"// If it is non-empty string, it must match spec defined format.",
"// Check Section 3 of specification for concrete syntax.",
"return",
"NON_EMPTY_POINTER_REGEXP",
".",
"test",
"(",
"pointer",
")",
";",
"}"
]
| Returns true if given |pointer| is valid, returns false otherwise.
@param {!string} pointer
@returns {boolean} Whether pointer is valid. | [
"Returns",
"true",
"if",
"given",
"|pointer|",
"is",
"valid",
"returns",
"false",
"otherwise",
"."
]
| 57d7cf484d906792255a7c30cbb6c2d90d4ab152 | https://github.com/alexeykuzmin/jsonpointer.js/blob/57d7cf484d906792255a7c30cbb6c2d90d4ab152/src/jsonpointer.js#L164-L180 |
41,355 | shaun-h/nodejs-disks | lib/disks.js | getDrives | function getDrives(command, callback) {
var child = exec(
command,
function (err, stdout, stderr) {
if (err) return callback(err);
var drives = stdout.split('\n');
drives.splice(0, 1);
drives.splice(-1, 1);
// Removes ram drives
drives = drives.filter(function(item){ return item != "none"});
callback(null, drives);
}
);
} | javascript | function getDrives(command, callback) {
var child = exec(
command,
function (err, stdout, stderr) {
if (err) return callback(err);
var drives = stdout.split('\n');
drives.splice(0, 1);
drives.splice(-1, 1);
// Removes ram drives
drives = drives.filter(function(item){ return item != "none"});
callback(null, drives);
}
);
} | [
"function",
"getDrives",
"(",
"command",
",",
"callback",
")",
"{",
"var",
"child",
"=",
"exec",
"(",
"command",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"var",
"drives",
"=",
"stdout",
".",
"split",
"(",
"'\\n'",
")",
";",
"drives",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"drives",
".",
"splice",
"(",
"-",
"1",
",",
"1",
")",
";",
"// Removes ram drives",
"drives",
"=",
"drives",
".",
"filter",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"item",
"!=",
"\"none\"",
"}",
")",
";",
"callback",
"(",
"null",
",",
"drives",
")",
";",
"}",
")",
";",
"}"
]
| Execute a command to retrieve disks list.
@param command
@param callback | [
"Execute",
"a",
"command",
"to",
"retrieve",
"disks",
"list",
"."
]
| 615c2c6477dbf81ff693f0b2ff0c44f669d5892b | https://github.com/shaun-h/nodejs-disks/blob/615c2c6477dbf81ff693f0b2ff0c44f669d5892b/lib/disks.js#L29-L44 |
41,356 | shaun-h/nodejs-disks | lib/disks.js | detail | function detail(drive, callback) {
async.series(
{
used: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetail('df -kl | grep ' + drive + ' | awk \'{print $3}\'', callback);
break;
case'linux':
default:
getDetail('df -P | grep ' + drive + ' | awk \'{print $3}\'', callback);
}
},
available: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetail('df -kl | grep ' + drive + ' | awk \'{print $4}\'', callback);
break;
case'linux':
default:
getDetail('df -P | grep ' + drive + ' | awk \'{print $4}\'', callback);
}
},
mountpoint: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetailNaN('df -kl | grep ' + drive + ' | awk \'{print $9}\'', function(e, d){
if (d) d = d.trim();
callback(e, d);
});
break;
case'linux':
default:
getDetailNaN('df -P | grep ' + drive + ' | awk \'{print $6}\'', function(e, d){
if (d) d = d.trim();
callback(e, d);
});
}
}
},
function (err, results) {
if (err) return callback(err);
results.freePer = Number(results.available / (results.used + results.available) * 100);
results.usedPer = Number(results.used / (results.used + results.available) * 100);
results.total = numeral(results.used + results.available).format('0.00 b');
results.used = numeral(results.used).format('0.00 b');
results.available = numeral(results.available).format('0.00 b');
results.drive = drive;
callback(null, results);
}
);
} | javascript | function detail(drive, callback) {
async.series(
{
used: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetail('df -kl | grep ' + drive + ' | awk \'{print $3}\'', callback);
break;
case'linux':
default:
getDetail('df -P | grep ' + drive + ' | awk \'{print $3}\'', callback);
}
},
available: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetail('df -kl | grep ' + drive + ' | awk \'{print $4}\'', callback);
break;
case'linux':
default:
getDetail('df -P | grep ' + drive + ' | awk \'{print $4}\'', callback);
}
},
mountpoint: function (callback) {
switch (os.platform().toLowerCase()) {
case'darwin':
getDetailNaN('df -kl | grep ' + drive + ' | awk \'{print $9}\'', function(e, d){
if (d) d = d.trim();
callback(e, d);
});
break;
case'linux':
default:
getDetailNaN('df -P | grep ' + drive + ' | awk \'{print $6}\'', function(e, d){
if (d) d = d.trim();
callback(e, d);
});
}
}
},
function (err, results) {
if (err) return callback(err);
results.freePer = Number(results.available / (results.used + results.available) * 100);
results.usedPer = Number(results.used / (results.used + results.available) * 100);
results.total = numeral(results.used + results.available).format('0.00 b');
results.used = numeral(results.used).format('0.00 b');
results.available = numeral(results.available).format('0.00 b');
results.drive = drive;
callback(null, results);
}
);
} | [
"function",
"detail",
"(",
"drive",
",",
"callback",
")",
"{",
"async",
".",
"series",
"(",
"{",
"used",
":",
"function",
"(",
"callback",
")",
"{",
"switch",
"(",
"os",
".",
"platform",
"(",
")",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'darwin'",
":",
"getDetail",
"(",
"'df -kl | grep '",
"+",
"drive",
"+",
"' | awk \\'{print $3}\\''",
",",
"callback",
")",
";",
"break",
";",
"case",
"'linux'",
":",
"default",
":",
"getDetail",
"(",
"'df -P | grep '",
"+",
"drive",
"+",
"' | awk \\'{print $3}\\''",
",",
"callback",
")",
";",
"}",
"}",
",",
"available",
":",
"function",
"(",
"callback",
")",
"{",
"switch",
"(",
"os",
".",
"platform",
"(",
")",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'darwin'",
":",
"getDetail",
"(",
"'df -kl | grep '",
"+",
"drive",
"+",
"' | awk \\'{print $4}\\''",
",",
"callback",
")",
";",
"break",
";",
"case",
"'linux'",
":",
"default",
":",
"getDetail",
"(",
"'df -P | grep '",
"+",
"drive",
"+",
"' | awk \\'{print $4}\\''",
",",
"callback",
")",
";",
"}",
"}",
",",
"mountpoint",
":",
"function",
"(",
"callback",
")",
"{",
"switch",
"(",
"os",
".",
"platform",
"(",
")",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'darwin'",
":",
"getDetailNaN",
"(",
"'df -kl | grep '",
"+",
"drive",
"+",
"' | awk \\'{print $9}\\''",
",",
"function",
"(",
"e",
",",
"d",
")",
"{",
"if",
"(",
"d",
")",
"d",
"=",
"d",
".",
"trim",
"(",
")",
";",
"callback",
"(",
"e",
",",
"d",
")",
";",
"}",
")",
";",
"break",
";",
"case",
"'linux'",
":",
"default",
":",
"getDetailNaN",
"(",
"'df -P | grep '",
"+",
"drive",
"+",
"' | awk \\'{print $6}\\''",
",",
"function",
"(",
"e",
",",
"d",
")",
"{",
"if",
"(",
"d",
")",
"d",
"=",
"d",
".",
"trim",
"(",
")",
";",
"callback",
"(",
"e",
",",
"d",
")",
";",
"}",
")",
";",
"}",
"}",
"}",
",",
"function",
"(",
"err",
",",
"results",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"results",
".",
"freePer",
"=",
"Number",
"(",
"results",
".",
"available",
"/",
"(",
"results",
".",
"used",
"+",
"results",
".",
"available",
")",
"*",
"100",
")",
";",
"results",
".",
"usedPer",
"=",
"Number",
"(",
"results",
".",
"used",
"/",
"(",
"results",
".",
"used",
"+",
"results",
".",
"available",
")",
"*",
"100",
")",
";",
"results",
".",
"total",
"=",
"numeral",
"(",
"results",
".",
"used",
"+",
"results",
".",
"available",
")",
".",
"format",
"(",
"'0.00 b'",
")",
";",
"results",
".",
"used",
"=",
"numeral",
"(",
"results",
".",
"used",
")",
".",
"format",
"(",
"'0.00 b'",
")",
";",
"results",
".",
"available",
"=",
"numeral",
"(",
"results",
".",
"available",
")",
".",
"format",
"(",
"'0.00 b'",
")",
";",
"results",
".",
"drive",
"=",
"drive",
";",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
";",
"}"
]
| Retrieve space information about one drive.
@param drive
@param callback | [
"Retrieve",
"space",
"information",
"about",
"one",
"drive",
"."
]
| 615c2c6477dbf81ff693f0b2ff0c44f669d5892b | https://github.com/shaun-h/nodejs-disks/blob/615c2c6477dbf81ff693f0b2ff0c44f669d5892b/lib/disks.js#L90-L142 |
41,357 | 71104/rwlock | src/lock.js | writeLock | function writeLock(key, callback, options) {
var lock;
if (typeof key !== 'function') {
if (!table.hasOwnProperty(key)) {
table[key] = new Lock();
}
lock = table[key];
} else {
options = callback;
callback = key;
lock = defaultLock;
}
if (!options) {
options = {};
}
var scope = null;
if (options.hasOwnProperty('scope')) {
scope = options.scope;
}
var release = (function () {
var released = false;
return function () {
if (!released) {
released = true;
lock.readers = 0;
if (lock.queue.length) {
lock.queue[0]();
}
}
};
}());
if (lock.readers || lock.queue.length) {
var terminated = false;
lock.queue.push(function () {
if (!terminated && !lock.readers) {
terminated = true;
lock.queue.shift();
lock.readers = -1;
callback.call(options.scope, release);
}
});
if (options.hasOwnProperty('timeout')) {
var timeoutCallback = null;
if (options.hasOwnProperty('timeoutCallback')) {
timeoutCallback = options.timeoutCallback;
}
setTimeout(function () {
if (!terminated) {
terminated = true;
lock.queue.shift();
if (timeoutCallback) {
timeoutCallback.call(scope);
}
}
}, options.timeout);
}
} else {
lock.readers = -1;
callback.call(options.scope, release);
}
} | javascript | function writeLock(key, callback, options) {
var lock;
if (typeof key !== 'function') {
if (!table.hasOwnProperty(key)) {
table[key] = new Lock();
}
lock = table[key];
} else {
options = callback;
callback = key;
lock = defaultLock;
}
if (!options) {
options = {};
}
var scope = null;
if (options.hasOwnProperty('scope')) {
scope = options.scope;
}
var release = (function () {
var released = false;
return function () {
if (!released) {
released = true;
lock.readers = 0;
if (lock.queue.length) {
lock.queue[0]();
}
}
};
}());
if (lock.readers || lock.queue.length) {
var terminated = false;
lock.queue.push(function () {
if (!terminated && !lock.readers) {
terminated = true;
lock.queue.shift();
lock.readers = -1;
callback.call(options.scope, release);
}
});
if (options.hasOwnProperty('timeout')) {
var timeoutCallback = null;
if (options.hasOwnProperty('timeoutCallback')) {
timeoutCallback = options.timeoutCallback;
}
setTimeout(function () {
if (!terminated) {
terminated = true;
lock.queue.shift();
if (timeoutCallback) {
timeoutCallback.call(scope);
}
}
}, options.timeout);
}
} else {
lock.readers = -1;
callback.call(options.scope, release);
}
} | [
"function",
"writeLock",
"(",
"key",
",",
"callback",
",",
"options",
")",
"{",
"var",
"lock",
";",
"if",
"(",
"typeof",
"key",
"!==",
"'function'",
")",
"{",
"if",
"(",
"!",
"table",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"table",
"[",
"key",
"]",
"=",
"new",
"Lock",
"(",
")",
";",
"}",
"lock",
"=",
"table",
"[",
"key",
"]",
";",
"}",
"else",
"{",
"options",
"=",
"callback",
";",
"callback",
"=",
"key",
";",
"lock",
"=",
"defaultLock",
";",
"}",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"var",
"scope",
"=",
"null",
";",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'scope'",
")",
")",
"{",
"scope",
"=",
"options",
".",
"scope",
";",
"}",
"var",
"release",
"=",
"(",
"function",
"(",
")",
"{",
"var",
"released",
"=",
"false",
";",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"released",
")",
"{",
"released",
"=",
"true",
";",
"lock",
".",
"readers",
"=",
"0",
";",
"if",
"(",
"lock",
".",
"queue",
".",
"length",
")",
"{",
"lock",
".",
"queue",
"[",
"0",
"]",
"(",
")",
";",
"}",
"}",
"}",
";",
"}",
"(",
")",
")",
";",
"if",
"(",
"lock",
".",
"readers",
"||",
"lock",
".",
"queue",
".",
"length",
")",
"{",
"var",
"terminated",
"=",
"false",
";",
"lock",
".",
"queue",
".",
"push",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"terminated",
"&&",
"!",
"lock",
".",
"readers",
")",
"{",
"terminated",
"=",
"true",
";",
"lock",
".",
"queue",
".",
"shift",
"(",
")",
";",
"lock",
".",
"readers",
"=",
"-",
"1",
";",
"callback",
".",
"call",
"(",
"options",
".",
"scope",
",",
"release",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'timeout'",
")",
")",
"{",
"var",
"timeoutCallback",
"=",
"null",
";",
"if",
"(",
"options",
".",
"hasOwnProperty",
"(",
"'timeoutCallback'",
")",
")",
"{",
"timeoutCallback",
"=",
"options",
".",
"timeoutCallback",
";",
"}",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"terminated",
")",
"{",
"terminated",
"=",
"true",
";",
"lock",
".",
"queue",
".",
"shift",
"(",
")",
";",
"if",
"(",
"timeoutCallback",
")",
"{",
"timeoutCallback",
".",
"call",
"(",
"scope",
")",
";",
"}",
"}",
"}",
",",
"options",
".",
"timeout",
")",
";",
"}",
"}",
"else",
"{",
"lock",
".",
"readers",
"=",
"-",
"1",
";",
"callback",
".",
"call",
"(",
"options",
".",
"scope",
",",
"release",
")",
";",
"}",
"}"
]
| Acquires a write lock and invokes a user-defined callback as soon as it
is acquired.
The operation might require some time as there may be one or more
readers. You can optionally specify a timeout in milliseconds: if it
expires before a read lock can be acquired, this request is canceled and
no lock will be acquired.
The `key` argument allows you to work on a specific lock; omitting it
will request the default lock.
@method writeLock
@param [key] {String} The name of the lock to write-acquire. The default
lock will be requested if no key is specified.
@param callback {Function} A user-defined function invoked as soon as a
write lock is acquired.
@param callback.release {Function} A function that releases the lock.
This must be called by the ReadWriteLock user at some point, otherwise
the write lock will remain and prevent future readers from operating.
Anyway you do not necessarily need to call it inside the `callback`
function: you can save a reference to the `release` function and call it
later.
@param [options] {Object} Further optional settings.
@param [options.scope] {Object} An optional object to use as `this` when
calling the `callback` function.
@param [options.timeout] {Number} A timeout in milliseconds within which
the lock must be acquired; if one ore more readers are still operating
and the timeout expires the request is canceled and no lock is acquired.
@param [options.timeoutCallback] {Function} An optional user-defined
callback function that gets invokes in case the timeout expires before
the lock can be acquired. | [
"Acquires",
"a",
"write",
"lock",
"and",
"invokes",
"a",
"user",
"-",
"defined",
"callback",
"as",
"soon",
"as",
"it",
"is",
"acquired",
"."
]
| 86a1affae69c3ec8cd1adbb7dad75befb75ea74e | https://github.com/71104/rwlock/blob/86a1affae69c3ec8cd1adbb7dad75befb75ea74e/src/lock.js#L158-L218 |
41,358 | http-auth/htdigest | src/processor.js | readPassword | function readPassword(program) {
prompt.message = "";
prompt.delimiter = "";
const passportOption = [{name: 'password', description: 'New password:', hidden: true}];
const rePassportOption = [{name: 'rePassword', description: 'Re-type new password:', hidden: true}];
// Try to read password.
prompt.get(passportOption, (err, result) => {
if (!err) {
const password = result.password;
setTimeout(function () {
prompt.get(rePassportOption, (err, result) => {
if (!err && password == result.rePassword) {
program.args.push(password);
try {
processor.syncFile(program);
} catch (err) {
console.error(err.message);
}
} else {
console.error("\nPassword verification error.");
}
});
}, 50);
} else {
console.error("\nPassword verification error.");
}
});
} | javascript | function readPassword(program) {
prompt.message = "";
prompt.delimiter = "";
const passportOption = [{name: 'password', description: 'New password:', hidden: true}];
const rePassportOption = [{name: 'rePassword', description: 'Re-type new password:', hidden: true}];
// Try to read password.
prompt.get(passportOption, (err, result) => {
if (!err) {
const password = result.password;
setTimeout(function () {
prompt.get(rePassportOption, (err, result) => {
if (!err && password == result.rePassword) {
program.args.push(password);
try {
processor.syncFile(program);
} catch (err) {
console.error(err.message);
}
} else {
console.error("\nPassword verification error.");
}
});
}, 50);
} else {
console.error("\nPassword verification error.");
}
});
} | [
"function",
"readPassword",
"(",
"program",
")",
"{",
"prompt",
".",
"message",
"=",
"\"\"",
";",
"prompt",
".",
"delimiter",
"=",
"\"\"",
";",
"const",
"passportOption",
"=",
"[",
"{",
"name",
":",
"'password'",
",",
"description",
":",
"'New password:'",
",",
"hidden",
":",
"true",
"}",
"]",
";",
"const",
"rePassportOption",
"=",
"[",
"{",
"name",
":",
"'rePassword'",
",",
"description",
":",
"'Re-type new password:'",
",",
"hidden",
":",
"true",
"}",
"]",
";",
"// Try to read password.",
"prompt",
".",
"get",
"(",
"passportOption",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"const",
"password",
"=",
"result",
".",
"password",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"prompt",
".",
"get",
"(",
"rePassportOption",
",",
"(",
"err",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"!",
"err",
"&&",
"password",
"==",
"result",
".",
"rePassword",
")",
"{",
"program",
".",
"args",
".",
"push",
"(",
"password",
")",
";",
"try",
"{",
"processor",
".",
"syncFile",
"(",
"program",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
".",
"message",
")",
";",
"}",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"\"\\nPassword verification error.\"",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"50",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"\"\\nPassword verification error.\"",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Read password. | [
"Read",
"password",
"."
]
| be5222ea2a72509750d4b5822ce55b97ed658d63 | https://github.com/http-auth/htdigest/blob/be5222ea2a72509750d4b5822ce55b97ed658d63/src/processor.js#L63-L93 |
41,359 | alexhisen/mobx-form-store | src/FormStore.js | observableChanged | function observableChanged(change) {
const store = this;
action(() => {
store.dataChanges.set(change.name, change.newValue);
if (store.isSame(store.dataChanges.get(change.name), store.dataServer[change.name])) {
store.dataChanges.delete(change.name);
}
})();
} | javascript | function observableChanged(change) {
const store = this;
action(() => {
store.dataChanges.set(change.name, change.newValue);
if (store.isSame(store.dataChanges.get(change.name), store.dataServer[change.name])) {
store.dataChanges.delete(change.name);
}
})();
} | [
"function",
"observableChanged",
"(",
"change",
")",
"{",
"const",
"store",
"=",
"this",
";",
"action",
"(",
"(",
")",
"=>",
"{",
"store",
".",
"dataChanges",
".",
"set",
"(",
"change",
".",
"name",
",",
"change",
".",
"newValue",
")",
";",
"if",
"(",
"store",
".",
"isSame",
"(",
"store",
".",
"dataChanges",
".",
"get",
"(",
"change",
".",
"name",
")",
",",
"store",
".",
"dataServer",
"[",
"change",
".",
"name",
"]",
")",
")",
"{",
"store",
".",
"dataChanges",
".",
"delete",
"(",
"change",
".",
"name",
")",
";",
"}",
"}",
")",
"(",
")",
";",
"}"
]
| Observes data and if changes come, add them to dataChanges,
unless it resets back to dataServer value, then clear that change
@this {FormStore}
@param {Object} change
@param {String} change.name - name of property that changed
@param {*} change.newValue | [
"Observes",
"data",
"and",
"if",
"changes",
"come",
"add",
"them",
"to",
"dataChanges",
"unless",
"it",
"resets",
"back",
"to",
"dataServer",
"value",
"then",
"clear",
"that",
"change"
]
| c2058a883c4658aaaefcf1dc3429958c68d59343 | https://github.com/alexhisen/mobx-form-store/blob/c2058a883c4658aaaefcf1dc3429958c68d59343/src/FormStore.js#L19-L28 |
41,360 | alexhisen/mobx-form-store | src/FormStore.js | processSaveResponse | async function processSaveResponse(store, updates, response) {
store.options.log(`[${store.options.name}] Response received from server.`);
if (response.status === 'error') {
action(() => {
let errorFields = [];
if (response.error) {
if (typeof response.error === 'string') {
store.serverError = response.error;
} else {
Object.assign(store.dataErrors, response.error);
errorFields = Object.keys(response.error);
}
}
// Supports an array of field names in error_field or a string
errorFields = errorFields.concat(response.error_field);
errorFields.forEach((field) => {
if (store.options.autoSaveInterval && !store.dataErrors[field] && store.isSame(updates[field], store.data[field])) {
store.data[field] = store.dataServer[field]; // revert or it'll keep trying to autosave it
}
delete updates[field]; // don't save it as the new dataServer value
});
})();
} else {
store.serverError = null;
}
Object.assign(store.dataServer, updates);
action(() => {
if (response.data) {
Object.assign(store.dataServer, response.data);
Object.assign(store.data, response.data);
}
store.dataChanges.forEach((value, key) => {
if (store.isSame(value, store.dataServer[key])) {
store.dataChanges.delete(key);
}
});
})();
if (typeof store.options.afterSave === 'function') {
await store.options.afterSave(store, updates, response);
}
return response.status;
} | javascript | async function processSaveResponse(store, updates, response) {
store.options.log(`[${store.options.name}] Response received from server.`);
if (response.status === 'error') {
action(() => {
let errorFields = [];
if (response.error) {
if (typeof response.error === 'string') {
store.serverError = response.error;
} else {
Object.assign(store.dataErrors, response.error);
errorFields = Object.keys(response.error);
}
}
// Supports an array of field names in error_field or a string
errorFields = errorFields.concat(response.error_field);
errorFields.forEach((field) => {
if (store.options.autoSaveInterval && !store.dataErrors[field] && store.isSame(updates[field], store.data[field])) {
store.data[field] = store.dataServer[field]; // revert or it'll keep trying to autosave it
}
delete updates[field]; // don't save it as the new dataServer value
});
})();
} else {
store.serverError = null;
}
Object.assign(store.dataServer, updates);
action(() => {
if (response.data) {
Object.assign(store.dataServer, response.data);
Object.assign(store.data, response.data);
}
store.dataChanges.forEach((value, key) => {
if (store.isSame(value, store.dataServer[key])) {
store.dataChanges.delete(key);
}
});
})();
if (typeof store.options.afterSave === 'function') {
await store.options.afterSave(store, updates, response);
}
return response.status;
} | [
"async",
"function",
"processSaveResponse",
"(",
"store",
",",
"updates",
",",
"response",
")",
"{",
"store",
".",
"options",
".",
"log",
"(",
"`",
"${",
"store",
".",
"options",
".",
"name",
"}",
"`",
")",
";",
"if",
"(",
"response",
".",
"status",
"===",
"'error'",
")",
"{",
"action",
"(",
"(",
")",
"=>",
"{",
"let",
"errorFields",
"=",
"[",
"]",
";",
"if",
"(",
"response",
".",
"error",
")",
"{",
"if",
"(",
"typeof",
"response",
".",
"error",
"===",
"'string'",
")",
"{",
"store",
".",
"serverError",
"=",
"response",
".",
"error",
";",
"}",
"else",
"{",
"Object",
".",
"assign",
"(",
"store",
".",
"dataErrors",
",",
"response",
".",
"error",
")",
";",
"errorFields",
"=",
"Object",
".",
"keys",
"(",
"response",
".",
"error",
")",
";",
"}",
"}",
"// Supports an array of field names in error_field or a string",
"errorFields",
"=",
"errorFields",
".",
"concat",
"(",
"response",
".",
"error_field",
")",
";",
"errorFields",
".",
"forEach",
"(",
"(",
"field",
")",
"=>",
"{",
"if",
"(",
"store",
".",
"options",
".",
"autoSaveInterval",
"&&",
"!",
"store",
".",
"dataErrors",
"[",
"field",
"]",
"&&",
"store",
".",
"isSame",
"(",
"updates",
"[",
"field",
"]",
",",
"store",
".",
"data",
"[",
"field",
"]",
")",
")",
"{",
"store",
".",
"data",
"[",
"field",
"]",
"=",
"store",
".",
"dataServer",
"[",
"field",
"]",
";",
"// revert or it'll keep trying to autosave it",
"}",
"delete",
"updates",
"[",
"field",
"]",
";",
"// don't save it as the new dataServer value",
"}",
")",
";",
"}",
")",
"(",
")",
";",
"}",
"else",
"{",
"store",
".",
"serverError",
"=",
"null",
";",
"}",
"Object",
".",
"assign",
"(",
"store",
".",
"dataServer",
",",
"updates",
")",
";",
"action",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"response",
".",
"data",
")",
"{",
"Object",
".",
"assign",
"(",
"store",
".",
"dataServer",
",",
"response",
".",
"data",
")",
";",
"Object",
".",
"assign",
"(",
"store",
".",
"data",
",",
"response",
".",
"data",
")",
";",
"}",
"store",
".",
"dataChanges",
".",
"forEach",
"(",
"(",
"value",
",",
"key",
")",
"=>",
"{",
"if",
"(",
"store",
".",
"isSame",
"(",
"value",
",",
"store",
".",
"dataServer",
"[",
"key",
"]",
")",
")",
"{",
"store",
".",
"dataChanges",
".",
"delete",
"(",
"key",
")",
";",
"}",
"}",
")",
";",
"}",
")",
"(",
")",
";",
"if",
"(",
"typeof",
"store",
".",
"options",
".",
"afterSave",
"===",
"'function'",
")",
"{",
"await",
"store",
".",
"options",
".",
"afterSave",
"(",
"store",
",",
"updates",
",",
"response",
")",
";",
"}",
"return",
"response",
".",
"status",
";",
"}"
]
| Records successfully saved data as saved
and reverts fields server indicates to be in error
@param {FormStore} store
@param {Object} updates - what we sent to the server
@param {Object} response
@param {String} [response.data] - optional updated data to merge into the store (server.create can return id here)
@param {String} [response.status] - 'error' indicates one or more fields were invalid and not saved.
@param {String|Object} [response.error] - either a single error message to show to user if string or field-specific error messages if object
@param {String|Array} [response.error_field] - name of the field (or array of field names) in error
If autoSave is enabled, any field in error_field for which there is no error message in response.error will be reverted
to prevent autoSave from endlessly trying to save the changed field.
@returns response.status | [
"Records",
"successfully",
"saved",
"data",
"as",
"saved",
"and",
"reverts",
"fields",
"server",
"indicates",
"to",
"be",
"in",
"error"
]
| c2058a883c4658aaaefcf1dc3429958c68d59343 | https://github.com/alexhisen/mobx-form-store/blob/c2058a883c4658aaaefcf1dc3429958c68d59343/src/FormStore.js#L43-L91 |
41,361 | AZaviruha/react-form-generator | src/tools/routing.js | buildRouter | function buildRouter () {
var args = g.argsToArray( arguments )
, simpleConf = {}
, regexpConf = []
, reLength
, i, len, route, handlers;
if ( (args.length === 0) || (args.length % 2 !== 0) )
throw new Error( 'Wrong number of arguments!' );
for ( i = 0, len = args.length; i < len; i+=2 ) {
route = args[ i ];
handlers = args[ i + 1 ];
if ( route instanceof RegExp )
regexpConf.push([ route, handlers ]);
else
simpleConf[ route ] = handlers;
}
reLength = regexpConf.length;
/**
* Search path in `simpleConf` and `regexpConf`
* and runs all handlers of mathed path.
* @param {String} path - path to route.
*/
return function route ( path ) {
var values = g.argsToArray( arguments ).slice( 1 )
, checkedPath, handlers
, i, len;
/** Checks simple routes first. */
handlers = simpleConf[ path ];
/** Checks regexp routes last. */
if ( !g.getOrNull( handlers, 'length' ) )
for ( i = 0; i < reLength; i++ ) {
checkedPath = regexpConf[ i ][ 0 ];
if ( checkedPath.test(path) ) {
handlers = regexpConf[ i ][ 1 ];
break;
}
}
/** Run each handler of matched route. */
if ( handlers && handlers.length )
for ( i = 0, len = handlers.length; i < len; i++ ) {
handlers[ i ].apply( this, values );
}
};
} | javascript | function buildRouter () {
var args = g.argsToArray( arguments )
, simpleConf = {}
, regexpConf = []
, reLength
, i, len, route, handlers;
if ( (args.length === 0) || (args.length % 2 !== 0) )
throw new Error( 'Wrong number of arguments!' );
for ( i = 0, len = args.length; i < len; i+=2 ) {
route = args[ i ];
handlers = args[ i + 1 ];
if ( route instanceof RegExp )
regexpConf.push([ route, handlers ]);
else
simpleConf[ route ] = handlers;
}
reLength = regexpConf.length;
/**
* Search path in `simpleConf` and `regexpConf`
* and runs all handlers of mathed path.
* @param {String} path - path to route.
*/
return function route ( path ) {
var values = g.argsToArray( arguments ).slice( 1 )
, checkedPath, handlers
, i, len;
/** Checks simple routes first. */
handlers = simpleConf[ path ];
/** Checks regexp routes last. */
if ( !g.getOrNull( handlers, 'length' ) )
for ( i = 0; i < reLength; i++ ) {
checkedPath = regexpConf[ i ][ 0 ];
if ( checkedPath.test(path) ) {
handlers = regexpConf[ i ][ 1 ];
break;
}
}
/** Run each handler of matched route. */
if ( handlers && handlers.length )
for ( i = 0, len = handlers.length; i < len; i++ ) {
handlers[ i ].apply( this, values );
}
};
} | [
"function",
"buildRouter",
"(",
")",
"{",
"var",
"args",
"=",
"g",
".",
"argsToArray",
"(",
"arguments",
")",
",",
"simpleConf",
"=",
"{",
"}",
",",
"regexpConf",
"=",
"[",
"]",
",",
"reLength",
",",
"i",
",",
"len",
",",
"route",
",",
"handlers",
";",
"if",
"(",
"(",
"args",
".",
"length",
"===",
"0",
")",
"||",
"(",
"args",
".",
"length",
"%",
"2",
"!==",
"0",
")",
")",
"throw",
"new",
"Error",
"(",
"'Wrong number of arguments!'",
")",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"args",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"2",
")",
"{",
"route",
"=",
"args",
"[",
"i",
"]",
";",
"handlers",
"=",
"args",
"[",
"i",
"+",
"1",
"]",
";",
"if",
"(",
"route",
"instanceof",
"RegExp",
")",
"regexpConf",
".",
"push",
"(",
"[",
"route",
",",
"handlers",
"]",
")",
";",
"else",
"simpleConf",
"[",
"route",
"]",
"=",
"handlers",
";",
"}",
"reLength",
"=",
"regexpConf",
".",
"length",
";",
"/**\n * Search path in `simpleConf` and `regexpConf`\n * and runs all handlers of mathed path.\n * @param {String} path - path to route.\n */",
"return",
"function",
"route",
"(",
"path",
")",
"{",
"var",
"values",
"=",
"g",
".",
"argsToArray",
"(",
"arguments",
")",
".",
"slice",
"(",
"1",
")",
",",
"checkedPath",
",",
"handlers",
",",
"i",
",",
"len",
";",
"/** Checks simple routes first. */",
"handlers",
"=",
"simpleConf",
"[",
"path",
"]",
";",
"/** Checks regexp routes last. */",
"if",
"(",
"!",
"g",
".",
"getOrNull",
"(",
"handlers",
",",
"'length'",
")",
")",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"reLength",
";",
"i",
"++",
")",
"{",
"checkedPath",
"=",
"regexpConf",
"[",
"i",
"]",
"[",
"0",
"]",
";",
"if",
"(",
"checkedPath",
".",
"test",
"(",
"path",
")",
")",
"{",
"handlers",
"=",
"regexpConf",
"[",
"i",
"]",
"[",
"1",
"]",
";",
"break",
";",
"}",
"}",
"/** Run each handler of matched route. */",
"if",
"(",
"handlers",
"&&",
"handlers",
".",
"length",
")",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"handlers",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"handlers",
"[",
"i",
"]",
".",
"apply",
"(",
"this",
",",
"values",
")",
";",
"}",
"}",
";",
"}"
]
| Builds a routing function, that matches
event's name to the list of handlers
and executes all of them.
@param {string|RegExp} event1 - event's mask.
@param [Function] handlers1 - handlers for event1.
@param {string|RegExp} event2 - event's mask.
@param [Function] handlers2 - handlers for event2.
...
@returns {Function} | [
"Builds",
"a",
"routing",
"function",
"that",
"matches",
"event",
"s",
"name",
"to",
"the",
"list",
"of",
"handlers",
"and",
"executes",
"all",
"of",
"them",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/tools/routing.js#L15-L66 |
41,362 | AZaviruha/react-form-generator | src/validation/index.js | composite | function composite ( comb, zero ) {
return function ( conf, value, fieldMeta ) {
var validators = conf.value;
return reduce(function ( acc, v ) {
var f = VALIDATORS[ v.rule ];
checkRuleExistence( f, v.rule );
return comb( acc, f( v, value, fieldMeta ) );
}, zero, validators );
};
} | javascript | function composite ( comb, zero ) {
return function ( conf, value, fieldMeta ) {
var validators = conf.value;
return reduce(function ( acc, v ) {
var f = VALIDATORS[ v.rule ];
checkRuleExistence( f, v.rule );
return comb( acc, f( v, value, fieldMeta ) );
}, zero, validators );
};
} | [
"function",
"composite",
"(",
"comb",
",",
"zero",
")",
"{",
"return",
"function",
"(",
"conf",
",",
"value",
",",
"fieldMeta",
")",
"{",
"var",
"validators",
"=",
"conf",
".",
"value",
";",
"return",
"reduce",
"(",
"function",
"(",
"acc",
",",
"v",
")",
"{",
"var",
"f",
"=",
"VALIDATORS",
"[",
"v",
".",
"rule",
"]",
";",
"checkRuleExistence",
"(",
"f",
",",
"v",
".",
"rule",
")",
";",
"return",
"comb",
"(",
"acc",
",",
"f",
"(",
"v",
",",
"value",
",",
"fieldMeta",
")",
")",
";",
"}",
",",
"zero",
",",
"validators",
")",
";",
"}",
";",
"}"
]
| Build composite validator, which
combines result of all nested validators
by `comb` function.
@param {Function} comp - `and`, `or`, etc.
@param {Object} zero - intital value of composite
validator result.
@returns {Function) | [
"Build",
"composite",
"validator",
"which",
"combines",
"result",
"of",
"all",
"nested",
"validators",
"by",
"comb",
"function",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L32-L41 |
41,363 | AZaviruha/react-form-generator | src/validation/index.js | checkByRule | function checkByRule ( ruleInfo, value, fieldMeta ) {
var rule = ruleInfo.rule
, isValid = VALIDATORS[ rule ];
checkRuleExistence( isValid, rule );
return isValid( ruleInfo, value, fieldMeta ) ? null : ruleInfo;
} | javascript | function checkByRule ( ruleInfo, value, fieldMeta ) {
var rule = ruleInfo.rule
, isValid = VALIDATORS[ rule ];
checkRuleExistence( isValid, rule );
return isValid( ruleInfo, value, fieldMeta ) ? null : ruleInfo;
} | [
"function",
"checkByRule",
"(",
"ruleInfo",
",",
"value",
",",
"fieldMeta",
")",
"{",
"var",
"rule",
"=",
"ruleInfo",
".",
"rule",
",",
"isValid",
"=",
"VALIDATORS",
"[",
"rule",
"]",
";",
"checkRuleExistence",
"(",
"isValid",
",",
"rule",
")",
";",
"return",
"isValid",
"(",
"ruleInfo",
",",
"value",
",",
"fieldMeta",
")",
"?",
"null",
":",
"ruleInfo",
";",
"}"
]
| Validates field's value against of validation rule.
Returs sublist of validateion rules that was not sutisfied
by value.
@param {Object} ruleInfo - validation rules.
@param {Object} value - value to validate.
@param {Object} fieldMeta - for some validation rules
field meta is required.
@returns {Object} | [
"Validates",
"field",
"s",
"value",
"against",
"of",
"validation",
"rule",
".",
"Returs",
"sublist",
"of",
"validateion",
"rules",
"that",
"was",
"not",
"sutisfied",
"by",
"value",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L54-L60 |
41,364 | AZaviruha/react-form-generator | src/validation/index.js | checkByAll | function checkByAll ( rules, value, fieldMeta ) {
return (rules || [])
.map(function ( rule ) {
return checkByRule( rule, value, fieldMeta );
})
.filter(function ( el ) { return null !== el; });
} | javascript | function checkByAll ( rules, value, fieldMeta ) {
return (rules || [])
.map(function ( rule ) {
return checkByRule( rule, value, fieldMeta );
})
.filter(function ( el ) { return null !== el; });
} | [
"function",
"checkByAll",
"(",
"rules",
",",
"value",
",",
"fieldMeta",
")",
"{",
"return",
"(",
"rules",
"||",
"[",
"]",
")",
".",
"map",
"(",
"function",
"(",
"rule",
")",
"{",
"return",
"checkByRule",
"(",
"rule",
",",
"value",
",",
"fieldMeta",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"null",
"!==",
"el",
";",
"}",
")",
";",
"}"
]
| Validates field's value against list of validation rules.
Returs sublist of validation rules that was not sutisfied
by value.
@param {Object[]} rules - list of validation rules.
@param {Object} value - value to validate.
@returns {Object[]} | [
"Validates",
"field",
"s",
"value",
"against",
"list",
"of",
"validation",
"rules",
".",
"Returs",
"sublist",
"of",
"validation",
"rules",
"that",
"was",
"not",
"sutisfied",
"by",
"value",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L76-L82 |
41,365 | AZaviruha/react-form-generator | src/validation/index.js | validateField | function validateField ( fldID, fieldMeta, value ) {
var res = {}
, errs = checkByAll( fieldMeta.validators, value, fieldMeta );
res[ fldID ] = errs.length ? errs : null;
return res;
} | javascript | function validateField ( fldID, fieldMeta, value ) {
var res = {}
, errs = checkByAll( fieldMeta.validators, value, fieldMeta );
res[ fldID ] = errs.length ? errs : null;
return res;
} | [
"function",
"validateField",
"(",
"fldID",
",",
"fieldMeta",
",",
"value",
")",
"{",
"var",
"res",
"=",
"{",
"}",
",",
"errs",
"=",
"checkByAll",
"(",
"fieldMeta",
".",
"validators",
",",
"value",
",",
"fieldMeta",
")",
";",
"res",
"[",
"fldID",
"]",
"=",
"errs",
".",
"length",
"?",
"errs",
":",
"null",
";",
"return",
"res",
";",
"}"
]
| Calculates field's validity by it's meta and value.
@param {Object} fieldMeta - metadata of one field
in FormGenerator format.
@param {Object} value - { %fieldID%: %fieldValue% }
@return {Object[]} - [ %failed_validators% ] | [
"Calculates",
"field",
"s",
"validity",
"by",
"it",
"s",
"meta",
"and",
"value",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L92-L97 |
41,366 | AZaviruha/react-form-generator | src/validation/index.js | validateFields | function validateFields ( fldsMeta, fldsValue ) {
return reduce(function ( acc, fldMeta, fldID ) {
var value = getOrNull( fldsValue, fldID )
, errors = validateField( fldID, fldMeta, value );
return t.merge( acc, errors );
}, {}, fldsMeta );
} | javascript | function validateFields ( fldsMeta, fldsValue ) {
return reduce(function ( acc, fldMeta, fldID ) {
var value = getOrNull( fldsValue, fldID )
, errors = validateField( fldID, fldMeta, value );
return t.merge( acc, errors );
}, {}, fldsMeta );
} | [
"function",
"validateFields",
"(",
"fldsMeta",
",",
"fldsValue",
")",
"{",
"return",
"reduce",
"(",
"function",
"(",
"acc",
",",
"fldMeta",
",",
"fldID",
")",
"{",
"var",
"value",
"=",
"getOrNull",
"(",
"fldsValue",
",",
"fldID",
")",
",",
"errors",
"=",
"validateField",
"(",
"fldID",
",",
"fldMeta",
",",
"value",
")",
";",
"return",
"t",
".",
"merge",
"(",
"acc",
",",
"errors",
")",
";",
"}",
",",
"{",
"}",
",",
"fldsMeta",
")",
";",
"}"
]
| Calculates validity of the array of fields.
@param {Object[]} fldsMeta - array of metadata.
@param {Object[]} fldsValue - map with fields value.
@returns {Object} - {
%fieldID%: [ %failed_validators% ],
...
} | [
"Calculates",
"validity",
"of",
"the",
"array",
"of",
"fields",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L109-L115 |
41,367 | AZaviruha/react-form-generator | src/validation/index.js | validateForm | function validateForm ( formMeta, formValue ) {
var fields = getOrNull( formMeta, 'fields' )
, validable = reduce(function ( acc, fld, fldID ) {
var noValidate = !t.isDefined( fld.validators )
|| fld.isHidden
|| fld.isReadOnly
, fldMeta = {};
if ( noValidate ) return acc;
else {
fldMeta[ fldID ] = fld;
return t.merge( acc, fldMeta );
}
}, {}, fields );
return validateFields( validable, formValue );
} | javascript | function validateForm ( formMeta, formValue ) {
var fields = getOrNull( formMeta, 'fields' )
, validable = reduce(function ( acc, fld, fldID ) {
var noValidate = !t.isDefined( fld.validators )
|| fld.isHidden
|| fld.isReadOnly
, fldMeta = {};
if ( noValidate ) return acc;
else {
fldMeta[ fldID ] = fld;
return t.merge( acc, fldMeta );
}
}, {}, fields );
return validateFields( validable, formValue );
} | [
"function",
"validateForm",
"(",
"formMeta",
",",
"formValue",
")",
"{",
"var",
"fields",
"=",
"getOrNull",
"(",
"formMeta",
",",
"'fields'",
")",
",",
"validable",
"=",
"reduce",
"(",
"function",
"(",
"acc",
",",
"fld",
",",
"fldID",
")",
"{",
"var",
"noValidate",
"=",
"!",
"t",
".",
"isDefined",
"(",
"fld",
".",
"validators",
")",
"||",
"fld",
".",
"isHidden",
"||",
"fld",
".",
"isReadOnly",
",",
"fldMeta",
"=",
"{",
"}",
";",
"if",
"(",
"noValidate",
")",
"return",
"acc",
";",
"else",
"{",
"fldMeta",
"[",
"fldID",
"]",
"=",
"fld",
";",
"return",
"t",
".",
"merge",
"(",
"acc",
",",
"fldMeta",
")",
";",
"}",
"}",
",",
"{",
"}",
",",
"fields",
")",
";",
"return",
"validateFields",
"(",
"validable",
",",
"formValue",
")",
";",
"}"
]
| Calculates form's validity by it's meta and value.
Wraps `validateFields` and filters array of fields
before validation.
@param {Object} formMeta - metadata in GeneratedForm format.
@param {Object} formValue - data in GeneratedForm format.
@returns {Object} - {
%fieldID%: [ %failed_validators% ],
...
} | [
"Calculates",
"form",
"s",
"validity",
"by",
"it",
"s",
"meta",
"and",
"value",
".",
"Wraps",
"validateFields",
"and",
"filters",
"array",
"of",
"fields",
"before",
"validation",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L129-L146 |
41,368 | AZaviruha/react-form-generator | src/validation/index.js | isFormValid | function isFormValid ( formErrors ) {
return t.reduce(function ( acc, v, k ) {
return acc && !(v && v.length);
}, true, formErrors );
} | javascript | function isFormValid ( formErrors ) {
return t.reduce(function ( acc, v, k ) {
return acc && !(v && v.length);
}, true, formErrors );
} | [
"function",
"isFormValid",
"(",
"formErrors",
")",
"{",
"return",
"t",
".",
"reduce",
"(",
"function",
"(",
"acc",
",",
"v",
",",
"k",
")",
"{",
"return",
"acc",
"&&",
"!",
"(",
"v",
"&&",
"v",
".",
"length",
")",
";",
"}",
",",
"true",
",",
"formErrors",
")",
";",
"}"
]
| Accepts result of `validateForm` and returns true
if `formErrors` contains only null-values.
@param {Object} formErrors - {
%fieldID%: [ %failed_validators% ],
...
}
@returns {Boolean} | [
"Accepts",
"result",
"of",
"validateForm",
"and",
"returns",
"true",
"if",
"formErrors",
"contains",
"only",
"null",
"-",
"values",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/validation/index.js#L158-L162 |
41,369 | julienetie/resizilla | dist/resizilla.js | setTimeoutWithTimestamp | function setTimeoutWithTimestamp(callback) {
const immediateTime = Date.now();
let lapsedTime = Math.max(previousTime + 16, immediateTime);
return setTimeout(function () {
callback(previousTime = lapsedTime);
}, lapsedTime - immediateTime);
} | javascript | function setTimeoutWithTimestamp(callback) {
const immediateTime = Date.now();
let lapsedTime = Math.max(previousTime + 16, immediateTime);
return setTimeout(function () {
callback(previousTime = lapsedTime);
}, lapsedTime - immediateTime);
} | [
"function",
"setTimeoutWithTimestamp",
"(",
"callback",
")",
"{",
"const",
"immediateTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"let",
"lapsedTime",
"=",
"Math",
".",
"max",
"(",
"previousTime",
"+",
"16",
",",
"immediateTime",
")",
";",
"return",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"callback",
"(",
"previousTime",
"=",
"lapsedTime",
")",
";",
"}",
",",
"lapsedTime",
"-",
"immediateTime",
")",
";",
"}"
]
| IE-9 Polyfill for requestAnimationFrame
@callback {Number} Timestamp.
@return {Function} setTimeout Function. | [
"IE",
"-",
"9",
"Polyfill",
"for",
"requestAnimationFrame"
]
| a73b4177dcf303438c6a93e8d33bd6dd578d3910 | https://github.com/julienetie/resizilla/blob/a73b4177dcf303438c6a93e8d33bd6dd578d3910/dist/resizilla.js#L45-L51 |
41,370 | julienetie/resizilla | dist/resizilla.js | debounce | function debounce(callback, delay, lead) {
var debounceRange = 0;
var currentTime;
var lastCall;
var setDelay;
var timeoutId;
const call = parameters => {
callback(parameters);
};
return parameters => {
if (lead) {
currentTime = Date.now();
if (currentTime > debounceRange) {
callback(parameters);
}
debounceRange = currentTime + delay;
} else {
/**
* setTimeout is only used with the trail option.
*/
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
call(parameters);
}, delay);
}
};
} | javascript | function debounce(callback, delay, lead) {
var debounceRange = 0;
var currentTime;
var lastCall;
var setDelay;
var timeoutId;
const call = parameters => {
callback(parameters);
};
return parameters => {
if (lead) {
currentTime = Date.now();
if (currentTime > debounceRange) {
callback(parameters);
}
debounceRange = currentTime + delay;
} else {
/**
* setTimeout is only used with the trail option.
*/
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
call(parameters);
}, delay);
}
};
} | [
"function",
"debounce",
"(",
"callback",
",",
"delay",
",",
"lead",
")",
"{",
"var",
"debounceRange",
"=",
"0",
";",
"var",
"currentTime",
";",
"var",
"lastCall",
";",
"var",
"setDelay",
";",
"var",
"timeoutId",
";",
"const",
"call",
"=",
"parameters",
"=>",
"{",
"callback",
"(",
"parameters",
")",
";",
"}",
";",
"return",
"parameters",
"=>",
"{",
"if",
"(",
"lead",
")",
"{",
"currentTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"if",
"(",
"currentTime",
">",
"debounceRange",
")",
"{",
"callback",
"(",
"parameters",
")",
";",
"}",
"debounceRange",
"=",
"currentTime",
"+",
"delay",
";",
"}",
"else",
"{",
"/**\n * setTimeout is only used with the trail option.\n */",
"clearTimeout",
"(",
"timeoutId",
")",
";",
"timeoutId",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"call",
"(",
"parameters",
")",
";",
"}",
",",
"delay",
")",
";",
"}",
"}",
";",
"}"
]
| Debounce a function call during repetiton.
@param {Function} callback - Callback function.
@param {Number} delay - Delay in milliseconds.
@param {Boolean} lead - Leading or trailing.
@return {Function} - The debounce function. | [
"Debounce",
"a",
"function",
"call",
"during",
"repetiton",
"."
]
| a73b4177dcf303438c6a93e8d33bd6dd578d3910 | https://github.com/julienetie/resizilla/blob/a73b4177dcf303438c6a93e8d33bd6dd578d3910/dist/resizilla.js#L90-L118 |
41,371 | timwhitlock/node-twitter-api | lib/twitter.js | uriEncodeParams | function uriEncodeParams( obj ){
var pairs = [], key;
for( key in obj ){
pairs.push( uriEncodeString(key) +'='+ uriEncodeString(obj[key]) );
}
return pairs.join('&');
} | javascript | function uriEncodeParams( obj ){
var pairs = [], key;
for( key in obj ){
pairs.push( uriEncodeString(key) +'='+ uriEncodeString(obj[key]) );
}
return pairs.join('&');
} | [
"function",
"uriEncodeParams",
"(",
"obj",
")",
"{",
"var",
"pairs",
"=",
"[",
"]",
",",
"key",
";",
"for",
"(",
"key",
"in",
"obj",
")",
"{",
"pairs",
".",
"push",
"(",
"uriEncodeString",
"(",
"key",
")",
"+",
"'='",
"+",
"uriEncodeString",
"(",
"obj",
"[",
"key",
"]",
")",
")",
";",
"}",
"return",
"pairs",
".",
"join",
"(",
"'&'",
")",
";",
"}"
]
| OAuth safe encodeURIComponent of params object | [
"OAuth",
"safe",
"encodeURIComponent",
"of",
"params",
"object"
]
| 6ac423f9c718153c7fac24ce76fb6ae90707ec30 | https://github.com/timwhitlock/node-twitter-api/blob/6ac423f9c718153c7fac24ce76fb6ae90707ec30/lib/twitter.js#L39-L45 |
41,372 | timwhitlock/node-twitter-api | lib/twitter.js | OAuthToken | function OAuthToken( key, secret ){
if( ! key || ! secret ){
throw new Error('OAuthToken params must not be empty');
}
this.key = key;
this.secret = secret;
} | javascript | function OAuthToken( key, secret ){
if( ! key || ! secret ){
throw new Error('OAuthToken params must not be empty');
}
this.key = key;
this.secret = secret;
} | [
"function",
"OAuthToken",
"(",
"key",
",",
"secret",
")",
"{",
"if",
"(",
"!",
"key",
"||",
"!",
"secret",
")",
"{",
"throw",
"new",
"Error",
"(",
"'OAuthToken params must not be empty'",
")",
";",
"}",
"this",
".",
"key",
"=",
"key",
";",
"this",
".",
"secret",
"=",
"secret",
";",
"}"
]
| Simple token object that holds key and secret | [
"Simple",
"token",
"object",
"that",
"holds",
"key",
"and",
"secret"
]
| 6ac423f9c718153c7fac24ce76fb6ae90707ec30 | https://github.com/timwhitlock/node-twitter-api/blob/6ac423f9c718153c7fac24ce76fb6ae90707ec30/lib/twitter.js#L51-L57 |
41,373 | FormidableLabs/multibot | lib/repos.js | function (cb) {
async.map(self._repos, function (repo, repoCb) {
self._client.gitdata.getReference({
user: self._repoParts[repo].org,
repo: self._repoParts[repo].repo,
ref: branchSrcFull
}, function (err, res) {
if (self._checkAndHandleError(err, repo, repoCb)) { return; }
repoCb(null, {
repo: repo,
sha: res.object.sha
});
});
}, cb);
} | javascript | function (cb) {
async.map(self._repos, function (repo, repoCb) {
self._client.gitdata.getReference({
user: self._repoParts[repo].org,
repo: self._repoParts[repo].repo,
ref: branchSrcFull
}, function (err, res) {
if (self._checkAndHandleError(err, repo, repoCb)) { return; }
repoCb(null, {
repo: repo,
sha: res.object.sha
});
});
}, cb);
} | [
"function",
"(",
"cb",
")",
"{",
"async",
".",
"map",
"(",
"self",
".",
"_repos",
",",
"function",
"(",
"repo",
",",
"repoCb",
")",
"{",
"self",
".",
"_client",
".",
"gitdata",
".",
"getReference",
"(",
"{",
"user",
":",
"self",
".",
"_repoParts",
"[",
"repo",
"]",
".",
"org",
",",
"repo",
":",
"self",
".",
"_repoParts",
"[",
"repo",
"]",
".",
"repo",
",",
"ref",
":",
"branchSrcFull",
"}",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"self",
".",
"_checkAndHandleError",
"(",
"err",
",",
"repo",
",",
"repoCb",
")",
")",
"{",
"return",
";",
"}",
"repoCb",
"(",
"null",
",",
"{",
"repo",
":",
"repo",
",",
"sha",
":",
"res",
".",
"object",
".",
"sha",
"}",
")",
";",
"}",
")",
";",
"}",
",",
"cb",
")",
";",
"}"
]
| Get the most recent commit of the source branch. | [
"Get",
"the",
"most",
"recent",
"commit",
"of",
"the",
"source",
"branch",
"."
]
| 2434455354f74926aa85b2bbf2eb1548e873cc82 | https://github.com/FormidableLabs/multibot/blob/2434455354f74926aa85b2bbf2eb1548e873cc82/lib/repos.js#L372-L386 |
|
41,374 | FormidableLabs/multibot | lib/repos.js | function (cb) {
async.map(self._repos, function (repo, repoCb) {
self._client.gitdata.getReference({
user: self._repoParts[repo].org,
repo: self._repoParts[repo].repo,
ref: branchDestFull
}, function (err, res) {
// Allow not found.
if (err && err.code === NOT_FOUND) {
repoCb(null, {
repo: repo,
exists: false,
sha: null
});
return;
}
// Real error.
if (self._checkAndHandleError(err, "branch.getDestRefs - " + repo, repoCb)) {
return;
}
// Error if existing branches are not allowed.
var sha = res.object.sha;
if (!self._allowExisting) {
self._checkAndHandleError(
new Error("Found existing dest branch in repo: " + repo + " with sha: " + sha),
null,
repoCb);
return;
}
// Have an allowed, existing branch.
repoCb(null, {
repo: repo,
exists: true,
sha: sha
});
});
}, cb);
} | javascript | function (cb) {
async.map(self._repos, function (repo, repoCb) {
self._client.gitdata.getReference({
user: self._repoParts[repo].org,
repo: self._repoParts[repo].repo,
ref: branchDestFull
}, function (err, res) {
// Allow not found.
if (err && err.code === NOT_FOUND) {
repoCb(null, {
repo: repo,
exists: false,
sha: null
});
return;
}
// Real error.
if (self._checkAndHandleError(err, "branch.getDestRefs - " + repo, repoCb)) {
return;
}
// Error if existing branches are not allowed.
var sha = res.object.sha;
if (!self._allowExisting) {
self._checkAndHandleError(
new Error("Found existing dest branch in repo: " + repo + " with sha: " + sha),
null,
repoCb);
return;
}
// Have an allowed, existing branch.
repoCb(null, {
repo: repo,
exists: true,
sha: sha
});
});
}, cb);
} | [
"function",
"(",
"cb",
")",
"{",
"async",
".",
"map",
"(",
"self",
".",
"_repos",
",",
"function",
"(",
"repo",
",",
"repoCb",
")",
"{",
"self",
".",
"_client",
".",
"gitdata",
".",
"getReference",
"(",
"{",
"user",
":",
"self",
".",
"_repoParts",
"[",
"repo",
"]",
".",
"org",
",",
"repo",
":",
"self",
".",
"_repoParts",
"[",
"repo",
"]",
".",
"repo",
",",
"ref",
":",
"branchDestFull",
"}",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"// Allow not found.",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"===",
"NOT_FOUND",
")",
"{",
"repoCb",
"(",
"null",
",",
"{",
"repo",
":",
"repo",
",",
"exists",
":",
"false",
",",
"sha",
":",
"null",
"}",
")",
";",
"return",
";",
"}",
"// Real error.",
"if",
"(",
"self",
".",
"_checkAndHandleError",
"(",
"err",
",",
"\"branch.getDestRefs - \"",
"+",
"repo",
",",
"repoCb",
")",
")",
"{",
"return",
";",
"}",
"// Error if existing branches are not allowed.",
"var",
"sha",
"=",
"res",
".",
"object",
".",
"sha",
";",
"if",
"(",
"!",
"self",
".",
"_allowExisting",
")",
"{",
"self",
".",
"_checkAndHandleError",
"(",
"new",
"Error",
"(",
"\"Found existing dest branch in repo: \"",
"+",
"repo",
"+",
"\" with sha: \"",
"+",
"sha",
")",
",",
"null",
",",
"repoCb",
")",
";",
"return",
";",
"}",
"// Have an allowed, existing branch.",
"repoCb",
"(",
"null",
",",
"{",
"repo",
":",
"repo",
",",
"exists",
":",
"true",
",",
"sha",
":",
"sha",
"}",
")",
";",
"}",
")",
";",
"}",
",",
"cb",
")",
";",
"}"
]
| Check if the destination branches exist. | [
"Check",
"if",
"the",
"destination",
"branches",
"exist",
"."
]
| 2434455354f74926aa85b2bbf2eb1548e873cc82 | https://github.com/FormidableLabs/multibot/blob/2434455354f74926aa85b2bbf2eb1548e873cc82/lib/repos.js#L389-L429 |
|
41,375 | balderdashy/angularSails | lib/sails.io.js | ajax | function ajax(opts, cb) {
opts = opts || {};
var xmlhttp;
if (typeof window === 'undefined') {
// TODO: refactor node usage to live in here
return cb();
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
};
xmlhttp.open(opts.method, opts.url, true);
xmlhttp.send();
return xmlhttp;
} | javascript | function ajax(opts, cb) {
opts = opts || {};
var xmlhttp;
if (typeof window === 'undefined') {
// TODO: refactor node usage to live in here
return cb();
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
};
xmlhttp.open(opts.method, opts.url, true);
xmlhttp.send();
return xmlhttp;
} | [
"function",
"ajax",
"(",
"opts",
",",
"cb",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"xmlhttp",
";",
"if",
"(",
"typeof",
"window",
"===",
"'undefined'",
")",
"{",
"// TODO: refactor node usage to live in here",
"return",
"cb",
"(",
")",
";",
"}",
"if",
"(",
"window",
".",
"XMLHttpRequest",
")",
"{",
"// code for IE7+, Firefox, Chrome, Opera, Safari",
"xmlhttp",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"}",
"else",
"{",
"// code for IE6, IE5",
"xmlhttp",
"=",
"new",
"ActiveXObject",
"(",
"\"Microsoft.XMLHTTP\"",
")",
";",
"}",
"xmlhttp",
".",
"onreadystatechange",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"xmlhttp",
".",
"readyState",
"==",
"4",
"&&",
"xmlhttp",
".",
"status",
"==",
"200",
")",
"{",
"cb",
"(",
"xmlhttp",
".",
"responseText",
")",
";",
"}",
"}",
";",
"xmlhttp",
".",
"open",
"(",
"opts",
".",
"method",
",",
"opts",
".",
"url",
",",
"true",
")",
";",
"xmlhttp",
".",
"send",
"(",
")",
";",
"return",
"xmlhttp",
";",
"}"
]
| Send an AJAX request.
@param {Object} opts [optional]
@param {Function} cb
@return {XMLHttpRequest} | [
"Send",
"an",
"AJAX",
"request",
"."
]
| 1deb8a05d737e5cb9224096378ebe949586cf570 | https://github.com/balderdashy/angularSails/blob/1deb8a05d737e5cb9224096378ebe949586cf570/lib/sails.io.js#L260-L286 |
41,376 | AZaviruha/react-form-generator | src/tools/general.js | getOrDefault | function getOrDefault ( source, path, defaultVal ) {
var isAlreadySplitted = isArray( path );
if ( !isDefined(source) ) return defaultVal;
if ( !isString(path) && !isAlreadySplitted ) return defaultVal;
var tokens = isAlreadySplitted ? path : path.split( '.' )
, idx, key;
for ( idx in tokens ) {
key = tokens[ idx ];
if ( isDefined( source[key] ) )
source = source[ key ];
else
return defaultVal;
}
return source;
} | javascript | function getOrDefault ( source, path, defaultVal ) {
var isAlreadySplitted = isArray( path );
if ( !isDefined(source) ) return defaultVal;
if ( !isString(path) && !isAlreadySplitted ) return defaultVal;
var tokens = isAlreadySplitted ? path : path.split( '.' )
, idx, key;
for ( idx in tokens ) {
key = tokens[ idx ];
if ( isDefined( source[key] ) )
source = source[ key ];
else
return defaultVal;
}
return source;
} | [
"function",
"getOrDefault",
"(",
"source",
",",
"path",
",",
"defaultVal",
")",
"{",
"var",
"isAlreadySplitted",
"=",
"isArray",
"(",
"path",
")",
";",
"if",
"(",
"!",
"isDefined",
"(",
"source",
")",
")",
"return",
"defaultVal",
";",
"if",
"(",
"!",
"isString",
"(",
"path",
")",
"&&",
"!",
"isAlreadySplitted",
")",
"return",
"defaultVal",
";",
"var",
"tokens",
"=",
"isAlreadySplitted",
"?",
"path",
":",
"path",
".",
"split",
"(",
"'.'",
")",
",",
"idx",
",",
"key",
";",
"for",
"(",
"idx",
"in",
"tokens",
")",
"{",
"key",
"=",
"tokens",
"[",
"idx",
"]",
";",
"if",
"(",
"isDefined",
"(",
"source",
"[",
"key",
"]",
")",
")",
"source",
"=",
"source",
"[",
"key",
"]",
";",
"else",
"return",
"defaultVal",
";",
"}",
"return",
"source",
";",
"}"
]
| Returns path's value or null if path's chain has undefined member.
@param {Object} source - root object.
@param {string} path - path to `source` value.
@return {Object} | [
"Returns",
"path",
"s",
"value",
"or",
"null",
"if",
"path",
"s",
"chain",
"has",
"undefined",
"member",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/tools/general.js#L33-L52 |
41,377 | AZaviruha/react-form-generator | src/tools/general.js | arrayToObject | function arrayToObject ( keyPath, arr ) {
var res = {}, key, element;
for ( var i = 0, len = arr.length; i < len; i++ ) {
element = arr[ i ];
key = getOrNull( element, keyPath );
if ( key ) res[ key ] = element;
}
return res;
} | javascript | function arrayToObject ( keyPath, arr ) {
var res = {}, key, element;
for ( var i = 0, len = arr.length; i < len; i++ ) {
element = arr[ i ];
key = getOrNull( element, keyPath );
if ( key ) res[ key ] = element;
}
return res;
} | [
"function",
"arrayToObject",
"(",
"keyPath",
",",
"arr",
")",
"{",
"var",
"res",
"=",
"{",
"}",
",",
"key",
",",
"element",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"element",
"=",
"arr",
"[",
"i",
"]",
";",
"key",
"=",
"getOrNull",
"(",
"element",
",",
"keyPath",
")",
";",
"if",
"(",
"key",
")",
"res",
"[",
"key",
"]",
"=",
"element",
";",
"}",
"return",
"res",
";",
"}"
]
| Converts array to object, using `keyPath`
for building unique keys.
@param {(String|Array)} keyPath - path to `key` value
in the array element.
@param {Object[]} - array to convert.
@return {Object} | [
"Converts",
"array",
"to",
"object",
"using",
"keyPath",
"for",
"building",
"unique",
"keys",
"."
]
| d3ce8ef216f9d888f5ed641c33456821fce902c2 | https://github.com/AZaviruha/react-form-generator/blob/d3ce8ef216f9d888f5ed641c33456821fce902c2/src/tools/general.js#L69-L79 |
41,378 | vincentmorneau/node-package-configurator | lib/src/js/bf.js | createPropertyProvider | function createPropertyProvider(getValue, onchange) {
var ret = new Object();
ret.getValue = getValue;
ret.onchange = onchange;
return ret;
} | javascript | function createPropertyProvider(getValue, onchange) {
var ret = new Object();
ret.getValue = getValue;
ret.onchange = onchange;
return ret;
} | [
"function",
"createPropertyProvider",
"(",
"getValue",
",",
"onchange",
")",
"{",
"var",
"ret",
"=",
"new",
"Object",
"(",
")",
";",
"ret",
".",
"getValue",
"=",
"getValue",
";",
"ret",
".",
"onchange",
"=",
"onchange",
";",
"return",
"ret",
";",
"}"
]
| Used in object additionalProperties and arrays
@param {type} getValue
@param {type} onchange
@returns {Object.create.createPropertyProvider.ret} | [
"Used",
"in",
"object",
"additionalProperties",
"and",
"arrays"
]
| 489df6129a26238e8d783a3dfab1f354e27994a9 | https://github.com/vincentmorneau/node-package-configurator/blob/489df6129a26238e8d783a3dfab1f354e27994a9/lib/src/js/bf.js#L1239-L1244 |
41,379 | jwilsson/domtokenlist | dist/domtokenlist.js | function (fn) {
return function () {
var tokens = arguments;
var i;
for (i = 0; i < tokens.length; i += 1) {
fn.call(this, tokens[i]);
}
};
} | javascript | function (fn) {
return function () {
var tokens = arguments;
var i;
for (i = 0; i < tokens.length; i += 1) {
fn.call(this, tokens[i]);
}
};
} | [
"function",
"(",
"fn",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"tokens",
"=",
"arguments",
";",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"tokens",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"fn",
".",
"call",
"(",
"this",
",",
"tokens",
"[",
"i",
"]",
")",
";",
"}",
"}",
";",
"}"
]
| Older versions of the HTMLElement.classList spec didn't allow multiple arguments, easy to test for | [
"Older",
"versions",
"of",
"the",
"HTMLElement",
".",
"classList",
"spec",
"didn",
"t",
"allow",
"multiple",
"arguments",
"easy",
"to",
"test",
"for"
]
| 4c643cd6aef8b8051822d86f60a4cdbccdca7dd2 | https://github.com/jwilsson/domtokenlist/blob/4c643cd6aef8b8051822d86f60a4cdbccdca7dd2/dist/domtokenlist.js#L19-L28 |
|
41,380 | Couto/Blueprint | src/Blueprint.js | function (methods) {
methods = [].concat(methods);
var i = methods.length - 1;
for (i; i >= 0; i -= 1) {
this[methods[i]] = proxy(this[methods[i]], this);
}
return this;
} | javascript | function (methods) {
methods = [].concat(methods);
var i = methods.length - 1;
for (i; i >= 0; i -= 1) {
this[methods[i]] = proxy(this[methods[i]], this);
}
return this;
} | [
"function",
"(",
"methods",
")",
"{",
"methods",
"=",
"[",
"]",
".",
"concat",
"(",
"methods",
")",
";",
"var",
"i",
"=",
"methods",
".",
"length",
"-",
"1",
";",
"for",
"(",
"i",
";",
"i",
">=",
"0",
";",
"i",
"-=",
"1",
")",
"{",
"this",
"[",
"methods",
"[",
"i",
"]",
"]",
"=",
"proxy",
"(",
"this",
"[",
"methods",
"[",
"i",
"]",
"]",
",",
"this",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| Describe what this method does
@public
@param {String|Object|Array|Boolean|Number} paramName Describe this parameter
@returns Describe what it returns
@type String|Object|Array|Boolean|Number | [
"Describe",
"what",
"this",
"method",
"does"
]
| 90dd099f40c6d6313a12a83d3450685704b6f6e0 | https://github.com/Couto/Blueprint/blob/90dd099f40c6d6313a12a83d3450685704b6f6e0/src/Blueprint.js#L123-L132 |
|
41,381 | voxel/voxel-mesher | mesh-buffer.js | createVoxelMesh | function createVoxelMesh(gl, voxels, voxelSideTextureIDs, voxelSideTextureSizes, position, pad, that) {
//Create mesh
var vert_data = createAOMesh(voxels, voxelSideTextureIDs, voxelSideTextureSizes)
var vertexArrayObjects = {}
if (vert_data === null) {
// no vertices allocated
} else {
//Upload triangle mesh to WebGL
var vert_buf = createBuffer(gl, vert_data)
var triangleVAO = createVAO(gl, [
{ "buffer": vert_buf,
"type": gl.UNSIGNED_BYTE,
"size": 4,
"offset": 0,
"stride": 8,
"normalized": false
},
{ "buffer": vert_buf,
"type": gl.UNSIGNED_BYTE,
"size": 4,
"offset": 4,
"stride": 8,
"normalized": false
}
])
triangleVAO.length = Math.floor(vert_data.length/8)
vertexArrayObjects.surface = triangleVAO
}
// move the chunk into place
var modelMatrix = mat4.create()
var w = voxels.shape[2] - pad // =[1]=[0]=game.chunkSize
var translateVector = [
position[0] * w,
position[1] * w,
position[2] * w]
mat4.translate(modelMatrix, modelMatrix, translateVector)
//Bundle result and return
var result = {
vertexArrayObjects: vertexArrayObjects, // other plugins can add their own VAOs
center: [w>>1, w>>1, w>>1],
radius: w,
modelMatrix: modelMatrix
}
if (that) that.emit('meshed', result, gl, vert_data, voxels)
return result
} | javascript | function createVoxelMesh(gl, voxels, voxelSideTextureIDs, voxelSideTextureSizes, position, pad, that) {
//Create mesh
var vert_data = createAOMesh(voxels, voxelSideTextureIDs, voxelSideTextureSizes)
var vertexArrayObjects = {}
if (vert_data === null) {
// no vertices allocated
} else {
//Upload triangle mesh to WebGL
var vert_buf = createBuffer(gl, vert_data)
var triangleVAO = createVAO(gl, [
{ "buffer": vert_buf,
"type": gl.UNSIGNED_BYTE,
"size": 4,
"offset": 0,
"stride": 8,
"normalized": false
},
{ "buffer": vert_buf,
"type": gl.UNSIGNED_BYTE,
"size": 4,
"offset": 4,
"stride": 8,
"normalized": false
}
])
triangleVAO.length = Math.floor(vert_data.length/8)
vertexArrayObjects.surface = triangleVAO
}
// move the chunk into place
var modelMatrix = mat4.create()
var w = voxels.shape[2] - pad // =[1]=[0]=game.chunkSize
var translateVector = [
position[0] * w,
position[1] * w,
position[2] * w]
mat4.translate(modelMatrix, modelMatrix, translateVector)
//Bundle result and return
var result = {
vertexArrayObjects: vertexArrayObjects, // other plugins can add their own VAOs
center: [w>>1, w>>1, w>>1],
radius: w,
modelMatrix: modelMatrix
}
if (that) that.emit('meshed', result, gl, vert_data, voxels)
return result
} | [
"function",
"createVoxelMesh",
"(",
"gl",
",",
"voxels",
",",
"voxelSideTextureIDs",
",",
"voxelSideTextureSizes",
",",
"position",
",",
"pad",
",",
"that",
")",
"{",
"//Create mesh",
"var",
"vert_data",
"=",
"createAOMesh",
"(",
"voxels",
",",
"voxelSideTextureIDs",
",",
"voxelSideTextureSizes",
")",
"var",
"vertexArrayObjects",
"=",
"{",
"}",
"if",
"(",
"vert_data",
"===",
"null",
")",
"{",
"// no vertices allocated",
"}",
"else",
"{",
"//Upload triangle mesh to WebGL",
"var",
"vert_buf",
"=",
"createBuffer",
"(",
"gl",
",",
"vert_data",
")",
"var",
"triangleVAO",
"=",
"createVAO",
"(",
"gl",
",",
"[",
"{",
"\"buffer\"",
":",
"vert_buf",
",",
"\"type\"",
":",
"gl",
".",
"UNSIGNED_BYTE",
",",
"\"size\"",
":",
"4",
",",
"\"offset\"",
":",
"0",
",",
"\"stride\"",
":",
"8",
",",
"\"normalized\"",
":",
"false",
"}",
",",
"{",
"\"buffer\"",
":",
"vert_buf",
",",
"\"type\"",
":",
"gl",
".",
"UNSIGNED_BYTE",
",",
"\"size\"",
":",
"4",
",",
"\"offset\"",
":",
"4",
",",
"\"stride\"",
":",
"8",
",",
"\"normalized\"",
":",
"false",
"}",
"]",
")",
"triangleVAO",
".",
"length",
"=",
"Math",
".",
"floor",
"(",
"vert_data",
".",
"length",
"/",
"8",
")",
"vertexArrayObjects",
".",
"surface",
"=",
"triangleVAO",
"}",
"// move the chunk into place",
"var",
"modelMatrix",
"=",
"mat4",
".",
"create",
"(",
")",
"var",
"w",
"=",
"voxels",
".",
"shape",
"[",
"2",
"]",
"-",
"pad",
"// =[1]=[0]=game.chunkSize",
"var",
"translateVector",
"=",
"[",
"position",
"[",
"0",
"]",
"*",
"w",
",",
"position",
"[",
"1",
"]",
"*",
"w",
",",
"position",
"[",
"2",
"]",
"*",
"w",
"]",
"mat4",
".",
"translate",
"(",
"modelMatrix",
",",
"modelMatrix",
",",
"translateVector",
")",
"//Bundle result and return",
"var",
"result",
"=",
"{",
"vertexArrayObjects",
":",
"vertexArrayObjects",
",",
"// other plugins can add their own VAOs",
"center",
":",
"[",
"w",
">>",
"1",
",",
"w",
">>",
"1",
",",
"w",
">>",
"1",
"]",
",",
"radius",
":",
"w",
",",
"modelMatrix",
":",
"modelMatrix",
"}",
"if",
"(",
"that",
")",
"that",
".",
"emit",
"(",
"'meshed'",
",",
"result",
",",
"gl",
",",
"vert_data",
",",
"voxels",
")",
"return",
"result",
"}"
]
| Creates a mesh from a set of voxels | [
"Creates",
"a",
"mesh",
"from",
"a",
"set",
"of",
"voxels"
]
| fc6d48247fd9393e32db89a6f239317212fdbb9b | https://github.com/voxel/voxel-mesher/blob/fc6d48247fd9393e32db89a6f239317212fdbb9b/mesh-buffer.js#L11-L63 |
41,382 | TendaDigital/Tournamenter | controllers/Group.js | function(req, res, next){
// Search for ID if requested
var id = req.param('id');
findAssociated(id, finishRendering);
// Render JSON content
function finishRendering(data){
// If none object found with given id return error
if(id && !data[0])
return next();
// If querying for id, then returns only the object
if(id)
data = data[0];
// Render the json
res.send(data);
}
} | javascript | function(req, res, next){
// Search for ID if requested
var id = req.param('id');
findAssociated(id, finishRendering);
// Render JSON content
function finishRendering(data){
// If none object found with given id return error
if(id && !data[0])
return next();
// If querying for id, then returns only the object
if(id)
data = data[0];
// Render the json
res.send(data);
}
} | [
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"// Search for ID if requested",
"var",
"id",
"=",
"req",
".",
"param",
"(",
"'id'",
")",
";",
"findAssociated",
"(",
"id",
",",
"finishRendering",
")",
";",
"// Render JSON content",
"function",
"finishRendering",
"(",
"data",
")",
"{",
"// If none object found with given id return error",
"if",
"(",
"id",
"&&",
"!",
"data",
"[",
"0",
"]",
")",
"return",
"next",
"(",
")",
";",
"// If querying for id, then returns only the object",
"if",
"(",
"id",
")",
"data",
"=",
"data",
"[",
"0",
"]",
";",
"// Render the json",
"res",
".",
"send",
"(",
"data",
")",
";",
"}",
"}"
]
| Mix in matches inside groups data | [
"Mix",
"in",
"matches",
"inside",
"groups",
"data"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L19-L39 |
|
41,383 | TendaDigital/Tournamenter | controllers/Group.js | finishRendering | function finishRendering(data){
// If none object found with given id return error
if(id && !data[0])
return next();
// If querying for id, then returns only the object
if(id)
data = data[0];
// Render the json
res.send(data);
} | javascript | function finishRendering(data){
// If none object found with given id return error
if(id && !data[0])
return next();
// If querying for id, then returns only the object
if(id)
data = data[0];
// Render the json
res.send(data);
} | [
"function",
"finishRendering",
"(",
"data",
")",
"{",
"// If none object found with given id return error",
"if",
"(",
"id",
"&&",
"!",
"data",
"[",
"0",
"]",
")",
"return",
"next",
"(",
")",
";",
"// If querying for id, then returns only the object",
"if",
"(",
"id",
")",
"data",
"=",
"data",
"[",
"0",
"]",
";",
"// Render the json",
"res",
".",
"send",
"(",
"data",
")",
";",
"}"
]
| Render JSON content | [
"Render",
"JSON",
"content"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L27-L38 |
41,384 | TendaDigital/Tournamenter | controllers/Group.js | afterFindGroups | function afterFindGroups(models){
data = models;
completed = 0;
if(data.length <= 0)
return next([]);
// Load Matches for each Group and associates
data.forEach(function(group){
app.models.Match.find()
.where({'groupId': group.id})
.sort('state DESC')
.sort('day ASC')
.sort('hour ASC')
.sort('id')
.then(function(matches){
// Associate matches with groups
group.matches = matches;
// Compute scoring table for each group
// (must be computed AFTER associating matches with it)
group.table = group.table();
// Callback
loadedModel();
});
});
} | javascript | function afterFindGroups(models){
data = models;
completed = 0;
if(data.length <= 0)
return next([]);
// Load Matches for each Group and associates
data.forEach(function(group){
app.models.Match.find()
.where({'groupId': group.id})
.sort('state DESC')
.sort('day ASC')
.sort('hour ASC')
.sort('id')
.then(function(matches){
// Associate matches with groups
group.matches = matches;
// Compute scoring table for each group
// (must be computed AFTER associating matches with it)
group.table = group.table();
// Callback
loadedModel();
});
});
} | [
"function",
"afterFindGroups",
"(",
"models",
")",
"{",
"data",
"=",
"models",
";",
"completed",
"=",
"0",
";",
"if",
"(",
"data",
".",
"length",
"<=",
"0",
")",
"return",
"next",
"(",
"[",
"]",
")",
";",
"// Load Matches for each Group and associates",
"data",
".",
"forEach",
"(",
"function",
"(",
"group",
")",
"{",
"app",
".",
"models",
".",
"Match",
".",
"find",
"(",
")",
".",
"where",
"(",
"{",
"'groupId'",
":",
"group",
".",
"id",
"}",
")",
".",
"sort",
"(",
"'state DESC'",
")",
".",
"sort",
"(",
"'day ASC'",
")",
".",
"sort",
"(",
"'hour ASC'",
")",
".",
"sort",
"(",
"'id'",
")",
".",
"then",
"(",
"function",
"(",
"matches",
")",
"{",
"// Associate matches with groups",
"group",
".",
"matches",
"=",
"matches",
";",
"// Compute scoring table for each group",
"// (must be computed AFTER associating matches with it)",
"group",
".",
"table",
"=",
"group",
".",
"table",
"(",
")",
";",
"// Callback",
"loadedModel",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| After finishing search | [
"After",
"finishing",
"search"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L78-L106 |
41,385 | TendaDigital/Tournamenter | controllers/Group.js | afterFindTeams | function afterFindTeams(err, teamData){
var teamList = {};
// Load teams and assing it's key as it's id
teamData.forEach(function(team){
teamList[team.id] = team;
});
// Includes team object in 'table' data
data.forEach(function(group){
// console.log(group);
// Go trough all the table adding key 'team' with team data
_.forEach(group.table, function(row){
row.team = teamList[row.teamId];
});
});
// Includes team object in 'match' data
data.forEach(function(group){
// console.log(group);
// Go trough all the table adding key 'team' with team data
_.forEach(group.matches, function(row){
row.teamA = teamList[row.teamAId];
row.teamB = teamList[row.teamBId];
});
});
next(data);
} | javascript | function afterFindTeams(err, teamData){
var teamList = {};
// Load teams and assing it's key as it's id
teamData.forEach(function(team){
teamList[team.id] = team;
});
// Includes team object in 'table' data
data.forEach(function(group){
// console.log(group);
// Go trough all the table adding key 'team' with team data
_.forEach(group.table, function(row){
row.team = teamList[row.teamId];
});
});
// Includes team object in 'match' data
data.forEach(function(group){
// console.log(group);
// Go trough all the table adding key 'team' with team data
_.forEach(group.matches, function(row){
row.teamA = teamList[row.teamAId];
row.teamB = teamList[row.teamBId];
});
});
next(data);
} | [
"function",
"afterFindTeams",
"(",
"err",
",",
"teamData",
")",
"{",
"var",
"teamList",
"=",
"{",
"}",
";",
"// Load teams and assing it's key as it's id",
"teamData",
".",
"forEach",
"(",
"function",
"(",
"team",
")",
"{",
"teamList",
"[",
"team",
".",
"id",
"]",
"=",
"team",
";",
"}",
")",
";",
"// Includes team object in 'table' data",
"data",
".",
"forEach",
"(",
"function",
"(",
"group",
")",
"{",
"// console.log(group);",
"// Go trough all the table adding key 'team' with team data",
"_",
".",
"forEach",
"(",
"group",
".",
"table",
",",
"function",
"(",
"row",
")",
"{",
"row",
".",
"team",
"=",
"teamList",
"[",
"row",
".",
"teamId",
"]",
";",
"}",
")",
";",
"}",
")",
";",
"// Includes team object in 'match' data",
"data",
".",
"forEach",
"(",
"function",
"(",
"group",
")",
"{",
"// console.log(group);",
"// Go trough all the table adding key 'team' with team data",
"_",
".",
"forEach",
"(",
"group",
".",
"matches",
",",
"function",
"(",
"row",
")",
"{",
"row",
".",
"teamA",
"=",
"teamList",
"[",
"row",
".",
"teamAId",
"]",
";",
"row",
".",
"teamB",
"=",
"teamList",
"[",
"row",
".",
"teamBId",
"]",
";",
"}",
")",
";",
"}",
")",
";",
"next",
"(",
"data",
")",
";",
"}"
]
| Associate keys with teams | [
"Associate",
"keys",
"with",
"teams"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Group.js#L122-L152 |
41,386 | jhaynie/request-ssl | lib/index.js | RequestSSLError | function RequestSSLError(message, id) {
Error.call(this);
Error.captureStackTrace(this, RequestSSLError);
this.id = id;
this.name = 'RequestSSLError';
this.message = message;
} | javascript | function RequestSSLError(message, id) {
Error.call(this);
Error.captureStackTrace(this, RequestSSLError);
this.id = id;
this.name = 'RequestSSLError';
this.message = message;
} | [
"function",
"RequestSSLError",
"(",
"message",
",",
"id",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"RequestSSLError",
")",
";",
"this",
".",
"id",
"=",
"id",
";",
"this",
".",
"name",
"=",
"'RequestSSLError'",
";",
"this",
".",
"message",
"=",
"message",
";",
"}"
]
| create a custom error so we can get proper error code | [
"create",
"a",
"custom",
"error",
"so",
"we",
"can",
"get",
"proper",
"error",
"code"
]
| 715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06 | https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L131-L137 |
41,387 | jhaynie/request-ssl | lib/index.js | createErrorMessage | function createErrorMessage(errorcode) {
if (errorcode in ERRORS) {
var args = Array.prototype.slice.call(arguments,1);
var entry = ERRORS[errorcode];
if (entry.argcount && entry.argcount!==args.length) {
// this should only ever get called if we have a bug in this library
throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid args) to the developer with the following stack trace:"+new Error().stack);
}
return new RequestSSLError((args.length ? util.format.apply(util.format,[entry.message].concat(args)) : entry.message), errorcode);
}
else {
// this should only ever get called if we have a bug in this library
throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid error code) to the developer with the following stack trace:"+new Error().stack);
}
} | javascript | function createErrorMessage(errorcode) {
if (errorcode in ERRORS) {
var args = Array.prototype.slice.call(arguments,1);
var entry = ERRORS[errorcode];
if (entry.argcount && entry.argcount!==args.length) {
// this should only ever get called if we have a bug in this library
throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid args) to the developer with the following stack trace:"+new Error().stack);
}
return new RequestSSLError((args.length ? util.format.apply(util.format,[entry.message].concat(args)) : entry.message), errorcode);
}
else {
// this should only ever get called if we have a bug in this library
throw new Error("Internal failure. Unexpected usage of internal command. Please report error code: "+errorcode+"(invalid error code) to the developer with the following stack trace:"+new Error().stack);
}
} | [
"function",
"createErrorMessage",
"(",
"errorcode",
")",
"{",
"if",
"(",
"errorcode",
"in",
"ERRORS",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"var",
"entry",
"=",
"ERRORS",
"[",
"errorcode",
"]",
";",
"if",
"(",
"entry",
".",
"argcount",
"&&",
"entry",
".",
"argcount",
"!==",
"args",
".",
"length",
")",
"{",
"// this should only ever get called if we have a bug in this library",
"throw",
"new",
"Error",
"(",
"\"Internal failure. Unexpected usage of internal command. Please report error code: \"",
"+",
"errorcode",
"+",
"\"(invalid args) to the developer with the following stack trace:\"",
"+",
"new",
"Error",
"(",
")",
".",
"stack",
")",
";",
"}",
"return",
"new",
"RequestSSLError",
"(",
"(",
"args",
".",
"length",
"?",
"util",
".",
"format",
".",
"apply",
"(",
"util",
".",
"format",
",",
"[",
"entry",
".",
"message",
"]",
".",
"concat",
"(",
"args",
")",
")",
":",
"entry",
".",
"message",
")",
",",
"errorcode",
")",
";",
"}",
"else",
"{",
"// this should only ever get called if we have a bug in this library",
"throw",
"new",
"Error",
"(",
"\"Internal failure. Unexpected usage of internal command. Please report error code: \"",
"+",
"errorcode",
"+",
"\"(invalid error code) to the developer with the following stack trace:\"",
"+",
"new",
"Error",
"(",
")",
".",
"stack",
")",
";",
"}",
"}"
]
| construct the proper error message | [
"construct",
"the",
"proper",
"error",
"message"
]
| 715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06 | https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L158-L172 |
41,388 | jhaynie/request-ssl | lib/index.js | getDomain | function getDomain(url) {
var domain = _.isObject(url) ? url.host : urlib.parse(url).host;
return domain || url;
} | javascript | function getDomain(url) {
var domain = _.isObject(url) ? url.host : urlib.parse(url).host;
return domain || url;
} | [
"function",
"getDomain",
"(",
"url",
")",
"{",
"var",
"domain",
"=",
"_",
".",
"isObject",
"(",
"url",
")",
"?",
"url",
".",
"host",
":",
"urlib",
".",
"parse",
"(",
"url",
")",
".",
"host",
";",
"return",
"domain",
"||",
"url",
";",
"}"
]
| given a url return a domain part | [
"given",
"a",
"url",
"return",
"a",
"domain",
"part"
]
| 715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06 | https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L177-L180 |
41,389 | jhaynie/request-ssl | lib/index.js | getFingerprintForURL | function getFingerprintForURL(url) {
var domain = getDomain(url);
var found = global.requestSSLFingerprints[domain];
debug('getFingerprintForURL %s -> %s=%s',url,domain,found);
if (!found) {
// try a wildcard search
var u = urlib.parse(domain),
tokens = (u && u.host || domain).split('.');
domain = '*.'+tokens.splice(tokens.length > 1 ? 0 : 1).join('.');
found = global.requestSSLFingerprints[domain];
debug('getFingerprintForURL (wildcard) %s -> %s=%s',url,domain,found);
}
return found;
} | javascript | function getFingerprintForURL(url) {
var domain = getDomain(url);
var found = global.requestSSLFingerprints[domain];
debug('getFingerprintForURL %s -> %s=%s',url,domain,found);
if (!found) {
// try a wildcard search
var u = urlib.parse(domain),
tokens = (u && u.host || domain).split('.');
domain = '*.'+tokens.splice(tokens.length > 1 ? 0 : 1).join('.');
found = global.requestSSLFingerprints[domain];
debug('getFingerprintForURL (wildcard) %s -> %s=%s',url,domain,found);
}
return found;
} | [
"function",
"getFingerprintForURL",
"(",
"url",
")",
"{",
"var",
"domain",
"=",
"getDomain",
"(",
"url",
")",
";",
"var",
"found",
"=",
"global",
".",
"requestSSLFingerprints",
"[",
"domain",
"]",
";",
"debug",
"(",
"'getFingerprintForURL %s -> %s=%s'",
",",
"url",
",",
"domain",
",",
"found",
")",
";",
"if",
"(",
"!",
"found",
")",
"{",
"// try a wildcard search",
"var",
"u",
"=",
"urlib",
".",
"parse",
"(",
"domain",
")",
",",
"tokens",
"=",
"(",
"u",
"&&",
"u",
".",
"host",
"||",
"domain",
")",
".",
"split",
"(",
"'.'",
")",
";",
"domain",
"=",
"'*.'",
"+",
"tokens",
".",
"splice",
"(",
"tokens",
".",
"length",
">",
"1",
"?",
"0",
":",
"1",
")",
".",
"join",
"(",
"'.'",
")",
";",
"found",
"=",
"global",
".",
"requestSSLFingerprints",
"[",
"domain",
"]",
";",
"debug",
"(",
"'getFingerprintForURL (wildcard) %s -> %s=%s'",
",",
"url",
",",
"domain",
",",
"found",
")",
";",
"}",
"return",
"found",
";",
"}"
]
| lookup a fingerprint for a given URL by using the domain. returns null if
not found | [
"lookup",
"a",
"fingerprint",
"for",
"a",
"given",
"URL",
"by",
"using",
"the",
"domain",
".",
"returns",
"null",
"if",
"not",
"found"
]
| 715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06 | https://github.com/jhaynie/request-ssl/blob/715d9ad7aa003b2ec4beae3b5c94ac7f0b942a06/lib/index.js#L186-L199 |
41,390 | stoprocent/node-itunesconnect | index.js | Connect | function Connect(username, password, options) {
// Default Options
this.options = {
baseURL : "https://itunesconnect.apple.com",
apiURL : "https://reportingitc2.apple.com/api/",
loginURL : "https://idmsa.apple.com/appleauth/auth/signin",
appleWidgetKey : "22d448248055bab0dc197c6271d738c3",
concurrentRequests : 2,
errorCallback : function(e) {},
loginCallback : function(c) {}
};
// Extend options
_.extend(this.options, options);
// Set cookies
this._cookies = [];
// Task Executor
this._queue = async.queue(
this.executeRequest.bind(this),
this.options.concurrentRequests
);
// Pasue queue and wait for login to complete
this._queue.pause();
// Login to iTunes Connect
if(typeof this.options["cookies"] !== 'undefined') {
this._cookies = this.options.cookies;
this._queue.resume();
}
else {
this.login(username, password);
}
} | javascript | function Connect(username, password, options) {
// Default Options
this.options = {
baseURL : "https://itunesconnect.apple.com",
apiURL : "https://reportingitc2.apple.com/api/",
loginURL : "https://idmsa.apple.com/appleauth/auth/signin",
appleWidgetKey : "22d448248055bab0dc197c6271d738c3",
concurrentRequests : 2,
errorCallback : function(e) {},
loginCallback : function(c) {}
};
// Extend options
_.extend(this.options, options);
// Set cookies
this._cookies = [];
// Task Executor
this._queue = async.queue(
this.executeRequest.bind(this),
this.options.concurrentRequests
);
// Pasue queue and wait for login to complete
this._queue.pause();
// Login to iTunes Connect
if(typeof this.options["cookies"] !== 'undefined') {
this._cookies = this.options.cookies;
this._queue.resume();
}
else {
this.login(username, password);
}
} | [
"function",
"Connect",
"(",
"username",
",",
"password",
",",
"options",
")",
"{",
"// Default Options",
"this",
".",
"options",
"=",
"{",
"baseURL",
":",
"\"https://itunesconnect.apple.com\"",
",",
"apiURL",
":",
"\"https://reportingitc2.apple.com/api/\"",
",",
"loginURL",
":",
"\"https://idmsa.apple.com/appleauth/auth/signin\"",
",",
"appleWidgetKey",
":",
"\"22d448248055bab0dc197c6271d738c3\"",
",",
"concurrentRequests",
":",
"2",
",",
"errorCallback",
":",
"function",
"(",
"e",
")",
"{",
"}",
",",
"loginCallback",
":",
"function",
"(",
"c",
")",
"{",
"}",
"}",
";",
"// Extend options",
"_",
".",
"extend",
"(",
"this",
".",
"options",
",",
"options",
")",
";",
"// Set cookies",
"this",
".",
"_cookies",
"=",
"[",
"]",
";",
"// Task Executor",
"this",
".",
"_queue",
"=",
"async",
".",
"queue",
"(",
"this",
".",
"executeRequest",
".",
"bind",
"(",
"this",
")",
",",
"this",
".",
"options",
".",
"concurrentRequests",
")",
";",
"// Pasue queue and wait for login to complete",
"this",
".",
"_queue",
".",
"pause",
"(",
")",
";",
"// Login to iTunes Connect",
"if",
"(",
"typeof",
"this",
".",
"options",
"[",
"\"cookies\"",
"]",
"!==",
"'undefined'",
")",
"{",
"this",
".",
"_cookies",
"=",
"this",
".",
"options",
".",
"cookies",
";",
"this",
".",
"_queue",
".",
"resume",
"(",
")",
";",
"}",
"else",
"{",
"this",
".",
"login",
"(",
"username",
",",
"password",
")",
";",
"}",
"}"
]
| Initialize a new `Connect` with the given `username`, `password` and `options`.
Examples:
// Import itc-report
var itc = require("itunesconnect"),
Report = itc.Report;
// Init new iTunes Connect
var itunes = new itc.Connect('[email protected]', 'password');
// Init new iTunes Connect
var itunes = new itc.Connect('[email protected]', 'password', {
errorCallback: function(error) {
console.log(error);
},
concurrentRequests: 1
});
@class Connect
@constructor
@param {String} username Apple ID login
@param {String} password Apple ID password
@param {Object} [options]
@param {String} [options.baseURL] iTunes Connect Login URL
@param {String} [options.apiURL] iTunes Connect API URL
@param {Number} [options.concurrentRequests] Number of concurrent requests
@param {Array} [options.cookies] Cookies array. If you provide cookies array it will not login and use this instead.
@param {Function} [options.errorCallback] Error callback function called when requests are failing
@param {Function} [options.errorCallback.error] Login error
@param {Function} [options.loginCallback] Login callback function called when login to iTunes Connect was a success.
@param {Function} [options.loginCallback.cookies] cookies are passed as a first argument. You can get it and cache it for later. | [
"Initialize",
"a",
"new",
"Connect",
"with",
"the",
"given",
"username",
"password",
"and",
"options",
"."
]
| 9d7c7ebe79eb8708a92631c55ce71e85ff89d1af | https://github.com/stoprocent/node-itunesconnect/blob/9d7c7ebe79eb8708a92631c55ce71e85ff89d1af/index.js#L110-L143 |
41,391 | stoprocent/node-itunesconnect | index.js | Report | function Report(type, config) {
var fn = Query.prototype[type];
if(typeof fn !== 'function') {
throw new Error('Unknown Report type: ' + type);
}
return new Query(config)[type]();
} | javascript | function Report(type, config) {
var fn = Query.prototype[type];
if(typeof fn !== 'function') {
throw new Error('Unknown Report type: ' + type);
}
return new Query(config)[type]();
} | [
"function",
"Report",
"(",
"type",
",",
"config",
")",
"{",
"var",
"fn",
"=",
"Query",
".",
"prototype",
"[",
"type",
"]",
";",
"if",
"(",
"typeof",
"fn",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown Report type: '",
"+",
"type",
")",
";",
"}",
"return",
"new",
"Query",
"(",
"config",
")",
"[",
"type",
"]",
"(",
")",
";",
"}"
]
| Initialize a new `Query` with the given `type` and `config`.
Examples:
// Import itc-report
var itc = require("itunesconnect"),
Report = itc.Report;
// Init new iTunes Connect
var itunes = new itc.Connect('[email protected]', 'password');
// Timed type query
var query = Report('timed');
// Ranked type query with config object
var query = Report('ranked', { limit: 100 });
// Advanced Example
var advancedQuery = Report('timed', {
start : '2014-04-08',
end : '2014-04-25',
limit : 100,
filters : {
content: [{AppID}, {AppID}, {AppID}],
location: [{LocationID}, {LocationID}],
transaction: itc.transaction.free,
type: [
itc.type.inapp,
itc.type.app
],
category: {CategoryID}
},
group: 'content'
});
@class Report
@constructor
@param {String} <type>
@param {Object} [config]
@param {String|Date} [config.start] Date or if String must be in format YYYY-MM-DD
@param {Object} [config.end] Date or if String must be in format YYYY-MM-DD
@param {String} [config.interval] One of the following:
@param {String} config.interval.day
@param {String} config.interval.week
@param {String} config.interval.month
@param {String} config.interval.quarter
@param {String} config.interval.year
@param {Object} [config.filters] Possible keys:
@param {Number|Array} [config.filters.content]
@param {String|Array} [config.filters.type]
@param {String|Array} [config.filters.transaction]
@param {Number|Array} [config.filters.category]
@param {String|Array} [config.filters.platform]
@param {Number|Array} [config.filters.location]
@param {String} [config.group] One of following:
@param {String} config.group.content
@param {String} config.group.type
@param {String} config.group.transaction
@param {String} config.group.category
@param {String} config.group.platform
@param {String} config.group.location
@param {Object} [config.measures]
@param {Number} [config.limit]
@return {Query} | [
"Initialize",
"a",
"new",
"Query",
"with",
"the",
"given",
"type",
"and",
"config",
"."
]
| 9d7c7ebe79eb8708a92631c55ce71e85ff89d1af | https://github.com/stoprocent/node-itunesconnect/blob/9d7c7ebe79eb8708a92631c55ce71e85ff89d1af/index.js#L397-L403 |
41,392 | stoprocent/node-itunesconnect | index.js | Query | function Query(config) {
this.type = null;
this.endpoint = null;
this.config = {
start : moment(),
end : moment(),
filters : {},
measures : ['units'],
limit : 100
};
// Extend options with user stuff
_.extend(this.config, config);
// Private Options
this._time = null;
this._body = {};
} | javascript | function Query(config) {
this.type = null;
this.endpoint = null;
this.config = {
start : moment(),
end : moment(),
filters : {},
measures : ['units'],
limit : 100
};
// Extend options with user stuff
_.extend(this.config, config);
// Private Options
this._time = null;
this._body = {};
} | [
"function",
"Query",
"(",
"config",
")",
"{",
"this",
".",
"type",
"=",
"null",
";",
"this",
".",
"endpoint",
"=",
"null",
";",
"this",
".",
"config",
"=",
"{",
"start",
":",
"moment",
"(",
")",
",",
"end",
":",
"moment",
"(",
")",
",",
"filters",
":",
"{",
"}",
",",
"measures",
":",
"[",
"'units'",
"]",
",",
"limit",
":",
"100",
"}",
";",
"// Extend options with user stuff",
"_",
".",
"extend",
"(",
"this",
".",
"config",
",",
"config",
")",
";",
"// Private Options",
"this",
".",
"_time",
"=",
"null",
";",
"this",
".",
"_body",
"=",
"{",
"}",
";",
"}"
]
| Initialize a new `Query` with the given `query`.
Constants to use with Query
// Import itc-report
var itc = require("itunesconnect"),
// Types
itc.type.inapp
itc.type.app
// Transactions
itc.transaction.free
itc.transaction.paid
itc.transaction.redownload
itc.transaction.update
itc.transaction.refund
// Platforms
itc.platform.desktop
itc.platform.iphone
itc.platform.ipad
itc.platform.ipod
// Measures
itc.measure.proceeds
itc.measure.units
@class Query
@constructor
@private
@param {Object} config
@chainable
@return {Query} | [
"Initialize",
"a",
"new",
"Query",
"with",
"the",
"given",
"query",
"."
]
| 9d7c7ebe79eb8708a92631c55ce71e85ff89d1af | https://github.com/stoprocent/node-itunesconnect/blob/9d7c7ebe79eb8708a92631c55ce71e85ff89d1af/index.js#L504-L521 |
41,393 | TendaDigital/Tournamenter | controllers/Match.js | afterFindMatch | function afterFindMatch(models){
if(models.length != 1) return next(404);
model = models[0];
// Fetch Both Teams
app.models.Team.findById(model.teamAId).exec(function(err, models){
model.teamA = models.length ? models[0] : null;
checkFetch();
});
app.models.Team.findById(model.teamBId).exec(function(err, models){
model.teamB = models.length ? models[0] : null;
checkFetch();
});
// Fetch Group
app.models.Group.findById(model.groupId).exec(function(err, models){
model.group = models.length ? models[0] : null;
checkFetch();
});
} | javascript | function afterFindMatch(models){
if(models.length != 1) return next(404);
model = models[0];
// Fetch Both Teams
app.models.Team.findById(model.teamAId).exec(function(err, models){
model.teamA = models.length ? models[0] : null;
checkFetch();
});
app.models.Team.findById(model.teamBId).exec(function(err, models){
model.teamB = models.length ? models[0] : null;
checkFetch();
});
// Fetch Group
app.models.Group.findById(model.groupId).exec(function(err, models){
model.group = models.length ? models[0] : null;
checkFetch();
});
} | [
"function",
"afterFindMatch",
"(",
"models",
")",
"{",
"if",
"(",
"models",
".",
"length",
"!=",
"1",
")",
"return",
"next",
"(",
"404",
")",
";",
"model",
"=",
"models",
"[",
"0",
"]",
";",
"// Fetch Both Teams",
"app",
".",
"models",
".",
"Team",
".",
"findById",
"(",
"model",
".",
"teamAId",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"models",
")",
"{",
"model",
".",
"teamA",
"=",
"models",
".",
"length",
"?",
"models",
"[",
"0",
"]",
":",
"null",
";",
"checkFetch",
"(",
")",
";",
"}",
")",
";",
"app",
".",
"models",
".",
"Team",
".",
"findById",
"(",
"model",
".",
"teamBId",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"models",
")",
"{",
"model",
".",
"teamB",
"=",
"models",
".",
"length",
"?",
"models",
"[",
"0",
"]",
":",
"null",
";",
"checkFetch",
"(",
")",
";",
"}",
")",
";",
"// Fetch Group",
"app",
".",
"models",
".",
"Group",
".",
"findById",
"(",
"model",
".",
"groupId",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"models",
")",
"{",
"model",
".",
"group",
"=",
"models",
".",
"length",
"?",
"models",
"[",
"0",
"]",
":",
"null",
";",
"checkFetch",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Called after match is fetched. Associate with Group and Teams | [
"Called",
"after",
"match",
"is",
"fetched",
".",
"Associate",
"with",
"Group",
"and",
"Teams"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Match.js#L56-L77 |
41,394 | voxel/voxel-mesher | mesh.js | computeMesh | function computeMesh(array, voxelSideTextureIDs, voxelSideTextureSizes) {
var shp = array.shape.slice(0)
var nx = (shp[0]-2)|0
var ny = (shp[1]-2)|0
var nz = (shp[2]-2)|0
var sz = nx * ny * nz
var scratch0 = pool.mallocInt32(sz)
var scratch1 = pool.mallocInt32(sz)
var scratch2 = pool.mallocInt32(sz)
var rshp = [nx, ny, nz]
var ao0 = ndarray(scratch0, rshp)
var ao1 = ndarray(scratch1, rshp)
var ao2 = ndarray(scratch2, rshp)
//Calculate ao fields
surfaceStencil(ao0, ao1, ao2, array)
//Build mesh slices
meshBuilder.ptr = 0
meshBuilder.voxelSideTextureIDs = voxelSideTextureIDs
meshBuilder.voxelSideTextureSizes = voxelSideTextureSizes
var buffers = [ao0, ao1, ao2]
for(var d=0; d<3; ++d) {
var u = (d+1)%3
var v = (d+2)%3
//Create slice
var st = buffers[d].transpose(d, u, v)
var slice = st.pick(0)
var n = rshp[d]|0
meshBuilder.d = d
meshBuilder.u = v
meshBuilder.v = u
//Generate slices
for(var i=0; i<n; ++i) {
meshBuilder.z = i
meshSlice(slice)
slice.offset += st.stride[0]
}
}
//Release buffers
pool.freeInt32(scratch0)
pool.freeInt32(scratch1)
pool.freeInt32(scratch2)
//Release uint8 array if no vertices were allocated
if(meshBuilder.ptr === 0) {
return null
}
//Slice out buffer
var rbuffer = meshBuilder.buffer
var rptr = meshBuilder.ptr
meshBuilder.buffer = pool.mallocUint8(1024)
meshBuilder.ptr = 0
return rbuffer.subarray(0, rptr)
} | javascript | function computeMesh(array, voxelSideTextureIDs, voxelSideTextureSizes) {
var shp = array.shape.slice(0)
var nx = (shp[0]-2)|0
var ny = (shp[1]-2)|0
var nz = (shp[2]-2)|0
var sz = nx * ny * nz
var scratch0 = pool.mallocInt32(sz)
var scratch1 = pool.mallocInt32(sz)
var scratch2 = pool.mallocInt32(sz)
var rshp = [nx, ny, nz]
var ao0 = ndarray(scratch0, rshp)
var ao1 = ndarray(scratch1, rshp)
var ao2 = ndarray(scratch2, rshp)
//Calculate ao fields
surfaceStencil(ao0, ao1, ao2, array)
//Build mesh slices
meshBuilder.ptr = 0
meshBuilder.voxelSideTextureIDs = voxelSideTextureIDs
meshBuilder.voxelSideTextureSizes = voxelSideTextureSizes
var buffers = [ao0, ao1, ao2]
for(var d=0; d<3; ++d) {
var u = (d+1)%3
var v = (d+2)%3
//Create slice
var st = buffers[d].transpose(d, u, v)
var slice = st.pick(0)
var n = rshp[d]|0
meshBuilder.d = d
meshBuilder.u = v
meshBuilder.v = u
//Generate slices
for(var i=0; i<n; ++i) {
meshBuilder.z = i
meshSlice(slice)
slice.offset += st.stride[0]
}
}
//Release buffers
pool.freeInt32(scratch0)
pool.freeInt32(scratch1)
pool.freeInt32(scratch2)
//Release uint8 array if no vertices were allocated
if(meshBuilder.ptr === 0) {
return null
}
//Slice out buffer
var rbuffer = meshBuilder.buffer
var rptr = meshBuilder.ptr
meshBuilder.buffer = pool.mallocUint8(1024)
meshBuilder.ptr = 0
return rbuffer.subarray(0, rptr)
} | [
"function",
"computeMesh",
"(",
"array",
",",
"voxelSideTextureIDs",
",",
"voxelSideTextureSizes",
")",
"{",
"var",
"shp",
"=",
"array",
".",
"shape",
".",
"slice",
"(",
"0",
")",
"var",
"nx",
"=",
"(",
"shp",
"[",
"0",
"]",
"-",
"2",
")",
"|",
"0",
"var",
"ny",
"=",
"(",
"shp",
"[",
"1",
"]",
"-",
"2",
")",
"|",
"0",
"var",
"nz",
"=",
"(",
"shp",
"[",
"2",
"]",
"-",
"2",
")",
"|",
"0",
"var",
"sz",
"=",
"nx",
"*",
"ny",
"*",
"nz",
"var",
"scratch0",
"=",
"pool",
".",
"mallocInt32",
"(",
"sz",
")",
"var",
"scratch1",
"=",
"pool",
".",
"mallocInt32",
"(",
"sz",
")",
"var",
"scratch2",
"=",
"pool",
".",
"mallocInt32",
"(",
"sz",
")",
"var",
"rshp",
"=",
"[",
"nx",
",",
"ny",
",",
"nz",
"]",
"var",
"ao0",
"=",
"ndarray",
"(",
"scratch0",
",",
"rshp",
")",
"var",
"ao1",
"=",
"ndarray",
"(",
"scratch1",
",",
"rshp",
")",
"var",
"ao2",
"=",
"ndarray",
"(",
"scratch2",
",",
"rshp",
")",
"//Calculate ao fields",
"surfaceStencil",
"(",
"ao0",
",",
"ao1",
",",
"ao2",
",",
"array",
")",
"//Build mesh slices",
"meshBuilder",
".",
"ptr",
"=",
"0",
"meshBuilder",
".",
"voxelSideTextureIDs",
"=",
"voxelSideTextureIDs",
"meshBuilder",
".",
"voxelSideTextureSizes",
"=",
"voxelSideTextureSizes",
"var",
"buffers",
"=",
"[",
"ao0",
",",
"ao1",
",",
"ao2",
"]",
"for",
"(",
"var",
"d",
"=",
"0",
";",
"d",
"<",
"3",
";",
"++",
"d",
")",
"{",
"var",
"u",
"=",
"(",
"d",
"+",
"1",
")",
"%",
"3",
"var",
"v",
"=",
"(",
"d",
"+",
"2",
")",
"%",
"3",
"//Create slice",
"var",
"st",
"=",
"buffers",
"[",
"d",
"]",
".",
"transpose",
"(",
"d",
",",
"u",
",",
"v",
")",
"var",
"slice",
"=",
"st",
".",
"pick",
"(",
"0",
")",
"var",
"n",
"=",
"rshp",
"[",
"d",
"]",
"|",
"0",
"meshBuilder",
".",
"d",
"=",
"d",
"meshBuilder",
".",
"u",
"=",
"v",
"meshBuilder",
".",
"v",
"=",
"u",
"//Generate slices",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"meshBuilder",
".",
"z",
"=",
"i",
"meshSlice",
"(",
"slice",
")",
"slice",
".",
"offset",
"+=",
"st",
".",
"stride",
"[",
"0",
"]",
"}",
"}",
"//Release buffers",
"pool",
".",
"freeInt32",
"(",
"scratch0",
")",
"pool",
".",
"freeInt32",
"(",
"scratch1",
")",
"pool",
".",
"freeInt32",
"(",
"scratch2",
")",
"//Release uint8 array if no vertices were allocated",
"if",
"(",
"meshBuilder",
".",
"ptr",
"===",
"0",
")",
"{",
"return",
"null",
"}",
"//Slice out buffer",
"var",
"rbuffer",
"=",
"meshBuilder",
".",
"buffer",
"var",
"rptr",
"=",
"meshBuilder",
".",
"ptr",
"meshBuilder",
".",
"buffer",
"=",
"pool",
".",
"mallocUint8",
"(",
"1024",
")",
"meshBuilder",
".",
"ptr",
"=",
"0",
"return",
"rbuffer",
".",
"subarray",
"(",
"0",
",",
"rptr",
")",
"}"
]
| Compute a mesh | [
"Compute",
"a",
"mesh"
]
| fc6d48247fd9393e32db89a6f239317212fdbb9b | https://github.com/voxel/voxel-mesher/blob/fc6d48247fd9393e32db89a6f239317212fdbb9b/mesh.js#L487-L547 |
41,395 | mafintosh/pbs | index.js | function () {
var self = this
pb.toJSON().enums.forEach(function (e) {
self[e.name] = e.values
})
pb.toJSON().messages.forEach(function (m) {
var message = {}
m.enums.forEach(function (e) {
message[e.name] = e
})
message.name = m.name
message.encode = encoder(m, pb)
message.decode = decoder(m, pb)
self[m.name] = message
})
} | javascript | function () {
var self = this
pb.toJSON().enums.forEach(function (e) {
self[e.name] = e.values
})
pb.toJSON().messages.forEach(function (m) {
var message = {}
m.enums.forEach(function (e) {
message[e.name] = e
})
message.name = m.name
message.encode = encoder(m, pb)
message.decode = decoder(m, pb)
self[m.name] = message
})
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
"pb",
".",
"toJSON",
"(",
")",
".",
"enums",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"self",
"[",
"e",
".",
"name",
"]",
"=",
"e",
".",
"values",
"}",
")",
"pb",
".",
"toJSON",
"(",
")",
".",
"messages",
".",
"forEach",
"(",
"function",
"(",
"m",
")",
"{",
"var",
"message",
"=",
"{",
"}",
"m",
".",
"enums",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"message",
"[",
"e",
".",
"name",
"]",
"=",
"e",
"}",
")",
"message",
".",
"name",
"=",
"m",
".",
"name",
"message",
".",
"encode",
"=",
"encoder",
"(",
"m",
",",
"pb",
")",
"message",
".",
"decode",
"=",
"decoder",
"(",
"m",
",",
"pb",
")",
"self",
"[",
"m",
".",
"name",
"]",
"=",
"message",
"}",
")",
"}"
]
| to not make toString,toJSON enumarable we make a fire-and-forget prototype | [
"to",
"not",
"make",
"toString",
"toJSON",
"enumarable",
"we",
"make",
"a",
"fire",
"-",
"and",
"-",
"forget",
"prototype"
]
| 163e2390e01bf81b83f3fda0ca2823d7eea96e2b | https://github.com/mafintosh/pbs/blob/163e2390e01bf81b83f3fda0ca2823d7eea96e2b/index.js#L9-L26 |
|
41,396 | TendaDigital/Tournamenter | modules/pageview-live-match/public/js/pageview-live-match.js | function($root) {
var match = this.model.get('data');
this.updateScore(match.teamAScore, $root.find('.team.left .team-score'));
this.updateScore(match.teamBScore, $root.find('.team.right .team-score'));
} | javascript | function($root) {
var match = this.model.get('data');
this.updateScore(match.teamAScore, $root.find('.team.left .team-score'));
this.updateScore(match.teamBScore, $root.find('.team.right .team-score'));
} | [
"function",
"(",
"$root",
")",
"{",
"var",
"match",
"=",
"this",
".",
"model",
".",
"get",
"(",
"'data'",
")",
";",
"this",
".",
"updateScore",
"(",
"match",
".",
"teamAScore",
",",
"$root",
".",
"find",
"(",
"'.team.left .team-score'",
")",
")",
";",
"this",
".",
"updateScore",
"(",
"match",
".",
"teamBScore",
",",
"$root",
".",
"find",
"(",
"'.team.right .team-score'",
")",
")",
";",
"}"
]
| Update both score values | [
"Update",
"both",
"score",
"values"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/modules/pageview-live-match/public/js/pageview-live-match.js#L182-L187 |
|
41,397 | TendaDigital/Tournamenter | modules/pageview-live-match/public/js/pageview-live-match.js | function(state){
var match = this.model.get('data');
var countryA = match.teamA ? match.teamA.country : null;
this.setFlagsState(state, countryA, this.$('.flag-3d-left'));
var countryB = match.teamB ? match.teamB.country : null;
this.setFlagsState(state, countryB, this.$('.flag-3d-right'));
} | javascript | function(state){
var match = this.model.get('data');
var countryA = match.teamA ? match.teamA.country : null;
this.setFlagsState(state, countryA, this.$('.flag-3d-left'));
var countryB = match.teamB ? match.teamB.country : null;
this.setFlagsState(state, countryB, this.$('.flag-3d-right'));
} | [
"function",
"(",
"state",
")",
"{",
"var",
"match",
"=",
"this",
".",
"model",
".",
"get",
"(",
"'data'",
")",
";",
"var",
"countryA",
"=",
"match",
".",
"teamA",
"?",
"match",
".",
"teamA",
".",
"country",
":",
"null",
";",
"this",
".",
"setFlagsState",
"(",
"state",
",",
"countryA",
",",
"this",
".",
"$",
"(",
"'.flag-3d-left'",
")",
")",
";",
"var",
"countryB",
"=",
"match",
".",
"teamB",
"?",
"match",
".",
"teamB",
".",
"country",
":",
"null",
";",
"this",
".",
"setFlagsState",
"(",
"state",
",",
"countryB",
",",
"this",
".",
"$",
"(",
"'.flag-3d-right'",
")",
")",
";",
"}"
]
| Animate both flags | [
"Animate",
"both",
"flags"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/modules/pageview-live-match/public/js/pageview-live-match.js#L204-L212 |
|
41,398 | fnogatz/CHR.js | src/index.js | tag | function tag (chrSource) {
var program
var replacements
// Examine caller format
if (typeof chrSource === 'object' && chrSource.type && chrSource.type === 'Program') {
// called with already parsed source code
// e.g. tag({ type: 'Program', body: [ ... ] })
program = chrSource
replacements = []
// allow to specify replacements as second argument
if (arguments[1] && typeof arguments[1] === 'object' && arguments[1] instanceof Array) {
replacements = arguments[1]
}
} else if (typeof chrSource === 'object' && chrSource instanceof Array && typeof chrSource[0] === 'string') {
// called as template tag
// e.g. tag`a ==> b`
// or tag`a ==> ${ function() { console.log('Replacement test') } }`
var combined = [
chrSource[0]
]
Array.prototype.slice.call(arguments, 1).forEach(function (repl, ix) {
combined.push(repl)
combined.push(chrSource[ix + 1])
})
chrSource = joinParts(combined)
replacements = Array.prototype.slice.call(arguments, 1)
program = parse(chrSource)
} else if (typeof chrSource === 'string' && arguments[1] && arguments[1] instanceof Array) {
// called with program and replacements array
// e.g. tag(
// 'a ==> ${ function() { console.log("Replacement test") } }',
// [ eval('( function() { console.log("Replacement test") } )') ]
// )
// this is useful to ensure the scope of the given replacements
program = parse(chrSource)
replacements = arguments[1]
} else if (typeof chrSource === 'string') {
// called as normal function
// e.g. tag('a ==> b')
// or tag('a ==> ', function() { console.log('Replacement test') })
replacements = Array.prototype.filter.call(arguments, isFunction)
chrSource = joinParts(Array.prototype.slice.call(arguments))
program = parse(chrSource)
}
var rules = program.body
rules.forEach(function (rule) {
tag.Rules.Add(rule, replacements)
})
} | javascript | function tag (chrSource) {
var program
var replacements
// Examine caller format
if (typeof chrSource === 'object' && chrSource.type && chrSource.type === 'Program') {
// called with already parsed source code
// e.g. tag({ type: 'Program', body: [ ... ] })
program = chrSource
replacements = []
// allow to specify replacements as second argument
if (arguments[1] && typeof arguments[1] === 'object' && arguments[1] instanceof Array) {
replacements = arguments[1]
}
} else if (typeof chrSource === 'object' && chrSource instanceof Array && typeof chrSource[0] === 'string') {
// called as template tag
// e.g. tag`a ==> b`
// or tag`a ==> ${ function() { console.log('Replacement test') } }`
var combined = [
chrSource[0]
]
Array.prototype.slice.call(arguments, 1).forEach(function (repl, ix) {
combined.push(repl)
combined.push(chrSource[ix + 1])
})
chrSource = joinParts(combined)
replacements = Array.prototype.slice.call(arguments, 1)
program = parse(chrSource)
} else if (typeof chrSource === 'string' && arguments[1] && arguments[1] instanceof Array) {
// called with program and replacements array
// e.g. tag(
// 'a ==> ${ function() { console.log("Replacement test") } }',
// [ eval('( function() { console.log("Replacement test") } )') ]
// )
// this is useful to ensure the scope of the given replacements
program = parse(chrSource)
replacements = arguments[1]
} else if (typeof chrSource === 'string') {
// called as normal function
// e.g. tag('a ==> b')
// or tag('a ==> ', function() { console.log('Replacement test') })
replacements = Array.prototype.filter.call(arguments, isFunction)
chrSource = joinParts(Array.prototype.slice.call(arguments))
program = parse(chrSource)
}
var rules = program.body
rules.forEach(function (rule) {
tag.Rules.Add(rule, replacements)
})
} | [
"function",
"tag",
"(",
"chrSource",
")",
"{",
"var",
"program",
"var",
"replacements",
"// Examine caller format",
"if",
"(",
"typeof",
"chrSource",
"===",
"'object'",
"&&",
"chrSource",
".",
"type",
"&&",
"chrSource",
".",
"type",
"===",
"'Program'",
")",
"{",
"// called with already parsed source code",
"// e.g. tag({ type: 'Program', body: [ ... ] })",
"program",
"=",
"chrSource",
"replacements",
"=",
"[",
"]",
"// allow to specify replacements as second argument",
"if",
"(",
"arguments",
"[",
"1",
"]",
"&&",
"typeof",
"arguments",
"[",
"1",
"]",
"===",
"'object'",
"&&",
"arguments",
"[",
"1",
"]",
"instanceof",
"Array",
")",
"{",
"replacements",
"=",
"arguments",
"[",
"1",
"]",
"}",
"}",
"else",
"if",
"(",
"typeof",
"chrSource",
"===",
"'object'",
"&&",
"chrSource",
"instanceof",
"Array",
"&&",
"typeof",
"chrSource",
"[",
"0",
"]",
"===",
"'string'",
")",
"{",
"// called as template tag",
"// e.g. tag`a ==> b`",
"// or tag`a ==> ${ function() { console.log('Replacement test') } }`",
"var",
"combined",
"=",
"[",
"chrSource",
"[",
"0",
"]",
"]",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
".",
"forEach",
"(",
"function",
"(",
"repl",
",",
"ix",
")",
"{",
"combined",
".",
"push",
"(",
"repl",
")",
"combined",
".",
"push",
"(",
"chrSource",
"[",
"ix",
"+",
"1",
"]",
")",
"}",
")",
"chrSource",
"=",
"joinParts",
"(",
"combined",
")",
"replacements",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
"program",
"=",
"parse",
"(",
"chrSource",
")",
"}",
"else",
"if",
"(",
"typeof",
"chrSource",
"===",
"'string'",
"&&",
"arguments",
"[",
"1",
"]",
"&&",
"arguments",
"[",
"1",
"]",
"instanceof",
"Array",
")",
"{",
"// called with program and replacements array",
"// e.g. tag(",
"// 'a ==> ${ function() { console.log(\"Replacement test\") } }',",
"// [ eval('( function() { console.log(\"Replacement test\") } )') ]",
"// )",
"// this is useful to ensure the scope of the given replacements",
"program",
"=",
"parse",
"(",
"chrSource",
")",
"replacements",
"=",
"arguments",
"[",
"1",
"]",
"}",
"else",
"if",
"(",
"typeof",
"chrSource",
"===",
"'string'",
")",
"{",
"// called as normal function",
"// e.g. tag('a ==> b')",
"// or tag('a ==> ', function() { console.log('Replacement test') })",
"replacements",
"=",
"Array",
".",
"prototype",
".",
"filter",
".",
"call",
"(",
"arguments",
",",
"isFunction",
")",
"chrSource",
"=",
"joinParts",
"(",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
"program",
"=",
"parse",
"(",
"chrSource",
")",
"}",
"var",
"rules",
"=",
"program",
".",
"body",
"rules",
".",
"forEach",
"(",
"function",
"(",
"rule",
")",
"{",
"tag",
".",
"Rules",
".",
"Add",
"(",
"rule",
",",
"replacements",
")",
"}",
")",
"}"
]
| Adds a number of rules given. | [
"Adds",
"a",
"number",
"of",
"rules",
"given",
"."
]
| d87688327f139d726993537c7da98fcac0a4a89f | https://github.com/fnogatz/CHR.js/blob/d87688327f139d726993537c7da98fcac0a4a89f/src/index.js#L30-L81 |
41,399 | TendaDigital/Tournamenter | controllers/Table.js | associateWithTeams | function associateWithTeams(teams, tableModel){
// Go through all team rows inside the table's data, and add's team object
// _.forEach(tableModel.table, function(teamRow){
// teamRow['team'] = teams[teamRow.teamId] || {};
// });
// Go through all team rows inside scores, and add's a team object
_.forEach(tableModel.scores, function(teamRow){
teamRow['team'] = teams[teamRow.teamId] || {};
});
} | javascript | function associateWithTeams(teams, tableModel){
// Go through all team rows inside the table's data, and add's team object
// _.forEach(tableModel.table, function(teamRow){
// teamRow['team'] = teams[teamRow.teamId] || {};
// });
// Go through all team rows inside scores, and add's a team object
_.forEach(tableModel.scores, function(teamRow){
teamRow['team'] = teams[teamRow.teamId] || {};
});
} | [
"function",
"associateWithTeams",
"(",
"teams",
",",
"tableModel",
")",
"{",
"// Go through all team rows inside the table's data, and add's team object",
"// _.forEach(tableModel.table, function(teamRow){",
"// \tteamRow['team'] = teams[teamRow.teamId] || {};",
"// });",
"// Go through all team rows inside scores, and add's a team object",
"_",
".",
"forEach",
"(",
"tableModel",
".",
"scores",
",",
"function",
"(",
"teamRow",
")",
"{",
"teamRow",
"[",
"'team'",
"]",
"=",
"teams",
"[",
"teamRow",
".",
"teamId",
"]",
"||",
"{",
"}",
";",
"}",
")",
";",
"}"
]
| Helper method used to save team data inside each table row | [
"Helper",
"method",
"used",
"to",
"save",
"team",
"data",
"inside",
"each",
"table",
"row"
]
| 2733ae9b454ae90896249ab1d7a07007eb4a69e4 | https://github.com/TendaDigital/Tournamenter/blob/2733ae9b454ae90896249ab1d7a07007eb4a69e4/controllers/Table.js#L217-L227 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.