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,600 | tmarshall/Google-Plus-API | google-plus-api.js | makeRequest | function makeRequest(apiKey, path, opts, callback) {
var
key,
req,
dataStr = '';
if(callback === undefined) {
throw 'No callback defined';
return;
}
path = '/plus/v1/' + path + '?key=' + apiKey;
for(key in opts) {
path += '&' + key + '=' + opts[key];
}
req = https.request({
host: 'www.googleapis.com',
port: 443,
path: path,
method: 'GET'
}, function(res) {
res.on('data', function(data) {
dataStr += data;
});
res.on('end', function() {
if(opts.alt === undefined || opts.alt.toLowerCase() == 'json') {
try {
callback(null, JSON.parse(dataStr));
} catch(err) {
callback(null, dataStr);
}
}
else {
callback(null, dataStr);
}
});
res.on('close', function () {
res.emit('end');
});
});
req.end();
req.on('error', function(err) {
callback(err);
});
return req;
} | javascript | function makeRequest(apiKey, path, opts, callback) {
var
key,
req,
dataStr = '';
if(callback === undefined) {
throw 'No callback defined';
return;
}
path = '/plus/v1/' + path + '?key=' + apiKey;
for(key in opts) {
path += '&' + key + '=' + opts[key];
}
req = https.request({
host: 'www.googleapis.com',
port: 443,
path: path,
method: 'GET'
}, function(res) {
res.on('data', function(data) {
dataStr += data;
});
res.on('end', function() {
if(opts.alt === undefined || opts.alt.toLowerCase() == 'json') {
try {
callback(null, JSON.parse(dataStr));
} catch(err) {
callback(null, dataStr);
}
}
else {
callback(null, dataStr);
}
});
res.on('close', function () {
res.emit('end');
});
});
req.end();
req.on('error', function(err) {
callback(err);
});
return req;
} | [
"function",
"makeRequest",
"(",
"apiKey",
",",
"path",
",",
"opts",
",",
"callback",
")",
"{",
"var",
"key",
",",
"req",
",",
"dataStr",
"=",
"''",
";",
"if",
"(",
"callback",
"===",
"undefined",
")",
"{",
"throw",
"'No callback defined'",
";",
"return",
";",
"}",
"path",
"=",
"'/plus/v1/'",
"+",
"path",
"+",
"'?key='",
"+",
"apiKey",
";",
"for",
"(",
"key",
"in",
"opts",
")",
"{",
"path",
"+=",
"'&'",
"+",
"key",
"+",
"'='",
"+",
"opts",
"[",
"key",
"]",
";",
"}",
"req",
"=",
"https",
".",
"request",
"(",
"{",
"host",
":",
"'www.googleapis.com'",
",",
"port",
":",
"443",
",",
"path",
":",
"path",
",",
"method",
":",
"'GET'",
"}",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"dataStr",
"+=",
"data",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"opts",
".",
"alt",
"===",
"undefined",
"||",
"opts",
".",
"alt",
".",
"toLowerCase",
"(",
")",
"==",
"'json'",
")",
"{",
"try",
"{",
"callback",
"(",
"null",
",",
"JSON",
".",
"parse",
"(",
"dataStr",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"callback",
"(",
"null",
",",
"dataStr",
")",
";",
"}",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"dataStr",
")",
";",
"}",
"}",
")",
";",
"res",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"res",
".",
"emit",
"(",
"'end'",
")",
";",
"}",
")",
";",
"}",
")",
";",
"req",
".",
"end",
"(",
")",
";",
"req",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"return",
"req",
";",
"}"
]
| Private function, used to make requests to G+
Takes the path, any options (becomes query params) & a callback
Returns the HTTP request instance | [
"Private",
"function",
"used",
"to",
"make",
"requests",
"to",
"G",
"+"
]
| 27f8593072910c1fbcd926ffe689e497337a8834 | https://github.com/tmarshall/Google-Plus-API/blob/27f8593072910c1fbcd926ffe689e497337a8834/google-plus-api.js#L175-L225 |
41,601 | atsid/circuits-js | js/plugins/DataProviderPlugin.js | function (args) {
this.type = "mixin";
this.fn = function (service) {
service.create = service[this.create];
service.read = service[this.read];
service.update = service[this.update];
service.remove = service[this.remove];
};
} | javascript | function (args) {
this.type = "mixin";
this.fn = function (service) {
service.create = service[this.create];
service.read = service[this.read];
service.update = service[this.update];
service.remove = service[this.remove];
};
} | [
"function",
"(",
"args",
")",
"{",
"this",
".",
"type",
"=",
"\"mixin\"",
";",
"this",
".",
"fn",
"=",
"function",
"(",
"service",
")",
"{",
"service",
".",
"create",
"=",
"service",
"[",
"this",
".",
"create",
"]",
";",
"service",
".",
"read",
"=",
"service",
"[",
"this",
".",
"read",
"]",
";",
"service",
".",
"update",
"=",
"service",
"[",
"this",
".",
"update",
"]",
";",
"service",
".",
"remove",
"=",
"service",
"[",
"this",
".",
"remove",
"]",
";",
"}",
";",
"}"
]
| Maps simple CRUD operations to actual service methods.
@param {Object} args should consist of 4 key/value pairs:
create, read, update and remove
Each value should be the equivalent operation on the service. | [
"Maps",
"simple",
"CRUD",
"operations",
"to",
"actual",
"service",
"methods",
"."
]
| f1fa5e98d406b3b9f577dd8995782c7115d6b346 | https://github.com/atsid/circuits-js/blob/f1fa5e98d406b3b9f577dd8995782c7115d6b346/js/plugins/DataProviderPlugin.js#L17-L25 |
|
41,602 | chip-js/observations-js | src/computed-properties/map.js | MapProperty | function MapProperty(sourceExpression, keyExpression, resultExpression, removeExpression) {
var parts = sourceExpression.split(/\s+in\s+/);
this.sourceExpression = parts.pop();
this.itemName = parts.pop();
this.keyExpression = keyExpression;
this.resultExpression = resultExpression;
this.removeExpression = removeExpression;
} | javascript | function MapProperty(sourceExpression, keyExpression, resultExpression, removeExpression) {
var parts = sourceExpression.split(/\s+in\s+/);
this.sourceExpression = parts.pop();
this.itemName = parts.pop();
this.keyExpression = keyExpression;
this.resultExpression = resultExpression;
this.removeExpression = removeExpression;
} | [
"function",
"MapProperty",
"(",
"sourceExpression",
",",
"keyExpression",
",",
"resultExpression",
",",
"removeExpression",
")",
"{",
"var",
"parts",
"=",
"sourceExpression",
".",
"split",
"(",
"/",
"\\s+in\\s+",
"/",
")",
";",
"this",
".",
"sourceExpression",
"=",
"parts",
".",
"pop",
"(",
")",
";",
"this",
".",
"itemName",
"=",
"parts",
".",
"pop",
"(",
")",
";",
"this",
".",
"keyExpression",
"=",
"keyExpression",
";",
"this",
".",
"resultExpression",
"=",
"resultExpression",
";",
"this",
".",
"removeExpression",
"=",
"removeExpression",
";",
"}"
]
| Creates an object hash with the key being the value of the `key` property of each item in `sourceExpression` and the
value being the result of `expression`. `key` is optional, defaulting to "id" when not provided. `sourceExpression`
can resolve to an array or an object hash.
@param {Array|Object} sourceExpression An array or object whose members will be added to the map.
@param {String} keyExpression The name of the property to key against as values are added to the map.
@param {String} resultExpression [Optional] The expression evaluated against the array/object member whose value is
added to the map. If not provided, the member will be added.
@return {Object} The object map of key=>value | [
"Creates",
"an",
"object",
"hash",
"with",
"the",
"key",
"being",
"the",
"value",
"of",
"the",
"key",
"property",
"of",
"each",
"item",
"in",
"sourceExpression",
"and",
"the",
"value",
"being",
"the",
"result",
"of",
"expression",
".",
"key",
"is",
"optional",
"defaulting",
"to",
"id",
"when",
"not",
"provided",
".",
"sourceExpression",
"can",
"resolve",
"to",
"an",
"array",
"or",
"an",
"object",
"hash",
"."
]
| a48b32a648089bc86b502712d78cd0b3f8317d50 | https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/computed-properties/map.js#L14-L21 |
41,603 | vesln/hydro | lib/suite/index.js | Suite | function Suite(title) {
this.title = _.title(title);
this.parent = null;
this.runnables = [];
this.events = {
pre: 'pre:suite',
post: 'post:suite'
};
} | javascript | function Suite(title) {
this.title = _.title(title);
this.parent = null;
this.runnables = [];
this.events = {
pre: 'pre:suite',
post: 'post:suite'
};
} | [
"function",
"Suite",
"(",
"title",
")",
"{",
"this",
".",
"title",
"=",
"_",
".",
"title",
"(",
"title",
")",
";",
"this",
".",
"parent",
"=",
"null",
";",
"this",
".",
"runnables",
"=",
"[",
"]",
";",
"this",
".",
"events",
"=",
"{",
"pre",
":",
"'pre:suite'",
",",
"post",
":",
"'post:suite'",
"}",
";",
"}"
]
| Test suite.
@param {String} title
@constructor | [
"Test",
"suite",
"."
]
| 3f4d2e4926f913976187376e82f1496514c39890 | https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/suite/index.js#L16-L24 |
41,604 | atsid/circuits-js | js/Request.js | function () {
var that = this,
paramHandler = this.params.handler,
params = util.mixin({}, this.params);
//wrap the handler callbacks in a cancel check
function handler(responseCode, data, ioArgs) {
that.xhr = ioArgs.xhr;
that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0;
if (that.canceled) {
logger.debug("Request [" + that.id + "] was canceled, not calling handler");
} else {
that.pending = false;
that.complete = true;
paramHandler(responseCode, data, ioArgs);
}
}
if (this.canceled) {
logger.debug("Request [" + that.id + "] was canceled, not executing");
} else {
this.pending = true;
this.fn(util.mixin(params, {
handler: handler
}));
}
} | javascript | function () {
var that = this,
paramHandler = this.params.handler,
params = util.mixin({}, this.params);
//wrap the handler callbacks in a cancel check
function handler(responseCode, data, ioArgs) {
that.xhr = ioArgs.xhr;
that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0;
if (that.canceled) {
logger.debug("Request [" + that.id + "] was canceled, not calling handler");
} else {
that.pending = false;
that.complete = true;
paramHandler(responseCode, data, ioArgs);
}
}
if (this.canceled) {
logger.debug("Request [" + that.id + "] was canceled, not executing");
} else {
this.pending = true;
this.fn(util.mixin(params, {
handler: handler
}));
}
} | [
"function",
"(",
")",
"{",
"var",
"that",
"=",
"this",
",",
"paramHandler",
"=",
"this",
".",
"params",
".",
"handler",
",",
"params",
"=",
"util",
".",
"mixin",
"(",
"{",
"}",
",",
"this",
".",
"params",
")",
";",
"//wrap the handler callbacks in a cancel check",
"function",
"handler",
"(",
"responseCode",
",",
"data",
",",
"ioArgs",
")",
"{",
"that",
".",
"xhr",
"=",
"ioArgs",
".",
"xhr",
";",
"that",
".",
"statusCode",
"=",
"that",
".",
"xhr",
"&&",
"!",
"that",
".",
"xhr",
".",
"timedOut",
"&&",
"that",
".",
"xhr",
".",
"status",
"||",
"0",
";",
"if",
"(",
"that",
".",
"canceled",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Request [\"",
"+",
"that",
".",
"id",
"+",
"\"] was canceled, not calling handler\"",
")",
";",
"}",
"else",
"{",
"that",
".",
"pending",
"=",
"false",
";",
"that",
".",
"complete",
"=",
"true",
";",
"paramHandler",
"(",
"responseCode",
",",
"data",
",",
"ioArgs",
")",
";",
"}",
"}",
"if",
"(",
"this",
".",
"canceled",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Request [\"",
"+",
"that",
".",
"id",
"+",
"\"] was canceled, not executing\"",
")",
";",
"}",
"else",
"{",
"this",
".",
"pending",
"=",
"true",
";",
"this",
".",
"fn",
"(",
"util",
".",
"mixin",
"(",
"params",
",",
"{",
"handler",
":",
"handler",
"}",
")",
")",
";",
"}",
"}"
]
| Calls the specified data function, passing in the params.
This allows us to wrap these calls with a cancellation check.
Note that scope is ignored - the ultimate callback scope is defined wherever the provider method is ultimately called. | [
"Calls",
"the",
"specified",
"data",
"function",
"passing",
"in",
"the",
"params",
".",
"This",
"allows",
"us",
"to",
"wrap",
"these",
"calls",
"with",
"a",
"cancellation",
"check",
".",
"Note",
"that",
"scope",
"is",
"ignored",
"-",
"the",
"ultimate",
"callback",
"scope",
"is",
"defined",
"wherever",
"the",
"provider",
"method",
"is",
"ultimately",
"called",
"."
]
| f1fa5e98d406b3b9f577dd8995782c7115d6b346 | https://github.com/atsid/circuits-js/blob/f1fa5e98d406b3b9f577dd8995782c7115d6b346/js/Request.js#L45-L72 |
|
41,605 | atsid/circuits-js | js/Request.js | handler | function handler(responseCode, data, ioArgs) {
that.xhr = ioArgs.xhr;
that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0;
if (that.canceled) {
logger.debug("Request [" + that.id + "] was canceled, not calling handler");
} else {
that.pending = false;
that.complete = true;
paramHandler(responseCode, data, ioArgs);
}
} | javascript | function handler(responseCode, data, ioArgs) {
that.xhr = ioArgs.xhr;
that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0;
if (that.canceled) {
logger.debug("Request [" + that.id + "] was canceled, not calling handler");
} else {
that.pending = false;
that.complete = true;
paramHandler(responseCode, data, ioArgs);
}
} | [
"function",
"handler",
"(",
"responseCode",
",",
"data",
",",
"ioArgs",
")",
"{",
"that",
".",
"xhr",
"=",
"ioArgs",
".",
"xhr",
";",
"that",
".",
"statusCode",
"=",
"that",
".",
"xhr",
"&&",
"!",
"that",
".",
"xhr",
".",
"timedOut",
"&&",
"that",
".",
"xhr",
".",
"status",
"||",
"0",
";",
"if",
"(",
"that",
".",
"canceled",
")",
"{",
"logger",
".",
"debug",
"(",
"\"Request [\"",
"+",
"that",
".",
"id",
"+",
"\"] was canceled, not calling handler\"",
")",
";",
"}",
"else",
"{",
"that",
".",
"pending",
"=",
"false",
";",
"that",
".",
"complete",
"=",
"true",
";",
"paramHandler",
"(",
"responseCode",
",",
"data",
",",
"ioArgs",
")",
";",
"}",
"}"
]
| wrap the handler callbacks in a cancel check | [
"wrap",
"the",
"handler",
"callbacks",
"in",
"a",
"cancel",
"check"
]
| f1fa5e98d406b3b9f577dd8995782c7115d6b346 | https://github.com/atsid/circuits-js/blob/f1fa5e98d406b3b9f577dd8995782c7115d6b346/js/Request.js#L52-L62 |
41,606 | Mammut-FE/nejm | src/util/ajax/xdr.js | function(_options){
var _upload = _isUpload(_options.headers);
if (!_isXDomain(_options.url)&&!_upload)
return _t._$$ProxyXHR._$allocate(_options);
return _h.__getProxyByMode(_options.mode,_upload,_options);
} | javascript | function(_options){
var _upload = _isUpload(_options.headers);
if (!_isXDomain(_options.url)&&!_upload)
return _t._$$ProxyXHR._$allocate(_options);
return _h.__getProxyByMode(_options.mode,_upload,_options);
} | [
"function",
"(",
"_options",
")",
"{",
"var",
"_upload",
"=",
"_isUpload",
"(",
"_options",
".",
"headers",
")",
";",
"if",
"(",
"!",
"_isXDomain",
"(",
"_options",
".",
"url",
")",
"&&",
"!",
"_upload",
")",
"return",
"_t",
".",
"_$$ProxyXHR",
".",
"_$allocate",
"(",
"_options",
")",
";",
"return",
"_h",
".",
"__getProxyByMode",
"(",
"_options",
".",
"mode",
",",
"_upload",
",",
"_options",
")",
";",
"}"
]
| get ajax proxy | [
"get",
"ajax",
"proxy"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/xdr.js#L208-L213 |
|
41,607 | Mammut-FE/nejm | src/util/ajax/xdr.js | function(_cache,_result){
var _data = {
data:_result
};
// parse ext headers
var _keys = _cache.result.headers;
if (!!_keys){
_data.headers = _cache.req._$header(_keys);
}
// TODO parse other ext data
return _data;
} | javascript | function(_cache,_result){
var _data = {
data:_result
};
// parse ext headers
var _keys = _cache.result.headers;
if (!!_keys){
_data.headers = _cache.req._$header(_keys);
}
// TODO parse other ext data
return _data;
} | [
"function",
"(",
"_cache",
",",
"_result",
")",
"{",
"var",
"_data",
"=",
"{",
"data",
":",
"_result",
"}",
";",
"// parse ext headers",
"var",
"_keys",
"=",
"_cache",
".",
"result",
".",
"headers",
";",
"if",
"(",
"!",
"!",
"_keys",
")",
"{",
"_data",
".",
"headers",
"=",
"_cache",
".",
"req",
".",
"_$header",
"(",
"_keys",
")",
";",
"}",
"// TODO parse other ext data",
"return",
"_data",
";",
"}"
]
| parse ext result | [
"parse",
"ext",
"result"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/xdr.js#L215-L226 |
|
41,608 | Mammut-FE/nejm | src/util/ajax/xdr.js | function(_url,_data){
var _sep = _url.indexOf('?')<0?'?':'&',
_data = _data||'';
if (_u._$isObject(_data))
_data = _u._$object2query(_data);
if (!!_data) _url += _sep+_data;
return _url;
} | javascript | function(_url,_data){
var _sep = _url.indexOf('?')<0?'?':'&',
_data = _data||'';
if (_u._$isObject(_data))
_data = _u._$object2query(_data);
if (!!_data) _url += _sep+_data;
return _url;
} | [
"function",
"(",
"_url",
",",
"_data",
")",
"{",
"var",
"_sep",
"=",
"_url",
".",
"indexOf",
"(",
"'?'",
")",
"<",
"0",
"?",
"'?'",
":",
"'&'",
",",
"_data",
"=",
"_data",
"||",
"''",
";",
"if",
"(",
"_u",
".",
"_$isObject",
"(",
"_data",
")",
")",
"_data",
"=",
"_u",
".",
"_$object2query",
"(",
"_data",
")",
";",
"if",
"(",
"!",
"!",
"_data",
")",
"_url",
"+=",
"_sep",
"+",
"_data",
";",
"return",
"_url",
";",
"}"
]
| check data for get method | [
"check",
"data",
"for",
"get",
"method"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/ajax/xdr.js#L262-L269 |
|
41,609 | veo-labs/openveo-api | lib/errors/StorageError.js | StorageError | function StorageError(message, code) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperties(this, {
/**
* The error code.
*
* @property code
* @type Number
* @final
*/
code: {value: code},
/**
* Error message.
*
* @property message
* @type String
* @final
*/
message: {value: 'A storage error occurred with code "' + code + '"', writable: true},
/**
* The error name.
*
* @property name
* @type String
* @final
*/
name: {value: 'StorageError', writable: true}
});
if (message) this.message = message;
} | javascript | function StorageError(message, code) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperties(this, {
/**
* The error code.
*
* @property code
* @type Number
* @final
*/
code: {value: code},
/**
* Error message.
*
* @property message
* @type String
* @final
*/
message: {value: 'A storage error occurred with code "' + code + '"', writable: true},
/**
* The error name.
*
* @property name
* @type String
* @final
*/
name: {value: 'StorageError', writable: true}
});
if (message) this.message = message;
} | [
"function",
"StorageError",
"(",
"message",
",",
"code",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"/**\n * The error code.\n *\n * @property code\n * @type Number\n * @final\n */",
"code",
":",
"{",
"value",
":",
"code",
"}",
",",
"/**\n * Error message.\n *\n * @property message\n * @type String\n * @final\n */",
"message",
":",
"{",
"value",
":",
"'A storage error occurred with code \"'",
"+",
"code",
"+",
"'\"'",
",",
"writable",
":",
"true",
"}",
",",
"/**\n * The error name.\n *\n * @property name\n * @type String\n * @final\n */",
"name",
":",
"{",
"value",
":",
"'StorageError'",
",",
"writable",
":",
"true",
"}",
"}",
")",
";",
"if",
"(",
"message",
")",
"this",
".",
"message",
"=",
"message",
";",
"}"
]
| Defines a StorageError to be thrown when a storage error occurred.
var openVeoApi = require('@openveo/api');
throw new openVeoApi.errors.StorageError(42);
@class StorageError
@extends Error
@constructor
@param {String} message The error message
@param {Number} code The code corresponding to the error | [
"Defines",
"a",
"StorageError",
"to",
"be",
"thrown",
"when",
"a",
"storage",
"error",
"occurred",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/errors/StorageError.js#L21-L56 |
41,610 | larvit/larvitfs | index.js | searchPathsRec | function searchPathsRec(thisPath, pathsToIgnore) {
const subLogPrefix = logPrefix + 'searchPathsRec() - ';
let result = [];
let thisPaths;
if (! pathsToIgnore) pathsToIgnore = [];
try {
if (that.fs.existsSync(thisPath + '/' + target) && result.indexOf(path.normalize(thisPath + '/' + target)) === - 1 && pathsToIgnore.indexOf(thisPath) === - 1) {
result.push(path.normalize(thisPath + '/' + target));
}
if (! that.fs.existsSync(thisPath)) {
return result;
}
thisPaths = that.fs.readdirSync(thisPath);
} catch (err) {
that.log.error(subLogPrefix + 'throwed fs error: ' + err.message);
return result;
}
for (let i = 0; thisPaths[i] !== undefined; i ++) {
try {
const subStat = that.fs.statSync(thisPath + '/' + thisPaths[i]);
if (subStat.isDirectory()) {
if (thisPaths[i] !== target && pathsToIgnore.indexOf(thisPaths[i]) === - 1) {
// If we've found a target dir, we do not wish to scan it
result = result.concat(searchPathsRec(thisPath + '/' + thisPaths[i], pathsToIgnore));
}
}
} catch (err) {
that.log.error(subLogPrefix + 'Could not read "' + thisPaths[i] + '": ' + err.message);
}
}
return result;
} | javascript | function searchPathsRec(thisPath, pathsToIgnore) {
const subLogPrefix = logPrefix + 'searchPathsRec() - ';
let result = [];
let thisPaths;
if (! pathsToIgnore) pathsToIgnore = [];
try {
if (that.fs.existsSync(thisPath + '/' + target) && result.indexOf(path.normalize(thisPath + '/' + target)) === - 1 && pathsToIgnore.indexOf(thisPath) === - 1) {
result.push(path.normalize(thisPath + '/' + target));
}
if (! that.fs.existsSync(thisPath)) {
return result;
}
thisPaths = that.fs.readdirSync(thisPath);
} catch (err) {
that.log.error(subLogPrefix + 'throwed fs error: ' + err.message);
return result;
}
for (let i = 0; thisPaths[i] !== undefined; i ++) {
try {
const subStat = that.fs.statSync(thisPath + '/' + thisPaths[i]);
if (subStat.isDirectory()) {
if (thisPaths[i] !== target && pathsToIgnore.indexOf(thisPaths[i]) === - 1) {
// If we've found a target dir, we do not wish to scan it
result = result.concat(searchPathsRec(thisPath + '/' + thisPaths[i], pathsToIgnore));
}
}
} catch (err) {
that.log.error(subLogPrefix + 'Could not read "' + thisPaths[i] + '": ' + err.message);
}
}
return result;
} | [
"function",
"searchPathsRec",
"(",
"thisPath",
",",
"pathsToIgnore",
")",
"{",
"const",
"subLogPrefix",
"=",
"logPrefix",
"+",
"'searchPathsRec() - '",
";",
"let",
"result",
"=",
"[",
"]",
";",
"let",
"thisPaths",
";",
"if",
"(",
"!",
"pathsToIgnore",
")",
"pathsToIgnore",
"=",
"[",
"]",
";",
"try",
"{",
"if",
"(",
"that",
".",
"fs",
".",
"existsSync",
"(",
"thisPath",
"+",
"'/'",
"+",
"target",
")",
"&&",
"result",
".",
"indexOf",
"(",
"path",
".",
"normalize",
"(",
"thisPath",
"+",
"'/'",
"+",
"target",
")",
")",
"===",
"-",
"1",
"&&",
"pathsToIgnore",
".",
"indexOf",
"(",
"thisPath",
")",
"===",
"-",
"1",
")",
"{",
"result",
".",
"push",
"(",
"path",
".",
"normalize",
"(",
"thisPath",
"+",
"'/'",
"+",
"target",
")",
")",
";",
"}",
"if",
"(",
"!",
"that",
".",
"fs",
".",
"existsSync",
"(",
"thisPath",
")",
")",
"{",
"return",
"result",
";",
"}",
"thisPaths",
"=",
"that",
".",
"fs",
".",
"readdirSync",
"(",
"thisPath",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"that",
".",
"log",
".",
"error",
"(",
"subLogPrefix",
"+",
"'throwed fs error: '",
"+",
"err",
".",
"message",
")",
";",
"return",
"result",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"thisPaths",
"[",
"i",
"]",
"!==",
"undefined",
";",
"i",
"++",
")",
"{",
"try",
"{",
"const",
"subStat",
"=",
"that",
".",
"fs",
".",
"statSync",
"(",
"thisPath",
"+",
"'/'",
"+",
"thisPaths",
"[",
"i",
"]",
")",
";",
"if",
"(",
"subStat",
".",
"isDirectory",
"(",
")",
")",
"{",
"if",
"(",
"thisPaths",
"[",
"i",
"]",
"!==",
"target",
"&&",
"pathsToIgnore",
".",
"indexOf",
"(",
"thisPaths",
"[",
"i",
"]",
")",
"===",
"-",
"1",
")",
"{",
"// If we've found a target dir, we do not wish to scan it",
"result",
"=",
"result",
".",
"concat",
"(",
"searchPathsRec",
"(",
"thisPath",
"+",
"'/'",
"+",
"thisPaths",
"[",
"i",
"]",
",",
"pathsToIgnore",
")",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"that",
".",
"log",
".",
"error",
"(",
"subLogPrefix",
"+",
"'Could not read \"'",
"+",
"thisPaths",
"[",
"i",
"]",
"+",
"'\": '",
"+",
"err",
".",
"message",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
]
| Search for paths recursively
@param {str} thisPath - the path to search for
@param {arr} pathsToIgnore - array of paths to ignore
@returns {str} - absolute path | [
"Search",
"for",
"paths",
"recursively"
]
| 3e0169577c2844b60f210a4e59a3d4f41821713c | https://github.com/larvit/larvitfs/blob/3e0169577c2844b60f210a4e59a3d4f41821713c/index.js#L128-L168 |
41,611 | larvit/larvitfs | index.js | loadPathsRec | function loadPathsRec(thisPath) {
const subLogPrefix = logPrefix + 'loadPathsRec() - ';
let thisPaths;
if (that.paths.indexOf(thisPath) === - 1) {
that.log.debug(subLogPrefix + 'Adding ' + path.basename(thisPath) + ' to paths with full path ' + thisPath);
that.paths.push(thisPath);
}
thisPaths = that.fs.readdirSync(thisPath + '/node_modules');
for (let i = 0; thisPaths[i] !== undefined; i ++) {
try {
const subStat = that.fs.statSync(thisPath + '/node_modules/' + thisPaths[i]);
if (subStat.isDirectory()) {
loadPathsRec(thisPath + '/node_modules/' + thisPaths[i]);
}
} catch (err) {
that.log.silly(subLogPrefix + 'Could not read "' + thisPaths[i] + '": ' + err.message);
}
}
} | javascript | function loadPathsRec(thisPath) {
const subLogPrefix = logPrefix + 'loadPathsRec() - ';
let thisPaths;
if (that.paths.indexOf(thisPath) === - 1) {
that.log.debug(subLogPrefix + 'Adding ' + path.basename(thisPath) + ' to paths with full path ' + thisPath);
that.paths.push(thisPath);
}
thisPaths = that.fs.readdirSync(thisPath + '/node_modules');
for (let i = 0; thisPaths[i] !== undefined; i ++) {
try {
const subStat = that.fs.statSync(thisPath + '/node_modules/' + thisPaths[i]);
if (subStat.isDirectory()) {
loadPathsRec(thisPath + '/node_modules/' + thisPaths[i]);
}
} catch (err) {
that.log.silly(subLogPrefix + 'Could not read "' + thisPaths[i] + '": ' + err.message);
}
}
} | [
"function",
"loadPathsRec",
"(",
"thisPath",
")",
"{",
"const",
"subLogPrefix",
"=",
"logPrefix",
"+",
"'loadPathsRec() - '",
";",
"let",
"thisPaths",
";",
"if",
"(",
"that",
".",
"paths",
".",
"indexOf",
"(",
"thisPath",
")",
"===",
"-",
"1",
")",
"{",
"that",
".",
"log",
".",
"debug",
"(",
"subLogPrefix",
"+",
"'Adding '",
"+",
"path",
".",
"basename",
"(",
"thisPath",
")",
"+",
"' to paths with full path '",
"+",
"thisPath",
")",
";",
"that",
".",
"paths",
".",
"push",
"(",
"thisPath",
")",
";",
"}",
"thisPaths",
"=",
"that",
".",
"fs",
".",
"readdirSync",
"(",
"thisPath",
"+",
"'/node_modules'",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"thisPaths",
"[",
"i",
"]",
"!==",
"undefined",
";",
"i",
"++",
")",
"{",
"try",
"{",
"const",
"subStat",
"=",
"that",
".",
"fs",
".",
"statSync",
"(",
"thisPath",
"+",
"'/node_modules/'",
"+",
"thisPaths",
"[",
"i",
"]",
")",
";",
"if",
"(",
"subStat",
".",
"isDirectory",
"(",
")",
")",
"{",
"loadPathsRec",
"(",
"thisPath",
"+",
"'/node_modules/'",
"+",
"thisPaths",
"[",
"i",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"that",
".",
"log",
".",
"silly",
"(",
"subLogPrefix",
"+",
"'Could not read \"'",
"+",
"thisPaths",
"[",
"i",
"]",
"+",
"'\": '",
"+",
"err",
".",
"message",
")",
";",
"}",
"}",
"}"
]
| Add all other paths, recursively
@param {str} thisPath - the path to search for | [
"Add",
"all",
"other",
"paths",
"recursively"
]
| 3e0169577c2844b60f210a4e59a3d4f41821713c | https://github.com/larvit/larvitfs/blob/3e0169577c2844b60f210a4e59a3d4f41821713c/index.js#L239-L262 |
41,612 | donejs/ir-reattach | src/reattach.js | depth | function depth(root) {
let i = 0;
let walker = document.createTreeWalker(root, 0xFFFFFFFF, {
acceptNode: function(node){
let nt = node.nodeType;
return nt === 1 || nt === 3;
}
});
while(walker.nextNode()) {
i++;
}
return i;
} | javascript | function depth(root) {
let i = 0;
let walker = document.createTreeWalker(root, 0xFFFFFFFF, {
acceptNode: function(node){
let nt = node.nodeType;
return nt === 1 || nt === 3;
}
});
while(walker.nextNode()) {
i++;
}
return i;
} | [
"function",
"depth",
"(",
"root",
")",
"{",
"let",
"i",
"=",
"0",
";",
"let",
"walker",
"=",
"document",
".",
"createTreeWalker",
"(",
"root",
",",
"0xFFFFFFFF",
",",
"{",
"acceptNode",
":",
"function",
"(",
"node",
")",
"{",
"let",
"nt",
"=",
"node",
".",
"nodeType",
";",
"return",
"nt",
"===",
"1",
"||",
"nt",
"===",
"3",
";",
"}",
"}",
")",
";",
"while",
"(",
"walker",
".",
"nextNode",
"(",
")",
")",
"{",
"i",
"++",
";",
"}",
"return",
"i",
";",
"}"
]
| Get the depth of a Node | [
"Get",
"the",
"depth",
"of",
"a",
"Node"
]
| 0440d4ed090982103d90347aa0b960f35a7e0628 | https://github.com/donejs/ir-reattach/blob/0440d4ed090982103d90347aa0b960f35a7e0628/src/reattach.js#L4-L17 |
41,613 | Bartvds/grunt-run-grunt | lib/runGruntfile.js | writeShell | function writeShell(grunt, options, src, cwd, argArr) {
let dir = options.writeShell;
if (grunt.file.isFile(options.writeShell)) {
dir = path.dirname(options.writeShell);
}
const gf = path.basename(src.toLowerCase(), path.extname(src));
const base = path.join(dir, options.target + '__' + gf);
const _ = grunt.util._;
const gruntCli = (_.isUndefined(options.gruntCli) || _.isNull(options.gruntCli)) ? 'grunt' : options.gruntCli;
// beh
const shPath = base + '.sh';
const shContent = [
'#!/bin/bash',
'',
'cd ' + path.resolve(cwd),
gruntCli + ' ' + argArr.join(' '),
''
].join('\n');
grunt.file.write(shPath, shContent);
//TODO chmod the shell-script?
// semi broken
const batPath = base + '.bat';
const batContent = [
'set PWD=%~dp0',
'cd ' + path.resolve(cwd),
gruntCli + ' ' + argArr.join(' '),
'cd "%PWD%"',
''
].join('\r\n');
grunt.file.write(batPath, batContent);
console.log('argArr: ' + argArr.join(' '));
} | javascript | function writeShell(grunt, options, src, cwd, argArr) {
let dir = options.writeShell;
if (grunt.file.isFile(options.writeShell)) {
dir = path.dirname(options.writeShell);
}
const gf = path.basename(src.toLowerCase(), path.extname(src));
const base = path.join(dir, options.target + '__' + gf);
const _ = grunt.util._;
const gruntCli = (_.isUndefined(options.gruntCli) || _.isNull(options.gruntCli)) ? 'grunt' : options.gruntCli;
// beh
const shPath = base + '.sh';
const shContent = [
'#!/bin/bash',
'',
'cd ' + path.resolve(cwd),
gruntCli + ' ' + argArr.join(' '),
''
].join('\n');
grunt.file.write(shPath, shContent);
//TODO chmod the shell-script?
// semi broken
const batPath = base + '.bat';
const batContent = [
'set PWD=%~dp0',
'cd ' + path.resolve(cwd),
gruntCli + ' ' + argArr.join(' '),
'cd "%PWD%"',
''
].join('\r\n');
grunt.file.write(batPath, batContent);
console.log('argArr: ' + argArr.join(' '));
} | [
"function",
"writeShell",
"(",
"grunt",
",",
"options",
",",
"src",
",",
"cwd",
",",
"argArr",
")",
"{",
"let",
"dir",
"=",
"options",
".",
"writeShell",
";",
"if",
"(",
"grunt",
".",
"file",
".",
"isFile",
"(",
"options",
".",
"writeShell",
")",
")",
"{",
"dir",
"=",
"path",
".",
"dirname",
"(",
"options",
".",
"writeShell",
")",
";",
"}",
"const",
"gf",
"=",
"path",
".",
"basename",
"(",
"src",
".",
"toLowerCase",
"(",
")",
",",
"path",
".",
"extname",
"(",
"src",
")",
")",
";",
"const",
"base",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"options",
".",
"target",
"+",
"'__'",
"+",
"gf",
")",
";",
"const",
"_",
"=",
"grunt",
".",
"util",
".",
"_",
";",
"const",
"gruntCli",
"=",
"(",
"_",
".",
"isUndefined",
"(",
"options",
".",
"gruntCli",
")",
"||",
"_",
".",
"isNull",
"(",
"options",
".",
"gruntCli",
")",
")",
"?",
"'grunt'",
":",
"options",
".",
"gruntCli",
";",
"// beh",
"const",
"shPath",
"=",
"base",
"+",
"'.sh'",
";",
"const",
"shContent",
"=",
"[",
"'#!/bin/bash'",
",",
"''",
",",
"'cd '",
"+",
"path",
".",
"resolve",
"(",
"cwd",
")",
",",
"gruntCli",
"+",
"' '",
"+",
"argArr",
".",
"join",
"(",
"' '",
")",
",",
"''",
"]",
".",
"join",
"(",
"'\\n'",
")",
";",
"grunt",
".",
"file",
".",
"write",
"(",
"shPath",
",",
"shContent",
")",
";",
"//TODO chmod the shell-script?",
"// semi broken",
"const",
"batPath",
"=",
"base",
"+",
"'.bat'",
";",
"const",
"batContent",
"=",
"[",
"'set PWD=%~dp0'",
",",
"'cd '",
"+",
"path",
".",
"resolve",
"(",
"cwd",
")",
",",
"gruntCli",
"+",
"' '",
"+",
"argArr",
".",
"join",
"(",
"' '",
")",
",",
"'cd \"%PWD%\"'",
",",
"''",
"]",
".",
"join",
"(",
"'\\r\\n'",
")",
";",
"grunt",
".",
"file",
".",
"write",
"(",
"batPath",
",",
"batContent",
")",
";",
"console",
".",
"log",
"(",
"'argArr: '",
"+",
"argArr",
".",
"join",
"(",
"' '",
")",
")",
";",
"}"
]
| write shell scripts | [
"write",
"shell",
"scripts"
]
| e347fe8e5a9e2e1b16c8e84fbbad2df884e84643 | https://github.com/Bartvds/grunt-run-grunt/blob/e347fe8e5a9e2e1b16c8e84fbbad2df884e84643/lib/runGruntfile.js#L10-L48 |
41,614 | veo-labs/openveo-api | lib/socket/Pilot.js | Pilot | function Pilot(clientEmitter, namespace) {
Pilot.super_.call(this);
Object.defineProperties(this, {
/**
* The list of actually connected clients.
*
* @property clients
* @type Array
* @final
*/
clients: {value: []},
/**
* The emitter to receive sockets' messages from clients.
*
* @property clientEmitter
* @type AdvancedEmitter
* @final
*/
clientEmitter: {value: clientEmitter},
/**
* The sockets' namespace to communicate with clients.
*
* @property namespace
* @type SocketNamespace
* @final
*/
namespace: {value: namespace}
});
} | javascript | function Pilot(clientEmitter, namespace) {
Pilot.super_.call(this);
Object.defineProperties(this, {
/**
* The list of actually connected clients.
*
* @property clients
* @type Array
* @final
*/
clients: {value: []},
/**
* The emitter to receive sockets' messages from clients.
*
* @property clientEmitter
* @type AdvancedEmitter
* @final
*/
clientEmitter: {value: clientEmitter},
/**
* The sockets' namespace to communicate with clients.
*
* @property namespace
* @type SocketNamespace
* @final
*/
namespace: {value: namespace}
});
} | [
"function",
"Pilot",
"(",
"clientEmitter",
",",
"namespace",
")",
"{",
"Pilot",
".",
"super_",
".",
"call",
"(",
"this",
")",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"/**\n * The list of actually connected clients.\n *\n * @property clients\n * @type Array\n * @final\n */",
"clients",
":",
"{",
"value",
":",
"[",
"]",
"}",
",",
"/**\n * The emitter to receive sockets' messages from clients.\n *\n * @property clientEmitter\n * @type AdvancedEmitter\n * @final\n */",
"clientEmitter",
":",
"{",
"value",
":",
"clientEmitter",
"}",
",",
"/**\n * The sockets' namespace to communicate with clients.\n *\n * @property namespace\n * @type SocketNamespace\n * @final\n */",
"namespace",
":",
"{",
"value",
":",
"namespace",
"}",
"}",
")",
";",
"}"
]
| Defines a base pilot for all pilots.
A Pilot is designed to interact with sockets' clients. It listens to sockets' messages
by listening to its associated client emitter. It sends information to
sockets' clients using its associated socket namespace.
A Pilot keeps a list of connected clients with associated sockets.
@class Pilot
@constructor
@param {AdvancedEmitter} clientEmitter The clients' emitter
@param {SocketNamespace} namespace The clients' namespace | [
"Defines",
"a",
"base",
"pilot",
"for",
"all",
"pilots",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/socket/Pilot.js#L24-L58 |
41,615 | bigeasy/chaperon | colleagues.js | Colleagues | function Colleagues (options) {
this._ua = options.ua
this._mingle = options.mingle
this._conduit = options.conduit
this._colleague = options.colleague
} | javascript | function Colleagues (options) {
this._ua = options.ua
this._mingle = options.mingle
this._conduit = options.conduit
this._colleague = options.colleague
} | [
"function",
"Colleagues",
"(",
"options",
")",
"{",
"this",
".",
"_ua",
"=",
"options",
".",
"ua",
"this",
".",
"_mingle",
"=",
"options",
".",
"mingle",
"this",
".",
"_conduit",
"=",
"options",
".",
"conduit",
"this",
".",
"_colleague",
"=",
"options",
".",
"colleague",
"}"
]
| Create a client with the given user agent that will query the Mingle end point URL at `mingle`. The `conduit` and `colleague` arguments are string formats used to create the URLs to query the conduit and colleague respectively. | [
"Create",
"a",
"client",
"with",
"the",
"given",
"user",
"agent",
"that",
"will",
"query",
"the",
"Mingle",
"end",
"point",
"URL",
"at",
"mingle",
".",
"The",
"conduit",
"and",
"colleague",
"arguments",
"are",
"string",
"formats",
"used",
"to",
"create",
"the",
"URLs",
"to",
"query",
"the",
"conduit",
"and",
"colleague",
"respectively",
"."
]
| e5285ebbb9dbdb020cd7fe989fd0ffc228482798 | https://github.com/bigeasy/chaperon/blob/e5285ebbb9dbdb020cd7fe989fd0ffc228482798/colleagues.js#L25-L30 |
41,616 | winterstein/wwutils.js | src/wwutils.js | function(obj, propName, message) {
assert(typeof(propName) === 'string');
if ( ! message) message = "Using this property indicates old/broken code.";
// already blocked?
bphush = true;
try {
let v = obj[propName];
} catch (err) {
return obj;
}
bphush = false;
if (obj[propName] !== undefined) {
// already set to a value :(
const ex = new Error("Having "+propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
}
if ( ! Object.isExtensible(obj)) {
// no need -- frozen or sealed
return;
}
Object.defineProperty(obj, propName, {
get: function () {
const ex = new Error(propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
},
set: function () {
const ex = new Error("Set "+propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
}
});
return obj;
} | javascript | function(obj, propName, message) {
assert(typeof(propName) === 'string');
if ( ! message) message = "Using this property indicates old/broken code.";
// already blocked?
bphush = true;
try {
let v = obj[propName];
} catch (err) {
return obj;
}
bphush = false;
if (obj[propName] !== undefined) {
// already set to a value :(
const ex = new Error("Having "+propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
}
if ( ! Object.isExtensible(obj)) {
// no need -- frozen or sealed
return;
}
Object.defineProperty(obj, propName, {
get: function () {
const ex = new Error(propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
},
set: function () {
const ex = new Error("Set "+propName+" is blocked! "+message);
if ( ! bphush) console.error(ex, this); // react can swallow stuff
throw ex;
}
});
return obj;
} | [
"function",
"(",
"obj",
",",
"propName",
",",
"message",
")",
"{",
"assert",
"(",
"typeof",
"(",
"propName",
")",
"===",
"'string'",
")",
";",
"if",
"(",
"!",
"message",
")",
"message",
"=",
"\"Using this property indicates old/broken code.\"",
";",
"// already blocked?\t",
"bphush",
"=",
"true",
";",
"try",
"{",
"let",
"v",
"=",
"obj",
"[",
"propName",
"]",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"obj",
";",
"}",
"bphush",
"=",
"false",
";",
"if",
"(",
"obj",
"[",
"propName",
"]",
"!==",
"undefined",
")",
"{",
"// already set to a value :(",
"const",
"ex",
"=",
"new",
"Error",
"(",
"\"Having \"",
"+",
"propName",
"+",
"\" is blocked! \"",
"+",
"message",
")",
";",
"if",
"(",
"!",
"bphush",
")",
"console",
".",
"error",
"(",
"ex",
",",
"this",
")",
";",
"// react can swallow stuff",
"throw",
"ex",
";",
"}",
"if",
"(",
"!",
"Object",
".",
"isExtensible",
"(",
"obj",
")",
")",
"{",
"// no need -- frozen or sealed\t",
"return",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"obj",
",",
"propName",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"const",
"ex",
"=",
"new",
"Error",
"(",
"propName",
"+",
"\" is blocked! \"",
"+",
"message",
")",
";",
"if",
"(",
"!",
"bphush",
")",
"console",
".",
"error",
"(",
"ex",
",",
"this",
")",
";",
"// react can swallow stuff",
"throw",
"ex",
";",
"}",
",",
"set",
":",
"function",
"(",
")",
"{",
"const",
"ex",
"=",
"new",
"Error",
"(",
"\"Set \"",
"+",
"propName",
"+",
"\" is blocked! \"",
"+",
"message",
")",
";",
"if",
"(",
"!",
"bphush",
")",
"console",
".",
"error",
"(",
"ex",
",",
"this",
")",
";",
"// react can swallow stuff",
"throw",
"ex",
";",
"}",
"}",
")",
";",
"return",
"obj",
";",
"}"
]
| Rig obj so that any use of obj.propName will trigger an Error.
@param {!String} propName
@param {?String} message Optional helpful message, like "use foo() instead."
@returns obj (allows for chaining) | [
"Rig",
"obj",
"so",
"that",
"any",
"use",
"of",
"obj",
".",
"propName",
"will",
"trigger",
"an",
"Error",
"."
]
| 683743df0c896993b9ec455738154972ac54f0b6 | https://github.com/winterstein/wwutils.js/blob/683743df0c896993b9ec455738154972ac54f0b6/src/wwutils.js#L414-L448 |
|
41,617 | vesln/hydro | lib/cli/commands/help.js | coreFlags | function coreFlags() {
console.log('Core flags:');
console.log();
flags.forEach(function(flag) {
console.log(' ' + flag);
});
} | javascript | function coreFlags() {
console.log('Core flags:');
console.log();
flags.forEach(function(flag) {
console.log(' ' + flag);
});
} | [
"function",
"coreFlags",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'Core flags:'",
")",
";",
"console",
".",
"log",
"(",
")",
";",
"flags",
".",
"forEach",
"(",
"function",
"(",
"flag",
")",
"{",
"console",
".",
"log",
"(",
"' '",
"+",
"flag",
")",
";",
"}",
")",
";",
"}"
]
| Print the code CLI flags.
@api private | [
"Print",
"the",
"code",
"CLI",
"flags",
"."
]
| 3f4d2e4926f913976187376e82f1496514c39890 | https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/cli/commands/help.js#L50-L56 |
41,618 | vesln/hydro | lib/cli/commands/help.js | pluginFlags | function pluginFlags(plugins) {
var pflags = [];
var len = 0;
plugins.forEach(function(plugin) {
Object.keys(plugin.flags || {}).forEach(function(flag) {
pflags.push([flag, plugin.flags[flag]]);
len = Math.max(flag.length, len);
});
});
if (pflags.length) {
console.log();
console.log('Plugin flags:');
console.log();
pflags.forEach(function(flag) {
console.log(' %s %s', ljust(flag[0], len), flag[1]);
});
}
console.log();
} | javascript | function pluginFlags(plugins) {
var pflags = [];
var len = 0;
plugins.forEach(function(plugin) {
Object.keys(plugin.flags || {}).forEach(function(flag) {
pflags.push([flag, plugin.flags[flag]]);
len = Math.max(flag.length, len);
});
});
if (pflags.length) {
console.log();
console.log('Plugin flags:');
console.log();
pflags.forEach(function(flag) {
console.log(' %s %s', ljust(flag[0], len), flag[1]);
});
}
console.log();
} | [
"function",
"pluginFlags",
"(",
"plugins",
")",
"{",
"var",
"pflags",
"=",
"[",
"]",
";",
"var",
"len",
"=",
"0",
";",
"plugins",
".",
"forEach",
"(",
"function",
"(",
"plugin",
")",
"{",
"Object",
".",
"keys",
"(",
"plugin",
".",
"flags",
"||",
"{",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"flag",
")",
"{",
"pflags",
".",
"push",
"(",
"[",
"flag",
",",
"plugin",
".",
"flags",
"[",
"flag",
"]",
"]",
")",
";",
"len",
"=",
"Math",
".",
"max",
"(",
"flag",
".",
"length",
",",
"len",
")",
";",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"pflags",
".",
"length",
")",
"{",
"console",
".",
"log",
"(",
")",
";",
"console",
".",
"log",
"(",
"'Plugin flags:'",
")",
";",
"console",
".",
"log",
"(",
")",
";",
"pflags",
".",
"forEach",
"(",
"function",
"(",
"flag",
")",
"{",
"console",
".",
"log",
"(",
"' %s %s'",
",",
"ljust",
"(",
"flag",
"[",
"0",
"]",
",",
"len",
")",
",",
"flag",
"[",
"1",
"]",
")",
";",
"}",
")",
";",
"}",
"console",
".",
"log",
"(",
")",
";",
"}"
]
| Print CLI flags from plugins.
@param {Array} plugins
@api private | [
"Print",
"CLI",
"flags",
"from",
"plugins",
"."
]
| 3f4d2e4926f913976187376e82f1496514c39890 | https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/cli/commands/help.js#L65-L86 |
41,619 | veo-labs/openveo-api | Gruntfile.js | loadConfig | function loadConfig(path) {
var configuration = {};
var configurationFiles = fs.readdirSync(path);
configurationFiles.forEach(function(configurationFile) {
configuration[configurationFile.replace(/\.js$/, '')] = require(path + '/' + configurationFile);
});
return configuration;
} | javascript | function loadConfig(path) {
var configuration = {};
var configurationFiles = fs.readdirSync(path);
configurationFiles.forEach(function(configurationFile) {
configuration[configurationFile.replace(/\.js$/, '')] = require(path + '/' + configurationFile);
});
return configuration;
} | [
"function",
"loadConfig",
"(",
"path",
")",
"{",
"var",
"configuration",
"=",
"{",
"}",
";",
"var",
"configurationFiles",
"=",
"fs",
".",
"readdirSync",
"(",
"path",
")",
";",
"configurationFiles",
".",
"forEach",
"(",
"function",
"(",
"configurationFile",
")",
"{",
"configuration",
"[",
"configurationFile",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
",",
"''",
")",
"]",
"=",
"require",
"(",
"path",
"+",
"'/'",
"+",
"configurationFile",
")",
";",
"}",
")",
";",
"return",
"configuration",
";",
"}"
]
| Loads a bunch of grunt configuration files from the given directory.
Loaded configurations can be referenced using the configuration file name.
For example, if myConf.js returns an object with a property "test", it will be accessible using myConf.test.
@param {String} path Path of the directory containing configuration files
@return {Object} The list of configurations indexed by filename without the extension | [
"Loads",
"a",
"bunch",
"of",
"grunt",
"configuration",
"files",
"from",
"the",
"given",
"directory",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/Gruntfile.js#L21-L30 |
41,620 | veo-labs/openveo-api | lib/socket/SocketServer.js | SocketServer | function SocketServer() {
Object.defineProperties(this, {
/**
* The Socket.io server.
*
* @property io
* @type Server
*/
io: {value: null, writable: true},
/**
* The list of namespaces added to the server indexed by names.
*
* @property namespaces
* @type Object
*/
namespaces: {value: {}}
});
} | javascript | function SocketServer() {
Object.defineProperties(this, {
/**
* The Socket.io server.
*
* @property io
* @type Server
*/
io: {value: null, writable: true},
/**
* The list of namespaces added to the server indexed by names.
*
* @property namespaces
* @type Object
*/
namespaces: {value: {}}
});
} | [
"function",
"SocketServer",
"(",
")",
"{",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"/**\n * The Socket.io server.\n *\n * @property io\n * @type Server\n */",
"io",
":",
"{",
"value",
":",
"null",
",",
"writable",
":",
"true",
"}",
",",
"/**\n * The list of namespaces added to the server indexed by names.\n *\n * @property namespaces\n * @type Object\n */",
"namespaces",
":",
"{",
"value",
":",
"{",
"}",
"}",
"}",
")",
";",
"}"
]
| Defines a SocketServer around a socket.io server.
Creating a server using socket.io can't be done without launching the server
and start listening to messages. SocketServer helps creating a socket server
and add namespaces to it without starting the server.
var openVeoApi = require('@openveo/api');
var namespace1 = new openVeoApi.socket.SocketNamespace();
var namespace2 = new openVeoApi.socket.SocketNamespace();
var server = new openVeoApi.socket.SocketServer();
// Listen to a message on first namespace
namespace1.on('namespace1.message', function() {
console.log('namespace1.message received');
});
// Listen to a message on second namespace
namespace2.on('namespace2.message', function() {
console.log('namespace2.message received');
});
// Add namespace1 to the server
server.addNamespace('/namespace1', namespace1);
// Start server
server.listen(80, function() {
console.log('Socket server started');
namespace.emit('namespace1.message');
// Adding a namespace after the server is started will also work
server.addNamespace('/namespace2', namespace2);
namespace2.emit('namespace2.message');
});
@class SocketServer
@constructor | [
"Defines",
"a",
"SocketServer",
"around",
"a",
"socket",
".",
"io",
"server",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/socket/SocketServer.js#L48-L70 |
41,621 | eface2face/meteor-html-tools | html-tools.js | function (scanner, matcher) {
var start = scanner.pos;
var result = matcher(scanner);
scanner.pos = start;
return result;
} | javascript | function (scanner, matcher) {
var start = scanner.pos;
var result = matcher(scanner);
scanner.pos = start;
return result;
} | [
"function",
"(",
"scanner",
",",
"matcher",
")",
"{",
"var",
"start",
"=",
"scanner",
".",
"pos",
";",
"var",
"result",
"=",
"matcher",
"(",
"scanner",
")",
";",
"scanner",
".",
"pos",
"=",
"start",
";",
"return",
"result",
";",
"}"
]
| Run a provided "matcher" function but reset the current position afterwards. Fatal failure of the matcher is not suppressed. | [
"Run",
"a",
"provided",
"matcher",
"function",
"but",
"reset",
"the",
"current",
"position",
"afterwards",
".",
"Fatal",
"failure",
"of",
"the",
"matcher",
"is",
"not",
"suppressed",
"."
]
| 93360c58596e7a9b88759d495cf8894d8c2c4f2d | https://github.com/eface2face/meteor-html-tools/blob/93360c58596e7a9b88759d495cf8894d8c2c4f2d/html-tools.js#L2400-L2405 |
|
41,622 | eface2face/meteor-html-tools | html-tools.js | function (scanner, inAttribute) {
// look for `&` followed by alphanumeric
if (! peekMatcher(scanner, getPossibleNamedEntityStart))
return null;
var matcher = getNamedEntityByFirstChar[scanner.rest().charAt(1)];
var entity = null;
if (matcher)
entity = peekMatcher(scanner, matcher);
if (entity) {
if (entity.slice(-1) !== ';') {
// Certain character references with no semi are an error, like `<`.
// In attribute values, however, this is not fatal if the next character
// is alphanumeric.
//
// This rule affects href attributes, for example, deeming "/?foo=bar<c=abc"
// to be ok but "/?foo=bar<=abc" to not be.
if (inAttribute && ALPHANUMERIC.test(scanner.rest().charAt(entity.length)))
return null;
scanner.fatal("Character reference requires semicolon: " + entity);
} else {
scanner.pos += entity.length;
return entity;
}
} else {
// we couldn't match any real entity, so see if this is a bad entity
// or something we can overlook.
var badEntity = peekMatcher(scanner, getApparentNamedEntity);
if (badEntity)
scanner.fatal("Invalid character reference: " + badEntity);
// `&aaaa` is ok with no semicolon
return null;
}
} | javascript | function (scanner, inAttribute) {
// look for `&` followed by alphanumeric
if (! peekMatcher(scanner, getPossibleNamedEntityStart))
return null;
var matcher = getNamedEntityByFirstChar[scanner.rest().charAt(1)];
var entity = null;
if (matcher)
entity = peekMatcher(scanner, matcher);
if (entity) {
if (entity.slice(-1) !== ';') {
// Certain character references with no semi are an error, like `<`.
// In attribute values, however, this is not fatal if the next character
// is alphanumeric.
//
// This rule affects href attributes, for example, deeming "/?foo=bar<c=abc"
// to be ok but "/?foo=bar<=abc" to not be.
if (inAttribute && ALPHANUMERIC.test(scanner.rest().charAt(entity.length)))
return null;
scanner.fatal("Character reference requires semicolon: " + entity);
} else {
scanner.pos += entity.length;
return entity;
}
} else {
// we couldn't match any real entity, so see if this is a bad entity
// or something we can overlook.
var badEntity = peekMatcher(scanner, getApparentNamedEntity);
if (badEntity)
scanner.fatal("Invalid character reference: " + badEntity);
// `&aaaa` is ok with no semicolon
return null;
}
} | [
"function",
"(",
"scanner",
",",
"inAttribute",
")",
"{",
"// look for `&` followed by alphanumeric",
"if",
"(",
"!",
"peekMatcher",
"(",
"scanner",
",",
"getPossibleNamedEntityStart",
")",
")",
"return",
"null",
";",
"var",
"matcher",
"=",
"getNamedEntityByFirstChar",
"[",
"scanner",
".",
"rest",
"(",
")",
".",
"charAt",
"(",
"1",
")",
"]",
";",
"var",
"entity",
"=",
"null",
";",
"if",
"(",
"matcher",
")",
"entity",
"=",
"peekMatcher",
"(",
"scanner",
",",
"matcher",
")",
";",
"if",
"(",
"entity",
")",
"{",
"if",
"(",
"entity",
".",
"slice",
"(",
"-",
"1",
")",
"!==",
"';'",
")",
"{",
"// Certain character references with no semi are an error, like `<`.",
"// In attribute values, however, this is not fatal if the next character",
"// is alphanumeric.",
"//",
"// This rule affects href attributes, for example, deeming \"/?foo=bar<c=abc\"",
"// to be ok but \"/?foo=bar<=abc\" to not be.",
"if",
"(",
"inAttribute",
"&&",
"ALPHANUMERIC",
".",
"test",
"(",
"scanner",
".",
"rest",
"(",
")",
".",
"charAt",
"(",
"entity",
".",
"length",
")",
")",
")",
"return",
"null",
";",
"scanner",
".",
"fatal",
"(",
"\"Character reference requires semicolon: \"",
"+",
"entity",
")",
";",
"}",
"else",
"{",
"scanner",
".",
"pos",
"+=",
"entity",
".",
"length",
";",
"return",
"entity",
";",
"}",
"}",
"else",
"{",
"// we couldn't match any real entity, so see if this is a bad entity",
"// or something we can overlook.",
"var",
"badEntity",
"=",
"peekMatcher",
"(",
"scanner",
",",
"getApparentNamedEntity",
")",
";",
"if",
"(",
"badEntity",
")",
"scanner",
".",
"fatal",
"(",
"\"Invalid character reference: \"",
"+",
"badEntity",
")",
";",
"// `&aaaa` is ok with no semicolon",
"return",
"null",
";",
"}",
"}"
]
| Returns a string like "&" or a falsy value if no match. Fails fatally if something looks like a named entity but isn't. | [
"Returns",
"a",
"string",
"like",
"&",
";",
"or",
"a",
"falsy",
"value",
"if",
"no",
"match",
".",
"Fails",
"fatally",
"if",
"something",
"looks",
"like",
"a",
"named",
"entity",
"but",
"isn",
"t",
"."
]
| 93360c58596e7a9b88759d495cf8894d8c2c4f2d | https://github.com/eface2face/meteor-html-tools/blob/93360c58596e7a9b88759d495cf8894d8c2c4f2d/html-tools.js#L2409-L2443 |
|
41,623 | andrewscwei/page-manager | src/PageManager.js | ready | function ready(callback) {
let onLoaded = (event) => {
if (document.addEventListener) {
document.removeEventListener('DOMContentLoaded', onLoaded, false);
window.removeEventListener('load', onLoaded, false);
}
else if (document.attachEvent) {
document.detachEvent('onreadystatechange', onLoaded);
window.detachEvent('onload', onLoaded);
}
setTimeout(callback, 1);
};
if (document.readyState === 'complete') return setTimeout(callback, 1);
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', onLoaded, false);
window.addEventListener('load', onLoaded, false);
}
else if (document.attachEvent) {
document.attachEvent('onreadystatechange', onLoaded);
window.attachEvent('onload', onLoaded);
}
} | javascript | function ready(callback) {
let onLoaded = (event) => {
if (document.addEventListener) {
document.removeEventListener('DOMContentLoaded', onLoaded, false);
window.removeEventListener('load', onLoaded, false);
}
else if (document.attachEvent) {
document.detachEvent('onreadystatechange', onLoaded);
window.detachEvent('onload', onLoaded);
}
setTimeout(callback, 1);
};
if (document.readyState === 'complete') return setTimeout(callback, 1);
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', onLoaded, false);
window.addEventListener('load', onLoaded, false);
}
else if (document.attachEvent) {
document.attachEvent('onreadystatechange', onLoaded);
window.attachEvent('onload', onLoaded);
}
} | [
"function",
"ready",
"(",
"callback",
")",
"{",
"let",
"onLoaded",
"=",
"(",
"event",
")",
"=>",
"{",
"if",
"(",
"document",
".",
"addEventListener",
")",
"{",
"document",
".",
"removeEventListener",
"(",
"'DOMContentLoaded'",
",",
"onLoaded",
",",
"false",
")",
";",
"window",
".",
"removeEventListener",
"(",
"'load'",
",",
"onLoaded",
",",
"false",
")",
";",
"}",
"else",
"if",
"(",
"document",
".",
"attachEvent",
")",
"{",
"document",
".",
"detachEvent",
"(",
"'onreadystatechange'",
",",
"onLoaded",
")",
";",
"window",
".",
"detachEvent",
"(",
"'onload'",
",",
"onLoaded",
")",
";",
"}",
"setTimeout",
"(",
"callback",
",",
"1",
")",
";",
"}",
";",
"if",
"(",
"document",
".",
"readyState",
"===",
"'complete'",
")",
"return",
"setTimeout",
"(",
"callback",
",",
"1",
")",
";",
"if",
"(",
"document",
".",
"addEventListener",
")",
"{",
"document",
".",
"addEventListener",
"(",
"'DOMContentLoaded'",
",",
"onLoaded",
",",
"false",
")",
";",
"window",
".",
"addEventListener",
"(",
"'load'",
",",
"onLoaded",
",",
"false",
")",
";",
"}",
"else",
"if",
"(",
"document",
".",
"attachEvent",
")",
"{",
"document",
".",
"attachEvent",
"(",
"'onreadystatechange'",
",",
"onLoaded",
")",
";",
"window",
".",
"attachEvent",
"(",
"'onload'",
",",
"onLoaded",
")",
";",
"}",
"}"
]
| Helper function for invoking a callback when the DOM is ready.
@param {Function} callback
@private | [
"Helper",
"function",
"for",
"invoking",
"a",
"callback",
"when",
"the",
"DOM",
"is",
"ready",
"."
]
| c356ce9734e879dc0fe7b41c14cd4d4e345b06f6 | https://github.com/andrewscwei/page-manager/blob/c356ce9734e879dc0fe7b41c14cd4d4e345b06f6/src/PageManager.js#L680-L704 |
41,624 | netbek/chrys-cli | src/illustrator/swatches.js | addSwatchGroup | function addSwatchGroup(name) {
var swatchGroup = doc.swatchGroups.add();
swatchGroup.name = name;
return swatchGroup;
} | javascript | function addSwatchGroup(name) {
var swatchGroup = doc.swatchGroups.add();
swatchGroup.name = name;
return swatchGroup;
} | [
"function",
"addSwatchGroup",
"(",
"name",
")",
"{",
"var",
"swatchGroup",
"=",
"doc",
".",
"swatchGroups",
".",
"add",
"(",
")",
";",
"swatchGroup",
".",
"name",
"=",
"name",
";",
"return",
"swatchGroup",
";",
"}"
]
| Adds swatch group.
@param {String} name
@returns {SwatchGroup} | [
"Adds",
"swatch",
"group",
"."
]
| e41e1c6261e964a97a5f773fbb5deefb602bc12f | https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L89-L94 |
41,625 | netbek/chrys-cli | src/illustrator/swatches.js | addSwatch | function addSwatch(name, color) {
var swatch = doc.swatches.add();
swatch.color = color;
swatch.name = name;
return swatch;
} | javascript | function addSwatch(name, color) {
var swatch = doc.swatches.add();
swatch.color = color;
swatch.name = name;
return swatch;
} | [
"function",
"addSwatch",
"(",
"name",
",",
"color",
")",
"{",
"var",
"swatch",
"=",
"doc",
".",
"swatches",
".",
"add",
"(",
")",
";",
"swatch",
".",
"color",
"=",
"color",
";",
"swatch",
".",
"name",
"=",
"name",
";",
"return",
"swatch",
";",
"}"
]
| Adds swatch.
@param {String} name
@param {Color} color
@returns {Swatch} | [
"Adds",
"swatch",
"."
]
| e41e1c6261e964a97a5f773fbb5deefb602bc12f | https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L103-L109 |
41,626 | netbek/chrys-cli | src/illustrator/swatches.js | removeAllSwatches | function removeAllSwatches() {
for (var i = 0; i < doc.swatches.length; i++) {
doc.swatches[i].remove();
}
} | javascript | function removeAllSwatches() {
for (var i = 0; i < doc.swatches.length; i++) {
doc.swatches[i].remove();
}
} | [
"function",
"removeAllSwatches",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"doc",
".",
"swatches",
".",
"length",
";",
"i",
"++",
")",
"{",
"doc",
".",
"swatches",
"[",
"i",
"]",
".",
"remove",
"(",
")",
";",
"}",
"}"
]
| Removes all swatches. | [
"Removes",
"all",
"swatches",
"."
]
| e41e1c6261e964a97a5f773fbb5deefb602bc12f | https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L114-L118 |
41,627 | netbek/chrys-cli | src/illustrator/swatches.js | removeAllSwatchGroups | function removeAllSwatchGroups() {
for (var i = 0; i < doc.swatchGroups.length; i++) {
doc.swatchGroups[i].remove();
}
} | javascript | function removeAllSwatchGroups() {
for (var i = 0; i < doc.swatchGroups.length; i++) {
doc.swatchGroups[i].remove();
}
} | [
"function",
"removeAllSwatchGroups",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"doc",
".",
"swatchGroups",
".",
"length",
";",
"i",
"++",
")",
"{",
"doc",
".",
"swatchGroups",
"[",
"i",
"]",
".",
"remove",
"(",
")",
";",
"}",
"}"
]
| Removes all swatch groups. | [
"Removes",
"all",
"swatch",
"groups",
"."
]
| e41e1c6261e964a97a5f773fbb5deefb602bc12f | https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L123-L127 |
41,628 | netbek/chrys-cli | src/illustrator/swatches.js | drawSwatchRect | function drawSwatchRect(top, left, width, height, name, color) {
var layer = doc.layers[0];
var rect = layer.pathItems.rectangle(top, left, width, height);
rect.filled = true;
rect.fillColor = color;
rect.stroked = false;
var textBounds = layer.pathItems.rectangle(top - height * config.swatchRect.textPosition, left + width * config.swatchRect.textPosition, width * (1 - config.swatchRect.textPosition * 2), height * (1 - config.swatchRect.textPosition * 2));
var text = layer.textFrames.areaText(textBounds);
text.contents = name + '\n' + colorToString(color);
charStyles['swatchRectTitle'].applyTo(text.textRange);
return rect;
} | javascript | function drawSwatchRect(top, left, width, height, name, color) {
var layer = doc.layers[0];
var rect = layer.pathItems.rectangle(top, left, width, height);
rect.filled = true;
rect.fillColor = color;
rect.stroked = false;
var textBounds = layer.pathItems.rectangle(top - height * config.swatchRect.textPosition, left + width * config.swatchRect.textPosition, width * (1 - config.swatchRect.textPosition * 2), height * (1 - config.swatchRect.textPosition * 2));
var text = layer.textFrames.areaText(textBounds);
text.contents = name + '\n' + colorToString(color);
charStyles['swatchRectTitle'].applyTo(text.textRange);
return rect;
} | [
"function",
"drawSwatchRect",
"(",
"top",
",",
"left",
",",
"width",
",",
"height",
",",
"name",
",",
"color",
")",
"{",
"var",
"layer",
"=",
"doc",
".",
"layers",
"[",
"0",
"]",
";",
"var",
"rect",
"=",
"layer",
".",
"pathItems",
".",
"rectangle",
"(",
"top",
",",
"left",
",",
"width",
",",
"height",
")",
";",
"rect",
".",
"filled",
"=",
"true",
";",
"rect",
".",
"fillColor",
"=",
"color",
";",
"rect",
".",
"stroked",
"=",
"false",
";",
"var",
"textBounds",
"=",
"layer",
".",
"pathItems",
".",
"rectangle",
"(",
"top",
"-",
"height",
"*",
"config",
".",
"swatchRect",
".",
"textPosition",
",",
"left",
"+",
"width",
"*",
"config",
".",
"swatchRect",
".",
"textPosition",
",",
"width",
"*",
"(",
"1",
"-",
"config",
".",
"swatchRect",
".",
"textPosition",
"*",
"2",
")",
",",
"height",
"*",
"(",
"1",
"-",
"config",
".",
"swatchRect",
".",
"textPosition",
"*",
"2",
")",
")",
";",
"var",
"text",
"=",
"layer",
".",
"textFrames",
".",
"areaText",
"(",
"textBounds",
")",
";",
"text",
".",
"contents",
"=",
"name",
"+",
"'\\n'",
"+",
"colorToString",
"(",
"color",
")",
";",
"charStyles",
"[",
"'swatchRectTitle'",
"]",
".",
"applyTo",
"(",
"text",
".",
"textRange",
")",
";",
"return",
"rect",
";",
"}"
]
| Draws rectangle on artboard.
@param {Number} top
@param {Number} left
@param {Number} width
@param {Number} height
@param {String} name
@param {Color} color
@returns {PathItem} | [
"Draws",
"rectangle",
"on",
"artboard",
"."
]
| e41e1c6261e964a97a5f773fbb5deefb602bc12f | https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L140-L155 |
41,629 | netbek/chrys-cli | src/illustrator/swatches.js | getColorGroups | function getColorGroups(colors) {
var colorGroups = [];
colors.forEach(function (color) {
if (colorGroups.indexOf(color.group) < 0) {
colorGroups.push(color.group);
}
});
return colorGroups;
} | javascript | function getColorGroups(colors) {
var colorGroups = [];
colors.forEach(function (color) {
if (colorGroups.indexOf(color.group) < 0) {
colorGroups.push(color.group);
}
});
return colorGroups;
} | [
"function",
"getColorGroups",
"(",
"colors",
")",
"{",
"var",
"colorGroups",
"=",
"[",
"]",
";",
"colors",
".",
"forEach",
"(",
"function",
"(",
"color",
")",
"{",
"if",
"(",
"colorGroups",
".",
"indexOf",
"(",
"color",
".",
"group",
")",
"<",
"0",
")",
"{",
"colorGroups",
".",
"push",
"(",
"color",
".",
"group",
")",
";",
"}",
"}",
")",
";",
"return",
"colorGroups",
";",
"}"
]
| Returns an array of unique group names.
@param {Array} colors
@returns {Array) | [
"Returns",
"an",
"array",
"of",
"unique",
"group",
"names",
"."
]
| e41e1c6261e964a97a5f773fbb5deefb602bc12f | https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L163-L173 |
41,630 | netbek/chrys-cli | src/illustrator/swatches.js | getMaxShades | function getMaxShades(colors) {
var max = 0;
var colorGroups = getColorGroups(colors);
colorGroups.forEach(function (colorGroup, colorGroupIndex) {
// Gets colors that belong to group.
var groupColors = colors.filter(function (o) {
return o.group === colorGroup;
});
var len = groupColors.length;
if (len > max) {
max = len;
}
});
return max;
} | javascript | function getMaxShades(colors) {
var max = 0;
var colorGroups = getColorGroups(colors);
colorGroups.forEach(function (colorGroup, colorGroupIndex) {
// Gets colors that belong to group.
var groupColors = colors.filter(function (o) {
return o.group === colorGroup;
});
var len = groupColors.length;
if (len > max) {
max = len;
}
});
return max;
} | [
"function",
"getMaxShades",
"(",
"colors",
")",
"{",
"var",
"max",
"=",
"0",
";",
"var",
"colorGroups",
"=",
"getColorGroups",
"(",
"colors",
")",
";",
"colorGroups",
".",
"forEach",
"(",
"function",
"(",
"colorGroup",
",",
"colorGroupIndex",
")",
"{",
"// Gets colors that belong to group.",
"var",
"groupColors",
"=",
"colors",
".",
"filter",
"(",
"function",
"(",
"o",
")",
"{",
"return",
"o",
".",
"group",
"===",
"colorGroup",
";",
"}",
")",
";",
"var",
"len",
"=",
"groupColors",
".",
"length",
";",
"if",
"(",
"len",
">",
"max",
")",
"{",
"max",
"=",
"len",
";",
"}",
"}",
")",
";",
"return",
"max",
";",
"}"
]
| Returns maximum number of shades.
@param {Array} colors
@returns {Number} | [
"Returns",
"maximum",
"number",
"of",
"shades",
"."
]
| e41e1c6261e964a97a5f773fbb5deefb602bc12f | https://github.com/netbek/chrys-cli/blob/e41e1c6261e964a97a5f773fbb5deefb602bc12f/src/illustrator/swatches.js#L181-L199 |
41,631 | Mammut-FE/nejm | src/base/platform/element.js | function(_tpl,_map){
_map = _map||_o;
return _tpl.replace(_reg1,function($1,$2){
var _arr = $2.split('|');
return _map[_arr[0]]||_arr[1]||'0';
});
} | javascript | function(_tpl,_map){
_map = _map||_o;
return _tpl.replace(_reg1,function($1,$2){
var _arr = $2.split('|');
return _map[_arr[0]]||_arr[1]||'0';
});
} | [
"function",
"(",
"_tpl",
",",
"_map",
")",
"{",
"_map",
"=",
"_map",
"||",
"_o",
";",
"return",
"_tpl",
".",
"replace",
"(",
"_reg1",
",",
"function",
"(",
"$1",
",",
"$2",
")",
"{",
"var",
"_arr",
"=",
"$2",
".",
"split",
"(",
"'|'",
")",
";",
"return",
"_map",
"[",
"_arr",
"[",
"0",
"]",
"]",
"||",
"_arr",
"[",
"1",
"]",
"||",
"'0'",
";",
"}",
")",
";",
"}"
]
| merge template and data | [
"merge",
"template",
"and",
"data"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/base/platform/element.js#L280-L286 |
|
41,632 | donejs/ir-reattach | src/render.js | read | async function read(reader, patcher) {
let {done, value} = await reader.read();
if(done || isAttached()) {
return false;
}
//!steal-remove-start
log.mutations(value);
//!steal-remove-end
patcher.patch(value);
return true;
} | javascript | async function read(reader, patcher) {
let {done, value} = await reader.read();
if(done || isAttached()) {
return false;
}
//!steal-remove-start
log.mutations(value);
//!steal-remove-end
patcher.patch(value);
return true;
} | [
"async",
"function",
"read",
"(",
"reader",
",",
"patcher",
")",
"{",
"let",
"{",
"done",
",",
"value",
"}",
"=",
"await",
"reader",
".",
"read",
"(",
")",
";",
"if",
"(",
"done",
"||",
"isAttached",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"//!steal-remove-start",
"log",
".",
"mutations",
"(",
"value",
")",
";",
"//!steal-remove-end",
"patcher",
".",
"patch",
"(",
"value",
")",
";",
"return",
"true",
";",
"}"
]
| !steal-remove-end Read a value from the stream and pass it to the patcher | [
"!steal",
"-",
"remove",
"-",
"end",
"Read",
"a",
"value",
"from",
"the",
"stream",
"and",
"pass",
"it",
"to",
"the",
"patcher"
]
| 0440d4ed090982103d90347aa0b960f35a7e0628 | https://github.com/donejs/ir-reattach/blob/0440d4ed090982103d90347aa0b960f35a7e0628/src/render.js#L10-L23 |
41,633 | LeisureLink/magicbus | lib/amqp/exchange.js | getLibOptions | function getLibOptions(aliases, itemsToOmit) {
let aliased = _.transform(options, function(result, value, key) {
let alias = aliases[key];
result[alias || key] = value;
});
return _.omit(aliased, itemsToOmit);
} | javascript | function getLibOptions(aliases, itemsToOmit) {
let aliased = _.transform(options, function(result, value, key) {
let alias = aliases[key];
result[alias || key] = value;
});
return _.omit(aliased, itemsToOmit);
} | [
"function",
"getLibOptions",
"(",
"aliases",
",",
"itemsToOmit",
")",
"{",
"let",
"aliased",
"=",
"_",
".",
"transform",
"(",
"options",
",",
"function",
"(",
"result",
",",
"value",
",",
"key",
")",
"{",
"let",
"alias",
"=",
"aliases",
"[",
"key",
"]",
";",
"result",
"[",
"alias",
"||",
"key",
"]",
"=",
"value",
";",
"}",
")",
";",
"return",
"_",
".",
"omit",
"(",
"aliased",
",",
"itemsToOmit",
")",
";",
"}"
]
| Get options for amqp assertExchange call
@private | [
"Get",
"options",
"for",
"amqp",
"assertExchange",
"call"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/exchange.js#L44-L50 |
41,634 | LeisureLink/magicbus | lib/amqp/exchange.js | define | function define() {
let libOptions = getLibOptions({
alternate: 'alternateExchange'
}, ['persistent', 'publishTimeout']);
topLog.debug(`Declaring ${options.type} exchange \'${options.name}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(libOptions, ['name', 'type']))}`);
return channel.assertExchange(options.name, options.type, libOptions);
} | javascript | function define() {
let libOptions = getLibOptions({
alternate: 'alternateExchange'
}, ['persistent', 'publishTimeout']);
topLog.debug(`Declaring ${options.type} exchange \'${options.name}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(libOptions, ['name', 'type']))}`);
return channel.assertExchange(options.name, options.type, libOptions);
} | [
"function",
"define",
"(",
")",
"{",
"let",
"libOptions",
"=",
"getLibOptions",
"(",
"{",
"alternate",
":",
"'alternateExchange'",
"}",
",",
"[",
"'persistent'",
",",
"'publishTimeout'",
"]",
")",
";",
"topLog",
".",
"debug",
"(",
"`",
"${",
"options",
".",
"type",
"}",
"\\'",
"${",
"options",
".",
"name",
"}",
"\\'",
"\\'",
"${",
"connectionName",
"}",
"\\'",
"${",
"JSON",
".",
"stringify",
"(",
"_",
".",
"omit",
"(",
"libOptions",
",",
"[",
"'name'",
",",
"'type'",
"]",
")",
")",
"}",
"`",
")",
";",
"return",
"channel",
".",
"assertExchange",
"(",
"options",
".",
"name",
",",
"options",
".",
"type",
",",
"libOptions",
")",
";",
"}"
]
| Define the exchange
@public | [
"Define",
"the",
"exchange"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/amqp/exchange.js#L56-L62 |
41,635 | chip-js/observations-js | src/computed-properties/when.js | WhenProperty | function WhenProperty(whenExpression, thenExpression) {
if (!thenExpression) {
thenExpression = whenExpression;
whenExpression = 'true';
}
this.whenExpression = whenExpression;
this.thenExpression = thenExpression;
} | javascript | function WhenProperty(whenExpression, thenExpression) {
if (!thenExpression) {
thenExpression = whenExpression;
whenExpression = 'true';
}
this.whenExpression = whenExpression;
this.thenExpression = thenExpression;
} | [
"function",
"WhenProperty",
"(",
"whenExpression",
",",
"thenExpression",
")",
"{",
"if",
"(",
"!",
"thenExpression",
")",
"{",
"thenExpression",
"=",
"whenExpression",
";",
"whenExpression",
"=",
"'true'",
";",
"}",
"this",
".",
"whenExpression",
"=",
"whenExpression",
";",
"this",
".",
"thenExpression",
"=",
"thenExpression",
";",
"}"
]
| Calls the `thenExpression` and assigns the results to the object's property when the `whenExpression` changes value
to anything other than a falsey value such as undefined. The return value of the `thenExpression` may be a Promise.
@param {String} whenExpression The conditional expression use to determine when to call the `thenExpression`
@param {String} thenExpression The expression which will be executed when the `when` value changes and the result (or
the result of the returned promise) is set on the object. | [
"Calls",
"the",
"thenExpression",
"and",
"assigns",
"the",
"results",
"to",
"the",
"object",
"s",
"property",
"when",
"the",
"whenExpression",
"changes",
"value",
"to",
"anything",
"other",
"than",
"a",
"falsey",
"value",
"such",
"as",
"undefined",
".",
"The",
"return",
"value",
"of",
"the",
"thenExpression",
"may",
"be",
"a",
"Promise",
"."
]
| a48b32a648089bc86b502712d78cd0b3f8317d50 | https://github.com/chip-js/observations-js/blob/a48b32a648089bc86b502712d78cd0b3f8317d50/src/computed-properties/when.js#L12-L20 |
41,636 | feedhenry/fh-component-metrics | lib/clients/statsd.js | StatsdClient | function StatsdClient(opts) {
BaseClient.apply(this, arguments);
opts = opts || {};
this.host = opts.host || '127.0.0.1';
this.port = opts.port || 8125;
this.keyBuilder = opts.keyBuilder || defaultMetricsKeyBuilder;
this.socket = dgram.createSocket('udp4');
} | javascript | function StatsdClient(opts) {
BaseClient.apply(this, arguments);
opts = opts || {};
this.host = opts.host || '127.0.0.1';
this.port = opts.port || 8125;
this.keyBuilder = opts.keyBuilder || defaultMetricsKeyBuilder;
this.socket = dgram.createSocket('udp4');
} | [
"function",
"StatsdClient",
"(",
"opts",
")",
"{",
"BaseClient",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"host",
"=",
"opts",
".",
"host",
"||",
"'127.0.0.1'",
";",
"this",
".",
"port",
"=",
"opts",
".",
"port",
"||",
"8125",
";",
"this",
".",
"keyBuilder",
"=",
"opts",
".",
"keyBuilder",
"||",
"defaultMetricsKeyBuilder",
";",
"this",
".",
"socket",
"=",
"dgram",
".",
"createSocket",
"(",
"'udp4'",
")",
";",
"}"
]
| A client that can send metrics data to a statsd backend
@param {Object} opts options about the statsd backend
@param {String} opts.host the host of the statsd server. Default is 127.0.0.1.
@param {Number} opts.port the port of the statsd server. Default is 8125.
@param {Function} opts.keyBuilder a function that will be used to format the meta data of a metric into a single key value. The signature of function is like this: function(key, tags, fieldName) | [
"A",
"client",
"that",
"can",
"send",
"metrics",
"data",
"to",
"a",
"statsd",
"backend"
]
| c97a1a82ff0144f2a7c2abecbc22084fade1cbc8 | https://github.com/feedhenry/fh-component-metrics/blob/c97a1a82ff0144f2a7c2abecbc22084fade1cbc8/lib/clients/statsd.js#L51-L58 |
41,637 | cronvel/server-kit | lib/mimeType.js | mimeType | function mimeType( path ) {
var extension = path.replace( /.*[./\\]/ , '' ).toLowerCase() ;
if ( ! mimeType.extension[ extension ] ) {
// default MIME type, when nothing is found
return 'application/octet-stream' ;
}
return mimeType.extension[ extension ] ;
} | javascript | function mimeType( path ) {
var extension = path.replace( /.*[./\\]/ , '' ).toLowerCase() ;
if ( ! mimeType.extension[ extension ] ) {
// default MIME type, when nothing is found
return 'application/octet-stream' ;
}
return mimeType.extension[ extension ] ;
} | [
"function",
"mimeType",
"(",
"path",
")",
"{",
"var",
"extension",
"=",
"path",
".",
"replace",
"(",
"/",
".*[./\\\\]",
"/",
",",
"''",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"!",
"mimeType",
".",
"extension",
"[",
"extension",
"]",
")",
"{",
"// default MIME type, when nothing is found",
"return",
"'application/octet-stream'",
";",
"}",
"return",
"mimeType",
".",
"extension",
"[",
"extension",
"]",
";",
"}"
]
| MIME types by extension, for most common files | [
"MIME",
"types",
"by",
"extension",
"for",
"most",
"common",
"files"
]
| 8d2a45aeddf7933559331f75e6b6199a12912d7f | https://github.com/cronvel/server-kit/blob/8d2a45aeddf7933559331f75e6b6199a12912d7f/lib/mimeType.js#L33-L42 |
41,638 | emeryrose/coalescent | lib/application.js | Application | function Application(options) {
var self = this;
if (!(self instanceof Application)) {
return new Application(options);
}
stream.Duplex.call(self, { objectMode: true });
self.id = hat();
self.server = net.createServer(self._handleInbound.bind(self));
self.options = merge(Object.create(Application.DEFAULTS), options);
self.connections = { inbound: [], outbound: [] };
// setup middlware stack with initial entry a simple passthrough
self.stack = [function(socket) {
return through(function(data) {
this.queue(data);
});
}];
Object.defineProperty(self, 'log', {
value: this.options.logger || {
info: NOOP, warn: NOOP, error: NOOP
}
});
// connect to seeds
self._enterNetwork();
setInterval(self._enterNetwork.bind(self), self.options.retryInterval);
} | javascript | function Application(options) {
var self = this;
if (!(self instanceof Application)) {
return new Application(options);
}
stream.Duplex.call(self, { objectMode: true });
self.id = hat();
self.server = net.createServer(self._handleInbound.bind(self));
self.options = merge(Object.create(Application.DEFAULTS), options);
self.connections = { inbound: [], outbound: [] };
// setup middlware stack with initial entry a simple passthrough
self.stack = [function(socket) {
return through(function(data) {
this.queue(data);
});
}];
Object.defineProperty(self, 'log', {
value: this.options.logger || {
info: NOOP, warn: NOOP, error: NOOP
}
});
// connect to seeds
self._enterNetwork();
setInterval(self._enterNetwork.bind(self), self.options.retryInterval);
} | [
"function",
"Application",
"(",
"options",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"Application",
")",
")",
"{",
"return",
"new",
"Application",
"(",
"options",
")",
";",
"}",
"stream",
".",
"Duplex",
".",
"call",
"(",
"self",
",",
"{",
"objectMode",
":",
"true",
"}",
")",
";",
"self",
".",
"id",
"=",
"hat",
"(",
")",
";",
"self",
".",
"server",
"=",
"net",
".",
"createServer",
"(",
"self",
".",
"_handleInbound",
".",
"bind",
"(",
"self",
")",
")",
";",
"self",
".",
"options",
"=",
"merge",
"(",
"Object",
".",
"create",
"(",
"Application",
".",
"DEFAULTS",
")",
",",
"options",
")",
";",
"self",
".",
"connections",
"=",
"{",
"inbound",
":",
"[",
"]",
",",
"outbound",
":",
"[",
"]",
"}",
";",
"// setup middlware stack with initial entry a simple passthrough",
"self",
".",
"stack",
"=",
"[",
"function",
"(",
"socket",
")",
"{",
"return",
"through",
"(",
"function",
"(",
"data",
")",
"{",
"this",
".",
"queue",
"(",
"data",
")",
";",
"}",
")",
";",
"}",
"]",
";",
"Object",
".",
"defineProperty",
"(",
"self",
",",
"'log'",
",",
"{",
"value",
":",
"this",
".",
"options",
".",
"logger",
"||",
"{",
"info",
":",
"NOOP",
",",
"warn",
":",
"NOOP",
",",
"error",
":",
"NOOP",
"}",
"}",
")",
";",
"// connect to seeds",
"self",
".",
"_enterNetwork",
"(",
")",
";",
"setInterval",
"(",
"self",
".",
"_enterNetwork",
".",
"bind",
"(",
"self",
")",
",",
"self",
".",
"options",
".",
"retryInterval",
")",
";",
"}"
]
| P2P application framework
@constructor
@param {object} options | [
"P2P",
"application",
"framework"
]
| 5e722d4e1c16b9a9e959b281f6bb07713c60c46a | https://github.com/emeryrose/coalescent/blob/5e722d4e1c16b9a9e959b281f6bb07713c60c46a/lib/application.js#L32-L62 |
41,639 | repetere/periodicjs.core.mailer | lib/sendEmail.js | sendEmail | function sendEmail(options = {}) {
return new Promise((resolve, reject) => {
try {
const mailoptions = options;
let mailTransportConfig = (this && this.config && this.config.transportConfig)
? this.config.transportConfig
: options.transportConfig;
let mailtransport = (this && this.transport)
? this.transport
: options.transport;
Promise.resolve(mailoptions)
.then(mailoptions => {
if (mailoptions.html || mailoptions.emailtemplatestring) {
return mailoptions.html || mailoptions.emailtemplatestring;
} else {
return getEmailTemplateHTMLString(mailoptions);
}
})
.then(emailTemplateString => {
mailoptions.emailtemplatestring = emailTemplateString;
if (mailoptions.html) {
return mailoptions.html;
} else {
if (mailoptions.emailtemplatefilepath && !mailoptions.emailtemplatedata.filename) {
mailoptions.emailtemplatedata.filename = mailoptions.emailtemplatefilepath;
}
mailoptions.html = ejs.render(mailoptions.emailtemplatestring, mailoptions.emailtemplatedata);
return mailoptions.html;
}
})
.then(mailhtml => {
if (mailtransport && mailtransport.sendMail) {
return mailtransport;
} else {
return getTransport({ transportObject: mailTransportConfig })
.then(transport => {
mailtransport = transport;
return Promise.resolve(transport);
})
.catch(reject);
}
})
.then(mt => {
mt.sendMail(mailoptions, (err, status) => {
if (err) {
reject(err);
} else {
resolve(status);
}
});
})
.catch(reject);
} catch (e) {
reject(e);
}
});
} | javascript | function sendEmail(options = {}) {
return new Promise((resolve, reject) => {
try {
const mailoptions = options;
let mailTransportConfig = (this && this.config && this.config.transportConfig)
? this.config.transportConfig
: options.transportConfig;
let mailtransport = (this && this.transport)
? this.transport
: options.transport;
Promise.resolve(mailoptions)
.then(mailoptions => {
if (mailoptions.html || mailoptions.emailtemplatestring) {
return mailoptions.html || mailoptions.emailtemplatestring;
} else {
return getEmailTemplateHTMLString(mailoptions);
}
})
.then(emailTemplateString => {
mailoptions.emailtemplatestring = emailTemplateString;
if (mailoptions.html) {
return mailoptions.html;
} else {
if (mailoptions.emailtemplatefilepath && !mailoptions.emailtemplatedata.filename) {
mailoptions.emailtemplatedata.filename = mailoptions.emailtemplatefilepath;
}
mailoptions.html = ejs.render(mailoptions.emailtemplatestring, mailoptions.emailtemplatedata);
return mailoptions.html;
}
})
.then(mailhtml => {
if (mailtransport && mailtransport.sendMail) {
return mailtransport;
} else {
return getTransport({ transportObject: mailTransportConfig })
.then(transport => {
mailtransport = transport;
return Promise.resolve(transport);
})
.catch(reject);
}
})
.then(mt => {
mt.sendMail(mailoptions, (err, status) => {
if (err) {
reject(err);
} else {
resolve(status);
}
});
})
.catch(reject);
} catch (e) {
reject(e);
}
});
} | [
"function",
"sendEmail",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"try",
"{",
"const",
"mailoptions",
"=",
"options",
";",
"let",
"mailTransportConfig",
"=",
"(",
"this",
"&&",
"this",
".",
"config",
"&&",
"this",
".",
"config",
".",
"transportConfig",
")",
"?",
"this",
".",
"config",
".",
"transportConfig",
":",
"options",
".",
"transportConfig",
";",
"let",
"mailtransport",
"=",
"(",
"this",
"&&",
"this",
".",
"transport",
")",
"?",
"this",
".",
"transport",
":",
"options",
".",
"transport",
";",
"Promise",
".",
"resolve",
"(",
"mailoptions",
")",
".",
"then",
"(",
"mailoptions",
"=>",
"{",
"if",
"(",
"mailoptions",
".",
"html",
"||",
"mailoptions",
".",
"emailtemplatestring",
")",
"{",
"return",
"mailoptions",
".",
"html",
"||",
"mailoptions",
".",
"emailtemplatestring",
";",
"}",
"else",
"{",
"return",
"getEmailTemplateHTMLString",
"(",
"mailoptions",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"emailTemplateString",
"=>",
"{",
"mailoptions",
".",
"emailtemplatestring",
"=",
"emailTemplateString",
";",
"if",
"(",
"mailoptions",
".",
"html",
")",
"{",
"return",
"mailoptions",
".",
"html",
";",
"}",
"else",
"{",
"if",
"(",
"mailoptions",
".",
"emailtemplatefilepath",
"&&",
"!",
"mailoptions",
".",
"emailtemplatedata",
".",
"filename",
")",
"{",
"mailoptions",
".",
"emailtemplatedata",
".",
"filename",
"=",
"mailoptions",
".",
"emailtemplatefilepath",
";",
"}",
"mailoptions",
".",
"html",
"=",
"ejs",
".",
"render",
"(",
"mailoptions",
".",
"emailtemplatestring",
",",
"mailoptions",
".",
"emailtemplatedata",
")",
";",
"return",
"mailoptions",
".",
"html",
";",
"}",
"}",
")",
".",
"then",
"(",
"mailhtml",
"=>",
"{",
"if",
"(",
"mailtransport",
"&&",
"mailtransport",
".",
"sendMail",
")",
"{",
"return",
"mailtransport",
";",
"}",
"else",
"{",
"return",
"getTransport",
"(",
"{",
"transportObject",
":",
"mailTransportConfig",
"}",
")",
".",
"then",
"(",
"transport",
"=>",
"{",
"mailtransport",
"=",
"transport",
";",
"return",
"Promise",
".",
"resolve",
"(",
"transport",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"mt",
"=>",
"{",
"mt",
".",
"sendMail",
"(",
"mailoptions",
",",
"(",
"err",
",",
"status",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"status",
")",
";",
"}",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"reject",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"reject",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
]
| sends email with nodemailer
@static
@param {any} [options={}] all of the options to a node mailer transport sendMail function
@param {object|string} options.to
@param {object|string} options.cc
@param {object|string} options.bcc
@param {object|string} options.replyto
@param {object|string} options.subject
@param {object|string} options.html
@param {object|string} options.text
@param {object|string} options.generateTextFromHTML
@param {object|string} options.emailtemplatestring
@param {object|string} options.emailtemplatedata
@returns {promise} resolves the status of an email
@memberof Mailer | [
"sends",
"email",
"with",
"nodemailer"
]
| f544584cb1520015adac0326f8b02c38fbbd3417 | https://github.com/repetere/periodicjs.core.mailer/blob/f544584cb1520015adac0326f8b02c38fbbd3417/lib/sendEmail.js#L25-L81 |
41,640 | nanlabs/econsole | sample.js | writeLogs | function writeLogs(customMethods) {
// Error level logging with a message but no error
console.error('Testing ERROR LEVEL without actual error')
// Error level logging with an error but no message
// This shows enhanced error parsing in logging
console.error(new Error("some error"));
// Error level logging with both message and error
// This shows enhanced error parsing in logging
console.error('Testing ERROR LEVEL with an error', new Error("some error"));
// Warn level logging
console.warn('Testing WARN LEVEL');
// Info level logging
console.info('Testing INFO LEVEL');
// Log/Debug level logging
console.log('Testing LOG LEVEL');
if(customMethods) {
// Log/Debug level loggin using "debug" alias (not standard but clearer)
console.debug('Testing DEBUG (AKA LOG) LEVEL');
// Verbose level logging (new level added to go beyond DEBUG)
console.verbose('Testing TRACE LEVEL');
}
} | javascript | function writeLogs(customMethods) {
// Error level logging with a message but no error
console.error('Testing ERROR LEVEL without actual error')
// Error level logging with an error but no message
// This shows enhanced error parsing in logging
console.error(new Error("some error"));
// Error level logging with both message and error
// This shows enhanced error parsing in logging
console.error('Testing ERROR LEVEL with an error', new Error("some error"));
// Warn level logging
console.warn('Testing WARN LEVEL');
// Info level logging
console.info('Testing INFO LEVEL');
// Log/Debug level logging
console.log('Testing LOG LEVEL');
if(customMethods) {
// Log/Debug level loggin using "debug" alias (not standard but clearer)
console.debug('Testing DEBUG (AKA LOG) LEVEL');
// Verbose level logging (new level added to go beyond DEBUG)
console.verbose('Testing TRACE LEVEL');
}
} | [
"function",
"writeLogs",
"(",
"customMethods",
")",
"{",
"// Error level logging with a message but no error",
"console",
".",
"error",
"(",
"'Testing ERROR LEVEL without actual error'",
")",
"// Error level logging with an error but no message",
"// This shows enhanced error parsing in logging ",
"console",
".",
"error",
"(",
"new",
"Error",
"(",
"\"some error\"",
")",
")",
";",
"// Error level logging with both message and error",
"// This shows enhanced error parsing in logging ",
"console",
".",
"error",
"(",
"'Testing ERROR LEVEL with an error'",
",",
"new",
"Error",
"(",
"\"some error\"",
")",
")",
";",
"// Warn level logging",
"console",
".",
"warn",
"(",
"'Testing WARN LEVEL'",
")",
";",
"// Info level logging",
"console",
".",
"info",
"(",
"'Testing INFO LEVEL'",
")",
";",
"// Log/Debug level logging",
"console",
".",
"log",
"(",
"'Testing LOG LEVEL'",
")",
";",
"if",
"(",
"customMethods",
")",
"{",
"// Log/Debug level loggin using \"debug\" alias (not standard but clearer)",
"console",
".",
"debug",
"(",
"'Testing DEBUG (AKA LOG) LEVEL'",
")",
";",
"// Verbose level logging (new level added to go beyond DEBUG)",
"console",
".",
"verbose",
"(",
"'Testing TRACE LEVEL'",
")",
";",
"}",
"}"
]
| Writes logs for the different levels
@param customMethods if false, only standard node's console methods will be called.
if true, besides standard methods, also the 2 new added methods are called | [
"Writes",
"logs",
"for",
"the",
"different",
"levels"
]
| 2377a33e266b4e39a35cf981ece14b6b6a16af46 | https://github.com/nanlabs/econsole/blob/2377a33e266b4e39a35cf981ece14b6b6a16af46/sample.js#L28-L57 |
41,641 | hoast/hoast-changed | library/index.js | function(hoast, filePath, content) {
return new Promise(function(resolve, reject) {
hoast.helpers.createDirectory(path.dirname(filePath))
.then(function() {
fs.writeFile(filePath, JSON.stringify(content), `utf8`, function(error) {
if (error) {
return reject(error);
}
resolve();
});
})
.catch(function(error) {
reject(error);
});
});
} | javascript | function(hoast, filePath, content) {
return new Promise(function(resolve, reject) {
hoast.helpers.createDirectory(path.dirname(filePath))
.then(function() {
fs.writeFile(filePath, JSON.stringify(content), `utf8`, function(error) {
if (error) {
return reject(error);
}
resolve();
});
})
.catch(function(error) {
reject(error);
});
});
} | [
"function",
"(",
"hoast",
",",
"filePath",
",",
"content",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"hoast",
".",
"helpers",
".",
"createDirectory",
"(",
"path",
".",
"dirname",
"(",
"filePath",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"JSON",
".",
"stringify",
"(",
"content",
")",
",",
"`",
"`",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"reject",
"(",
"error",
")",
";",
"}",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Writes JS object to storage.
@param {Object} hoast hoast instance.
@param {String} filePath File path.
@param {Object} content Object to write to storage. | [
"Writes",
"JS",
"object",
"to",
"storage",
"."
]
| 51f6e699fd023720d724fd5139efc4a08a6af1fd | https://github.com/hoast/hoast-changed/blob/51f6e699fd023720d724fd5139efc4a08a6af1fd/library/index.js#L28-L43 |
|
41,642 | hoast/hoast-changed | library/index.js | function(hoast, files) {
debug(`Running module.`);
// Loop through the files.
const filtered = files.filter(function(file) {
debug(`Filtering file '${file.path}'.`);
// If it does not match
if (this.expressions && hoast.helpers.matchExpressions(file.path, this.expressions, options.patternOptions.all)) {
debug(`File path valid for skipping.`);
return true;
}
// If it is in the list and not changed since the last time do not process.
if (this.list[file.path] && this.list[file.path] >= file.stats.mtimeMs) {
debug(`File not changed since last process.`);
return false;
}
debug(`File changed or not processed before.`);
// Update changed time and process.
this.list[file.path] = file.stats.mtimeMs;
return true;
}, mod);
debug(`Finished filtering files.`);
// Return filtered files.
return filtered;
} | javascript | function(hoast, files) {
debug(`Running module.`);
// Loop through the files.
const filtered = files.filter(function(file) {
debug(`Filtering file '${file.path}'.`);
// If it does not match
if (this.expressions && hoast.helpers.matchExpressions(file.path, this.expressions, options.patternOptions.all)) {
debug(`File path valid for skipping.`);
return true;
}
// If it is in the list and not changed since the last time do not process.
if (this.list[file.path] && this.list[file.path] >= file.stats.mtimeMs) {
debug(`File not changed since last process.`);
return false;
}
debug(`File changed or not processed before.`);
// Update changed time and process.
this.list[file.path] = file.stats.mtimeMs;
return true;
}, mod);
debug(`Finished filtering files.`);
// Return filtered files.
return filtered;
} | [
"function",
"(",
"hoast",
",",
"files",
")",
"{",
"debug",
"(",
"`",
"`",
")",
";",
"// Loop through the files.",
"const",
"filtered",
"=",
"files",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"debug",
"(",
"`",
"${",
"file",
".",
"path",
"}",
"`",
")",
";",
"// If it does not match",
"if",
"(",
"this",
".",
"expressions",
"&&",
"hoast",
".",
"helpers",
".",
"matchExpressions",
"(",
"file",
".",
"path",
",",
"this",
".",
"expressions",
",",
"options",
".",
"patternOptions",
".",
"all",
")",
")",
"{",
"debug",
"(",
"`",
"`",
")",
";",
"return",
"true",
";",
"}",
"// If it is in the list and not changed since the last time do not process.",
"if",
"(",
"this",
".",
"list",
"[",
"file",
".",
"path",
"]",
"&&",
"this",
".",
"list",
"[",
"file",
".",
"path",
"]",
">=",
"file",
".",
"stats",
".",
"mtimeMs",
")",
"{",
"debug",
"(",
"`",
"`",
")",
";",
"return",
"false",
";",
"}",
"debug",
"(",
"`",
"`",
")",
";",
"// Update changed time and process.",
"this",
".",
"list",
"[",
"file",
".",
"path",
"]",
"=",
"file",
".",
"stats",
".",
"mtimeMs",
";",
"return",
"true",
";",
"}",
",",
"mod",
")",
";",
"debug",
"(",
"`",
"`",
")",
";",
"// Return filtered files.",
"return",
"filtered",
";",
"}"
]
| Main module method. | [
"Main",
"module",
"method",
"."
]
| 51f6e699fd023720d724fd5139efc4a08a6af1fd | https://github.com/hoast/hoast-changed/blob/51f6e699fd023720d724fd5139efc4a08a6af1fd/library/index.js#L58-L86 |
|
41,643 | cronvel/logfella-common-transport | lib/Common.transport.js | CommonTransport | function CommonTransport( logger , config = {} ) {
this.logger = null ;
this.monitoring = false ;
this.minLevel = 0 ;
this.maxLevel = 7 ;
this.messageFormatter = logger.messageFormatter.text ;
this.timeFormatter = logger.timeFormatter.dateTime ;
Object.defineProperty( this , 'logger' , { value: logger } ) ;
if ( config.monitoring !== undefined ) { this.monitoring = !! config.monitoring ; }
if ( config.minLevel !== undefined ) {
if ( typeof config.minLevel === 'number' ) { this.minLevel = config.minLevel ; }
else if ( typeof config.minLevel === 'string' ) { this.minLevel = this.logger.levelHash[ config.minLevel ] ; }
}
if ( config.maxLevel !== undefined ) {
if ( typeof config.maxLevel === 'number' ) { this.maxLevel = config.maxLevel ; }
else if ( typeof config.maxLevel === 'string' ) { this.maxLevel = this.logger.levelHash[ config.maxLevel ] ; }
}
if ( config.messageFormatter ) {
if ( typeof config.messageFormatter === 'function' ) { this.messageFormatter = config.messageFormatter ; }
else { this.messageFormatter = this.logger.messageFormatter[ config.messageFormatter ] ; }
}
if ( config.timeFormatter ) {
if ( typeof config.timeFormatter === 'function' ) { this.timeFormatter = config.timeFormatter ; }
else { this.timeFormatter = this.logger.timeFormatter[ config.timeFormatter ] ; }
}
} | javascript | function CommonTransport( logger , config = {} ) {
this.logger = null ;
this.monitoring = false ;
this.minLevel = 0 ;
this.maxLevel = 7 ;
this.messageFormatter = logger.messageFormatter.text ;
this.timeFormatter = logger.timeFormatter.dateTime ;
Object.defineProperty( this , 'logger' , { value: logger } ) ;
if ( config.monitoring !== undefined ) { this.monitoring = !! config.monitoring ; }
if ( config.minLevel !== undefined ) {
if ( typeof config.minLevel === 'number' ) { this.minLevel = config.minLevel ; }
else if ( typeof config.minLevel === 'string' ) { this.minLevel = this.logger.levelHash[ config.minLevel ] ; }
}
if ( config.maxLevel !== undefined ) {
if ( typeof config.maxLevel === 'number' ) { this.maxLevel = config.maxLevel ; }
else if ( typeof config.maxLevel === 'string' ) { this.maxLevel = this.logger.levelHash[ config.maxLevel ] ; }
}
if ( config.messageFormatter ) {
if ( typeof config.messageFormatter === 'function' ) { this.messageFormatter = config.messageFormatter ; }
else { this.messageFormatter = this.logger.messageFormatter[ config.messageFormatter ] ; }
}
if ( config.timeFormatter ) {
if ( typeof config.timeFormatter === 'function' ) { this.timeFormatter = config.timeFormatter ; }
else { this.timeFormatter = this.logger.timeFormatter[ config.timeFormatter ] ; }
}
} | [
"function",
"CommonTransport",
"(",
"logger",
",",
"config",
"=",
"{",
"}",
")",
"{",
"this",
".",
"logger",
"=",
"null",
";",
"this",
".",
"monitoring",
"=",
"false",
";",
"this",
".",
"minLevel",
"=",
"0",
";",
"this",
".",
"maxLevel",
"=",
"7",
";",
"this",
".",
"messageFormatter",
"=",
"logger",
".",
"messageFormatter",
".",
"text",
";",
"this",
".",
"timeFormatter",
"=",
"logger",
".",
"timeFormatter",
".",
"dateTime",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'logger'",
",",
"{",
"value",
":",
"logger",
"}",
")",
";",
"if",
"(",
"config",
".",
"monitoring",
"!==",
"undefined",
")",
"{",
"this",
".",
"monitoring",
"=",
"!",
"!",
"config",
".",
"monitoring",
";",
"}",
"if",
"(",
"config",
".",
"minLevel",
"!==",
"undefined",
")",
"{",
"if",
"(",
"typeof",
"config",
".",
"minLevel",
"===",
"'number'",
")",
"{",
"this",
".",
"minLevel",
"=",
"config",
".",
"minLevel",
";",
"}",
"else",
"if",
"(",
"typeof",
"config",
".",
"minLevel",
"===",
"'string'",
")",
"{",
"this",
".",
"minLevel",
"=",
"this",
".",
"logger",
".",
"levelHash",
"[",
"config",
".",
"minLevel",
"]",
";",
"}",
"}",
"if",
"(",
"config",
".",
"maxLevel",
"!==",
"undefined",
")",
"{",
"if",
"(",
"typeof",
"config",
".",
"maxLevel",
"===",
"'number'",
")",
"{",
"this",
".",
"maxLevel",
"=",
"config",
".",
"maxLevel",
";",
"}",
"else",
"if",
"(",
"typeof",
"config",
".",
"maxLevel",
"===",
"'string'",
")",
"{",
"this",
".",
"maxLevel",
"=",
"this",
".",
"logger",
".",
"levelHash",
"[",
"config",
".",
"maxLevel",
"]",
";",
"}",
"}",
"if",
"(",
"config",
".",
"messageFormatter",
")",
"{",
"if",
"(",
"typeof",
"config",
".",
"messageFormatter",
"===",
"'function'",
")",
"{",
"this",
".",
"messageFormatter",
"=",
"config",
".",
"messageFormatter",
";",
"}",
"else",
"{",
"this",
".",
"messageFormatter",
"=",
"this",
".",
"logger",
".",
"messageFormatter",
"[",
"config",
".",
"messageFormatter",
"]",
";",
"}",
"}",
"if",
"(",
"config",
".",
"timeFormatter",
")",
"{",
"if",
"(",
"typeof",
"config",
".",
"timeFormatter",
"===",
"'function'",
")",
"{",
"this",
".",
"timeFormatter",
"=",
"config",
".",
"timeFormatter",
";",
"}",
"else",
"{",
"this",
".",
"timeFormatter",
"=",
"this",
".",
"logger",
".",
"timeFormatter",
"[",
"config",
".",
"timeFormatter",
"]",
";",
"}",
"}",
"}"
]
| Empty constructor, it is just there to support instanceof operator | [
"Empty",
"constructor",
"it",
"is",
"just",
"there",
"to",
"support",
"instanceof",
"operator"
]
| 194bba790fa864591394c8a1566bb0dff1670c33 | https://github.com/cronvel/logfella-common-transport/blob/194bba790fa864591394c8a1566bb0dff1670c33/lib/Common.transport.js#L32-L63 |
41,644 | hairyhenderson/node-fellowshipone | lib/household_communications.js | HouseholdCommunications | function HouseholdCommunications (f1, householdID) {
if (!householdID) {
throw new Error('HouseholdCommunications requires a household ID!')
}
Communications.call(this, f1, {
path: '/Households/' + householdID + '/Communications'
})
} | javascript | function HouseholdCommunications (f1, householdID) {
if (!householdID) {
throw new Error('HouseholdCommunications requires a household ID!')
}
Communications.call(this, f1, {
path: '/Households/' + householdID + '/Communications'
})
} | [
"function",
"HouseholdCommunications",
"(",
"f1",
",",
"householdID",
")",
"{",
"if",
"(",
"!",
"householdID",
")",
"{",
"throw",
"new",
"Error",
"(",
"'HouseholdCommunications requires a household ID!'",
")",
"}",
"Communications",
".",
"call",
"(",
"this",
",",
"f1",
",",
"{",
"path",
":",
"'/Households/'",
"+",
"householdID",
"+",
"'/Communications'",
"}",
")",
"}"
]
| The Communications object, in a Household context.
@param {Object} f1 - the F1 object
@param {Number} householdID - the Household ID, for context | [
"The",
"Communications",
"object",
"in",
"a",
"Household",
"context",
"."
]
| 5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b | https://github.com/hairyhenderson/node-fellowshipone/blob/5e80eb9ec31fb6dceee1e8c211e7b6e0e373b08b/lib/household_communications.js#L10-L17 |
41,645 | LaxarJS/laxar-tooling | src/page_assembler.js | assemble | function assemble( page ) {
if( typeof page !== 'object' ) {
return Promise.reject( new Error(
'PageAssembler.assemble must be called with a page artifact (object)'
) );
}
removeDisabledItems( page );
return loadPageRecursively( page, page.name, [] );
} | javascript | function assemble( page ) {
if( typeof page !== 'object' ) {
return Promise.reject( new Error(
'PageAssembler.assemble must be called with a page artifact (object)'
) );
}
removeDisabledItems( page );
return loadPageRecursively( page, page.name, [] );
} | [
"function",
"assemble",
"(",
"page",
")",
"{",
"if",
"(",
"typeof",
"page",
"!==",
"'object'",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'PageAssembler.assemble must be called with a page artifact (object)'",
")",
")",
";",
"}",
"removeDisabledItems",
"(",
"page",
")",
";",
"return",
"loadPageRecursively",
"(",
"page",
",",
"page",
".",
"name",
",",
"[",
"]",
")",
";",
"}"
]
| Loads a page specification and resolves all extension and compositions. The result is a page were all
referenced page fragments are merged in to one JavaScript object. Returns a promise that is either
resolved with the constructed page or rejected with a JavaScript `Error` instance.
@param {String} page
the page to load. Usually a path relative to the base url, with the `.json` suffix omitted
@return {Promise}
the result promise | [
"Loads",
"a",
"page",
"specification",
"and",
"resolves",
"all",
"extension",
"and",
"compositions",
".",
"The",
"result",
"is",
"a",
"page",
"were",
"all",
"referenced",
"page",
"fragments",
"are",
"merged",
"in",
"to",
"one",
"JavaScript",
"object",
".",
"Returns",
"a",
"promise",
"that",
"is",
"either",
"resolved",
"with",
"the",
"constructed",
"page",
"or",
"rejected",
"with",
"a",
"JavaScript",
"Error",
"instance",
"."
]
| 1c4a221994f342ec03a98b68533c4de77ccfeec6 | https://github.com/LaxarJS/laxar-tooling/blob/1c4a221994f342ec03a98b68533c4de77ccfeec6/src/page_assembler.js#L56-L64 |
41,646 | hoast/hoast-transform | library/index.js | function(extension) {
// If transformer already cached return that.
if (extension in transformers) {
return transformers[extension];
}
// Retrieve the transformer if available.
const transformer = totransformer(extension);
transformers[extension] = transformer ? jstransformer(transformer) : false;
// Return transformer.
return transformers[extension];
} | javascript | function(extension) {
// If transformer already cached return that.
if (extension in transformers) {
return transformers[extension];
}
// Retrieve the transformer if available.
const transformer = totransformer(extension);
transformers[extension] = transformer ? jstransformer(transformer) : false;
// Return transformer.
return transformers[extension];
} | [
"function",
"(",
"extension",
")",
"{",
"// If transformer already cached return that.",
"if",
"(",
"extension",
"in",
"transformers",
")",
"{",
"return",
"transformers",
"[",
"extension",
"]",
";",
"}",
"// Retrieve the transformer if available.",
"const",
"transformer",
"=",
"totransformer",
"(",
"extension",
")",
";",
"transformers",
"[",
"extension",
"]",
"=",
"transformer",
"?",
"jstransformer",
"(",
"transformer",
")",
":",
"false",
";",
"// Return transformer.",
"return",
"transformers",
"[",
"extension",
"]",
";",
"}"
]
| Matches the extension to the transformer.
@param {String} extension The file extension. | [
"Matches",
"the",
"extension",
"to",
"the",
"transformer",
"."
]
| c6c03f1aa8a1557d985fef41d7d07fcbe932090b | https://github.com/hoast/hoast-transform/blob/c6c03f1aa8a1557d985fef41d7d07fcbe932090b/library/index.js#L14-L26 |
|
41,647 | veo-labs/openveo-api | lib/storages/databases/Database.js | Database | function Database(configuration) {
Database.super_.call(this, configuration);
Object.defineProperties(this, {
/**
* Database host.
*
* @property host
* @type String
* @final
*/
host: {value: configuration.host},
/**
* Database port.
*
* @property port
* @type Number
* @final
*/
port: {value: configuration.port},
/**
* Database name.
*
* @property name
* @type String
* @final
*/
name: {value: configuration.database},
/**
* Database user name.
*
* @property username
* @type String
* @final
*/
username: {value: configuration.username},
/**
* Database user password.
*
* @property password
* @type String
* @final
*/
password: {value: configuration.password}
});
} | javascript | function Database(configuration) {
Database.super_.call(this, configuration);
Object.defineProperties(this, {
/**
* Database host.
*
* @property host
* @type String
* @final
*/
host: {value: configuration.host},
/**
* Database port.
*
* @property port
* @type Number
* @final
*/
port: {value: configuration.port},
/**
* Database name.
*
* @property name
* @type String
* @final
*/
name: {value: configuration.database},
/**
* Database user name.
*
* @property username
* @type String
* @final
*/
username: {value: configuration.username},
/**
* Database user password.
*
* @property password
* @type String
* @final
*/
password: {value: configuration.password}
});
} | [
"function",
"Database",
"(",
"configuration",
")",
"{",
"Database",
".",
"super_",
".",
"call",
"(",
"this",
",",
"configuration",
")",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"/**\n * Database host.\n *\n * @property host\n * @type String\n * @final\n */",
"host",
":",
"{",
"value",
":",
"configuration",
".",
"host",
"}",
",",
"/**\n * Database port.\n *\n * @property port\n * @type Number\n * @final\n */",
"port",
":",
"{",
"value",
":",
"configuration",
".",
"port",
"}",
",",
"/**\n * Database name.\n *\n * @property name\n * @type String\n * @final\n */",
"name",
":",
"{",
"value",
":",
"configuration",
".",
"database",
"}",
",",
"/**\n * Database user name.\n *\n * @property username\n * @type String\n * @final\n */",
"username",
":",
"{",
"value",
":",
"configuration",
".",
"username",
"}",
",",
"/**\n * Database user password.\n *\n * @property password\n * @type String\n * @final\n */",
"password",
":",
"{",
"value",
":",
"configuration",
".",
"password",
"}",
"}",
")",
";",
"}"
]
| Defines base database for all databases.
This should not be used directly, use one of its subclasses instead.
@class Database
@extends Storage
@constructor
@param {Object} configuration A database configuration object depending on the database type
@param {String} configuration.type The database type
@param {String} configuration.host Database server host
@param {Number} configuration.port Database server port
@param {String} configuration.database The name of the database
@param {String} configuration.username The name of the database user
@param {String} configuration.password The password of the database user | [
"Defines",
"base",
"database",
"for",
"all",
"databases",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/storages/databases/Database.js#L26-L77 |
41,648 | AnyFetch/anyfetch-hydrater.js | lib/helpers/hydrater.js | function(err, changes) {
if(cleaner.called) {
return;
}
cleaner.called = true;
if(err) {
// Build a custom extra object, with hydration error details
var extra = JSON.parse(JSON.stringify(task));
extra.changes = changes;
extra.stdout = stdout;
extra.stderr = stderr;
logError(err, extra);
child.reset();
}
else {
// Make the child available again
child.available = true;
}
cb(err, changes);
if(stdout !== "") {
loggingTask.std = "out";
log.info(loggingTask, stdout);
}
if(stderr !== "") {
loggingTask.std = "err";
log.info(loggingTask, stderr);
}
clearTimeout(timeout);
} | javascript | function(err, changes) {
if(cleaner.called) {
return;
}
cleaner.called = true;
if(err) {
// Build a custom extra object, with hydration error details
var extra = JSON.parse(JSON.stringify(task));
extra.changes = changes;
extra.stdout = stdout;
extra.stderr = stderr;
logError(err, extra);
child.reset();
}
else {
// Make the child available again
child.available = true;
}
cb(err, changes);
if(stdout !== "") {
loggingTask.std = "out";
log.info(loggingTask, stdout);
}
if(stderr !== "") {
loggingTask.std = "err";
log.info(loggingTask, stderr);
}
clearTimeout(timeout);
} | [
"function",
"(",
"err",
",",
"changes",
")",
"{",
"if",
"(",
"cleaner",
".",
"called",
")",
"{",
"return",
";",
"}",
"cleaner",
".",
"called",
"=",
"true",
";",
"if",
"(",
"err",
")",
"{",
"// Build a custom extra object, with hydration error details",
"var",
"extra",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"task",
")",
")",
";",
"extra",
".",
"changes",
"=",
"changes",
";",
"extra",
".",
"stdout",
"=",
"stdout",
";",
"extra",
".",
"stderr",
"=",
"stderr",
";",
"logError",
"(",
"err",
",",
"extra",
")",
";",
"child",
".",
"reset",
"(",
")",
";",
"}",
"else",
"{",
"// Make the child available again",
"child",
".",
"available",
"=",
"true",
";",
"}",
"cb",
"(",
"err",
",",
"changes",
")",
";",
"if",
"(",
"stdout",
"!==",
"\"\"",
")",
"{",
"loggingTask",
".",
"std",
"=",
"\"out\"",
";",
"log",
".",
"info",
"(",
"loggingTask",
",",
"stdout",
")",
";",
"}",
"if",
"(",
"stderr",
"!==",
"\"\"",
")",
"{",
"loggingTask",
".",
"std",
"=",
"\"err\"",
";",
"log",
".",
"info",
"(",
"loggingTask",
",",
"stderr",
")",
";",
"}",
"clearTimeout",
"(",
"timeout",
")",
";",
"}"
]
| Function to call, either on domain error, on hydration error or successful hydration. | [
"Function",
"to",
"call",
"either",
"on",
"domain",
"error",
"on",
"hydration",
"error",
"or",
"successful",
"hydration",
"."
]
| 1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae | https://github.com/AnyFetch/anyfetch-hydrater.js/blob/1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae/lib/helpers/hydrater.js#L50-L82 |
|
41,649 | AnyFetch/anyfetch-hydrater.js | lib/helpers/hydrater.js | function(elem) {
if(util.isArray(elem)) {
return (elem.length === 0);
}
if(elem instanceof Object) {
if(util.isDate(elem)) {
return false;
}
return (Object.getOwnPropertyNames(elem).length === 0);
}
return false;
} | javascript | function(elem) {
if(util.isArray(elem)) {
return (elem.length === 0);
}
if(elem instanceof Object) {
if(util.isDate(elem)) {
return false;
}
return (Object.getOwnPropertyNames(elem).length === 0);
}
return false;
} | [
"function",
"(",
"elem",
")",
"{",
"if",
"(",
"util",
".",
"isArray",
"(",
"elem",
")",
")",
"{",
"return",
"(",
"elem",
".",
"length",
"===",
"0",
")",
";",
"}",
"if",
"(",
"elem",
"instanceof",
"Object",
")",
"{",
"if",
"(",
"util",
".",
"isDate",
"(",
"elem",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
"Object",
".",
"getOwnPropertyNames",
"(",
"elem",
")",
".",
"length",
"===",
"0",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| Removing empty changes to patch only effective changes | [
"Removing",
"empty",
"changes",
"to",
"patch",
"only",
"effective",
"changes"
]
| 1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae | https://github.com/AnyFetch/anyfetch-hydrater.js/blob/1e70fdb5d8dcd26382e2a16de747b91a5b3ef3ae/lib/helpers/hydrater.js#L169-L180 |
|
41,650 | ouroboroscoding/format-oc-javascript | format-oc.1.4.2.js | DateToStr | function DateToStr(date) {
// Init the return variable
var sRet = '';
// Add the year
sRet += date.getFullYear() + '-';
// Add the month
var iMonth = date.getMonth();
sRet += ((iMonth < 10) ? '0' + iMonth : iMonth.toString()) + '-'
// Add the day
var iDay = date.getDate();
sRet += ((iDay < 10) ? '0' + iDay : iDay.toString())
// Return the date
return sRet;
} | javascript | function DateToStr(date) {
// Init the return variable
var sRet = '';
// Add the year
sRet += date.getFullYear() + '-';
// Add the month
var iMonth = date.getMonth();
sRet += ((iMonth < 10) ? '0' + iMonth : iMonth.toString()) + '-'
// Add the day
var iDay = date.getDate();
sRet += ((iDay < 10) ? '0' + iDay : iDay.toString())
// Return the date
return sRet;
} | [
"function",
"DateToStr",
"(",
"date",
")",
"{",
"// Init the return variable",
"var",
"sRet",
"=",
"''",
";",
"// Add the year",
"sRet",
"+=",
"date",
".",
"getFullYear",
"(",
")",
"+",
"'-'",
";",
"// Add the month",
"var",
"iMonth",
"=",
"date",
".",
"getMonth",
"(",
")",
";",
"sRet",
"+=",
"(",
"(",
"iMonth",
"<",
"10",
")",
"?",
"'0'",
"+",
"iMonth",
":",
"iMonth",
".",
"toString",
"(",
")",
")",
"+",
"'-'",
"// Add the day",
"var",
"iDay",
"=",
"date",
".",
"getDate",
"(",
")",
";",
"sRet",
"+=",
"(",
"(",
"iDay",
"<",
"10",
")",
"?",
"'0'",
"+",
"iDay",
":",
"iDay",
".",
"toString",
"(",
")",
")",
"// Return the date",
"return",
"sRet",
";",
"}"
]
| Date to String
Turns a Date Object into a date string
@name DateToStr
@param Date date The value to turn into a string
@return String | [
"Date",
"to",
"String"
]
| bbcef0a11250053366df7596efc08ea4b45622e2 | https://github.com/ouroboroscoding/format-oc-javascript/blob/bbcef0a11250053366df7596efc08ea4b45622e2/format-oc.1.4.2.js#L139-L157 |
41,651 | ouroboroscoding/format-oc-javascript | format-oc.1.4.2.js | DateTimeToStr | function DateTimeToStr(datetime) {
// Init the return variable with the date
var sRet = DateToStr(datetime);
// Add the time
sRet += ' ' + datetime.toTimeString().substr(0,8);
// Return the new date/time
return sRet;
} | javascript | function DateTimeToStr(datetime) {
// Init the return variable with the date
var sRet = DateToStr(datetime);
// Add the time
sRet += ' ' + datetime.toTimeString().substr(0,8);
// Return the new date/time
return sRet;
} | [
"function",
"DateTimeToStr",
"(",
"datetime",
")",
"{",
"// Init the return variable with the date",
"var",
"sRet",
"=",
"DateToStr",
"(",
"datetime",
")",
";",
"// Add the time",
"sRet",
"+=",
"' '",
"+",
"datetime",
".",
"toTimeString",
"(",
")",
".",
"substr",
"(",
"0",
",",
"8",
")",
";",
"// Return the new date/time",
"return",
"sRet",
";",
"}"
]
| DateTime to String
Turns a Date Object into a date and time string
@name DateTimeToStr
@param Date datetime The value to turn into a string
@return String | [
"DateTime",
"to",
"String"
]
| bbcef0a11250053366df7596efc08ea4b45622e2 | https://github.com/ouroboroscoding/format-oc-javascript/blob/bbcef0a11250053366df7596efc08ea4b45622e2/format-oc.1.4.2.js#L168-L178 |
41,652 | vesln/hydro | lib/hydro.js | Hydro | function Hydro() {
if (!(this instanceof Hydro)) {
return new Hydro();
}
this.loader = loader;
this.plugins = [];
this.emitter = new EventEmitter;
this.runner = new Runner;
this.frame = new Frame(this.runner.topLevel);
this.interface = new Interface(this, this.frame);
this.config = new Config;
} | javascript | function Hydro() {
if (!(this instanceof Hydro)) {
return new Hydro();
}
this.loader = loader;
this.plugins = [];
this.emitter = new EventEmitter;
this.runner = new Runner;
this.frame = new Frame(this.runner.topLevel);
this.interface = new Interface(this, this.frame);
this.config = new Config;
} | [
"function",
"Hydro",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Hydro",
")",
")",
"{",
"return",
"new",
"Hydro",
"(",
")",
";",
"}",
"this",
".",
"loader",
"=",
"loader",
";",
"this",
".",
"plugins",
"=",
"[",
"]",
";",
"this",
".",
"emitter",
"=",
"new",
"EventEmitter",
";",
"this",
".",
"runner",
"=",
"new",
"Runner",
";",
"this",
".",
"frame",
"=",
"new",
"Frame",
"(",
"this",
".",
"runner",
".",
"topLevel",
")",
";",
"this",
".",
"interface",
"=",
"new",
"Interface",
"(",
"this",
",",
"this",
".",
"frame",
")",
";",
"this",
".",
"config",
"=",
"new",
"Config",
";",
"}"
]
| Hydro - the main class that external parties
interact with.
TODO(vesln): use `delegates`?
@constructor | [
"Hydro",
"-",
"the",
"main",
"class",
"that",
"external",
"parties",
"interact",
"with",
"."
]
| 3f4d2e4926f913976187376e82f1496514c39890 | https://github.com/vesln/hydro/blob/3f4d2e4926f913976187376e82f1496514c39890/lib/hydro.js#L28-L40 |
41,653 | DavidSouther/JEFRi | modeler/angular/app/scripts/lib/codemirror/mode/tiddlywiki/tiddlywiki.js | twTokenStrike | function twTokenStrike(stream, state) {
var maybeEnd = false,
ch, nr;
while (ch = stream.next()) {
if (ch == "-" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "-");
}
return ret("text", "strikethrough");
} | javascript | function twTokenStrike(stream, state) {
var maybeEnd = false,
ch, nr;
while (ch = stream.next()) {
if (ch == "-" && maybeEnd) {
state.tokenize = jsTokenBase;
break;
}
maybeEnd = (ch == "-");
}
return ret("text", "strikethrough");
} | [
"function",
"twTokenStrike",
"(",
"stream",
",",
"state",
")",
"{",
"var",
"maybeEnd",
"=",
"false",
",",
"ch",
",",
"nr",
";",
"while",
"(",
"ch",
"=",
"stream",
".",
"next",
"(",
")",
")",
"{",
"if",
"(",
"ch",
"==",
"\"-\"",
"&&",
"maybeEnd",
")",
"{",
"state",
".",
"tokenize",
"=",
"jsTokenBase",
";",
"break",
";",
"}",
"maybeEnd",
"=",
"(",
"ch",
"==",
"\"-\"",
")",
";",
"}",
"return",
"ret",
"(",
"\"text\"",
",",
"\"strikethrough\"",
")",
";",
"}"
]
| tw strike through text looks ugly change CSS if needed | [
"tw",
"strike",
"through",
"text",
"looks",
"ugly",
"change",
"CSS",
"if",
"needed"
]
| 161f24e242e05b9b2114cc1123a257141a60eaf2 | https://github.com/DavidSouther/JEFRi/blob/161f24e242e05b9b2114cc1123a257141a60eaf2/modeler/angular/app/scripts/lib/codemirror/mode/tiddlywiki/tiddlywiki.js#L316-L328 |
41,654 | veo-labs/openveo-api | lib/providers/Provider.js | Provider | function Provider(storage) {
Object.defineProperties(this, {
/**
* The provider storage.
*
* @property storage
* @type Storage
* @final
*/
storage: {value: storage}
});
if (!(this.storage instanceof Storage))
throw new TypeError('storage must be of type Storage');
} | javascript | function Provider(storage) {
Object.defineProperties(this, {
/**
* The provider storage.
*
* @property storage
* @type Storage
* @final
*/
storage: {value: storage}
});
if (!(this.storage instanceof Storage))
throw new TypeError('storage must be of type Storage');
} | [
"function",
"Provider",
"(",
"storage",
")",
"{",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"/**\n * The provider storage.\n *\n * @property storage\n * @type Storage\n * @final\n */",
"storage",
":",
"{",
"value",
":",
"storage",
"}",
"}",
")",
";",
"if",
"(",
"!",
"(",
"this",
".",
"storage",
"instanceof",
"Storage",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'storage must be of type Storage'",
")",
";",
"}"
]
| Defines the base provider for all providers.
A provider manages resources from its associated storage.
@class Provider
@constructor
@param {Storage} storage The storage to use to store provider resources
@throws {TypeError} If storage is not valid | [
"Defines",
"the",
"base",
"provider",
"for",
"all",
"providers",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/providers/Provider.js#L19-L35 |
41,655 | LeisureLink/magicbus | lib/config/subscriber-configuration.js | function() {
return {
useConsumer: useConsumer,
useEventDispatcher: useEventDispatcher,
useEnvelope: useEnvelope,
usePipeline: usePipeline,
useRouteName: useRouteName,
useRoutePattern: useRoutePattern
};
} | javascript | function() {
return {
useConsumer: useConsumer,
useEventDispatcher: useEventDispatcher,
useEnvelope: useEnvelope,
usePipeline: usePipeline,
useRouteName: useRouteName,
useRoutePattern: useRoutePattern
};
} | [
"function",
"(",
")",
"{",
"return",
"{",
"useConsumer",
":",
"useConsumer",
",",
"useEventDispatcher",
":",
"useEventDispatcher",
",",
"useEnvelope",
":",
"useEnvelope",
",",
"usePipeline",
":",
"usePipeline",
",",
"useRouteName",
":",
"useRouteName",
",",
"useRoutePattern",
":",
"useRoutePattern",
"}",
";",
"}"
]
| Gets the target for a configurator function to run on
@public
@param {Function} configFunc - the configuration function for the instance | [
"Gets",
"the",
"target",
"for",
"a",
"configurator",
"function",
"to",
"run",
"on"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/subscriber-configuration.js#L91-L100 |
|
41,656 | Runnable/monitor-dog | lib/timer.js | Timer | function Timer (callback, start) {
this.callback = callback;
this.startDate = null;
if (!exists(start) || start !== false) {
this.start();
}
} | javascript | function Timer (callback, start) {
this.callback = callback;
this.startDate = null;
if (!exists(start) || start !== false) {
this.start();
}
} | [
"function",
"Timer",
"(",
"callback",
",",
"start",
")",
"{",
"this",
".",
"callback",
"=",
"callback",
";",
"this",
".",
"startDate",
"=",
"null",
";",
"if",
"(",
"!",
"exists",
"(",
"start",
")",
"||",
"start",
"!==",
"false",
")",
"{",
"this",
".",
"start",
"(",
")",
";",
"}",
"}"
]
| Timer class for performing time calculations through the monitor
module.
@class
@param {function} callback Callback to execute when the timer is stopped.
@param {boolean} start Whether or not to start the timer upon construction,
default: `true`. | [
"Timer",
"class",
"for",
"performing",
"time",
"calculations",
"through",
"the",
"monitor",
"module",
"."
]
| 040b259dfc8c6b5d934dc235f76028e5ab9094cc | https://github.com/Runnable/monitor-dog/blob/040b259dfc8c6b5d934dc235f76028e5ab9094cc/lib/timer.js#L20-L26 |
41,657 | Mammut-FE/nejm | src/base/util.js | function(_list,_low,_high){
if (_low>_high) return -1;
var _middle = Math.ceil((_low+_high)/2),
_result = _docheck(_list[_middle],_middle,_list);
if (_result==0)
return _middle;
if (_result<0)
return _doSearch(_list,_low,_middle-1);
return _doSearch(_list,_middle+1,_high);
} | javascript | function(_list,_low,_high){
if (_low>_high) return -1;
var _middle = Math.ceil((_low+_high)/2),
_result = _docheck(_list[_middle],_middle,_list);
if (_result==0)
return _middle;
if (_result<0)
return _doSearch(_list,_low,_middle-1);
return _doSearch(_list,_middle+1,_high);
} | [
"function",
"(",
"_list",
",",
"_low",
",",
"_high",
")",
"{",
"if",
"(",
"_low",
">",
"_high",
")",
"return",
"-",
"1",
";",
"var",
"_middle",
"=",
"Math",
".",
"ceil",
"(",
"(",
"_low",
"+",
"_high",
")",
"/",
"2",
")",
",",
"_result",
"=",
"_docheck",
"(",
"_list",
"[",
"_middle",
"]",
",",
"_middle",
",",
"_list",
")",
";",
"if",
"(",
"_result",
"==",
"0",
")",
"return",
"_middle",
";",
"if",
"(",
"_result",
"<",
"0",
")",
"return",
"_doSearch",
"(",
"_list",
",",
"_low",
",",
"_middle",
"-",
"1",
")",
";",
"return",
"_doSearch",
"(",
"_list",
",",
"_middle",
"+",
"1",
",",
"_high",
")",
";",
"}"
]
| do binary search | [
"do",
"binary",
"search"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/base/util.js#L299-L308 |
|
41,658 | urturn/urturn-expression-api | lib/expression-api/Image.js | function(url, img) {
var svgImage = document.createElementNS(SVG_NS_URL, 'image');
svgImage.setAttributeNS(XLINK_NS_URL, 'xlink:href', url);
svgImage.setAttribute('x', 0);
svgImage.setAttribute('y', 0);
svgImage.setAttribute('width', img.width);
svgImage.setAttribute('height', img.height);
return svgImage;
} | javascript | function(url, img) {
var svgImage = document.createElementNS(SVG_NS_URL, 'image');
svgImage.setAttributeNS(XLINK_NS_URL, 'xlink:href', url);
svgImage.setAttribute('x', 0);
svgImage.setAttribute('y', 0);
svgImage.setAttribute('width', img.width);
svgImage.setAttribute('height', img.height);
return svgImage;
} | [
"function",
"(",
"url",
",",
"img",
")",
"{",
"var",
"svgImage",
"=",
"document",
".",
"createElementNS",
"(",
"SVG_NS_URL",
",",
"'image'",
")",
";",
"svgImage",
".",
"setAttributeNS",
"(",
"XLINK_NS_URL",
",",
"'xlink:href'",
",",
"url",
")",
";",
"svgImage",
".",
"setAttribute",
"(",
"'x'",
",",
"0",
")",
";",
"svgImage",
".",
"setAttribute",
"(",
"'y'",
",",
"0",
")",
";",
"svgImage",
".",
"setAttribute",
"(",
"'width'",
",",
"img",
".",
"width",
")",
";",
"svgImage",
".",
"setAttribute",
"(",
"'height'",
",",
"img",
".",
"height",
")",
";",
"return",
"svgImage",
";",
"}"
]
| Build an svg image tag. | [
"Build",
"an",
"svg",
"image",
"tag",
"."
]
| 009a272ee670dbbe5eefb5c070ed827dd778bb07 | https://github.com/urturn/urturn-expression-api/blob/009a272ee670dbbe5eefb5c070ed827dd778bb07/lib/expression-api/Image.js#L199-L207 |
|
41,659 | Mammut-FE/nejm | src/util/highlight/touch.js | function(_id,_clazz,_event){
_cache[_id] = _v._$page(_event);
_e._$addClassName(_id,_clazz);
} | javascript | function(_id,_clazz,_event){
_cache[_id] = _v._$page(_event);
_e._$addClassName(_id,_clazz);
} | [
"function",
"(",
"_id",
",",
"_clazz",
",",
"_event",
")",
"{",
"_cache",
"[",
"_id",
"]",
"=",
"_v",
".",
"_$page",
"(",
"_event",
")",
";",
"_e",
".",
"_$addClassName",
"(",
"_id",
",",
"_clazz",
")",
";",
"}"
]
| touch start event | [
"touch",
"start",
"event"
]
| dfc09ac66a8d67620a7aea65e34d8a179976b3fb | https://github.com/Mammut-FE/nejm/blob/dfc09ac66a8d67620a7aea65e34d8a179976b3fb/src/util/highlight/touch.js#L54-L57 |
|
41,660 | aldojs/http | lib/server.js | _wrap | function _wrap (handler, emitter) {
return async (req, res) => {
try {
let response = await handler(req)
await response.send(res)
} catch (err) {
// normalize
if (! (err instanceof Error)) {
err = new Error(`Non-error thrown: "${typeof err}"`)
}
// support ENOENT
if (err.code === 'ENOENT') {
err.expose = true
err.status = 404
}
// send
res.statusCode = err.status || err.statusCode || 500
res.end()
// delegate
emitter.emit('error', err)
}
}
} | javascript | function _wrap (handler, emitter) {
return async (req, res) => {
try {
let response = await handler(req)
await response.send(res)
} catch (err) {
// normalize
if (! (err instanceof Error)) {
err = new Error(`Non-error thrown: "${typeof err}"`)
}
// support ENOENT
if (err.code === 'ENOENT') {
err.expose = true
err.status = 404
}
// send
res.statusCode = err.status || err.statusCode || 500
res.end()
// delegate
emitter.emit('error', err)
}
}
} | [
"function",
"_wrap",
"(",
"handler",
",",
"emitter",
")",
"{",
"return",
"async",
"(",
"req",
",",
"res",
")",
"=>",
"{",
"try",
"{",
"let",
"response",
"=",
"await",
"handler",
"(",
"req",
")",
"await",
"response",
".",
"send",
"(",
"res",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"// normalize",
"if",
"(",
"!",
"(",
"err",
"instanceof",
"Error",
")",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"`",
"${",
"typeof",
"err",
"}",
"`",
")",
"}",
"// support ENOENT",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"err",
".",
"expose",
"=",
"true",
"err",
".",
"status",
"=",
"404",
"}",
"// send",
"res",
".",
"statusCode",
"=",
"err",
".",
"status",
"||",
"err",
".",
"statusCode",
"||",
"500",
"res",
".",
"end",
"(",
")",
"// delegate",
"emitter",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
"}",
"}",
"}"
]
| Wrap the request handler
@param {Function} handler The request handler
@param {EventEmitter} emitter
@private | [
"Wrap",
"the",
"request",
"handler"
]
| e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7 | https://github.com/aldojs/http/blob/e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7/lib/server.js#L138-L164 |
41,661 | aldojs/http | lib/server.js | _onError | function _onError (err) {
if (err.status === 404 || err.statusCode === 404 || err.expose) return
let msg = err.stack || err.toString()
console.error(`\n${msg.replace(/^/gm, ' ')}\n`)
} | javascript | function _onError (err) {
if (err.status === 404 || err.statusCode === 404 || err.expose) return
let msg = err.stack || err.toString()
console.error(`\n${msg.replace(/^/gm, ' ')}\n`)
} | [
"function",
"_onError",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"status",
"===",
"404",
"||",
"err",
".",
"statusCode",
"===",
"404",
"||",
"err",
".",
"expose",
")",
"return",
"let",
"msg",
"=",
"err",
".",
"stack",
"||",
"err",
".",
"toString",
"(",
")",
"console",
".",
"error",
"(",
"`",
"\\n",
"${",
"msg",
".",
"replace",
"(",
"/",
"^",
"/",
"gm",
",",
"' '",
")",
"}",
"\\n",
"`",
")",
"}"
]
| The default `error` handler
@param {Error} err The error object
@private | [
"The",
"default",
"error",
"handler"
]
| e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7 | https://github.com/aldojs/http/blob/e8e7d92cbe8c7ae3cc3471b67774b9ef7d06d1c7/lib/server.js#L172-L178 |
41,662 | eface2face/meteor-spacebars-compiler | spacebars-compiler.js | function (ttag, scanner) {
if (ttag.type === 'INCLUSION' || ttag.type === 'BLOCKOPEN') {
var args = ttag.args;
if (ttag.path[0] === 'each' && args[1] && args[1][0] === 'PATH' &&
args[1][1][0] === 'in') {
// For slightly better error messages, we detect the each-in case
// here in order not to complain if the user writes `{{#each 3 in x}}`
// that "3 is not a function"
} else {
if (args.length > 1 && args[0].length === 2 && args[0][0] !== 'PATH') {
// we have a positional argument that is not a PATH followed by
// other arguments
scanner.fatal("First argument must be a function, to be called on " +
"the rest of the arguments; found " + args[0][0]);
}
}
}
var position = ttag.position || TEMPLATE_TAG_POSITION.ELEMENT;
if (position === TEMPLATE_TAG_POSITION.IN_ATTRIBUTE) {
if (ttag.type === 'DOUBLE' || ttag.type === 'ESCAPE') {
return;
} else if (ttag.type === 'BLOCKOPEN') {
var path = ttag.path;
var path0 = path[0];
if (! (path.length === 1 && (path0 === 'if' ||
path0 === 'unless' ||
path0 === 'with' ||
path0 === 'each'))) {
scanner.fatal("Custom block helpers are not allowed in an HTML attribute, only built-in ones like #each and #if");
}
} else {
scanner.fatal(ttag.type + " template tag is not allowed in an HTML attribute");
}
} else if (position === TEMPLATE_TAG_POSITION.IN_START_TAG) {
if (! (ttag.type === 'DOUBLE')) {
scanner.fatal("Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type " + ttag.type + " is not allowed here.");
}
if (scanner.peek() === '=') {
scanner.fatal("Template tags are not allowed in attribute names, only in attribute values or in the form of a single {{helper}} that evaluates to a dictionary of name=value pairs.");
}
}
} | javascript | function (ttag, scanner) {
if (ttag.type === 'INCLUSION' || ttag.type === 'BLOCKOPEN') {
var args = ttag.args;
if (ttag.path[0] === 'each' && args[1] && args[1][0] === 'PATH' &&
args[1][1][0] === 'in') {
// For slightly better error messages, we detect the each-in case
// here in order not to complain if the user writes `{{#each 3 in x}}`
// that "3 is not a function"
} else {
if (args.length > 1 && args[0].length === 2 && args[0][0] !== 'PATH') {
// we have a positional argument that is not a PATH followed by
// other arguments
scanner.fatal("First argument must be a function, to be called on " +
"the rest of the arguments; found " + args[0][0]);
}
}
}
var position = ttag.position || TEMPLATE_TAG_POSITION.ELEMENT;
if (position === TEMPLATE_TAG_POSITION.IN_ATTRIBUTE) {
if (ttag.type === 'DOUBLE' || ttag.type === 'ESCAPE') {
return;
} else if (ttag.type === 'BLOCKOPEN') {
var path = ttag.path;
var path0 = path[0];
if (! (path.length === 1 && (path0 === 'if' ||
path0 === 'unless' ||
path0 === 'with' ||
path0 === 'each'))) {
scanner.fatal("Custom block helpers are not allowed in an HTML attribute, only built-in ones like #each and #if");
}
} else {
scanner.fatal(ttag.type + " template tag is not allowed in an HTML attribute");
}
} else if (position === TEMPLATE_TAG_POSITION.IN_START_TAG) {
if (! (ttag.type === 'DOUBLE')) {
scanner.fatal("Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type " + ttag.type + " is not allowed here.");
}
if (scanner.peek() === '=') {
scanner.fatal("Template tags are not allowed in attribute names, only in attribute values or in the form of a single {{helper}} that evaluates to a dictionary of name=value pairs.");
}
}
} | [
"function",
"(",
"ttag",
",",
"scanner",
")",
"{",
"if",
"(",
"ttag",
".",
"type",
"===",
"'INCLUSION'",
"||",
"ttag",
".",
"type",
"===",
"'BLOCKOPEN'",
")",
"{",
"var",
"args",
"=",
"ttag",
".",
"args",
";",
"if",
"(",
"ttag",
".",
"path",
"[",
"0",
"]",
"===",
"'each'",
"&&",
"args",
"[",
"1",
"]",
"&&",
"args",
"[",
"1",
"]",
"[",
"0",
"]",
"===",
"'PATH'",
"&&",
"args",
"[",
"1",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"===",
"'in'",
")",
"{",
"// For slightly better error messages, we detect the each-in case",
"// here in order not to complain if the user writes `{{#each 3 in x}}`",
"// that \"3 is not a function\"",
"}",
"else",
"{",
"if",
"(",
"args",
".",
"length",
">",
"1",
"&&",
"args",
"[",
"0",
"]",
".",
"length",
"===",
"2",
"&&",
"args",
"[",
"0",
"]",
"[",
"0",
"]",
"!==",
"'PATH'",
")",
"{",
"// we have a positional argument that is not a PATH followed by",
"// other arguments",
"scanner",
".",
"fatal",
"(",
"\"First argument must be a function, to be called on \"",
"+",
"\"the rest of the arguments; found \"",
"+",
"args",
"[",
"0",
"]",
"[",
"0",
"]",
")",
";",
"}",
"}",
"}",
"var",
"position",
"=",
"ttag",
".",
"position",
"||",
"TEMPLATE_TAG_POSITION",
".",
"ELEMENT",
";",
"if",
"(",
"position",
"===",
"TEMPLATE_TAG_POSITION",
".",
"IN_ATTRIBUTE",
")",
"{",
"if",
"(",
"ttag",
".",
"type",
"===",
"'DOUBLE'",
"||",
"ttag",
".",
"type",
"===",
"'ESCAPE'",
")",
"{",
"return",
";",
"}",
"else",
"if",
"(",
"ttag",
".",
"type",
"===",
"'BLOCKOPEN'",
")",
"{",
"var",
"path",
"=",
"ttag",
".",
"path",
";",
"var",
"path0",
"=",
"path",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"(",
"path",
".",
"length",
"===",
"1",
"&&",
"(",
"path0",
"===",
"'if'",
"||",
"path0",
"===",
"'unless'",
"||",
"path0",
"===",
"'with'",
"||",
"path0",
"===",
"'each'",
")",
")",
")",
"{",
"scanner",
".",
"fatal",
"(",
"\"Custom block helpers are not allowed in an HTML attribute, only built-in ones like #each and #if\"",
")",
";",
"}",
"}",
"else",
"{",
"scanner",
".",
"fatal",
"(",
"ttag",
".",
"type",
"+",
"\" template tag is not allowed in an HTML attribute\"",
")",
";",
"}",
"}",
"else",
"if",
"(",
"position",
"===",
"TEMPLATE_TAG_POSITION",
".",
"IN_START_TAG",
")",
"{",
"if",
"(",
"!",
"(",
"ttag",
".",
"type",
"===",
"'DOUBLE'",
")",
")",
"{",
"scanner",
".",
"fatal",
"(",
"\"Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type \"",
"+",
"ttag",
".",
"type",
"+",
"\" is not allowed here.\"",
")",
";",
"}",
"if",
"(",
"scanner",
".",
"peek",
"(",
")",
"===",
"'='",
")",
"{",
"scanner",
".",
"fatal",
"(",
"\"Template tags are not allowed in attribute names, only in attribute values or in the form of a single {{helper}} that evaluates to a dictionary of name=value pairs.\"",
")",
";",
"}",
"}",
"}"
]
| Validate that `templateTag` is correctly formed and legal for its HTML position. Use `scanner` to report errors. On success, does nothing. | [
"Validate",
"that",
"templateTag",
"is",
"correctly",
"formed",
"and",
"legal",
"for",
"its",
"HTML",
"position",
".",
"Use",
"scanner",
"to",
"report",
"errors",
".",
"On",
"success",
"does",
"nothing",
"."
]
| ad197c715cdcafebaa2fca31a6c17173d29746d7 | https://github.com/eface2face/meteor-spacebars-compiler/blob/ad197c715cdcafebaa2fca31a6c17173d29746d7/spacebars-compiler.js#L472-L516 |
|
41,663 | eface2face/meteor-spacebars-compiler | spacebars-compiler.js | function (path, args, mustacheType) {
var self = this;
var nameCode = self.codeGenPath(path);
var argCode = self.codeGenMustacheArgs(args);
var mustache = (mustacheType || 'mustache');
return 'Spacebars.' + mustache + '(' + nameCode +
(argCode ? ', ' + argCode.join(', ') : '') + ')';
} | javascript | function (path, args, mustacheType) {
var self = this;
var nameCode = self.codeGenPath(path);
var argCode = self.codeGenMustacheArgs(args);
var mustache = (mustacheType || 'mustache');
return 'Spacebars.' + mustache + '(' + nameCode +
(argCode ? ', ' + argCode.join(', ') : '') + ')';
} | [
"function",
"(",
"path",
",",
"args",
",",
"mustacheType",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"nameCode",
"=",
"self",
".",
"codeGenPath",
"(",
"path",
")",
";",
"var",
"argCode",
"=",
"self",
".",
"codeGenMustacheArgs",
"(",
"args",
")",
";",
"var",
"mustache",
"=",
"(",
"mustacheType",
"||",
"'mustache'",
")",
";",
"return",
"'Spacebars.'",
"+",
"mustache",
"+",
"'('",
"+",
"nameCode",
"+",
"(",
"argCode",
"?",
"', '",
"+",
"argCode",
".",
"join",
"(",
"', '",
")",
":",
"''",
")",
"+",
"')'",
";",
"}"
]
| Generates a call to `Spacebars.fooMustache` on evaluated arguments. The resulting code has no function literals and must be wrapped in one for fine-grained reactivity. | [
"Generates",
"a",
"call",
"to",
"Spacebars",
".",
"fooMustache",
"on",
"evaluated",
"arguments",
".",
"The",
"resulting",
"code",
"has",
"no",
"function",
"literals",
"and",
"must",
"be",
"wrapped",
"in",
"one",
"for",
"fine",
"-",
"grained",
"reactivity",
"."
]
| ad197c715cdcafebaa2fca31a6c17173d29746d7 | https://github.com/eface2face/meteor-spacebars-compiler/blob/ad197c715cdcafebaa2fca31a6c17173d29746d7/spacebars-compiler.js#L1049-L1058 |
|
41,664 | mozilla-jetpack/jetpack-validation | index.js | validate | function validate (rootPath) {
var manifest;
var webextensionManifest;
var errors = {};
try {
manifest = JSON.parse(fs.readFileSync(join(rootPath, "package.json")));
} catch (e) {
errors.parsing = utils.getErrorMessage("COULD_NOT_PARSE") + "\n" + e.message;
return errors;
}
if (!validateID(manifest)) {
errors.id = utils.getErrorMessage("INVALID_ID");
}
if (!validateMain(rootPath)) {
errors.main = utils.getErrorMessage("MAIN_DNE");
}
if (!validateTitle(manifest)) {
errors.title = utils.getErrorMessage("INVALID_TITLE");
}
if (!validateName(manifest)) {
errors.name = utils.getErrorMessage("INVALID_NAME");
}
if (!validateVersion(manifest)) {
errors.version = utils.getErrorMessage("INVALID_VERSION");
}
// If both a package.json and a manifest.json files exists in the addon
// root dir, raise an helpful error message that suggest to use web-ext instead.
if (fs.existsSync(join(rootPath, "manifest.json"))) {
errors.webextensionManifestFound = utils.getErrorMessage("WEBEXT_ERROR");
}
return errors;
} | javascript | function validate (rootPath) {
var manifest;
var webextensionManifest;
var errors = {};
try {
manifest = JSON.parse(fs.readFileSync(join(rootPath, "package.json")));
} catch (e) {
errors.parsing = utils.getErrorMessage("COULD_NOT_PARSE") + "\n" + e.message;
return errors;
}
if (!validateID(manifest)) {
errors.id = utils.getErrorMessage("INVALID_ID");
}
if (!validateMain(rootPath)) {
errors.main = utils.getErrorMessage("MAIN_DNE");
}
if (!validateTitle(manifest)) {
errors.title = utils.getErrorMessage("INVALID_TITLE");
}
if (!validateName(manifest)) {
errors.name = utils.getErrorMessage("INVALID_NAME");
}
if (!validateVersion(manifest)) {
errors.version = utils.getErrorMessage("INVALID_VERSION");
}
// If both a package.json and a manifest.json files exists in the addon
// root dir, raise an helpful error message that suggest to use web-ext instead.
if (fs.existsSync(join(rootPath, "manifest.json"))) {
errors.webextensionManifestFound = utils.getErrorMessage("WEBEXT_ERROR");
}
return errors;
} | [
"function",
"validate",
"(",
"rootPath",
")",
"{",
"var",
"manifest",
";",
"var",
"webextensionManifest",
";",
"var",
"errors",
"=",
"{",
"}",
";",
"try",
"{",
"manifest",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"join",
"(",
"rootPath",
",",
"\"package.json\"",
")",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"errors",
".",
"parsing",
"=",
"utils",
".",
"getErrorMessage",
"(",
"\"COULD_NOT_PARSE\"",
")",
"+",
"\"\\n\"",
"+",
"e",
".",
"message",
";",
"return",
"errors",
";",
"}",
"if",
"(",
"!",
"validateID",
"(",
"manifest",
")",
")",
"{",
"errors",
".",
"id",
"=",
"utils",
".",
"getErrorMessage",
"(",
"\"INVALID_ID\"",
")",
";",
"}",
"if",
"(",
"!",
"validateMain",
"(",
"rootPath",
")",
")",
"{",
"errors",
".",
"main",
"=",
"utils",
".",
"getErrorMessage",
"(",
"\"MAIN_DNE\"",
")",
";",
"}",
"if",
"(",
"!",
"validateTitle",
"(",
"manifest",
")",
")",
"{",
"errors",
".",
"title",
"=",
"utils",
".",
"getErrorMessage",
"(",
"\"INVALID_TITLE\"",
")",
";",
"}",
"if",
"(",
"!",
"validateName",
"(",
"manifest",
")",
")",
"{",
"errors",
".",
"name",
"=",
"utils",
".",
"getErrorMessage",
"(",
"\"INVALID_NAME\"",
")",
";",
"}",
"if",
"(",
"!",
"validateVersion",
"(",
"manifest",
")",
")",
"{",
"errors",
".",
"version",
"=",
"utils",
".",
"getErrorMessage",
"(",
"\"INVALID_VERSION\"",
")",
";",
"}",
"// If both a package.json and a manifest.json files exists in the addon",
"// root dir, raise an helpful error message that suggest to use web-ext instead.",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"join",
"(",
"rootPath",
",",
"\"manifest.json\"",
")",
")",
")",
"{",
"errors",
".",
"webextensionManifestFound",
"=",
"utils",
".",
"getErrorMessage",
"(",
"\"WEBEXT_ERROR\"",
")",
";",
"}",
"return",
"errors",
";",
"}"
]
| Takes a root directory for an addon, where the package.json lives,
and build options and validates the information available in the addon.
@param {Object} rootPath
@return {Object} | [
"Takes",
"a",
"root",
"directory",
"for",
"an",
"addon",
"where",
"the",
"package",
".",
"json",
"lives",
"and",
"build",
"options",
"and",
"validates",
"the",
"information",
"available",
"in",
"the",
"addon",
"."
]
| d6b104ed98e295b527d3cc743a1dbde98bed7baa | https://github.com/mozilla-jetpack/jetpack-validation/blob/d6b104ed98e295b527d3cc743a1dbde98bed7baa/index.js#L16-L56 |
41,665 | eface2face/meteor-htmljs | html.js | function (tagName) {
// HTMLTag is the per-tagName constructor of a HTML.Tag subclass
var HTMLTag = function (/*arguments*/) {
// Work with or without `new`. If not called with `new`,
// perform instantiation by recursively calling this constructor.
// We can't pass varargs, so pass no args.
var instance = (this instanceof HTML.Tag) ? this : new HTMLTag;
var i = 0;
var attrs = arguments.length && arguments[0];
if (attrs && (typeof attrs === 'object')) {
// Treat vanilla JS object as an attributes dictionary.
if (! HTML.isConstructedObject(attrs)) {
instance.attrs = attrs;
i++;
} else if (attrs instanceof HTML.Attrs) {
var array = attrs.value;
if (array.length === 1) {
instance.attrs = array[0];
} else if (array.length > 1) {
instance.attrs = array;
}
i++;
}
}
// If no children, don't create an array at all, use the prototype's
// (frozen, empty) array. This way we don't create an empty array
// every time someone creates a tag without `new` and this constructor
// calls itself with no arguments (above).
if (i < arguments.length)
instance.children = SLICE.call(arguments, i);
return instance;
};
HTMLTag.prototype = new HTML.Tag;
HTMLTag.prototype.constructor = HTMLTag;
HTMLTag.prototype.tagName = tagName;
return HTMLTag;
} | javascript | function (tagName) {
// HTMLTag is the per-tagName constructor of a HTML.Tag subclass
var HTMLTag = function (/*arguments*/) {
// Work with or without `new`. If not called with `new`,
// perform instantiation by recursively calling this constructor.
// We can't pass varargs, so pass no args.
var instance = (this instanceof HTML.Tag) ? this : new HTMLTag;
var i = 0;
var attrs = arguments.length && arguments[0];
if (attrs && (typeof attrs === 'object')) {
// Treat vanilla JS object as an attributes dictionary.
if (! HTML.isConstructedObject(attrs)) {
instance.attrs = attrs;
i++;
} else if (attrs instanceof HTML.Attrs) {
var array = attrs.value;
if (array.length === 1) {
instance.attrs = array[0];
} else if (array.length > 1) {
instance.attrs = array;
}
i++;
}
}
// If no children, don't create an array at all, use the prototype's
// (frozen, empty) array. This way we don't create an empty array
// every time someone creates a tag without `new` and this constructor
// calls itself with no arguments (above).
if (i < arguments.length)
instance.children = SLICE.call(arguments, i);
return instance;
};
HTMLTag.prototype = new HTML.Tag;
HTMLTag.prototype.constructor = HTMLTag;
HTMLTag.prototype.tagName = tagName;
return HTMLTag;
} | [
"function",
"(",
"tagName",
")",
"{",
"// HTMLTag is the per-tagName constructor of a HTML.Tag subclass",
"var",
"HTMLTag",
"=",
"function",
"(",
"/*arguments*/",
")",
"{",
"// Work with or without `new`. If not called with `new`,",
"// perform instantiation by recursively calling this constructor.",
"// We can't pass varargs, so pass no args.",
"var",
"instance",
"=",
"(",
"this",
"instanceof",
"HTML",
".",
"Tag",
")",
"?",
"this",
":",
"new",
"HTMLTag",
";",
"var",
"i",
"=",
"0",
";",
"var",
"attrs",
"=",
"arguments",
".",
"length",
"&&",
"arguments",
"[",
"0",
"]",
";",
"if",
"(",
"attrs",
"&&",
"(",
"typeof",
"attrs",
"===",
"'object'",
")",
")",
"{",
"// Treat vanilla JS object as an attributes dictionary.",
"if",
"(",
"!",
"HTML",
".",
"isConstructedObject",
"(",
"attrs",
")",
")",
"{",
"instance",
".",
"attrs",
"=",
"attrs",
";",
"i",
"++",
";",
"}",
"else",
"if",
"(",
"attrs",
"instanceof",
"HTML",
".",
"Attrs",
")",
"{",
"var",
"array",
"=",
"attrs",
".",
"value",
";",
"if",
"(",
"array",
".",
"length",
"===",
"1",
")",
"{",
"instance",
".",
"attrs",
"=",
"array",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"array",
".",
"length",
">",
"1",
")",
"{",
"instance",
".",
"attrs",
"=",
"array",
";",
"}",
"i",
"++",
";",
"}",
"}",
"// If no children, don't create an array at all, use the prototype's",
"// (frozen, empty) array. This way we don't create an empty array",
"// every time someone creates a tag without `new` and this constructor",
"// calls itself with no arguments (above).",
"if",
"(",
"i",
"<",
"arguments",
".",
"length",
")",
"instance",
".",
"children",
"=",
"SLICE",
".",
"call",
"(",
"arguments",
",",
"i",
")",
";",
"return",
"instance",
";",
"}",
";",
"HTMLTag",
".",
"prototype",
"=",
"new",
"HTML",
".",
"Tag",
";",
"HTMLTag",
".",
"prototype",
".",
"constructor",
"=",
"HTMLTag",
";",
"HTMLTag",
".",
"prototype",
".",
"tagName",
"=",
"tagName",
";",
"return",
"HTMLTag",
";",
"}"
]
| Given "p" create the function `HTML.P`. | [
"Given",
"p",
"create",
"the",
"function",
"HTML",
".",
"P",
"."
]
| 6f7c221af9a2153648c37d26721f90d1dad4561d | https://github.com/eface2face/meteor-htmljs/blob/6f7c221af9a2153648c37d26721f90d1dad4561d/html.js#L349-L390 |
|
41,666 | veo-labs/openveo-api | lib/errors/NotFoundError.js | NotFoundError | function NotFoundError(id) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperties(this, {
/**
* The resource id which hasn't been found.
*
* @property id
* @type Mixed
* @final
*/
id: {value: id},
/**
* Error message.
*
* @property message
* @type String
* @final
*/
message: {value: 'Could not found resource "' + id + '"', writable: true},
/**
* The error name.
*
* @property name
* @type String
* @final
*/
name: {value: 'NotFoundError', writable: true}
});
} | javascript | function NotFoundError(id) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperties(this, {
/**
* The resource id which hasn't been found.
*
* @property id
* @type Mixed
* @final
*/
id: {value: id},
/**
* Error message.
*
* @property message
* @type String
* @final
*/
message: {value: 'Could not found resource "' + id + '"', writable: true},
/**
* The error name.
*
* @property name
* @type String
* @final
*/
name: {value: 'NotFoundError', writable: true}
});
} | [
"function",
"NotFoundError",
"(",
"id",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"/**\n * The resource id which hasn't been found.\n *\n * @property id\n * @type Mixed\n * @final\n */",
"id",
":",
"{",
"value",
":",
"id",
"}",
",",
"/**\n * Error message.\n *\n * @property message\n * @type String\n * @final\n */",
"message",
":",
"{",
"value",
":",
"'Could not found resource \"'",
"+",
"id",
"+",
"'\"'",
",",
"writable",
":",
"true",
"}",
",",
"/**\n * The error name.\n *\n * @property name\n * @type String\n * @final\n */",
"name",
":",
"{",
"value",
":",
"'NotFoundError'",
",",
"writable",
":",
"true",
"}",
"}",
")",
";",
"}"
]
| Defines a NotFoundError to be thrown when a resource is not found.
var openVeoApi = require('@openveo/api');
throw new openVeoApi.errors.NotFoundError(42);
@class NotFoundError
@extends Error
@constructor
@param {String|Number} id The resource id which hasn't been found | [
"Defines",
"a",
"NotFoundError",
"to",
"be",
"thrown",
"when",
"a",
"resource",
"is",
"not",
"found",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/errors/NotFoundError.js#L20-L54 |
41,667 | veo-labs/openveo-api | lib/fileSystem.js | mkdirRecursive | function mkdirRecursive(directoryPath, callback) {
directoryPath = path.resolve(directoryPath);
// Try to create directory
fs.mkdir(directoryPath, function(error) {
if (error && error.code === 'EEXIST') {
// Can't create directory it already exists
// It may have been created by another loop
callback();
} else if (error && error.code === 'ENOENT') {
// Can't create directory, parent directory does not exist
// Create parent directory
mkdirRecursive(path.dirname(directoryPath), function(error) {
if (!error) {
// Now that parent directory is created, create requested directory
fs.mkdir(directoryPath, function(error) {
if (error && error.code === 'EEXIST') {
// Can't create directory it already exists
// It may have been created by another loop
callback();
} else
callback(error);
});
} else
callback(error);
});
} else
callback(error);
});
} | javascript | function mkdirRecursive(directoryPath, callback) {
directoryPath = path.resolve(directoryPath);
// Try to create directory
fs.mkdir(directoryPath, function(error) {
if (error && error.code === 'EEXIST') {
// Can't create directory it already exists
// It may have been created by another loop
callback();
} else if (error && error.code === 'ENOENT') {
// Can't create directory, parent directory does not exist
// Create parent directory
mkdirRecursive(path.dirname(directoryPath), function(error) {
if (!error) {
// Now that parent directory is created, create requested directory
fs.mkdir(directoryPath, function(error) {
if (error && error.code === 'EEXIST') {
// Can't create directory it already exists
// It may have been created by another loop
callback();
} else
callback(error);
});
} else
callback(error);
});
} else
callback(error);
});
} | [
"function",
"mkdirRecursive",
"(",
"directoryPath",
",",
"callback",
")",
"{",
"directoryPath",
"=",
"path",
".",
"resolve",
"(",
"directoryPath",
")",
";",
"// Try to create directory",
"fs",
".",
"mkdir",
"(",
"directoryPath",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
"&&",
"error",
".",
"code",
"===",
"'EEXIST'",
")",
"{",
"// Can't create directory it already exists",
"// It may have been created by another loop",
"callback",
"(",
")",
";",
"}",
"else",
"if",
"(",
"error",
"&&",
"error",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"// Can't create directory, parent directory does not exist",
"// Create parent directory",
"mkdirRecursive",
"(",
"path",
".",
"dirname",
"(",
"directoryPath",
")",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"!",
"error",
")",
"{",
"// Now that parent directory is created, create requested directory",
"fs",
".",
"mkdir",
"(",
"directoryPath",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
"&&",
"error",
".",
"code",
"===",
"'EEXIST'",
")",
"{",
"// Can't create directory it already exists",
"// It may have been created by another loop",
"callback",
"(",
")",
";",
"}",
"else",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
"else",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
"else",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
]
| Creates a directory recursively and asynchronously.
If parent directories do not exist, they will be automatically created.
@method mkdirRecursive
@private
@static
@async
@param {String} directoryPath The directory system path to create
@param {Function} callback The function to call when done
- **Error** The error if an error occurred, null otherwise | [
"Creates",
"a",
"directory",
"recursively",
"and",
"asynchronously",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/fileSystem.js#L32-L70 |
41,668 | veo-labs/openveo-api | lib/fileSystem.js | rmdirRecursive | function rmdirRecursive(directoryPath, callback) {
// Open directory
fs.readdir(directoryPath, function(error, resources) {
// Failed reading directory
if (error)
return callback(error);
var pendingResourceNumber = resources.length;
// No more pending resources, done for this directory
if (!pendingResourceNumber) {
// Remove directory
fs.rmdir(directoryPath, callback);
}
// Iterate through the list of resources in the directory
resources.forEach(function(resource) {
var resourcePath = path.join(directoryPath, resource);
// Get resource stats
fs.stat(resourcePath, function(error, stats) {
if (error)
return callback(error);
// Resource correspond to a directory
if (stats.isDirectory()) {
resources = rmdirRecursive(path.join(directoryPath, resource), function(error) {
if (error)
return callback(error);
pendingResourceNumber--;
if (!pendingResourceNumber)
fs.rmdir(directoryPath, callback);
});
} else {
// Resource does not correspond to a directory
// Mark resource as treated
// Remove file
fs.unlink(resourcePath, function(error) {
if (error)
return callback(error);
else {
pendingResourceNumber--;
if (!pendingResourceNumber)
fs.rmdir(directoryPath, callback);
}
});
}
});
});
});
} | javascript | function rmdirRecursive(directoryPath, callback) {
// Open directory
fs.readdir(directoryPath, function(error, resources) {
// Failed reading directory
if (error)
return callback(error);
var pendingResourceNumber = resources.length;
// No more pending resources, done for this directory
if (!pendingResourceNumber) {
// Remove directory
fs.rmdir(directoryPath, callback);
}
// Iterate through the list of resources in the directory
resources.forEach(function(resource) {
var resourcePath = path.join(directoryPath, resource);
// Get resource stats
fs.stat(resourcePath, function(error, stats) {
if (error)
return callback(error);
// Resource correspond to a directory
if (stats.isDirectory()) {
resources = rmdirRecursive(path.join(directoryPath, resource), function(error) {
if (error)
return callback(error);
pendingResourceNumber--;
if (!pendingResourceNumber)
fs.rmdir(directoryPath, callback);
});
} else {
// Resource does not correspond to a directory
// Mark resource as treated
// Remove file
fs.unlink(resourcePath, function(error) {
if (error)
return callback(error);
else {
pendingResourceNumber--;
if (!pendingResourceNumber)
fs.rmdir(directoryPath, callback);
}
});
}
});
});
});
} | [
"function",
"rmdirRecursive",
"(",
"directoryPath",
",",
"callback",
")",
"{",
"// Open directory",
"fs",
".",
"readdir",
"(",
"directoryPath",
",",
"function",
"(",
"error",
",",
"resources",
")",
"{",
"// Failed reading directory",
"if",
"(",
"error",
")",
"return",
"callback",
"(",
"error",
")",
";",
"var",
"pendingResourceNumber",
"=",
"resources",
".",
"length",
";",
"// No more pending resources, done for this directory",
"if",
"(",
"!",
"pendingResourceNumber",
")",
"{",
"// Remove directory",
"fs",
".",
"rmdir",
"(",
"directoryPath",
",",
"callback",
")",
";",
"}",
"// Iterate through the list of resources in the directory",
"resources",
".",
"forEach",
"(",
"function",
"(",
"resource",
")",
"{",
"var",
"resourcePath",
"=",
"path",
".",
"join",
"(",
"directoryPath",
",",
"resource",
")",
";",
"// Get resource stats",
"fs",
".",
"stat",
"(",
"resourcePath",
",",
"function",
"(",
"error",
",",
"stats",
")",
"{",
"if",
"(",
"error",
")",
"return",
"callback",
"(",
"error",
")",
";",
"// Resource correspond to a directory",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"resources",
"=",
"rmdirRecursive",
"(",
"path",
".",
"join",
"(",
"directoryPath",
",",
"resource",
")",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"return",
"callback",
"(",
"error",
")",
";",
"pendingResourceNumber",
"--",
";",
"if",
"(",
"!",
"pendingResourceNumber",
")",
"fs",
".",
"rmdir",
"(",
"directoryPath",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// Resource does not correspond to a directory",
"// Mark resource as treated",
"// Remove file",
"fs",
".",
"unlink",
"(",
"resourcePath",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"return",
"callback",
"(",
"error",
")",
";",
"else",
"{",
"pendingResourceNumber",
"--",
";",
"if",
"(",
"!",
"pendingResourceNumber",
")",
"fs",
".",
"rmdir",
"(",
"directoryPath",
",",
"callback",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Removes a directory and all its content recursively and asynchronously.
It is assumed that the directory exists.
@method rmdirRecursive
@private
@static
@async
@param {String} directoryPath Path of the directory to remove
@param {Function} callback The function to call when done
- **Error** The error if an error occurred, null otherwise | [
"Removes",
"a",
"directory",
"and",
"all",
"its",
"content",
"recursively",
"and",
"asynchronously",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/fileSystem.js#L85-L154 |
41,669 | veo-labs/openveo-api | lib/fileSystem.js | copyFile | function copyFile(sourceFilePath, destinationFilePath, callback) {
var onError = function(error) {
callback(error);
};
var safecopy = function(sourceFilePath, destinationFilePath, callback) {
if (sourceFilePath && destinationFilePath && callback) {
try {
var is = fs.createReadStream(sourceFilePath);
var os = fs.createWriteStream(destinationFilePath);
is.on('error', onError);
os.on('error', onError);
is.on('end', function() {
os.end();
});
os.on('finish', function() {
callback();
});
is.pipe(os);
} catch (e) {
callback(new Error(e.message));
}
} else callback(new Error('File path not defined'));
};
var pathDir = path.dirname(destinationFilePath);
this.mkdir(pathDir,
function(error) {
if (error) callback(error);
else safecopy(sourceFilePath, destinationFilePath, callback);
}
);
} | javascript | function copyFile(sourceFilePath, destinationFilePath, callback) {
var onError = function(error) {
callback(error);
};
var safecopy = function(sourceFilePath, destinationFilePath, callback) {
if (sourceFilePath && destinationFilePath && callback) {
try {
var is = fs.createReadStream(sourceFilePath);
var os = fs.createWriteStream(destinationFilePath);
is.on('error', onError);
os.on('error', onError);
is.on('end', function() {
os.end();
});
os.on('finish', function() {
callback();
});
is.pipe(os);
} catch (e) {
callback(new Error(e.message));
}
} else callback(new Error('File path not defined'));
};
var pathDir = path.dirname(destinationFilePath);
this.mkdir(pathDir,
function(error) {
if (error) callback(error);
else safecopy(sourceFilePath, destinationFilePath, callback);
}
);
} | [
"function",
"copyFile",
"(",
"sourceFilePath",
",",
"destinationFilePath",
",",
"callback",
")",
"{",
"var",
"onError",
"=",
"function",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
")",
";",
"}",
";",
"var",
"safecopy",
"=",
"function",
"(",
"sourceFilePath",
",",
"destinationFilePath",
",",
"callback",
")",
"{",
"if",
"(",
"sourceFilePath",
"&&",
"destinationFilePath",
"&&",
"callback",
")",
"{",
"try",
"{",
"var",
"is",
"=",
"fs",
".",
"createReadStream",
"(",
"sourceFilePath",
")",
";",
"var",
"os",
"=",
"fs",
".",
"createWriteStream",
"(",
"destinationFilePath",
")",
";",
"is",
".",
"on",
"(",
"'error'",
",",
"onError",
")",
";",
"os",
".",
"on",
"(",
"'error'",
",",
"onError",
")",
";",
"is",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"os",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"os",
".",
"on",
"(",
"'finish'",
",",
"function",
"(",
")",
"{",
"callback",
"(",
")",
";",
"}",
")",
";",
"is",
".",
"pipe",
"(",
"os",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"e",
".",
"message",
")",
")",
";",
"}",
"}",
"else",
"callback",
"(",
"new",
"Error",
"(",
"'File path not defined'",
")",
")",
";",
"}",
";",
"var",
"pathDir",
"=",
"path",
".",
"dirname",
"(",
"destinationFilePath",
")",
";",
"this",
".",
"mkdir",
"(",
"pathDir",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"callback",
"(",
"error",
")",
";",
"else",
"safecopy",
"(",
"sourceFilePath",
",",
"destinationFilePath",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
]
| Copies a file.
If directory does not exist it will be automatically created.
@method copyFile
@private
@static
@async
@param {String} sourceFilePath Path of the file
@param {String} destinationFilePath Final path of the file
@param {Function} callback The function to call when done
- **Error** The error if an error occurred, null otherwise | [
"Copies",
"a",
"file",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/fileSystem.js#L245-L282 |
41,670 | ofidj/fidj | .todo/miapp.tools.resize.js | removeResizeListener | function removeResizeListener(resizeListener) {
removeIdFromList(rootListener, resizeListener.id);
if (a4p.isDefined(listenersIndex[resizeListener.id])) {
delete listenersIndex[resizeListener.id];
}
if (a4p.isDefined(listenersIndex[resizeListener.name]) && (listenersIndex[resizeListener.name].id == resizeListener.id)) {
delete listenersIndex[resizeListener.name];
}
} | javascript | function removeResizeListener(resizeListener) {
removeIdFromList(rootListener, resizeListener.id);
if (a4p.isDefined(listenersIndex[resizeListener.id])) {
delete listenersIndex[resizeListener.id];
}
if (a4p.isDefined(listenersIndex[resizeListener.name]) && (listenersIndex[resizeListener.name].id == resizeListener.id)) {
delete listenersIndex[resizeListener.name];
}
} | [
"function",
"removeResizeListener",
"(",
"resizeListener",
")",
"{",
"removeIdFromList",
"(",
"rootListener",
",",
"resizeListener",
".",
"id",
")",
";",
"if",
"(",
"a4p",
".",
"isDefined",
"(",
"listenersIndex",
"[",
"resizeListener",
".",
"id",
"]",
")",
")",
"{",
"delete",
"listenersIndex",
"[",
"resizeListener",
".",
"id",
"]",
";",
"}",
"if",
"(",
"a4p",
".",
"isDefined",
"(",
"listenersIndex",
"[",
"resizeListener",
".",
"name",
"]",
")",
"&&",
"(",
"listenersIndex",
"[",
"resizeListener",
".",
"name",
"]",
".",
"id",
"==",
"resizeListener",
".",
"id",
")",
")",
"{",
"delete",
"listenersIndex",
"[",
"resizeListener",
".",
"name",
"]",
";",
"}",
"}"
]
| Remove a listener
@param resizeListener | [
"Remove",
"a",
"listener"
]
| e57ebece54ee68211d43802a8e0feeef098d3e36 | https://github.com/ofidj/fidj/blob/e57ebece54ee68211d43802a8e0feeef098d3e36/.todo/miapp.tools.resize.js#L282-L290 |
41,671 | ofidj/fidj | .todo/miapp.tools.aes.js | keyExpansion | function keyExpansion(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [�5.2]
var Nb = 4; // Number of columns (32-bit words) comprising the State. For this standard, Nb = 4.
var Nk = key.length / 4; // Number of 32-bit words comprising the Cipher Key. Nk = 4/6/8 for 128/192/256-bit keys
var Nr = Nk + 6; // Number of rounds. Nr = 10/12/14 for 128/192/256-bit keys
var trace;
var w = new Array(Nb * (Nr + 1));
var temp = new Array(4);
for (var i = 0; i < Nk; i++) {
var r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
w[i] = r;
/*
trace = new Array(4);
for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);
console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));
*/
}
for (var i = Nk; i < (Nb * (Nr + 1)); i++) {
w[i] = new Array(4);
for (var t = 0; t < 4; t++) temp[t] = w[i - 1][t];
if (i % Nk == 0) {
temp = subWord(rotWord(temp));
for (var t = 0; t < 4; t++) temp[t] ^= rCon[i / Nk][t];
} else if (Nk > 6 && i % Nk == 4) {
temp = subWord(temp);
}
for (var t = 0; t < 4; t++) w[i][t] = w[i - Nk][t] ^ temp[t];
/*
trace = new Array(4);
for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);
console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));
*/
}
return w;
} | javascript | function keyExpansion(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [�5.2]
var Nb = 4; // Number of columns (32-bit words) comprising the State. For this standard, Nb = 4.
var Nk = key.length / 4; // Number of 32-bit words comprising the Cipher Key. Nk = 4/6/8 for 128/192/256-bit keys
var Nr = Nk + 6; // Number of rounds. Nr = 10/12/14 for 128/192/256-bit keys
var trace;
var w = new Array(Nb * (Nr + 1));
var temp = new Array(4);
for (var i = 0; i < Nk; i++) {
var r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
w[i] = r;
/*
trace = new Array(4);
for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);
console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));
*/
}
for (var i = Nk; i < (Nb * (Nr + 1)); i++) {
w[i] = new Array(4);
for (var t = 0; t < 4; t++) temp[t] = w[i - 1][t];
if (i % Nk == 0) {
temp = subWord(rotWord(temp));
for (var t = 0; t < 4; t++) temp[t] ^= rCon[i / Nk][t];
} else if (Nk > 6 && i % Nk == 4) {
temp = subWord(temp);
}
for (var t = 0; t < 4; t++) w[i][t] = w[i - Nk][t] ^ temp[t];
/*
trace = new Array(4);
for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);
console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));
*/
}
return w;
} | [
"function",
"keyExpansion",
"(",
"key",
")",
"{",
"// generate Key Schedule (byte-array Nr+1 x Nb) from Key [�5.2]",
"var",
"Nb",
"=",
"4",
";",
"// Number of columns (32-bit words) comprising the State. For this standard, Nb = 4.",
"var",
"Nk",
"=",
"key",
".",
"length",
"/",
"4",
";",
"// Number of 32-bit words comprising the Cipher Key. Nk = 4/6/8 for 128/192/256-bit keys",
"var",
"Nr",
"=",
"Nk",
"+",
"6",
";",
"// Number of rounds. Nr = 10/12/14 for 128/192/256-bit keys",
"var",
"trace",
";",
"var",
"w",
"=",
"new",
"Array",
"(",
"Nb",
"*",
"(",
"Nr",
"+",
"1",
")",
")",
";",
"var",
"temp",
"=",
"new",
"Array",
"(",
"4",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"Nk",
";",
"i",
"++",
")",
"{",
"var",
"r",
"=",
"[",
"key",
"[",
"4",
"*",
"i",
"]",
",",
"key",
"[",
"4",
"*",
"i",
"+",
"1",
"]",
",",
"key",
"[",
"4",
"*",
"i",
"+",
"2",
"]",
",",
"key",
"[",
"4",
"*",
"i",
"+",
"3",
"]",
"]",
";",
"w",
"[",
"i",
"]",
"=",
"r",
";",
"/*\n trace = new Array(4);\n for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);\n console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));\n */",
"}",
"for",
"(",
"var",
"i",
"=",
"Nk",
";",
"i",
"<",
"(",
"Nb",
"*",
"(",
"Nr",
"+",
"1",
")",
")",
";",
"i",
"++",
")",
"{",
"w",
"[",
"i",
"]",
"=",
"new",
"Array",
"(",
"4",
")",
";",
"for",
"(",
"var",
"t",
"=",
"0",
";",
"t",
"<",
"4",
";",
"t",
"++",
")",
"temp",
"[",
"t",
"]",
"=",
"w",
"[",
"i",
"-",
"1",
"]",
"[",
"t",
"]",
";",
"if",
"(",
"i",
"%",
"Nk",
"==",
"0",
")",
"{",
"temp",
"=",
"subWord",
"(",
"rotWord",
"(",
"temp",
")",
")",
";",
"for",
"(",
"var",
"t",
"=",
"0",
";",
"t",
"<",
"4",
";",
"t",
"++",
")",
"temp",
"[",
"t",
"]",
"^=",
"rCon",
"[",
"i",
"/",
"Nk",
"]",
"[",
"t",
"]",
";",
"}",
"else",
"if",
"(",
"Nk",
">",
"6",
"&&",
"i",
"%",
"Nk",
"==",
"4",
")",
"{",
"temp",
"=",
"subWord",
"(",
"temp",
")",
";",
"}",
"for",
"(",
"var",
"t",
"=",
"0",
";",
"t",
"<",
"4",
";",
"t",
"++",
")",
"w",
"[",
"i",
"]",
"[",
"t",
"]",
"=",
"w",
"[",
"i",
"-",
"Nk",
"]",
"[",
"t",
"]",
"^",
"temp",
"[",
"t",
"]",
";",
"/*\n trace = new Array(4);\n for (var t = 0; t < 4; t++) trace[t] = String.fromCharCode(w[i][t]);\n console.log('w['+i+']='+fidj.Hex.encode(trace.join('')));\n */",
"}",
"return",
"w",
";",
"}"
]
| Perform Key Expansion to generate a Key Schedule
@param {Number[]} key Key as 16/24/32-byte array
@returns {Number[][]} Expanded key schedule as 2D byte-array (Nr+1 x Nb bytes) | [
"Perform",
"Key",
"Expansion",
"to",
"generate",
"a",
"Key",
"Schedule"
]
| e57ebece54ee68211d43802a8e0feeef098d3e36 | https://github.com/ofidj/fidj/blob/e57ebece54ee68211d43802a8e0feeef098d3e36/.todo/miapp.tools.aes.js#L430-L467 |
41,672 | jldec/pub-util | pub-util.js | slugify | function slugify(s, opts) {
opts = opts || {};
s = str(s);
if (!opts.mixedCase) { s = s.toLowerCase(); }
return s
.replace(/&/g, '-and-')
.replace(/\+/g, '-plus-')
.replace((opts.allow ?
new RegExp('[^-.a-zA-Z0-9' + _.escapeRegExp(opts.allow) + ']+', 'g') :
/[^-.a-zA-Z0-9]+/g), '-')
.replace(/--+/g, '-')
.replace(/^-(.)/, '$1')
.replace(/(.)-$/, '$1');
} | javascript | function slugify(s, opts) {
opts = opts || {};
s = str(s);
if (!opts.mixedCase) { s = s.toLowerCase(); }
return s
.replace(/&/g, '-and-')
.replace(/\+/g, '-plus-')
.replace((opts.allow ?
new RegExp('[^-.a-zA-Z0-9' + _.escapeRegExp(opts.allow) + ']+', 'g') :
/[^-.a-zA-Z0-9]+/g), '-')
.replace(/--+/g, '-')
.replace(/^-(.)/, '$1')
.replace(/(.)-$/, '$1');
} | [
"function",
"slugify",
"(",
"s",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"s",
"=",
"str",
"(",
"s",
")",
";",
"if",
"(",
"!",
"opts",
".",
"mixedCase",
")",
"{",
"s",
"=",
"s",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"s",
".",
"replace",
"(",
"/",
"&",
"/",
"g",
",",
"'-and-'",
")",
".",
"replace",
"(",
"/",
"\\+",
"/",
"g",
",",
"'-plus-'",
")",
".",
"replace",
"(",
"(",
"opts",
".",
"allow",
"?",
"new",
"RegExp",
"(",
"'[^-.a-zA-Z0-9'",
"+",
"_",
".",
"escapeRegExp",
"(",
"opts",
".",
"allow",
")",
"+",
"']+'",
",",
"'g'",
")",
":",
"/",
"[^-.a-zA-Z0-9]+",
"/",
"g",
")",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"--+",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"^-(.)",
"/",
",",
"'$1'",
")",
".",
"replace",
"(",
"/",
"(.)-$",
"/",
",",
"'$1'",
")",
";",
"}"
]
| convert names to slugified url strings containing only - . a-z 0-9 opts.noprefix => remove leading numbers opts.mixedCase => don't lowercase opts.allow => string of additional characters to allow | [
"convert",
"names",
"to",
"slugified",
"url",
"strings",
"containing",
"only",
"-",
".",
"a",
"-",
"z",
"0",
"-",
"9",
"opts",
".",
"noprefix",
"=",
">",
"remove",
"leading",
"numbers",
"opts",
".",
"mixedCase",
"=",
">",
"don",
"t",
"lowercase",
"opts",
".",
"allow",
"=",
">",
"string",
"of",
"additional",
"characters",
"to",
"allow"
]
| 18a95ec03e81a70cf34fce4a4467a5a6052d4fce | https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L123-L136 |
41,673 | jldec/pub-util | pub-util.js | unPrefix | function unPrefix(s, prefix) {
s = str(s);
if (!prefix) return s;
if (s.slice(0, prefix.length) === prefix) return s.slice(prefix.length);
return s;
} | javascript | function unPrefix(s, prefix) {
s = str(s);
if (!prefix) return s;
if (s.slice(0, prefix.length) === prefix) return s.slice(prefix.length);
return s;
} | [
"function",
"unPrefix",
"(",
"s",
",",
"prefix",
")",
"{",
"s",
"=",
"str",
"(",
"s",
")",
";",
"if",
"(",
"!",
"prefix",
")",
"return",
"s",
";",
"if",
"(",
"s",
".",
"slice",
"(",
"0",
",",
"prefix",
".",
"length",
")",
"===",
"prefix",
")",
"return",
"s",
".",
"slice",
"(",
"prefix",
".",
"length",
")",
";",
"return",
"s",
";",
"}"
]
| return string minus prefix, if the prefix matches | [
"return",
"string",
"minus",
"prefix",
"if",
"the",
"prefix",
"matches"
]
| 18a95ec03e81a70cf34fce4a4467a5a6052d4fce | https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L168-L173 |
41,674 | jldec/pub-util | pub-util.js | cap1 | function cap1(s) {
s = str(s);
return s.slice(0,1).toUpperCase() + s.slice(1);
} | javascript | function cap1(s) {
s = str(s);
return s.slice(0,1).toUpperCase() + s.slice(1);
} | [
"function",
"cap1",
"(",
"s",
")",
"{",
"s",
"=",
"str",
"(",
"s",
")",
";",
"return",
"s",
".",
"slice",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"s",
".",
"slice",
"(",
"1",
")",
";",
"}"
]
| return string with first letter capitalized | [
"return",
"string",
"with",
"first",
"letter",
"capitalized"
]
| 18a95ec03e81a70cf34fce4a4467a5a6052d4fce | https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L182-L185 |
41,675 | jldec/pub-util | pub-util.js | csv | function csv(arg) {
return ( _.isArray(arg) ? arg :
_.isObject(arg) ? _.values(arg) :
[arg]).join(', ');
} | javascript | function csv(arg) {
return ( _.isArray(arg) ? arg :
_.isObject(arg) ? _.values(arg) :
[arg]).join(', ');
} | [
"function",
"csv",
"(",
"arg",
")",
"{",
"return",
"(",
"_",
".",
"isArray",
"(",
"arg",
")",
"?",
"arg",
":",
"_",
".",
"isObject",
"(",
"arg",
")",
"?",
"_",
".",
"values",
"(",
"arg",
")",
":",
"[",
"arg",
"]",
")",
".",
"join",
"(",
"', '",
")",
";",
"}"
]
| turns a vector into a single string of comma-separated values | [
"turns",
"a",
"vector",
"into",
"a",
"single",
"string",
"of",
"comma",
"-",
"separated",
"values"
]
| 18a95ec03e81a70cf34fce4a4467a5a6052d4fce | https://github.com/jldec/pub-util/blob/18a95ec03e81a70cf34fce4a4467a5a6052d4fce/pub-util.js#L251-L255 |
41,676 | andrewscwei/gulp-prismic-mpa-builder | plugins/metadata.js | matchedMetadata | function matchedMetadata(file, metadata) {
for (let name in metadata) {
const data = metadata[name];
if (!data.pattern) return undefined;
if (minimatch(file, data.pattern)) return data.metadata;
}
return undefined;
} | javascript | function matchedMetadata(file, metadata) {
for (let name in metadata) {
const data = metadata[name];
if (!data.pattern) return undefined;
if (minimatch(file, data.pattern)) return data.metadata;
}
return undefined;
} | [
"function",
"matchedMetadata",
"(",
"file",
",",
"metadata",
")",
"{",
"for",
"(",
"let",
"name",
"in",
"metadata",
")",
"{",
"const",
"data",
"=",
"metadata",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"data",
".",
"pattern",
")",
"return",
"undefined",
";",
"if",
"(",
"minimatch",
"(",
"file",
",",
"data",
".",
"pattern",
")",
")",
"return",
"data",
".",
"metadata",
";",
"}",
"return",
"undefined",
";",
"}"
]
| Checks if the given file matches the pattern in the metadata object and
returns the metadata if there is a match.
@param {string} file - File path.
@param {Object} metadata - Object containing all metadata of all file
patterns.
@return {Object} Matching metadata. | [
"Checks",
"if",
"the",
"given",
"file",
"matches",
"the",
"pattern",
"in",
"the",
"metadata",
"object",
"and",
"returns",
"the",
"metadata",
"if",
"there",
"is",
"a",
"match",
"."
]
| c7fb9180de2aeca2657f0318c0befbd166a9bff5 | https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/plugins/metadata.js#L39-L46 |
41,677 | Runnable/api-client | lib/remove-url-path.js | removeUrlPath | function removeUrlPath (uri) {
var parsed = url.parse(uri);
if (parsed.host) {
delete parsed.pathname;
}
return url.format(parsed);
} | javascript | function removeUrlPath (uri) {
var parsed = url.parse(uri);
if (parsed.host) {
delete parsed.pathname;
}
return url.format(parsed);
} | [
"function",
"removeUrlPath",
"(",
"uri",
")",
"{",
"var",
"parsed",
"=",
"url",
".",
"parse",
"(",
"uri",
")",
";",
"if",
"(",
"parsed",
".",
"host",
")",
"{",
"delete",
"parsed",
".",
"pathname",
";",
"}",
"return",
"url",
".",
"format",
"(",
"parsed",
")",
";",
"}"
]
| remove path from url
@param {string} uri full url
@return {string} uriWithoutPath | [
"remove",
"path",
"from",
"url"
]
| e6089c4ed0b8c6ed383a82cbd50514e1e720f154 | https://github.com/Runnable/api-client/blob/e6089c4ed0b8c6ed383a82cbd50514e1e720f154/lib/remove-url-path.js#L10-L16 |
41,678 | mozilla/marketplace-gulp | plugins/imgurls-parse.js | transform | function transform(file) {
// Parses CSS file and turns it into a \n-separated img URLs.
var data = file.contents.toString('utf-8');
var matches = [];
var match;
while ((match = url_pattern.exec(data)) !== null) {
var url = match[1];
// Ensure it is an absolute URL (no relative URLs).
var has_origin = url.search(/(https?):|\/\//) === 0 || url[0] === '/';
if (!has_origin) {
var absolute_path = path.join(MKT_CONFIG.CSS_DEST_PATH, url);
url = '/' + path.relative('src', absolute_path);
}
if (img_urls.indexOf(url) === -1) {
matches.push(url);
img_urls.push(url);
}
}
return matches.join('\n');
} | javascript | function transform(file) {
// Parses CSS file and turns it into a \n-separated img URLs.
var data = file.contents.toString('utf-8');
var matches = [];
var match;
while ((match = url_pattern.exec(data)) !== null) {
var url = match[1];
// Ensure it is an absolute URL (no relative URLs).
var has_origin = url.search(/(https?):|\/\//) === 0 || url[0] === '/';
if (!has_origin) {
var absolute_path = path.join(MKT_CONFIG.CSS_DEST_PATH, url);
url = '/' + path.relative('src', absolute_path);
}
if (img_urls.indexOf(url) === -1) {
matches.push(url);
img_urls.push(url);
}
}
return matches.join('\n');
} | [
"function",
"transform",
"(",
"file",
")",
"{",
"// Parses CSS file and turns it into a \\n-separated img URLs.",
"var",
"data",
"=",
"file",
".",
"contents",
".",
"toString",
"(",
"'utf-8'",
")",
";",
"var",
"matches",
"=",
"[",
"]",
";",
"var",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"url_pattern",
".",
"exec",
"(",
"data",
")",
")",
"!==",
"null",
")",
"{",
"var",
"url",
"=",
"match",
"[",
"1",
"]",
";",
"// Ensure it is an absolute URL (no relative URLs).",
"var",
"has_origin",
"=",
"url",
".",
"search",
"(",
"/",
"(https?):|\\/\\/",
"/",
")",
"===",
"0",
"||",
"url",
"[",
"0",
"]",
"===",
"'/'",
";",
"if",
"(",
"!",
"has_origin",
")",
"{",
"var",
"absolute_path",
"=",
"path",
".",
"join",
"(",
"MKT_CONFIG",
".",
"CSS_DEST_PATH",
",",
"url",
")",
";",
"url",
"=",
"'/'",
"+",
"path",
".",
"relative",
"(",
"'src'",
",",
"absolute_path",
")",
";",
"}",
"if",
"(",
"img_urls",
".",
"indexOf",
"(",
"url",
")",
"===",
"-",
"1",
")",
"{",
"matches",
".",
"push",
"(",
"url",
")",
";",
"img_urls",
".",
"push",
"(",
"url",
")",
";",
"}",
"}",
"return",
"matches",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
]
| Keep track of duplicates. | [
"Keep",
"track",
"of",
"duplicates",
"."
]
| 6c0e405275342edf70bdf265670d64053d1d9a43 | https://github.com/mozilla/marketplace-gulp/blob/6c0e405275342edf70bdf265670d64053d1d9a43/plugins/imgurls-parse.js#L12-L35 |
41,679 | andrewscwei/gulp-prismic-mpa-builder | tasks/views.js | build | function build(config, locale, done) {
const shouldWatch = (util.env[`watch`] || util.env[`w`]) && (config.watch !== false);
if (locale && config.i18n && (config.i18n.locales instanceof Array) && (locale === config.i18n.locales[0]))
locale = undefined;
config = normalizeConfig(config, locale);
metalsmith(config.base || __dirname)
.clean(false)
.source(config.src)
.ignore(config.ignore)
.destination(config.dest)
.metadata(config.metadata.global)
.use(collections(config.collections))
.use(related(config.related))
.use((config.tags) ? tags(config.tags) : noop())
.use(pagination(config.pagination))
.use(metadata(config.metadata.collections))
.use(markdown(config.markdown))
.use(config.multilingual ? multilingual(locale) : noop())
.use(permalinks(config.permalinks))
.use(pathfinder(locale, config.i18n && config.i18n.locales))
.use(layouts(config.layouts))
.use(inPlace(config.inPlace))
.use((config.prism !== false) ? prism(config.prism, locale) : noop())
.use((config.mathjax !== false) ? mathjax(config.mathjax, locale) : noop())
.use(permalinks(config.permalinks))
.use(reporter(locale))
.build(function(err) {
if (err && shouldWatch) util.log(util.colors.blue(`[metalsmith]`), util.colors.red(err));
done(!shouldWatch && err);
});
} | javascript | function build(config, locale, done) {
const shouldWatch = (util.env[`watch`] || util.env[`w`]) && (config.watch !== false);
if (locale && config.i18n && (config.i18n.locales instanceof Array) && (locale === config.i18n.locales[0]))
locale = undefined;
config = normalizeConfig(config, locale);
metalsmith(config.base || __dirname)
.clean(false)
.source(config.src)
.ignore(config.ignore)
.destination(config.dest)
.metadata(config.metadata.global)
.use(collections(config.collections))
.use(related(config.related))
.use((config.tags) ? tags(config.tags) : noop())
.use(pagination(config.pagination))
.use(metadata(config.metadata.collections))
.use(markdown(config.markdown))
.use(config.multilingual ? multilingual(locale) : noop())
.use(permalinks(config.permalinks))
.use(pathfinder(locale, config.i18n && config.i18n.locales))
.use(layouts(config.layouts))
.use(inPlace(config.inPlace))
.use((config.prism !== false) ? prism(config.prism, locale) : noop())
.use((config.mathjax !== false) ? mathjax(config.mathjax, locale) : noop())
.use(permalinks(config.permalinks))
.use(reporter(locale))
.build(function(err) {
if (err && shouldWatch) util.log(util.colors.blue(`[metalsmith]`), util.colors.red(err));
done(!shouldWatch && err);
});
} | [
"function",
"build",
"(",
"config",
",",
"locale",
",",
"done",
")",
"{",
"const",
"shouldWatch",
"=",
"(",
"util",
".",
"env",
"[",
"`",
"`",
"]",
"||",
"util",
".",
"env",
"[",
"`",
"`",
"]",
")",
"&&",
"(",
"config",
".",
"watch",
"!==",
"false",
")",
";",
"if",
"(",
"locale",
"&&",
"config",
".",
"i18n",
"&&",
"(",
"config",
".",
"i18n",
".",
"locales",
"instanceof",
"Array",
")",
"&&",
"(",
"locale",
"===",
"config",
".",
"i18n",
".",
"locales",
"[",
"0",
"]",
")",
")",
"locale",
"=",
"undefined",
";",
"config",
"=",
"normalizeConfig",
"(",
"config",
",",
"locale",
")",
";",
"metalsmith",
"(",
"config",
".",
"base",
"||",
"__dirname",
")",
".",
"clean",
"(",
"false",
")",
".",
"source",
"(",
"config",
".",
"src",
")",
".",
"ignore",
"(",
"config",
".",
"ignore",
")",
".",
"destination",
"(",
"config",
".",
"dest",
")",
".",
"metadata",
"(",
"config",
".",
"metadata",
".",
"global",
")",
".",
"use",
"(",
"collections",
"(",
"config",
".",
"collections",
")",
")",
".",
"use",
"(",
"related",
"(",
"config",
".",
"related",
")",
")",
".",
"use",
"(",
"(",
"config",
".",
"tags",
")",
"?",
"tags",
"(",
"config",
".",
"tags",
")",
":",
"noop",
"(",
")",
")",
".",
"use",
"(",
"pagination",
"(",
"config",
".",
"pagination",
")",
")",
".",
"use",
"(",
"metadata",
"(",
"config",
".",
"metadata",
".",
"collections",
")",
")",
".",
"use",
"(",
"markdown",
"(",
"config",
".",
"markdown",
")",
")",
".",
"use",
"(",
"config",
".",
"multilingual",
"?",
"multilingual",
"(",
"locale",
")",
":",
"noop",
"(",
")",
")",
".",
"use",
"(",
"permalinks",
"(",
"config",
".",
"permalinks",
")",
")",
".",
"use",
"(",
"pathfinder",
"(",
"locale",
",",
"config",
".",
"i18n",
"&&",
"config",
".",
"i18n",
".",
"locales",
")",
")",
".",
"use",
"(",
"layouts",
"(",
"config",
".",
"layouts",
")",
")",
".",
"use",
"(",
"inPlace",
"(",
"config",
".",
"inPlace",
")",
")",
".",
"use",
"(",
"(",
"config",
".",
"prism",
"!==",
"false",
")",
"?",
"prism",
"(",
"config",
".",
"prism",
",",
"locale",
")",
":",
"noop",
"(",
")",
")",
".",
"use",
"(",
"(",
"config",
".",
"mathjax",
"!==",
"false",
")",
"?",
"mathjax",
"(",
"config",
".",
"mathjax",
",",
"locale",
")",
":",
"noop",
"(",
")",
")",
".",
"use",
"(",
"permalinks",
"(",
"config",
".",
"permalinks",
")",
")",
".",
"use",
"(",
"reporter",
"(",
"locale",
")",
")",
".",
"build",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"shouldWatch",
")",
"util",
".",
"log",
"(",
"util",
".",
"colors",
".",
"blue",
"(",
"`",
"`",
")",
",",
"util",
".",
"colors",
".",
"red",
"(",
"err",
")",
")",
";",
"done",
"(",
"!",
"shouldWatch",
"&&",
"err",
")",
";",
"}",
")",
";",
"}"
]
| Runs Metalsmith build on specified locale.
@param {Object} config
@param {string} locale
@param {Function} done | [
"Runs",
"Metalsmith",
"build",
"on",
"specified",
"locale",
"."
]
| c7fb9180de2aeca2657f0318c0befbd166a9bff5 | https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/tasks/views.js#L175-L208 |
41,680 | andrewscwei/gulp-prismic-mpa-builder | tasks/views.js | getDefaults | function getDefaults(context, options) {
const defaults = _.cloneDeep(DEFAULT_CONFIG);
const taskName = context && context.seq[0];
if (options.src) {
if (taskName)
defaults.watch = {
files: [$.glob(`**/*`, { base: $.glob(options.src, { base: options.base }), exts: FILE_EXTENSIONS })],
tasks: [taskName]
};
defaults.jade.basedir = $.glob(options.src, { base: options.base });
defaults.pug.basedir = $.glob(options.src, { base: options.base });
defaults.inPlace.engineOptions.basedir = $.glob(options.src, { base: options.base });
}
return defaults;
} | javascript | function getDefaults(context, options) {
const defaults = _.cloneDeep(DEFAULT_CONFIG);
const taskName = context && context.seq[0];
if (options.src) {
if (taskName)
defaults.watch = {
files: [$.glob(`**/*`, { base: $.glob(options.src, { base: options.base }), exts: FILE_EXTENSIONS })],
tasks: [taskName]
};
defaults.jade.basedir = $.glob(options.src, { base: options.base });
defaults.pug.basedir = $.glob(options.src, { base: options.base });
defaults.inPlace.engineOptions.basedir = $.glob(options.src, { base: options.base });
}
return defaults;
} | [
"function",
"getDefaults",
"(",
"context",
",",
"options",
")",
"{",
"const",
"defaults",
"=",
"_",
".",
"cloneDeep",
"(",
"DEFAULT_CONFIG",
")",
";",
"const",
"taskName",
"=",
"context",
"&&",
"context",
".",
"seq",
"[",
"0",
"]",
";",
"if",
"(",
"options",
".",
"src",
")",
"{",
"if",
"(",
"taskName",
")",
"defaults",
".",
"watch",
"=",
"{",
"files",
":",
"[",
"$",
".",
"glob",
"(",
"`",
"`",
",",
"{",
"base",
":",
"$",
".",
"glob",
"(",
"options",
".",
"src",
",",
"{",
"base",
":",
"options",
".",
"base",
"}",
")",
",",
"exts",
":",
"FILE_EXTENSIONS",
"}",
")",
"]",
",",
"tasks",
":",
"[",
"taskName",
"]",
"}",
";",
"defaults",
".",
"jade",
".",
"basedir",
"=",
"$",
".",
"glob",
"(",
"options",
".",
"src",
",",
"{",
"base",
":",
"options",
".",
"base",
"}",
")",
";",
"defaults",
".",
"pug",
".",
"basedir",
"=",
"$",
".",
"glob",
"(",
"options",
".",
"src",
",",
"{",
"base",
":",
"options",
".",
"base",
"}",
")",
";",
"defaults",
".",
"inPlace",
".",
"engineOptions",
".",
"basedir",
"=",
"$",
".",
"glob",
"(",
"options",
".",
"src",
",",
"{",
"base",
":",
"options",
".",
"base",
"}",
")",
";",
"}",
"return",
"defaults",
";",
"}"
]
| Gets preprocessed default config.
@param {Object} context
@param {Object} options
@return {Object} | [
"Gets",
"preprocessed",
"default",
"config",
"."
]
| c7fb9180de2aeca2657f0318c0befbd166a9bff5 | https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/tasks/views.js#L218-L235 |
41,681 | andrewscwei/gulp-prismic-mpa-builder | tasks/views.js | getConfig | function getConfig(context, options, extendsDefaults) {
const defaults = getDefaults(context, options);
const config = $.config(options, defaults, (typeof extendsDefaults !== `boolean`) || extendsDefaults);
config.metadata = { global: config.metadata, collections: {
'error-pages': {
pattern: `**/{500,404}.*`,
metadata: {
permalink: false
}
}
}};
return config;
} | javascript | function getConfig(context, options, extendsDefaults) {
const defaults = getDefaults(context, options);
const config = $.config(options, defaults, (typeof extendsDefaults !== `boolean`) || extendsDefaults);
config.metadata = { global: config.metadata, collections: {
'error-pages': {
pattern: `**/{500,404}.*`,
metadata: {
permalink: false
}
}
}};
return config;
} | [
"function",
"getConfig",
"(",
"context",
",",
"options",
",",
"extendsDefaults",
")",
"{",
"const",
"defaults",
"=",
"getDefaults",
"(",
"context",
",",
"options",
")",
";",
"const",
"config",
"=",
"$",
".",
"config",
"(",
"options",
",",
"defaults",
",",
"(",
"typeof",
"extendsDefaults",
"!==",
"`",
"`",
")",
"||",
"extendsDefaults",
")",
";",
"config",
".",
"metadata",
"=",
"{",
"global",
":",
"config",
".",
"metadata",
",",
"collections",
":",
"{",
"'error-pages'",
":",
"{",
"pattern",
":",
"`",
"`",
",",
"metadata",
":",
"{",
"permalink",
":",
"false",
"}",
"}",
"}",
"}",
";",
"return",
"config",
";",
"}"
]
| Gets postprocessed config.
@param {Object} context
@param {Object} options
@param {boolean} extendsDefaults
@return {Object} | [
"Gets",
"postprocessed",
"config",
"."
]
| c7fb9180de2aeca2657f0318c0befbd166a9bff5 | https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/tasks/views.js#L351-L363 |
41,682 | taskcluster/pulse-publisher | src/exchanges.js | function(entries, exchangePrefix, connectionFunc, options) {
events.EventEmitter.call(this);
assert(options.validator, 'options.validator must be provided');
this._conn = null;
this.__reconnectTimer = null;
this._connectionFunc = connectionFunc;
this._channel = null;
this._connecting = null;
this._entries = entries;
this._exchangePrefix = exchangePrefix;
this._options = options;
this._errCount = 0;
this._lastErr = Date.now();
this._lastTime = 0;
this._sleeping = null;
this._sleepingTimeout = null;
if (options.drain || options.component) {
console.log('taskcluster-lib-stats is now deprecated!\n' +
'Use the `monitor` option rather than `drain`.\n' +
'`monitor` should be an instance of taskcluster-lib-monitor.\n' +
'`component` is no longer needed. Prefix your `monitor` before use.');
}
var monitor = null;
if (options.monitor) {
monitor = options.monitor;
}
entries.forEach((entry) => {
this[entry.name] = (...args) => {
// Construct message and routing key from arguments
var message = entry.messageBuilder.apply(undefined, args);
common.validateMessage(this._options.rootUrl, this._options.serviceName, this._options.version,
options.validator, entry, message);
var routingKey = common.routingKeyToString(entry, entry.routingKeyBuilder.apply(undefined, args));
var CCs = entry.CCBuilder.apply(undefined, args);
assert(CCs instanceof Array, 'CCBuilder must return an array');
// Serialize message to buffer
var payload = new Buffer(JSON.stringify(message), 'utf8');
// Find exchange name
var exchange = exchangePrefix + entry.exchange;
// Log that we're publishing a message
debug('Publishing message on exchange: %s', exchange);
// Return promise
return this._connect().then(channel => {
return new Promise((accept, reject) => {
// Start timer
var start = null;
if (monitor) {
start = process.hrtime();
}
// Set a timeout
let done = false;
this._sleep12Seconds().then(() => {
if (!done) {
let err = new Error('publish message timed out after 12s');
this._handleError(err);
reject(err);
}
});
// Publish message
channel.publish(exchange, routingKey, payload, {
persistent: true,
contentType: 'application/json',
contentEncoding: 'utf-8',
CC: CCs,
}, (err, val) => {
// NOTE: many channel errors will not invoke this callback at all,
// hence the 12-second timeout
done = true;
if (monitor) {
var d = process.hrtime(start);
monitor.measure(exchange, d[0] * 1000 + d[1] / 1000000);
monitor.count(exchange);
}
// Handle errors
if (err) {
err.methodName = entry.name;
err.exchange = exchange;
err.routingKey = routingKey;
err.payload = payload;
err.ccRoutingKeys = CCs;
debug('Failed to publish message: %j and routingKey: %s, ' +
'with error: %s, %j', message, routingKey, err, err);
if (monitor) {
monitor.reportError(err);
}
return reject(err);
}
accept(val);
});
});
});
};
});
} | javascript | function(entries, exchangePrefix, connectionFunc, options) {
events.EventEmitter.call(this);
assert(options.validator, 'options.validator must be provided');
this._conn = null;
this.__reconnectTimer = null;
this._connectionFunc = connectionFunc;
this._channel = null;
this._connecting = null;
this._entries = entries;
this._exchangePrefix = exchangePrefix;
this._options = options;
this._errCount = 0;
this._lastErr = Date.now();
this._lastTime = 0;
this._sleeping = null;
this._sleepingTimeout = null;
if (options.drain || options.component) {
console.log('taskcluster-lib-stats is now deprecated!\n' +
'Use the `monitor` option rather than `drain`.\n' +
'`monitor` should be an instance of taskcluster-lib-monitor.\n' +
'`component` is no longer needed. Prefix your `monitor` before use.');
}
var monitor = null;
if (options.monitor) {
monitor = options.monitor;
}
entries.forEach((entry) => {
this[entry.name] = (...args) => {
// Construct message and routing key from arguments
var message = entry.messageBuilder.apply(undefined, args);
common.validateMessage(this._options.rootUrl, this._options.serviceName, this._options.version,
options.validator, entry, message);
var routingKey = common.routingKeyToString(entry, entry.routingKeyBuilder.apply(undefined, args));
var CCs = entry.CCBuilder.apply(undefined, args);
assert(CCs instanceof Array, 'CCBuilder must return an array');
// Serialize message to buffer
var payload = new Buffer(JSON.stringify(message), 'utf8');
// Find exchange name
var exchange = exchangePrefix + entry.exchange;
// Log that we're publishing a message
debug('Publishing message on exchange: %s', exchange);
// Return promise
return this._connect().then(channel => {
return new Promise((accept, reject) => {
// Start timer
var start = null;
if (monitor) {
start = process.hrtime();
}
// Set a timeout
let done = false;
this._sleep12Seconds().then(() => {
if (!done) {
let err = new Error('publish message timed out after 12s');
this._handleError(err);
reject(err);
}
});
// Publish message
channel.publish(exchange, routingKey, payload, {
persistent: true,
contentType: 'application/json',
contentEncoding: 'utf-8',
CC: CCs,
}, (err, val) => {
// NOTE: many channel errors will not invoke this callback at all,
// hence the 12-second timeout
done = true;
if (monitor) {
var d = process.hrtime(start);
monitor.measure(exchange, d[0] * 1000 + d[1] / 1000000);
monitor.count(exchange);
}
// Handle errors
if (err) {
err.methodName = entry.name;
err.exchange = exchange;
err.routingKey = routingKey;
err.payload = payload;
err.ccRoutingKeys = CCs;
debug('Failed to publish message: %j and routingKey: %s, ' +
'with error: %s, %j', message, routingKey, err, err);
if (monitor) {
monitor.reportError(err);
}
return reject(err);
}
accept(val);
});
});
});
};
});
} | [
"function",
"(",
"entries",
",",
"exchangePrefix",
",",
"connectionFunc",
",",
"options",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"assert",
"(",
"options",
".",
"validator",
",",
"'options.validator must be provided'",
")",
";",
"this",
".",
"_conn",
"=",
"null",
";",
"this",
".",
"__reconnectTimer",
"=",
"null",
";",
"this",
".",
"_connectionFunc",
"=",
"connectionFunc",
";",
"this",
".",
"_channel",
"=",
"null",
";",
"this",
".",
"_connecting",
"=",
"null",
";",
"this",
".",
"_entries",
"=",
"entries",
";",
"this",
".",
"_exchangePrefix",
"=",
"exchangePrefix",
";",
"this",
".",
"_options",
"=",
"options",
";",
"this",
".",
"_errCount",
"=",
"0",
";",
"this",
".",
"_lastErr",
"=",
"Date",
".",
"now",
"(",
")",
";",
"this",
".",
"_lastTime",
"=",
"0",
";",
"this",
".",
"_sleeping",
"=",
"null",
";",
"this",
".",
"_sleepingTimeout",
"=",
"null",
";",
"if",
"(",
"options",
".",
"drain",
"||",
"options",
".",
"component",
")",
"{",
"console",
".",
"log",
"(",
"'taskcluster-lib-stats is now deprecated!\\n'",
"+",
"'Use the `monitor` option rather than `drain`.\\n'",
"+",
"'`monitor` should be an instance of taskcluster-lib-monitor.\\n'",
"+",
"'`component` is no longer needed. Prefix your `monitor` before use.'",
")",
";",
"}",
"var",
"monitor",
"=",
"null",
";",
"if",
"(",
"options",
".",
"monitor",
")",
"{",
"monitor",
"=",
"options",
".",
"monitor",
";",
"}",
"entries",
".",
"forEach",
"(",
"(",
"entry",
")",
"=>",
"{",
"this",
"[",
"entry",
".",
"name",
"]",
"=",
"(",
"...",
"args",
")",
"=>",
"{",
"// Construct message and routing key from arguments",
"var",
"message",
"=",
"entry",
".",
"messageBuilder",
".",
"apply",
"(",
"undefined",
",",
"args",
")",
";",
"common",
".",
"validateMessage",
"(",
"this",
".",
"_options",
".",
"rootUrl",
",",
"this",
".",
"_options",
".",
"serviceName",
",",
"this",
".",
"_options",
".",
"version",
",",
"options",
".",
"validator",
",",
"entry",
",",
"message",
")",
";",
"var",
"routingKey",
"=",
"common",
".",
"routingKeyToString",
"(",
"entry",
",",
"entry",
".",
"routingKeyBuilder",
".",
"apply",
"(",
"undefined",
",",
"args",
")",
")",
";",
"var",
"CCs",
"=",
"entry",
".",
"CCBuilder",
".",
"apply",
"(",
"undefined",
",",
"args",
")",
";",
"assert",
"(",
"CCs",
"instanceof",
"Array",
",",
"'CCBuilder must return an array'",
")",
";",
"// Serialize message to buffer",
"var",
"payload",
"=",
"new",
"Buffer",
"(",
"JSON",
".",
"stringify",
"(",
"message",
")",
",",
"'utf8'",
")",
";",
"// Find exchange name",
"var",
"exchange",
"=",
"exchangePrefix",
"+",
"entry",
".",
"exchange",
";",
"// Log that we're publishing a message",
"debug",
"(",
"'Publishing message on exchange: %s'",
",",
"exchange",
")",
";",
"// Return promise",
"return",
"this",
".",
"_connect",
"(",
")",
".",
"then",
"(",
"channel",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"(",
"accept",
",",
"reject",
")",
"=>",
"{",
"// Start timer",
"var",
"start",
"=",
"null",
";",
"if",
"(",
"monitor",
")",
"{",
"start",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"}",
"// Set a timeout",
"let",
"done",
"=",
"false",
";",
"this",
".",
"_sleep12Seconds",
"(",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"done",
")",
"{",
"let",
"err",
"=",
"new",
"Error",
"(",
"'publish message timed out after 12s'",
")",
";",
"this",
".",
"_handleError",
"(",
"err",
")",
";",
"reject",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"// Publish message",
"channel",
".",
"publish",
"(",
"exchange",
",",
"routingKey",
",",
"payload",
",",
"{",
"persistent",
":",
"true",
",",
"contentType",
":",
"'application/json'",
",",
"contentEncoding",
":",
"'utf-8'",
",",
"CC",
":",
"CCs",
",",
"}",
",",
"(",
"err",
",",
"val",
")",
"=>",
"{",
"// NOTE: many channel errors will not invoke this callback at all,",
"// hence the 12-second timeout",
"done",
"=",
"true",
";",
"if",
"(",
"monitor",
")",
"{",
"var",
"d",
"=",
"process",
".",
"hrtime",
"(",
"start",
")",
";",
"monitor",
".",
"measure",
"(",
"exchange",
",",
"d",
"[",
"0",
"]",
"*",
"1000",
"+",
"d",
"[",
"1",
"]",
"/",
"1000000",
")",
";",
"monitor",
".",
"count",
"(",
"exchange",
")",
";",
"}",
"// Handle errors",
"if",
"(",
"err",
")",
"{",
"err",
".",
"methodName",
"=",
"entry",
".",
"name",
";",
"err",
".",
"exchange",
"=",
"exchange",
";",
"err",
".",
"routingKey",
"=",
"routingKey",
";",
"err",
".",
"payload",
"=",
"payload",
";",
"err",
".",
"ccRoutingKeys",
"=",
"CCs",
";",
"debug",
"(",
"'Failed to publish message: %j and routingKey: %s, '",
"+",
"'with error: %s, %j'",
",",
"message",
",",
"routingKey",
",",
"err",
",",
"err",
")",
";",
"if",
"(",
"monitor",
")",
"{",
"monitor",
".",
"reportError",
"(",
"err",
")",
";",
"}",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"accept",
"(",
"val",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
";",
"}",
")",
";",
"}"
]
| Class for publishing to a set of declared exchanges | [
"Class",
"for",
"publishing",
"to",
"a",
"set",
"of",
"declared",
"exchanges"
]
| a2f9afb48bf7b425a460d389e81999b8c9a5c038 | https://github.com/taskcluster/pulse-publisher/blob/a2f9afb48bf7b425a460d389e81999b8c9a5c038/src/exchanges.js#L25-L129 |
|
41,683 | taskcluster/pulse-publisher | src/exchanges.js | function(options) {
this._entries = [];
this._options = {
durableExchanges: true,
};
assert(options.serviceName, 'serviceName must be provided');
assert(options.projectName, 'projectName must be provided');
assert(options.version, 'version must be provided');
assert(options.title, 'title must be provided');
assert(options.description, 'description must be provided');
assert(!options.exchangePrefix, 'exchangePrefix is not allowed');
assert(!options.schemaPrefix, 'schemaPrefix is not allowed');
this.configure(options);
} | javascript | function(options) {
this._entries = [];
this._options = {
durableExchanges: true,
};
assert(options.serviceName, 'serviceName must be provided');
assert(options.projectName, 'projectName must be provided');
assert(options.version, 'version must be provided');
assert(options.title, 'title must be provided');
assert(options.description, 'description must be provided');
assert(!options.exchangePrefix, 'exchangePrefix is not allowed');
assert(!options.schemaPrefix, 'schemaPrefix is not allowed');
this.configure(options);
} | [
"function",
"(",
"options",
")",
"{",
"this",
".",
"_entries",
"=",
"[",
"]",
";",
"this",
".",
"_options",
"=",
"{",
"durableExchanges",
":",
"true",
",",
"}",
";",
"assert",
"(",
"options",
".",
"serviceName",
",",
"'serviceName must be provided'",
")",
";",
"assert",
"(",
"options",
".",
"projectName",
",",
"'projectName must be provided'",
")",
";",
"assert",
"(",
"options",
".",
"version",
",",
"'version must be provided'",
")",
";",
"assert",
"(",
"options",
".",
"title",
",",
"'title must be provided'",
")",
";",
"assert",
"(",
"options",
".",
"description",
",",
"'description must be provided'",
")",
";",
"assert",
"(",
"!",
"options",
".",
"exchangePrefix",
",",
"'exchangePrefix is not allowed'",
")",
";",
"assert",
"(",
"!",
"options",
".",
"schemaPrefix",
",",
"'schemaPrefix is not allowed'",
")",
";",
"this",
".",
"configure",
"(",
"options",
")",
";",
"}"
]
| Create a collection of exchange declarations
options:
{
serviceName: 'foo',
version: 'v1',
title: "Title of documentation page",
description: "Description in markdown",
durableExchanges: true || false // If exchanges are durable (default true)
} | [
"Create",
"a",
"collection",
"of",
"exchange",
"declarations"
]
| a2f9afb48bf7b425a460d389e81999b8c9a5c038 | https://github.com/taskcluster/pulse-publisher/blob/a2f9afb48bf7b425a460d389e81999b8c9a5c038/src/exchanges.js#L310-L323 |
|
41,684 | LeisureLink/magicbus | lib/config/index.js | LoggerConfiguration | function LoggerConfiguration(logger) {
/**
* Override default logger instance with the provided logger
* @public
* @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function
*/
function useLogger(loggerOrFactoryFunction) {
cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction');
if (typeof(loggerOrFactoryFunction) === 'function') {
logger = loggerOrFactoryFunction();
}
else {
logger = loggerOrFactoryFunction;
}
};
/**
* Gets the default or overridden logger
* @public
*/
function getParams() {
return { logger };
}
return {
/**
* Gets the target for a configurator function to run on
* @public
*/
getTarget: function() {
return { useLogger: useLogger };
},
getParams: getParams
};
} | javascript | function LoggerConfiguration(logger) {
/**
* Override default logger instance with the provided logger
* @public
* @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function
*/
function useLogger(loggerOrFactoryFunction) {
cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction');
if (typeof(loggerOrFactoryFunction) === 'function') {
logger = loggerOrFactoryFunction();
}
else {
logger = loggerOrFactoryFunction;
}
};
/**
* Gets the default or overridden logger
* @public
*/
function getParams() {
return { logger };
}
return {
/**
* Gets the target for a configurator function to run on
* @public
*/
getTarget: function() {
return { useLogger: useLogger };
},
getParams: getParams
};
} | [
"function",
"LoggerConfiguration",
"(",
"logger",
")",
"{",
"/**\n * Override default logger instance with the provided logger\n * @public\n * @param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function\n */",
"function",
"useLogger",
"(",
"loggerOrFactoryFunction",
")",
"{",
"cutil",
".",
"assertObjectOrFunction",
"(",
"loggerOrFactoryFunction",
",",
"'loggerOrFactoryFunction'",
")",
";",
"if",
"(",
"typeof",
"(",
"loggerOrFactoryFunction",
")",
"===",
"'function'",
")",
"{",
"logger",
"=",
"loggerOrFactoryFunction",
"(",
")",
";",
"}",
"else",
"{",
"logger",
"=",
"loggerOrFactoryFunction",
";",
"}",
"}",
";",
"/**\n * Gets the default or overridden logger\n * @public\n */",
"function",
"getParams",
"(",
")",
"{",
"return",
"{",
"logger",
"}",
";",
"}",
"return",
"{",
"/**\n * Gets the target for a configurator function to run on\n * @public\n */",
"getTarget",
":",
"function",
"(",
")",
"{",
"return",
"{",
"useLogger",
":",
"useLogger",
"}",
";",
"}",
",",
"getParams",
":",
"getParams",
"}",
";",
"}"
]
| Provides logger configurability
@private
@param {Object} logger - the default logger | [
"Provides",
"logger",
"configurability"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L28-L63 |
41,685 | LeisureLink/magicbus | lib/config/index.js | useLogger | function useLogger(loggerOrFactoryFunction) {
cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction');
if (typeof(loggerOrFactoryFunction) === 'function') {
logger = loggerOrFactoryFunction();
}
else {
logger = loggerOrFactoryFunction;
}
} | javascript | function useLogger(loggerOrFactoryFunction) {
cutil.assertObjectOrFunction(loggerOrFactoryFunction, 'loggerOrFactoryFunction');
if (typeof(loggerOrFactoryFunction) === 'function') {
logger = loggerOrFactoryFunction();
}
else {
logger = loggerOrFactoryFunction;
}
} | [
"function",
"useLogger",
"(",
"loggerOrFactoryFunction",
")",
"{",
"cutil",
".",
"assertObjectOrFunction",
"(",
"loggerOrFactoryFunction",
",",
"'loggerOrFactoryFunction'",
")",
";",
"if",
"(",
"typeof",
"(",
"loggerOrFactoryFunction",
")",
"===",
"'function'",
")",
"{",
"logger",
"=",
"loggerOrFactoryFunction",
"(",
")",
";",
"}",
"else",
"{",
"logger",
"=",
"loggerOrFactoryFunction",
";",
"}",
"}"
]
| Override default logger instance with the provided logger
@public
@param {Object|Function} loggerOrFactoryFunction - the logger instance or factory function | [
"Override",
"default",
"logger",
"instance",
"with",
"the",
"provided",
"logger"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L34-L43 |
41,686 | LeisureLink/magicbus | lib/config/index.js | getParams | function getParams(configFunc, configurator) {
assert.optionalFunc(configurator, 'configurator');
let config = configFunc();
let loggerConfig = LoggerConfiguration(logger);
if (configurator) {
let configTarget = _.assign({}, config.getTarget(), loggerConfig.getTarget());
configurator(configTarget);
}
return _.assign({}, config.getParams(), loggerConfig.getParams());
} | javascript | function getParams(configFunc, configurator) {
assert.optionalFunc(configurator, 'configurator');
let config = configFunc();
let loggerConfig = LoggerConfiguration(logger);
if (configurator) {
let configTarget = _.assign({}, config.getTarget(), loggerConfig.getTarget());
configurator(configTarget);
}
return _.assign({}, config.getParams(), loggerConfig.getParams());
} | [
"function",
"getParams",
"(",
"configFunc",
",",
"configurator",
")",
"{",
"assert",
".",
"optionalFunc",
"(",
"configurator",
",",
"'configurator'",
")",
";",
"let",
"config",
"=",
"configFunc",
"(",
")",
";",
"let",
"loggerConfig",
"=",
"LoggerConfiguration",
"(",
"logger",
")",
";",
"if",
"(",
"configurator",
")",
"{",
"let",
"configTarget",
"=",
"_",
".",
"assign",
"(",
"{",
"}",
",",
"config",
".",
"getTarget",
"(",
")",
",",
"loggerConfig",
".",
"getTarget",
"(",
")",
")",
";",
"configurator",
"(",
"configTarget",
")",
";",
"}",
"return",
"_",
".",
"assign",
"(",
"{",
"}",
",",
"config",
".",
"getParams",
"(",
")",
",",
"loggerConfig",
".",
"getParams",
"(",
")",
")",
";",
"}"
]
| Gets the parameters for the construction of the instance
@private
@param {Function} configFunc - the configuration function for the instance
@param {Function} configFunc - the configuration function for the instance | [
"Gets",
"the",
"parameters",
"for",
"the",
"construction",
"of",
"the",
"instance"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L93-L102 |
41,687 | LeisureLink/magicbus | lib/config/index.js | createTopology | function createTopology(connectionInfo, logger) {
let options = connectionInfo;
if (typeof(connectionInfo) === 'string') {
let parsed = url.parse(connectionInfo);
options = {
server: parsed.hostname,
port: parsed.port || '5672',
protocol: parsed.protocol || 'amqp://',
user: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[0]) : 'guest',
pass: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[1]) : 'guest',
vhost: parsed.path && parsed.path.substring(1)
};
}
let connection = Connection(options, logger.withNamespace('connection'));
let topology = Topology(connection, logger.withNamespace('topology'));
return topology;
} | javascript | function createTopology(connectionInfo, logger) {
let options = connectionInfo;
if (typeof(connectionInfo) === 'string') {
let parsed = url.parse(connectionInfo);
options = {
server: parsed.hostname,
port: parsed.port || '5672',
protocol: parsed.protocol || 'amqp://',
user: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[0]) : 'guest',
pass: parsed.auth && parsed.auth.indexOf(':') !== -1 ? unescape(parsed.auth.split(':')[1]) : 'guest',
vhost: parsed.path && parsed.path.substring(1)
};
}
let connection = Connection(options, logger.withNamespace('connection'));
let topology = Topology(connection, logger.withNamespace('topology'));
return topology;
} | [
"function",
"createTopology",
"(",
"connectionInfo",
",",
"logger",
")",
"{",
"let",
"options",
"=",
"connectionInfo",
";",
"if",
"(",
"typeof",
"(",
"connectionInfo",
")",
"===",
"'string'",
")",
"{",
"let",
"parsed",
"=",
"url",
".",
"parse",
"(",
"connectionInfo",
")",
";",
"options",
"=",
"{",
"server",
":",
"parsed",
".",
"hostname",
",",
"port",
":",
"parsed",
".",
"port",
"||",
"'5672'",
",",
"protocol",
":",
"parsed",
".",
"protocol",
"||",
"'amqp://'",
",",
"user",
":",
"parsed",
".",
"auth",
"&&",
"parsed",
".",
"auth",
".",
"indexOf",
"(",
"':'",
")",
"!==",
"-",
"1",
"?",
"unescape",
"(",
"parsed",
".",
"auth",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
")",
":",
"'guest'",
",",
"pass",
":",
"parsed",
".",
"auth",
"&&",
"parsed",
".",
"auth",
".",
"indexOf",
"(",
"':'",
")",
"!==",
"-",
"1",
"?",
"unescape",
"(",
"parsed",
".",
"auth",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
")",
":",
"'guest'",
",",
"vhost",
":",
"parsed",
".",
"path",
"&&",
"parsed",
".",
"path",
".",
"substring",
"(",
"1",
")",
"}",
";",
"}",
"let",
"connection",
"=",
"Connection",
"(",
"options",
",",
"logger",
".",
"withNamespace",
"(",
"'connection'",
")",
")",
";",
"let",
"topology",
"=",
"Topology",
"(",
"connection",
",",
"logger",
".",
"withNamespace",
"(",
"'topology'",
")",
")",
";",
"return",
"topology",
";",
"}"
]
| Create a Topology instance, for use in broker or binder
@public
@param {Object|String} connectionInfo - connection info to be passed to amqplib's connect method (required)
@param {String} connectionInfo.name - connection name (for logging purposes)
@param {String} connectionInfo.server - list of servers to connect to, separated by ','
@param {String} connectionInfo.port - list of ports to connect to, separated by ','. Must have the same number of entries as connectionInfo.server
@param {Number} connectionInfo.heartbeat - heartbeat timer - defaults to 30 seconds
@param {String} connectionInfo.protocol - connection protocol - defaults to amqp:// or amqps://
@param {String} connectionInfo.user - user name - defaults to guest
@param {String} connectionInfo.pass - password - defaults to guest
@param {String} connectionInfo.vhost - vhost to connect to - defaults to '/'
@param {String} connectionInfo.timeout - connection timeout
@param {String} connectionInfo.certPath - certificate file path (for SSL)
@param {String} connectionInfo.keyPath - key file path (for SSL)
@param {String} connectionInfo.caPath - certificate file path(s), separated by ',' (for SSL)
@param {String} connectionInfo.passphrase - certificate passphrase (for SSL)
@param {String} connectionInfo.pfxPath - pfx file path (for SSL)
@param {Object} logger - the logger to use when creating the connection & topology
/* eslint-disable complexity | [
"Create",
"a",
"Topology",
"instance",
"for",
"use",
"in",
"broker",
"or",
"binder"
]
| 0370c38ebb8c7917cfd3894263d734aefc2d3d29 | https://github.com/LeisureLink/magicbus/blob/0370c38ebb8c7917cfd3894263d734aefc2d3d29/lib/config/index.js#L141-L157 |
41,688 | andrewscwei/gulp-prismic-mpa-builder | index.js | generatePrismicDocuments | function generatePrismicDocuments(config) {
return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken })
.then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`)))))
.then(res => {
util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`);
if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`));
const documents = prismic.reduce(res.results, false, config);
// Populate config metadata with retrieved documents.
if (!config.metadata) config.metadata = { $data: {} };
_.merge(config.metadata.$data, documents);
for (let docType in documents) {
const c = _.get(config, `collections.${docType}`);
if (c && c.permalink) {
const subdir = `.prismic/${docType}`;
const dir = path.join(path.join(config.base || ``, config.src || ``), subdir);
c.pattern = path.join(subdir, `**/*`);
documents[docType].forEach(doc => {
const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`;
const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`]));
fs.mkdirsSync(dir);
fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`);
});
}
}
return;
});
} | javascript | function generatePrismicDocuments(config) {
return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken })
.then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`)))))
.then(res => {
util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`);
if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`));
const documents = prismic.reduce(res.results, false, config);
// Populate config metadata with retrieved documents.
if (!config.metadata) config.metadata = { $data: {} };
_.merge(config.metadata.$data, documents);
for (let docType in documents) {
const c = _.get(config, `collections.${docType}`);
if (c && c.permalink) {
const subdir = `.prismic/${docType}`;
const dir = path.join(path.join(config.base || ``, config.src || ``), subdir);
c.pattern = path.join(subdir, `**/*`);
documents[docType].forEach(doc => {
const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`;
const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`]));
fs.mkdirsSync(dir);
fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`);
});
}
}
return;
});
} | [
"function",
"generatePrismicDocuments",
"(",
"config",
")",
"{",
"return",
"prismic",
".",
"getAPI",
"(",
"config",
".",
"apiEndpoint",
",",
"{",
"accessToken",
":",
"config",
".",
"accessToken",
"}",
")",
".",
"then",
"(",
"api",
"=>",
"(",
"prismic",
".",
"getEverything",
"(",
"api",
",",
"null",
",",
"`",
"`",
",",
"_",
".",
"flatMap",
"(",
"config",
".",
"collections",
",",
"(",
"val",
",",
"key",
")",
"=>",
"(",
"`",
"${",
"key",
"}",
"${",
"val",
".",
"sortBy",
"}",
"${",
"val",
".",
"reverse",
"?",
"`",
"`",
":",
"`",
"`",
"}",
"`",
")",
")",
")",
")",
")",
".",
"then",
"(",
"res",
"=>",
"{",
"util",
".",
"log",
"(",
"util",
".",
"colors",
".",
"blue",
"(",
"`",
"`",
")",
",",
"`",
"${",
"res",
".",
"results",
".",
"length",
"}",
"`",
")",
";",
"if",
"(",
"res",
".",
"results",
".",
"length",
")",
"res",
".",
"results",
".",
"forEach",
"(",
"doc",
"=>",
"util",
".",
"log",
"(",
"util",
".",
"colors",
".",
"blue",
"(",
"`",
"`",
")",
",",
"`",
"${",
"doc",
".",
"type",
"}",
"${",
"doc",
".",
"slug",
"}",
"`",
")",
")",
";",
"const",
"documents",
"=",
"prismic",
".",
"reduce",
"(",
"res",
".",
"results",
",",
"false",
",",
"config",
")",
";",
"// Populate config metadata with retrieved documents.",
"if",
"(",
"!",
"config",
".",
"metadata",
")",
"config",
".",
"metadata",
"=",
"{",
"$data",
":",
"{",
"}",
"}",
";",
"_",
".",
"merge",
"(",
"config",
".",
"metadata",
".",
"$data",
",",
"documents",
")",
";",
"for",
"(",
"let",
"docType",
"in",
"documents",
")",
"{",
"const",
"c",
"=",
"_",
".",
"get",
"(",
"config",
",",
"`",
"${",
"docType",
"}",
"`",
")",
";",
"if",
"(",
"c",
"&&",
"c",
".",
"permalink",
")",
"{",
"const",
"subdir",
"=",
"`",
"${",
"docType",
"}",
"`",
";",
"const",
"dir",
"=",
"path",
".",
"join",
"(",
"path",
".",
"join",
"(",
"config",
".",
"base",
"||",
"`",
"`",
",",
"config",
".",
"src",
"||",
"`",
"`",
")",
",",
"subdir",
")",
";",
"c",
".",
"pattern",
"=",
"path",
".",
"join",
"(",
"subdir",
",",
"`",
"`",
")",
";",
"documents",
"[",
"docType",
"]",
".",
"forEach",
"(",
"doc",
"=>",
"{",
"const",
"filename",
"=",
"`",
"${",
"doc",
".",
"uid",
"||",
"_",
".",
"kebabCase",
"(",
"doc",
".",
"slug",
")",
"}",
"`",
";",
"const",
"frontMatter",
"=",
"yaml",
".",
"stringify",
"(",
"_",
".",
"omit",
"(",
"doc",
",",
"[",
"`",
"`",
",",
"`",
"`",
"]",
")",
")",
";",
"fs",
".",
"mkdirsSync",
"(",
"dir",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"filename",
")",
",",
"`",
"\\n",
"${",
"frontMatter",
"}",
"\\n",
"`",
")",
";",
"}",
")",
";",
"}",
"}",
"return",
";",
"}",
")",
";",
"}"
]
| Generates HTML files with YAML front matters from Prismic documents.
@param {Object} config - Config object.
@return {Promise} - Promise with no fulfillment value. | [
"Generates",
"HTML",
"files",
"with",
"YAML",
"front",
"matters",
"from",
"Prismic",
"documents",
"."
]
| c7fb9180de2aeca2657f0318c0befbd166a9bff5 | https://github.com/andrewscwei/gulp-prismic-mpa-builder/blob/c7fb9180de2aeca2657f0318c0befbd166a9bff5/index.js#L276-L307 |
41,689 | veo-labs/openveo-api | lib/imageProcessor.js | function(linesImagesPaths, linePath, lineWidth, lineHeight, horizontally, lineQuality) {
return function(callback) {
self.aggregate(
linesImagesPaths,
linePath,
lineWidth,
lineHeight,
horizontally,
lineQuality,
temporaryDirectoryPath,
callback
);
};
} | javascript | function(linesImagesPaths, linePath, lineWidth, lineHeight, horizontally, lineQuality) {
return function(callback) {
self.aggregate(
linesImagesPaths,
linePath,
lineWidth,
lineHeight,
horizontally,
lineQuality,
temporaryDirectoryPath,
callback
);
};
} | [
"function",
"(",
"linesImagesPaths",
",",
"linePath",
",",
"lineWidth",
",",
"lineHeight",
",",
"horizontally",
",",
"lineQuality",
")",
"{",
"return",
"function",
"(",
"callback",
")",
"{",
"self",
".",
"aggregate",
"(",
"linesImagesPaths",
",",
"linePath",
",",
"lineWidth",
",",
"lineHeight",
",",
"horizontally",
",",
"lineQuality",
",",
"temporaryDirectoryPath",
",",
"callback",
")",
";",
"}",
";",
"}"
]
| Creates sprite lines by aggregating images.
@param {Array} linesImagesPaths The list of images paths to aggregate
@param {String} linePath The path of the image to generate
@param {Number} lineWidth The line width (in px)
@param {Number} lineHeight The line height (in px)
@param {Boolean} horizontally true to create an horizontal line, false to create a vertical line
@param {Number} lineQuality The line quality from 0 to 100 (default to 90 with 100 the best)
@return {Function} The async function of the operation | [
"Creates",
"sprite",
"lines",
"by",
"aggregating",
"images",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L258-L271 |
|
41,690 | veo-labs/openveo-api | lib/imageProcessor.js | function(callback) {
if (imagesPaths.length >= numberOfColumns * numberOfRows) return callback();
var transparentImagePath = path.join(temporaryDirectoryPath, 'transparent.png');
gm(width, height, '#00000000').write(transparentImagePath, function(error) {
// Add as many as needed transparent images to the list of images
var totalMissingImages = numberOfColumns * numberOfRows - imagesPaths.length;
for (var i = 0; i < totalMissingImages; i++)
imagesPaths.push(transparentImagePath);
callback(error);
});
} | javascript | function(callback) {
if (imagesPaths.length >= numberOfColumns * numberOfRows) return callback();
var transparentImagePath = path.join(temporaryDirectoryPath, 'transparent.png');
gm(width, height, '#00000000').write(transparentImagePath, function(error) {
// Add as many as needed transparent images to the list of images
var totalMissingImages = numberOfColumns * numberOfRows - imagesPaths.length;
for (var i = 0; i < totalMissingImages; i++)
imagesPaths.push(transparentImagePath);
callback(error);
});
} | [
"function",
"(",
"callback",
")",
"{",
"if",
"(",
"imagesPaths",
".",
"length",
">=",
"numberOfColumns",
"*",
"numberOfRows",
")",
"return",
"callback",
"(",
")",
";",
"var",
"transparentImagePath",
"=",
"path",
".",
"join",
"(",
"temporaryDirectoryPath",
",",
"'transparent.png'",
")",
";",
"gm",
"(",
"width",
",",
"height",
",",
"'#00000000'",
")",
".",
"write",
"(",
"transparentImagePath",
",",
"function",
"(",
"error",
")",
"{",
"// Add as many as needed transparent images to the list of images",
"var",
"totalMissingImages",
"=",
"numberOfColumns",
"*",
"numberOfRows",
"-",
"imagesPaths",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"totalMissingImages",
";",
"i",
"++",
")",
"imagesPaths",
".",
"push",
"(",
"transparentImagePath",
")",
";",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
]
| Complete the grid defined by numberOfColumns and numberOfRows using transparent images if needed | [
"Complete",
"the",
"grid",
"defined",
"by",
"numberOfColumns",
"and",
"numberOfRows",
"using",
"transparent",
"images",
"if",
"needed"
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L290-L304 |
|
41,691 | veo-labs/openveo-api | lib/imageProcessor.js | function(callback) {
var asyncFunctions = [];
for (var i = 0; i < numberOfRows; i++) {
var rowsImagesPaths = imagesPaths.slice(i * numberOfColumns, i * numberOfColumns + numberOfColumns);
var lineWidth = width;
var lineHeight = height;
var linePath = path.join(temporaryDirectoryPath, 'line-' + i);
linesPaths.push(linePath);
asyncFunctions.push(createLine(rowsImagesPaths, linePath, lineWidth, lineHeight, true, 100));
}
async.parallel(asyncFunctions, function(error, results) {
if (error) return callback(error);
results.forEach(function(line) {
line.forEach(function(image) {
if (image.image === path.join(temporaryDirectoryPath, 'transparent.png')) return;
var spritePathChunks = path.parse(image.sprite).name.match(/-([0-9]+)$/);
var lineIndex = (spritePathChunks && parseInt(spritePathChunks[1])) || 0;
image.y = image.y + (lineIndex * height);
image.sprite = destinationPath;
images.push(image);
});
});
callback();
});
} | javascript | function(callback) {
var asyncFunctions = [];
for (var i = 0; i < numberOfRows; i++) {
var rowsImagesPaths = imagesPaths.slice(i * numberOfColumns, i * numberOfColumns + numberOfColumns);
var lineWidth = width;
var lineHeight = height;
var linePath = path.join(temporaryDirectoryPath, 'line-' + i);
linesPaths.push(linePath);
asyncFunctions.push(createLine(rowsImagesPaths, linePath, lineWidth, lineHeight, true, 100));
}
async.parallel(asyncFunctions, function(error, results) {
if (error) return callback(error);
results.forEach(function(line) {
line.forEach(function(image) {
if (image.image === path.join(temporaryDirectoryPath, 'transparent.png')) return;
var spritePathChunks = path.parse(image.sprite).name.match(/-([0-9]+)$/);
var lineIndex = (spritePathChunks && parseInt(spritePathChunks[1])) || 0;
image.y = image.y + (lineIndex * height);
image.sprite = destinationPath;
images.push(image);
});
});
callback();
});
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"asyncFunctions",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numberOfRows",
";",
"i",
"++",
")",
"{",
"var",
"rowsImagesPaths",
"=",
"imagesPaths",
".",
"slice",
"(",
"i",
"*",
"numberOfColumns",
",",
"i",
"*",
"numberOfColumns",
"+",
"numberOfColumns",
")",
";",
"var",
"lineWidth",
"=",
"width",
";",
"var",
"lineHeight",
"=",
"height",
";",
"var",
"linePath",
"=",
"path",
".",
"join",
"(",
"temporaryDirectoryPath",
",",
"'line-'",
"+",
"i",
")",
";",
"linesPaths",
".",
"push",
"(",
"linePath",
")",
";",
"asyncFunctions",
".",
"push",
"(",
"createLine",
"(",
"rowsImagesPaths",
",",
"linePath",
",",
"lineWidth",
",",
"lineHeight",
",",
"true",
",",
"100",
")",
")",
";",
"}",
"async",
".",
"parallel",
"(",
"asyncFunctions",
",",
"function",
"(",
"error",
",",
"results",
")",
"{",
"if",
"(",
"error",
")",
"return",
"callback",
"(",
"error",
")",
";",
"results",
".",
"forEach",
"(",
"function",
"(",
"line",
")",
"{",
"line",
".",
"forEach",
"(",
"function",
"(",
"image",
")",
"{",
"if",
"(",
"image",
".",
"image",
"===",
"path",
".",
"join",
"(",
"temporaryDirectoryPath",
",",
"'transparent.png'",
")",
")",
"return",
";",
"var",
"spritePathChunks",
"=",
"path",
".",
"parse",
"(",
"image",
".",
"sprite",
")",
".",
"name",
".",
"match",
"(",
"/",
"-([0-9]+)$",
"/",
")",
";",
"var",
"lineIndex",
"=",
"(",
"spritePathChunks",
"&&",
"parseInt",
"(",
"spritePathChunks",
"[",
"1",
"]",
")",
")",
"||",
"0",
";",
"image",
".",
"y",
"=",
"image",
".",
"y",
"+",
"(",
"lineIndex",
"*",
"height",
")",
";",
"image",
".",
"sprite",
"=",
"destinationPath",
";",
"images",
".",
"push",
"(",
"image",
")",
";",
"}",
")",
";",
"}",
")",
";",
"callback",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Create sprite horizontal lines | [
"Create",
"sprite",
"horizontal",
"lines"
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L307-L338 |
|
41,692 | veo-labs/openveo-api | lib/imageProcessor.js | function(callback) {
createLine(linesPaths, destinationPath, width * numberOfColumns, height, false, quality)(callback);
} | javascript | function(callback) {
createLine(linesPaths, destinationPath, width * numberOfColumns, height, false, quality)(callback);
} | [
"function",
"(",
"callback",
")",
"{",
"createLine",
"(",
"linesPaths",
",",
"destinationPath",
",",
"width",
"*",
"numberOfColumns",
",",
"height",
",",
"false",
",",
"quality",
")",
"(",
"callback",
")",
";",
"}"
]
| Aggregate lines vertically | [
"Aggregate",
"lines",
"vertically"
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L341-L343 |
|
41,693 | veo-labs/openveo-api | lib/imageProcessor.js | function(spriteImagesPaths, spriteDestinationPath) {
return function(callback) {
self.generateSprite(
spriteImagesPaths,
spriteDestinationPath,
width,
height,
totalColumns,
maxRows,
quality,
temporaryDirectoryPath,
callback
);
};
} | javascript | function(spriteImagesPaths, spriteDestinationPath) {
return function(callback) {
self.generateSprite(
spriteImagesPaths,
spriteDestinationPath,
width,
height,
totalColumns,
maxRows,
quality,
temporaryDirectoryPath,
callback
);
};
} | [
"function",
"(",
"spriteImagesPaths",
",",
"spriteDestinationPath",
")",
"{",
"return",
"function",
"(",
"callback",
")",
"{",
"self",
".",
"generateSprite",
"(",
"spriteImagesPaths",
",",
"spriteDestinationPath",
",",
"width",
",",
"height",
",",
"totalColumns",
",",
"maxRows",
",",
"quality",
",",
"temporaryDirectoryPath",
",",
"callback",
")",
";",
"}",
";",
"}"
]
| Creates a sprite.
@param {Array} spriteImagesPaths The list of images to include in the sprite
@param {String} spriteDestinationPath The sprite path
@return {Function} The async function of the operation | [
"Creates",
"a",
"sprite",
"."
]
| 493a811e9a5ba4d3e14910facaa7452caba1ab38 | https://github.com/veo-labs/openveo-api/blob/493a811e9a5ba4d3e14910facaa7452caba1ab38/lib/imageProcessor.js#L400-L414 |
|
41,694 | nanw1103/otherlib | lib/index.js | delay | function delay(millis, obj) {
return new Promise((resolve, reject) => {
let resolveImpl = d => {
if (d === null || d === undefined) {
resolve(d)
} else if (d instanceof Promise || typeof d.then === 'function' && typeof d.catch === 'function') {
d.then(resolve).catch(reject)
} else if (typeof d === 'function') {
resolveImpl(d())
} else {
resolve(d)
}
}
setTimeout(() => resolveImpl(obj), millis)
})
} | javascript | function delay(millis, obj) {
return new Promise((resolve, reject) => {
let resolveImpl = d => {
if (d === null || d === undefined) {
resolve(d)
} else if (d instanceof Promise || typeof d.then === 'function' && typeof d.catch === 'function') {
d.then(resolve).catch(reject)
} else if (typeof d === 'function') {
resolveImpl(d())
} else {
resolve(d)
}
}
setTimeout(() => resolveImpl(obj), millis)
})
} | [
"function",
"delay",
"(",
"millis",
",",
"obj",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"resolveImpl",
"=",
"d",
"=>",
"{",
"if",
"(",
"d",
"===",
"null",
"||",
"d",
"===",
"undefined",
")",
"{",
"resolve",
"(",
"d",
")",
"}",
"else",
"if",
"(",
"d",
"instanceof",
"Promise",
"||",
"typeof",
"d",
".",
"then",
"===",
"'function'",
"&&",
"typeof",
"d",
".",
"catch",
"===",
"'function'",
")",
"{",
"d",
".",
"then",
"(",
"resolve",
")",
".",
"catch",
"(",
"reject",
")",
"}",
"else",
"if",
"(",
"typeof",
"d",
"===",
"'function'",
")",
"{",
"resolveImpl",
"(",
"d",
"(",
")",
")",
"}",
"else",
"{",
"resolve",
"(",
"d",
")",
"}",
"}",
"setTimeout",
"(",
"(",
")",
"=>",
"resolveImpl",
"(",
"obj",
")",
",",
"millis",
")",
"}",
")",
"}"
]
| Return a promise which resolves the provided data after specified delay.
@param {number} millis - Delay before resolving of the promise
@param {promise|function|object} obj - If promise, it will be resolved/rejected in a delayed manner; if function, it's return value will be resolved. Otherwise the obj is resolved directly.
@return {Promise} - A promise that resolves after millis delay | [
"Return",
"a",
"promise",
"which",
"resolves",
"the",
"provided",
"data",
"after",
"specified",
"delay",
"."
]
| 187315e12cd829ddf39a38fcbb38d36f8cd34819 | https://github.com/nanw1103/otherlib/blob/187315e12cd829ddf39a38fcbb38d36f8cd34819/lib/index.js#L11-L27 |
41,695 | nanw1103/otherlib | lib/index.js | retry | async function retry(func, options) {
if (!options.timeoutMs && !options.retry)
throw new Error('Invalid argument: either options.timeoutMs or options.retry must be specified')
if (options.timeoutMs < 0)
throw new Error('Invalid argument: options.timeoutMs < 0')
if (options.retry < 0)
throw new Error('Invalid argument: options.retry < 0')
if (options.intervalMs < 0)
throw new Error('Invalid argument: options.intervalMs < 0')
if (!options.intervalMs && options.timeoutMs) {
options.intervalMs = options.timeoutMs / 60
if (options.intervalMs < 10000)
options.intervalMs = 10000
}
let filter = options.filter || ((err, ret, _hasError) => _hasError)
//start of backward compatibility
if (options.filterReject || options.filterResolve) {
filter = (err, ret, _hasError) => {
if (_hasError)
return options.filterReject && options.filterReject(err)
return options.filterResolve && options.filterResolve(ret)
}
}
//end of backward compatibility
let start = Date.now()
let log = options.log || (()=>0)
let name = options.name || '<no name>'
let n = 0
let checkRetry = async (state) => {
if (options.retry && ++n > options.retry) {
let msg = `RetryTask [${name}] - State=${state}. FAILED: Retry limit reached.`
log(msg)
throw new Error(msg)
}
let now = Date.now()
if (options.timeoutMs && now - start > options.timeoutMs) {
let msg = `RetryTask [${name}] - State=${state}. FAILED: Retry Timeout.`
log(msg)
throw new Error(msg)
}
let msg = ''
if (options.retry) {
msg = `${n}/${options.retry}`
}
if (options.timeoutMs) {
let percent = (now - start) / options.timeoutMs * 100 | 0
if (options.retry)
msg += ', '
msg += `timeout ${percent}%`
}
log(`RetryTask [${name}] - State=${state}. Retry=${msg}...`)
await delay(options.intervalMs)
}
let ret
let err
let _hasError
for (;;) {
ret = undefined
err = undefined
_hasError = undefined
try {
ret = await func()
} catch (e) {
err = e
_hasError = true
}
if (await filter(err, ret, _hasError)) {
await checkRetry(err || ret)
continue
}
if (err)
throw err
return ret
}
} | javascript | async function retry(func, options) {
if (!options.timeoutMs && !options.retry)
throw new Error('Invalid argument: either options.timeoutMs or options.retry must be specified')
if (options.timeoutMs < 0)
throw new Error('Invalid argument: options.timeoutMs < 0')
if (options.retry < 0)
throw new Error('Invalid argument: options.retry < 0')
if (options.intervalMs < 0)
throw new Error('Invalid argument: options.intervalMs < 0')
if (!options.intervalMs && options.timeoutMs) {
options.intervalMs = options.timeoutMs / 60
if (options.intervalMs < 10000)
options.intervalMs = 10000
}
let filter = options.filter || ((err, ret, _hasError) => _hasError)
//start of backward compatibility
if (options.filterReject || options.filterResolve) {
filter = (err, ret, _hasError) => {
if (_hasError)
return options.filterReject && options.filterReject(err)
return options.filterResolve && options.filterResolve(ret)
}
}
//end of backward compatibility
let start = Date.now()
let log = options.log || (()=>0)
let name = options.name || '<no name>'
let n = 0
let checkRetry = async (state) => {
if (options.retry && ++n > options.retry) {
let msg = `RetryTask [${name}] - State=${state}. FAILED: Retry limit reached.`
log(msg)
throw new Error(msg)
}
let now = Date.now()
if (options.timeoutMs && now - start > options.timeoutMs) {
let msg = `RetryTask [${name}] - State=${state}. FAILED: Retry Timeout.`
log(msg)
throw new Error(msg)
}
let msg = ''
if (options.retry) {
msg = `${n}/${options.retry}`
}
if (options.timeoutMs) {
let percent = (now - start) / options.timeoutMs * 100 | 0
if (options.retry)
msg += ', '
msg += `timeout ${percent}%`
}
log(`RetryTask [${name}] - State=${state}. Retry=${msg}...`)
await delay(options.intervalMs)
}
let ret
let err
let _hasError
for (;;) {
ret = undefined
err = undefined
_hasError = undefined
try {
ret = await func()
} catch (e) {
err = e
_hasError = true
}
if (await filter(err, ret, _hasError)) {
await checkRetry(err || ret)
continue
}
if (err)
throw err
return ret
}
} | [
"async",
"function",
"retry",
"(",
"func",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
".",
"timeoutMs",
"&&",
"!",
"options",
".",
"retry",
")",
"throw",
"new",
"Error",
"(",
"'Invalid argument: either options.timeoutMs or options.retry must be specified'",
")",
"if",
"(",
"options",
".",
"timeoutMs",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'Invalid argument: options.timeoutMs < 0'",
")",
"if",
"(",
"options",
".",
"retry",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'Invalid argument: options.retry < 0'",
")",
"if",
"(",
"options",
".",
"intervalMs",
"<",
"0",
")",
"throw",
"new",
"Error",
"(",
"'Invalid argument: options.intervalMs < 0'",
")",
"if",
"(",
"!",
"options",
".",
"intervalMs",
"&&",
"options",
".",
"timeoutMs",
")",
"{",
"options",
".",
"intervalMs",
"=",
"options",
".",
"timeoutMs",
"/",
"60",
"if",
"(",
"options",
".",
"intervalMs",
"<",
"10000",
")",
"options",
".",
"intervalMs",
"=",
"10000",
"}",
"let",
"filter",
"=",
"options",
".",
"filter",
"||",
"(",
"(",
"err",
",",
"ret",
",",
"_hasError",
")",
"=>",
"_hasError",
")",
"//start of backward compatibility",
"if",
"(",
"options",
".",
"filterReject",
"||",
"options",
".",
"filterResolve",
")",
"{",
"filter",
"=",
"(",
"err",
",",
"ret",
",",
"_hasError",
")",
"=>",
"{",
"if",
"(",
"_hasError",
")",
"return",
"options",
".",
"filterReject",
"&&",
"options",
".",
"filterReject",
"(",
"err",
")",
"return",
"options",
".",
"filterResolve",
"&&",
"options",
".",
"filterResolve",
"(",
"ret",
")",
"}",
"}",
"//end of backward compatibility",
"let",
"start",
"=",
"Date",
".",
"now",
"(",
")",
"let",
"log",
"=",
"options",
".",
"log",
"||",
"(",
"(",
")",
"=>",
"0",
")",
"let",
"name",
"=",
"options",
".",
"name",
"||",
"'<no name>'",
"let",
"n",
"=",
"0",
"let",
"checkRetry",
"=",
"async",
"(",
"state",
")",
"=>",
"{",
"if",
"(",
"options",
".",
"retry",
"&&",
"++",
"n",
">",
"options",
".",
"retry",
")",
"{",
"let",
"msg",
"=",
"`",
"${",
"name",
"}",
"${",
"state",
"}",
"`",
"log",
"(",
"msg",
")",
"throw",
"new",
"Error",
"(",
"msg",
")",
"}",
"let",
"now",
"=",
"Date",
".",
"now",
"(",
")",
"if",
"(",
"options",
".",
"timeoutMs",
"&&",
"now",
"-",
"start",
">",
"options",
".",
"timeoutMs",
")",
"{",
"let",
"msg",
"=",
"`",
"${",
"name",
"}",
"${",
"state",
"}",
"`",
"log",
"(",
"msg",
")",
"throw",
"new",
"Error",
"(",
"msg",
")",
"}",
"let",
"msg",
"=",
"''",
"if",
"(",
"options",
".",
"retry",
")",
"{",
"msg",
"=",
"`",
"${",
"n",
"}",
"${",
"options",
".",
"retry",
"}",
"`",
"}",
"if",
"(",
"options",
".",
"timeoutMs",
")",
"{",
"let",
"percent",
"=",
"(",
"now",
"-",
"start",
")",
"/",
"options",
".",
"timeoutMs",
"*",
"100",
"|",
"0",
"if",
"(",
"options",
".",
"retry",
")",
"msg",
"+=",
"', '",
"msg",
"+=",
"`",
"${",
"percent",
"}",
"`",
"}",
"log",
"(",
"`",
"${",
"name",
"}",
"${",
"state",
"}",
"${",
"msg",
"}",
"`",
")",
"await",
"delay",
"(",
"options",
".",
"intervalMs",
")",
"}",
"let",
"ret",
"let",
"err",
"let",
"_hasError",
"for",
"(",
";",
";",
")",
"{",
"ret",
"=",
"undefined",
"err",
"=",
"undefined",
"_hasError",
"=",
"undefined",
"try",
"{",
"ret",
"=",
"await",
"func",
"(",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"err",
"=",
"e",
"_hasError",
"=",
"true",
"}",
"if",
"(",
"await",
"filter",
"(",
"err",
",",
"ret",
",",
"_hasError",
")",
")",
"{",
"await",
"checkRetry",
"(",
"err",
"||",
"ret",
")",
"continue",
"}",
"if",
"(",
"err",
")",
"throw",
"err",
"return",
"ret",
"}",
"}"
]
| Retry the specific task conditionally
@param {function} func
@param {object} options
@property {function} options.filter - A callback filter to control retry, based on result or error.
Retry on true return. The default filter is: (err, ret)=>err
@property {number} options.retry - max retry attempt. 0 indicates no limit
@property {number} options.timeoutMs - total timeout limit. 0 indicates no total timeout
@property {number} options.intervalMs - wait before retry
@property {function} [options.log] - optionally, log the details
@property {string} [options.name] - name shown in log
@return {Promise} | [
"Retry",
"the",
"specific",
"task",
"conditionally"
]
| 187315e12cd829ddf39a38fcbb38d36f8cd34819 | https://github.com/nanw1103/otherlib/blob/187315e12cd829ddf39a38fcbb38d36f8cd34819/lib/index.js#L44-L126 |
41,696 | nanw1103/otherlib | lib/index.js | deepMerge | function deepMerge(target, ...sources) {
let src
while (true) {
if (!sources.length)
return target
src = sources.shift()
if (src)
break
}
for (let k in src) {
let v = src[k]
let existing = target[k]
if (typeof v === 'object') {
if (v === null) {
target[k] = null
} else if (Array.isArray(v)) {
target[k] = v.slice()
} else {
if (typeof existing !== 'object')
target[k] = deepMerge({}, v)
else
deepMerge(existing, v)
}
} else {
//v is not object/array
target[k] = v
}
}
return deepMerge(target, ...sources)
} | javascript | function deepMerge(target, ...sources) {
let src
while (true) {
if (!sources.length)
return target
src = sources.shift()
if (src)
break
}
for (let k in src) {
let v = src[k]
let existing = target[k]
if (typeof v === 'object') {
if (v === null) {
target[k] = null
} else if (Array.isArray(v)) {
target[k] = v.slice()
} else {
if (typeof existing !== 'object')
target[k] = deepMerge({}, v)
else
deepMerge(existing, v)
}
} else {
//v is not object/array
target[k] = v
}
}
return deepMerge(target, ...sources)
} | [
"function",
"deepMerge",
"(",
"target",
",",
"...",
"sources",
")",
"{",
"let",
"src",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"!",
"sources",
".",
"length",
")",
"return",
"target",
"src",
"=",
"sources",
".",
"shift",
"(",
")",
"if",
"(",
"src",
")",
"break",
"}",
"for",
"(",
"let",
"k",
"in",
"src",
")",
"{",
"let",
"v",
"=",
"src",
"[",
"k",
"]",
"let",
"existing",
"=",
"target",
"[",
"k",
"]",
"if",
"(",
"typeof",
"v",
"===",
"'object'",
")",
"{",
"if",
"(",
"v",
"===",
"null",
")",
"{",
"target",
"[",
"k",
"]",
"=",
"null",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"v",
")",
")",
"{",
"target",
"[",
"k",
"]",
"=",
"v",
".",
"slice",
"(",
")",
"}",
"else",
"{",
"if",
"(",
"typeof",
"existing",
"!==",
"'object'",
")",
"target",
"[",
"k",
"]",
"=",
"deepMerge",
"(",
"{",
"}",
",",
"v",
")",
"else",
"deepMerge",
"(",
"existing",
",",
"v",
")",
"}",
"}",
"else",
"{",
"//v is not object/array",
"target",
"[",
"k",
"]",
"=",
"v",
"}",
"}",
"return",
"deepMerge",
"(",
"target",
",",
"...",
"sources",
")",
"}"
]
| Like Object.assign, but works in a deep manner.
@param {object} target - Target object to be merged into
@param {object} sources - Source objects to be merged onto target
@return {object} The target object | [
"Like",
"Object",
".",
"assign",
"but",
"works",
"in",
"a",
"deep",
"manner",
"."
]
| 187315e12cd829ddf39a38fcbb38d36f8cd34819 | https://github.com/nanw1103/otherlib/blob/187315e12cd829ddf39a38fcbb38d36f8cd34819/lib/index.js#L244-L277 |
41,697 | urturn/urturn-expression-api | lib/expression-api/compat.js | restoreEventListenerImplementation | function restoreEventListenerImplementation() {
global.Element.prototype.addEventListener = nativeAddEventListener;
global.Element.prototype.removeEventListener = nativeRemoveEventListener;
global.document.addEventListener = nativeAddEventListener;
global.document.removeEventListener = nativeRemoveEventListener;
} | javascript | function restoreEventListenerImplementation() {
global.Element.prototype.addEventListener = nativeAddEventListener;
global.Element.prototype.removeEventListener = nativeRemoveEventListener;
global.document.addEventListener = nativeAddEventListener;
global.document.removeEventListener = nativeRemoveEventListener;
} | [
"function",
"restoreEventListenerImplementation",
"(",
")",
"{",
"global",
".",
"Element",
".",
"prototype",
".",
"addEventListener",
"=",
"nativeAddEventListener",
";",
"global",
".",
"Element",
".",
"prototype",
".",
"removeEventListener",
"=",
"nativeRemoveEventListener",
";",
"global",
".",
"document",
".",
"addEventListener",
"=",
"nativeAddEventListener",
";",
"global",
".",
"document",
".",
"removeEventListener",
"=",
"nativeRemoveEventListener",
";",
"}"
]
| Not public for now | [
"Not",
"public",
"for",
"now"
]
| 009a272ee670dbbe5eefb5c070ed827dd778bb07 | https://github.com/urturn/urturn-expression-api/blob/009a272ee670dbbe5eefb5c070ed827dd778bb07/lib/expression-api/compat.js#L130-L135 |
41,698 | feedhenry/fh-component-metrics | lib/clients/base.js | BaseClient | function BaseClient(opts) {
this.opts = opts || {};
var self = this;
this.sendQConcurrency = opts.sendQueueConcurrency || 5;
this.sendQ = async.queue(function(data, cb) {
self.doSend(data, cb);
}, this.sendQConcurrency);
} | javascript | function BaseClient(opts) {
this.opts = opts || {};
var self = this;
this.sendQConcurrency = opts.sendQueueConcurrency || 5;
this.sendQ = async.queue(function(data, cb) {
self.doSend(data, cb);
}, this.sendQConcurrency);
} | [
"function",
"BaseClient",
"(",
"opts",
")",
"{",
"this",
".",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"sendQConcurrency",
"=",
"opts",
".",
"sendQueueConcurrency",
"||",
"5",
";",
"this",
".",
"sendQ",
"=",
"async",
".",
"queue",
"(",
"function",
"(",
"data",
",",
"cb",
")",
"{",
"self",
".",
"doSend",
"(",
"data",
",",
"cb",
")",
";",
"}",
",",
"this",
".",
"sendQConcurrency",
")",
";",
"}"
]
| A base implementation for all the clients | [
"A",
"base",
"implementation",
"for",
"all",
"the",
"clients"
]
| c97a1a82ff0144f2a7c2abecbc22084fade1cbc8 | https://github.com/feedhenry/fh-component-metrics/blob/c97a1a82ff0144f2a7c2abecbc22084fade1cbc8/lib/clients/base.js#L6-L13 |
41,699 | bootprint/customize-write-files | lib/changed.js | compareString | async function compareString (filename, expectedContents) {
try {
const actualContents = await fs.readFile(filename, { encoding: 'utf8' })
return actualContents !== expectedContents
} catch (err) {
return handleError(err)
}
} | javascript | async function compareString (filename, expectedContents) {
try {
const actualContents = await fs.readFile(filename, { encoding: 'utf8' })
return actualContents !== expectedContents
} catch (err) {
return handleError(err)
}
} | [
"async",
"function",
"compareString",
"(",
"filename",
",",
"expectedContents",
")",
"{",
"try",
"{",
"const",
"actualContents",
"=",
"await",
"fs",
".",
"readFile",
"(",
"filename",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
"return",
"actualContents",
"!==",
"expectedContents",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"handleError",
"(",
"err",
")",
"}",
"}"
]
| Compares a string with a file contents. Returns true, if they differ or the file does not exist.
@param {string} filename the file name
@param {string} expectedContents the file contents
@returns {Promise<boolean>|boolean}
@private | [
"Compares",
"a",
"string",
"with",
"a",
"file",
"contents",
".",
"Returns",
"true",
"if",
"they",
"differ",
"or",
"the",
"file",
"does",
"not",
"exist",
"."
]
| af77ce78b5196f40ce90670bfdb6e1e7e496a415 | https://github.com/bootprint/customize-write-files/blob/af77ce78b5196f40ce90670bfdb6e1e7e496a415/lib/changed.js#L51-L58 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.