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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
imonology/scalra | monitor/REST_handle.js | function (ports) {
var port = ports[0];
var list = '';
for (var i=0; i < ports.length; i++) {
list += (ports[i] + ', ');
delete l_ports[ports[i]];
}
LOG.warn('release ports: ' + list, 'SR.Monitor');
// remove all other ports associated with this port
for (var i in l_ports) {
if (l_ports[i] === port) {
LOG.warn('release port: ' + i, 'SR.Monitor');
delete l_ports[i];
}
}
} | javascript | function (ports) {
var port = ports[0];
var list = '';
for (var i=0; i < ports.length; i++) {
list += (ports[i] + ', ');
delete l_ports[ports[i]];
}
LOG.warn('release ports: ' + list, 'SR.Monitor');
// remove all other ports associated with this port
for (var i in l_ports) {
if (l_ports[i] === port) {
LOG.warn('release port: ' + i, 'SR.Monitor');
delete l_ports[i];
}
}
} | [
"function",
"(",
"ports",
")",
"{",
"var",
"port",
"=",
"ports",
"[",
"0",
"]",
";",
"var",
"list",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ports",
".",
"length",
";",
"i",
"++",
")",
"{",
"list",
"+=",
"(",
"ports",
"[",
"i",
"]",
"+",
"', '",
")",
";",
"delete",
"l_ports",
"[",
"ports",
"[",
"i",
"]",
"]",
";",
"}",
"LOG",
".",
"warn",
"(",
"'release ports: '",
"+",
"list",
",",
"'SR.Monitor'",
")",
";",
"for",
"(",
"var",
"i",
"in",
"l_ports",
")",
"{",
"if",
"(",
"l_ports",
"[",
"i",
"]",
"===",
"port",
")",
"{",
"LOG",
".",
"warn",
"(",
"'release port: '",
"+",
"i",
",",
"'SR.Monitor'",
")",
";",
"delete",
"l_ports",
"[",
"i",
"]",
";",
"}",
"}",
"}"
] | recycle an app port | [
"recycle",
"an",
"app",
"port"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/monitor/REST_handle.js#L49-L68 | train |
|
imonology/scalra | monitor/REST_handle.js | function (port, parent_port) {
// check if the port wasn't reported
if (l_ports.hasOwnProperty(port) === false) {
LOG.warn('recording used port [' + port + ']...', 'SR.Monitor');
l_ports[port] = parent_port || port;
}
} | javascript | function (port, parent_port) {
// check if the port wasn't reported
if (l_ports.hasOwnProperty(port) === false) {
LOG.warn('recording used port [' + port + ']...', 'SR.Monitor');
l_ports[port] = parent_port || port;
}
} | [
"function",
"(",
"port",
",",
"parent_port",
")",
"{",
"if",
"(",
"l_ports",
".",
"hasOwnProperty",
"(",
"port",
")",
"===",
"false",
")",
"{",
"LOG",
".",
"warn",
"(",
"'recording used port ['",
"+",
"port",
"+",
"']...'",
",",
"'SR.Monitor'",
")",
";",
"l_ports",
"[",
"port",
"]",
"=",
"parent_port",
"||",
"port",
";",
"}",
"}"
] | record an existing port 'parent_port' indicats the which port, if released, will also release the current port | [
"record",
"an",
"existing",
"port",
"parent_port",
"indicats",
"the",
"which",
"port",
"if",
"released",
"will",
"also",
"release",
"the",
"current",
"port"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/monitor/REST_handle.js#L72-L80 | train |
|
imonology/scalra | monitor/REST_handle.js | function (size) {
size = size || 1;
LOG.warn('trying to assign ' + size + ' new ports...', 'SR.Monitor');
// find first available port
var port = SR.Settings.PORT_APP_RANGE_START;
var last_port = SR.Settings.PORT_APP_RANGE_END;
// first port found
var first_port = undefined;
var results = [];
while (port <= last_port) {
if (l_ports.hasOwnProperty(port) === false || l_ports[port] === null) {
// found a unique port
if (!first_port)
first_port = port;
// mark the port as assigned
l_ports[port] = first_port;
results.push(port);
LOG.warn('assigning port: ' + port, 'SR.Monitor');
if (--size === 0)
break;
}
port++;
}
// no available ports found, or not enough ports found
if (port > last_port)
return 0;
if (results.length > 1)
return results;
else
return results[0];
} | javascript | function (size) {
size = size || 1;
LOG.warn('trying to assign ' + size + ' new ports...', 'SR.Monitor');
// find first available port
var port = SR.Settings.PORT_APP_RANGE_START;
var last_port = SR.Settings.PORT_APP_RANGE_END;
// first port found
var first_port = undefined;
var results = [];
while (port <= last_port) {
if (l_ports.hasOwnProperty(port) === false || l_ports[port] === null) {
// found a unique port
if (!first_port)
first_port = port;
// mark the port as assigned
l_ports[port] = first_port;
results.push(port);
LOG.warn('assigning port: ' + port, 'SR.Monitor');
if (--size === 0)
break;
}
port++;
}
// no available ports found, or not enough ports found
if (port > last_port)
return 0;
if (results.length > 1)
return results;
else
return results[0];
} | [
"function",
"(",
"size",
")",
"{",
"size",
"=",
"size",
"||",
"1",
";",
"LOG",
".",
"warn",
"(",
"'trying to assign '",
"+",
"size",
"+",
"' new ports...'",
",",
"'SR.Monitor'",
")",
";",
"var",
"port",
"=",
"SR",
".",
"Settings",
".",
"PORT_APP_RANGE_START",
";",
"var",
"last_port",
"=",
"SR",
".",
"Settings",
".",
"PORT_APP_RANGE_END",
";",
"var",
"first_port",
"=",
"undefined",
";",
"var",
"results",
"=",
"[",
"]",
";",
"while",
"(",
"port",
"<=",
"last_port",
")",
"{",
"if",
"(",
"l_ports",
".",
"hasOwnProperty",
"(",
"port",
")",
"===",
"false",
"||",
"l_ports",
"[",
"port",
"]",
"===",
"null",
")",
"{",
"if",
"(",
"!",
"first_port",
")",
"first_port",
"=",
"port",
";",
"l_ports",
"[",
"port",
"]",
"=",
"first_port",
";",
"results",
".",
"push",
"(",
"port",
")",
";",
"LOG",
".",
"warn",
"(",
"'assigning port: '",
"+",
"port",
",",
"'SR.Monitor'",
")",
";",
"if",
"(",
"--",
"size",
"===",
"0",
")",
"break",
";",
"}",
"port",
"++",
";",
"}",
"if",
"(",
"port",
">",
"last_port",
")",
"return",
"0",
";",
"if",
"(",
"results",
".",
"length",
">",
"1",
")",
"return",
"results",
";",
"else",
"return",
"results",
"[",
"0",
"]",
";",
"}"
] | assign a unique application port | [
"assign",
"a",
"unique",
"application",
"port"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/monitor/REST_handle.js#L83-L123 | train |
|
imonology/scalra | monitor/REST_handle.js | function () {
var currTime = new Date();
var overtime = (SR.Settings.INTERVAL_STAT_REPORT * 2);
// remove servers no longer reporting
for (var serverID in SR.Report.servers) {
var stat = SR.Report.servers[serverID];
if (!stat || !stat.reportedTime)
continue;
// server considered dead
if (currTime - stat.reportedTime > overtime) {
var ip_port = stat.server.IP + ':' + stat.server.port;
LOG.sys(ip_port + ' overtime: ' + overtime + ' last: ' + stat.reportedTime);
LOG.error('server: ' + ip_port + ' (' + stat.server.type + ') not responding after ' + overtime + ' ms, mark dead...', 'SR.Monitor');
SR.Report.removeStat(serverID);
// recycle port if it's from a local server
if (stat.server.IP === SR.Settings.SERVER_INFO.IP) {
LOG.warn('server is a local server, re-cycle its ports...', 'SR.Monitor');
l_recyclePort(stat.ports);
}
}
}
} | javascript | function () {
var currTime = new Date();
var overtime = (SR.Settings.INTERVAL_STAT_REPORT * 2);
// remove servers no longer reporting
for (var serverID in SR.Report.servers) {
var stat = SR.Report.servers[serverID];
if (!stat || !stat.reportedTime)
continue;
// server considered dead
if (currTime - stat.reportedTime > overtime) {
var ip_port = stat.server.IP + ':' + stat.server.port;
LOG.sys(ip_port + ' overtime: ' + overtime + ' last: ' + stat.reportedTime);
LOG.error('server: ' + ip_port + ' (' + stat.server.type + ') not responding after ' + overtime + ' ms, mark dead...', 'SR.Monitor');
SR.Report.removeStat(serverID);
// recycle port if it's from a local server
if (stat.server.IP === SR.Settings.SERVER_INFO.IP) {
LOG.warn('server is a local server, re-cycle its ports...', 'SR.Monitor');
l_recyclePort(stat.ports);
}
}
}
} | [
"function",
"(",
")",
"{",
"var",
"currTime",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"overtime",
"=",
"(",
"SR",
".",
"Settings",
".",
"INTERVAL_STAT_REPORT",
"*",
"2",
")",
";",
"for",
"(",
"var",
"serverID",
"in",
"SR",
".",
"Report",
".",
"servers",
")",
"{",
"var",
"stat",
"=",
"SR",
".",
"Report",
".",
"servers",
"[",
"serverID",
"]",
";",
"if",
"(",
"!",
"stat",
"||",
"!",
"stat",
".",
"reportedTime",
")",
"continue",
";",
"if",
"(",
"currTime",
"-",
"stat",
".",
"reportedTime",
">",
"overtime",
")",
"{",
"var",
"ip_port",
"=",
"stat",
".",
"server",
".",
"IP",
"+",
"':'",
"+",
"stat",
".",
"server",
".",
"port",
";",
"LOG",
".",
"sys",
"(",
"ip_port",
"+",
"' overtime: '",
"+",
"overtime",
"+",
"' last: '",
"+",
"stat",
".",
"reportedTime",
")",
";",
"LOG",
".",
"error",
"(",
"'server: '",
"+",
"ip_port",
"+",
"' ('",
"+",
"stat",
".",
"server",
".",
"type",
"+",
"') not responding after '",
"+",
"overtime",
"+",
"' ms, mark dead...'",
",",
"'SR.Monitor'",
")",
";",
"SR",
".",
"Report",
".",
"removeStat",
"(",
"serverID",
")",
";",
"if",
"(",
"stat",
".",
"server",
".",
"IP",
"===",
"SR",
".",
"Settings",
".",
"SERVER_INFO",
".",
"IP",
")",
"{",
"LOG",
".",
"warn",
"(",
"'server is a local server, re-cycle its ports...'",
",",
"'SR.Monitor'",
")",
";",
"l_recyclePort",
"(",
"stat",
".",
"ports",
")",
";",
"}",
"}",
"}",
"}"
] | internal functions periodic checking liveness of app servers | [
"internal",
"functions",
"periodic",
"checking",
"liveness",
"of",
"app",
"servers"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/monitor/REST_handle.js#L131-L158 | train |
|
imonology/scalra | core/REST/handler.js | function(req) {
return ((req.headers.origin && req.headers.origin !== "null") ? req.headers.origin : "*");
} | javascript | function(req) {
return ((req.headers.origin && req.headers.origin !== "null") ? req.headers.origin : "*");
} | [
"function",
"(",
"req",
")",
"{",
"return",
"(",
"(",
"req",
".",
"headers",
".",
"origin",
"&&",
"req",
".",
"headers",
".",
"origin",
"!==",
"\"null\"",
")",
"?",
"req",
".",
"headers",
".",
"origin",
":",
"\"*\"",
")",
";",
"}"
] | helper code get origin from request | [
"helper",
"code",
"get",
"origin",
"from",
"request"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/REST/handler.js#L32-L34 | train |
|
imonology/scalra | core/REST/handler.js | function (res_obj, data, conn) {
// check if we should return empty response
if (typeof res_obj === 'undefined') {
SR.REST.reply(res, {});
return true;
}
// check for special case processing (SR_REDIRECT)
if (res_obj[SR.Tags.UPDATE] === 'SR_REDIRECT' && res_obj[SR.Tags.PARA] && res_obj[SR.Tags.PARA].url) {
var url = res_obj[SR.Tags.PARA].url;
LOG.warn('redirecting to: ' + url, l_name);
/*
res.writeHead(302, {
'Location': url
});
res.end();
*/
// redirect by page
// TODO: merge with same code in FB.js
var page =
'<html><body><script>\n' +
'if (navigator.appName.indexOf("Microsoft") != -1)\n' +
' window.top.location.href="' + url + '";\n' +
'else\n' +
' top.location.href="' + url + '";\n' +
'</script></body></html>\n';
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(page);
return true;
}
// check for special case processing (SR_HTML)
if (res_obj[SR.Tags.UPDATE] === 'SR_HTML' && res_obj[SR.Tags.PARA].page) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(res_obj[SR.Tags.PARA].page);
return true;
}
// check for special case processing (SR_DOWNLOAD)
if (res_obj[SR.Tags.UPDATE] === 'SR_DOWNLOAD' && res_obj[SR.Tags.PARA].data && res_obj[SR.Tags.PARA].filename) {
var filename = res_obj[SR.Tags.PARA].filename;
LOG.warn('allow client to download file: ' + filename, l_name);
var data = res_obj[SR.Tags.PARA].data;
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename=' + filename,
'Content-Length': data.length
});
res.end(data);
return true;
}
// check for special case processing (SR_RESOURCE)
if (res_obj[SR.Tags.UPDATE] === 'SR_RESOURCE' && res_obj[SR.Tags.PARA].address) {
var file = res_obj[SR.Tags.PARA].address;
// check if resource exists & its states
SR.fs.stat(file, function (err, stats) {
var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
if (err) {
LOG.error(err, l_name);
res.writeHead(404, resHeader);
res.end();
return;
}
var extFilename = file.match(/[\W\w]*\.([\W\w]*)/)[1];
if (typeof extFilename === 'string')
extFilename = extFilename.toLowerCase();
// default to 200 status
var resStatus = 200;
resHeader['Accept-Ranges'] = 'bytes';
resHeader['Cache-Control'] = 'no-cache';
resHeader['Content-Length'] = stats.size;
if (l_extList[extFilename]) {
resHeader['Content-Type'] = l_extList[extFilename];
};
var start = undefined;
var end = undefined;
// check if request range exists (e.g., streaming media such as webm/mp4) to return 206 status
// see: https://delog.wordpress.com/2011/04/25/stream-webm-file-to-chrome-using-node-js/
if (req.headers.range) {
var range = req.headers.range.split(/bytes=([0-9]*)-([0-9]*)/);
resStatus = 206;
start = parseInt(range[1] || 0);
end = parseInt(range[2] || stats.size - 1);
if (start > end) {
LOG.error('stream file start > end. start: ' + start + ' end: ' + end, l_name);
var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
res.writeHead(404, resHeader);
res.end();
return; // abnormal if we've reached here
}
LOG.debug('requesting bytes ' + start + ' to ' + end + ' for file: ' + file, l_name);
resHeader['Connection'] = 'close';
resHeader['Content-Length'] = end - start + 1;
resHeader['Content-Range'] = 'bytes ' + start + '-' + end + '/' + stats.size;
resHeader['Transfer-Encoding'] = 'chunked';
}
// otherwise assume it's a regular file
else if (l_directExt.hasOwnProperty(extFilename)) {
// NOTE: code below will cause the file be downloaded in a "Save As.." format
// (instead of being displayed directly), we only want this behavior for certain file types (such as .zip)
var filename = file.replace(/^.*[\\\/]/, '')
LOG.warn('requesting a file: ' + filename, l_name);
resHeader['Content-Disposition'] = 'attachment; filename=' + filename;
}
LOG.sys('SR_RESOURCE header:', l_name);
LOG.sys(resHeader);
res.writeHead(resStatus, resHeader);
// start streaming
SR.fs.createReadStream(file, {
flags: 'r',
start: start,
end: end
}).pipe(res);
});
return true;
}
var origin = _getOrigin(req);
// send back via res object if hadn't responded yet
if (res.headersSent === false) {
// NOTE: cookie may be undefined;
SR.REST.reply(res, data, {
origin: origin,
cookie: cookie
});
}
else {
LOG.error('HTTP request has already responded (cannot respond twice)', l_name);
LOG.stack();
}
return true;
} | javascript | function (res_obj, data, conn) {
// check if we should return empty response
if (typeof res_obj === 'undefined') {
SR.REST.reply(res, {});
return true;
}
// check for special case processing (SR_REDIRECT)
if (res_obj[SR.Tags.UPDATE] === 'SR_REDIRECT' && res_obj[SR.Tags.PARA] && res_obj[SR.Tags.PARA].url) {
var url = res_obj[SR.Tags.PARA].url;
LOG.warn('redirecting to: ' + url, l_name);
/*
res.writeHead(302, {
'Location': url
});
res.end();
*/
// redirect by page
// TODO: merge with same code in FB.js
var page =
'<html><body><script>\n' +
'if (navigator.appName.indexOf("Microsoft") != -1)\n' +
' window.top.location.href="' + url + '";\n' +
'else\n' +
' top.location.href="' + url + '";\n' +
'</script></body></html>\n';
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(page);
return true;
}
// check for special case processing (SR_HTML)
if (res_obj[SR.Tags.UPDATE] === 'SR_HTML' && res_obj[SR.Tags.PARA].page) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(res_obj[SR.Tags.PARA].page);
return true;
}
// check for special case processing (SR_DOWNLOAD)
if (res_obj[SR.Tags.UPDATE] === 'SR_DOWNLOAD' && res_obj[SR.Tags.PARA].data && res_obj[SR.Tags.PARA].filename) {
var filename = res_obj[SR.Tags.PARA].filename;
LOG.warn('allow client to download file: ' + filename, l_name);
var data = res_obj[SR.Tags.PARA].data;
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename=' + filename,
'Content-Length': data.length
});
res.end(data);
return true;
}
// check for special case processing (SR_RESOURCE)
if (res_obj[SR.Tags.UPDATE] === 'SR_RESOURCE' && res_obj[SR.Tags.PARA].address) {
var file = res_obj[SR.Tags.PARA].address;
// check if resource exists & its states
SR.fs.stat(file, function (err, stats) {
var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
if (err) {
LOG.error(err, l_name);
res.writeHead(404, resHeader);
res.end();
return;
}
var extFilename = file.match(/[\W\w]*\.([\W\w]*)/)[1];
if (typeof extFilename === 'string')
extFilename = extFilename.toLowerCase();
// default to 200 status
var resStatus = 200;
resHeader['Accept-Ranges'] = 'bytes';
resHeader['Cache-Control'] = 'no-cache';
resHeader['Content-Length'] = stats.size;
if (l_extList[extFilename]) {
resHeader['Content-Type'] = l_extList[extFilename];
};
var start = undefined;
var end = undefined;
// check if request range exists (e.g., streaming media such as webm/mp4) to return 206 status
// see: https://delog.wordpress.com/2011/04/25/stream-webm-file-to-chrome-using-node-js/
if (req.headers.range) {
var range = req.headers.range.split(/bytes=([0-9]*)-([0-9]*)/);
resStatus = 206;
start = parseInt(range[1] || 0);
end = parseInt(range[2] || stats.size - 1);
if (start > end) {
LOG.error('stream file start > end. start: ' + start + ' end: ' + end, l_name);
var resHeader = typeof res_obj[SR.Tags.PARA].header === 'object' ? res_obj[SR.Tags.PARA].header : {};
res.writeHead(404, resHeader);
res.end();
return; // abnormal if we've reached here
}
LOG.debug('requesting bytes ' + start + ' to ' + end + ' for file: ' + file, l_name);
resHeader['Connection'] = 'close';
resHeader['Content-Length'] = end - start + 1;
resHeader['Content-Range'] = 'bytes ' + start + '-' + end + '/' + stats.size;
resHeader['Transfer-Encoding'] = 'chunked';
}
// otherwise assume it's a regular file
else if (l_directExt.hasOwnProperty(extFilename)) {
// NOTE: code below will cause the file be downloaded in a "Save As.." format
// (instead of being displayed directly), we only want this behavior for certain file types (such as .zip)
var filename = file.replace(/^.*[\\\/]/, '')
LOG.warn('requesting a file: ' + filename, l_name);
resHeader['Content-Disposition'] = 'attachment; filename=' + filename;
}
LOG.sys('SR_RESOURCE header:', l_name);
LOG.sys(resHeader);
res.writeHead(resStatus, resHeader);
// start streaming
SR.fs.createReadStream(file, {
flags: 'r',
start: start,
end: end
}).pipe(res);
});
return true;
}
var origin = _getOrigin(req);
// send back via res object if hadn't responded yet
if (res.headersSent === false) {
// NOTE: cookie may be undefined;
SR.REST.reply(res, data, {
origin: origin,
cookie: cookie
});
}
else {
LOG.error('HTTP request has already responded (cannot respond twice)', l_name);
LOG.stack();
}
return true;
} | [
"function",
"(",
"res_obj",
",",
"data",
",",
"conn",
")",
"{",
"if",
"(",
"typeof",
"res_obj",
"===",
"'undefined'",
")",
"{",
"SR",
".",
"REST",
".",
"reply",
"(",
"res",
",",
"{",
"}",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"res_obj",
"[",
"SR",
".",
"Tags",
".",
"UPDATE",
"]",
"===",
"'SR_REDIRECT'",
"&&",
"res_obj",
"[",
"SR",
".",
"Tags",
".",
"PARA",
"]",
"&&",
"res_obj",
"[",
"SR",
".",
"Tags",
".",
"PARA",
"]",
".",
"url",
")",
"{",
"var",
"url",
"=",
"res_obj",
"[",
"SR",
".",
"Tags",
".",
"PARA",
"]",
".",
"url",
";",
"LOG",
".",
"warn",
"(",
"'redirecting to: '",
"+",
"url",
",",
"l_name",
")",
";",
"var",
"page",
"=",
"'<html><body><script>\\n'",
"+",
"\\n",
"+",
"'if (navigator.appName.indexOf(\"Microsoft\") != -1)\\n'",
"+",
"\\n",
"+",
"' window.top.location.href=\"'",
"+",
"url",
"+",
"'\";\\n'",
"+",
"\\n",
"+",
"'else\\n'",
"+",
"\\n",
";",
"'\t top.location.href=\"'",
"url",
"'\";\\n'",
"}",
"\\n",
"'</script></body></html>\\n'",
"\\n",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"'text/html'",
"}",
")",
";",
"res",
".",
"end",
"(",
"page",
")",
";",
"return",
"true",
";",
"}"
] | callback to return response to client | [
"callback",
"to",
"return",
"response",
"to",
"client"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/REST/handler.js#L81-L243 | train |
|
imonology/scalra | core/REST/handler.js | function() {
var origin = _getOrigin(req);
SR.REST.reply(res, res_str, {
origin: origin
});
} | javascript | function() {
var origin = _getOrigin(req);
SR.REST.reply(res, res_str, {
origin: origin
});
} | [
"function",
"(",
")",
"{",
"var",
"origin",
"=",
"_getOrigin",
"(",
"req",
")",
";",
"SR",
".",
"REST",
".",
"reply",
"(",
"res",
",",
"res_str",
",",
"{",
"origin",
":",
"origin",
"}",
")",
";",
"}"
] | replying the request | [
"replying",
"the",
"request"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/REST/handler.js#L329-L334 | train |
|
imonology/scalra | core/DB.js | function (clt_name, op, err, onFail, is_exception) {
var msg = 'DB ' + op + ' error for [' + clt_name + ']';
LOG.error(msg, 'SR.DB');
LOG.error(err, 'SR.DB');
if (typeof err.stack !== 'undefined') {
LOG.error(err.stack, 'SR.DB');
msg += ('\n\n' + err.stack);
}
UTIL.safeCall(onFail, err);
if (is_exception) {
return;
}
// notify project admin if it's not code exception
// NOTE: only project admins are notified
UTIL.notifyAdmin(
'[SR DB error: ' + clt_name + ']',
msg
);
} | javascript | function (clt_name, op, err, onFail, is_exception) {
var msg = 'DB ' + op + ' error for [' + clt_name + ']';
LOG.error(msg, 'SR.DB');
LOG.error(err, 'SR.DB');
if (typeof err.stack !== 'undefined') {
LOG.error(err.stack, 'SR.DB');
msg += ('\n\n' + err.stack);
}
UTIL.safeCall(onFail, err);
if (is_exception) {
return;
}
// notify project admin if it's not code exception
// NOTE: only project admins are notified
UTIL.notifyAdmin(
'[SR DB error: ' + clt_name + ']',
msg
);
} | [
"function",
"(",
"clt_name",
",",
"op",
",",
"err",
",",
"onFail",
",",
"is_exception",
")",
"{",
"var",
"msg",
"=",
"'DB '",
"+",
"op",
"+",
"' error for ['",
"+",
"clt_name",
"+",
"']'",
";",
"LOG",
".",
"error",
"(",
"msg",
",",
"'SR.DB'",
")",
";",
"LOG",
".",
"error",
"(",
"err",
",",
"'SR.DB'",
")",
";",
"if",
"(",
"typeof",
"err",
".",
"stack",
"!==",
"'undefined'",
")",
"{",
"LOG",
".",
"error",
"(",
"err",
".",
"stack",
",",
"'SR.DB'",
")",
";",
"msg",
"+=",
"(",
"'\\n\\n'",
"+",
"\\n",
")",
";",
"}",
"\\n",
"err",
".",
"stack",
"UTIL",
".",
"safeCall",
"(",
"onFail",
",",
"err",
")",
";",
"}"
] | helper to notify DB error | [
"helper",
"to",
"notify",
"DB",
"error"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/DB.js#L263-L284 | train |
|
imonology/scalra | core/DB.js | function (err_toArray, array) {
if (err_toArray) {
return l_notifyError(clt_name, 'getPage.toArray', err_toArray, cb);
}
//LOG.sys('array found succces, length: ' + array.length, 'SR.DB');
// NOTE: probably no need to check
if (array.length === _opts.limit) {
UTIL.safeCall(cb, null, array, array[array.length - 1]);
} else {
UTIL.safeCall(cb, null, array, null);
}
} | javascript | function (err_toArray, array) {
if (err_toArray) {
return l_notifyError(clt_name, 'getPage.toArray', err_toArray, cb);
}
//LOG.sys('array found succces, length: ' + array.length, 'SR.DB');
// NOTE: probably no need to check
if (array.length === _opts.limit) {
UTIL.safeCall(cb, null, array, array[array.length - 1]);
} else {
UTIL.safeCall(cb, null, array, null);
}
} | [
"function",
"(",
"err_toArray",
",",
"array",
")",
"{",
"if",
"(",
"err_toArray",
")",
"{",
"return",
"l_notifyError",
"(",
"clt_name",
",",
"'getPage.toArray'",
",",
"err_toArray",
",",
"cb",
")",
";",
"}",
"if",
"(",
"array",
".",
"length",
"===",
"_opts",
".",
"limit",
")",
"{",
"UTIL",
".",
"safeCall",
"(",
"cb",
",",
"null",
",",
"array",
",",
"array",
"[",
"array",
".",
"length",
"-",
"1",
"]",
")",
";",
"}",
"else",
"{",
"UTIL",
".",
"safeCall",
"(",
"cb",
",",
"null",
",",
"array",
",",
"null",
")",
";",
"}",
"}"
] | convert result to an array | [
"convert",
"result",
"to",
"an",
"array"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/DB.js#L867-L880 | train |
|
particle-iot/particle-commands | src/cmd/library_install.js | nameVersionInstallStrategy | function nameVersionInstallStrategy(baseDir) {
return (name, version) => {
if (!version) {
throw Error('hey I need a version!');
}
// todo - should probably instead instantiate the appropriate library repository
// so we get reuse and consistency
return path.join(baseDir, name+'@'+version);
};
} | javascript | function nameVersionInstallStrategy(baseDir) {
return (name, version) => {
if (!version) {
throw Error('hey I need a version!');
}
// todo - should probably instead instantiate the appropriate library repository
// so we get reuse and consistency
return path.join(baseDir, name+'@'+version);
};
} | [
"function",
"nameVersionInstallStrategy",
"(",
"baseDir",
")",
"{",
"return",
"(",
"name",
",",
"version",
")",
"=>",
"{",
"if",
"(",
"!",
"version",
")",
"{",
"throw",
"Error",
"(",
"'hey I need a version!'",
")",
";",
"}",
"return",
"path",
".",
"join",
"(",
"baseDir",
",",
"name",
"+",
"'@'",
"+",
"version",
")",
";",
"}",
";",
"}"
] | A strategy factory that determines where to place libraries when installed to
a shared directory.
@param {string} baseDir the shared directory where the library should be installed ot
@returns {function(*, *=)} A function that provides the target library directory | [
"A",
"strategy",
"factory",
"that",
"determines",
"where",
"to",
"place",
"libraries",
"when",
"installed",
"to",
"a",
"shared",
"directory",
"."
] | 012252e0faef5f4ee21aa3b36c58eace7296a633 | https://github.com/particle-iot/particle-commands/blob/012252e0faef5f4ee21aa3b36c58eace7296a633/src/cmd/library_install.js#L101-L110 | train |
imonology/scalra | lib/SR_REST.js | function (type, para) {
// avoid flooding if SR_PUBLISH is sending streaming data
SR.Log('[' + type + '] received');
switch (type) {
//
// pubsub related
//
// when a new published message arrives
case 'SR_MSG':
// handle server-published messages
case 'SR_PUBLISH':
if (onChannelMessages.hasOwnProperty(para.channel)) {
if (typeof onChannelMessages[para.channel] !== 'function')
SR.Error('channel [' + para.channel + '] handler is not a function');
else
onChannelMessages[para.channel](para.msg, para.channel);
}
else
SR.Error('cannot find channel [' + para.channel + '] to publish');
return true;
// when a list of messages arrive (in array)
case 'SR_MSGLIST':
var msg_list = para.msgs;
if (msg_list && msg_list.length > 0 && onChannelMessages.hasOwnProperty(para.channel)) {
for (var i=0; i < msg_list.length; i++)
onChannelMessages[para.channel](msg_list[i], para.channel);
}
return true;
// redirect to another webpage
case 'SR_REDIRECT':
window.location.href = para.url;
return true;
case "SR_NOTIFY" :
SR.Warn('SR_NOTIFY para: ');
SR.Warn(para);
console.log(onChannelMessages);
if (onChannelMessages.hasOwnProperty('notify'))
onChannelMessages['notify'](para, 'notify');
return true;
//
// login related
//
case "SR_LOGIN_RESPONSE":
case "SR_LOGOUT_RESPONSE":
replyLogin(para);
return true;
case "SR_MESSAGE":
alert('SR_MESSAGE: ' + para.msg);
return true;
case "SR_WARNING":
alert('SR_WARNING: ' + para.msg);
return true;
case "SR_ERROR":
alert('SR_ERROR: ' + para.msg);
return true;
default:
// check if custom handlers exist and can handle it
if (responseHandlers.hasOwnProperty(type)) {
var callbacks = responseHandlers[type];
// extract rid if available
var rid = undefined;
if (para.hasOwnProperty('_rid') === true) {
rid = para['_rid'];
delete para['_rid'];
}
if (rid) {
callbacks[rid](para, type);
// remove callback once done
if (rid !== 'keep') {
delete callbacks[rid];
}
}
// otherwise ALL registered callbacks will be called
else {
if (Object.keys(callbacks).length > 1)
SR.Warn('[' + type + '] no rid in update, dispatching to first of ' + Object.keys(callbacks).length + ' callbacks');
// call the first in callbacks then remove it
// so only one callback is called unless it's registered via the 'keep_callback' flag
for (var key in callbacks) {
callbacks[key](para, type);
if (key !== 'keep') {
delete callbacks[key];
break;
}
}
}
return true;
}
// still un-handled
console.error('onResponse: unrecongized type: ' + type);
return false;
}
} | javascript | function (type, para) {
// avoid flooding if SR_PUBLISH is sending streaming data
SR.Log('[' + type + '] received');
switch (type) {
//
// pubsub related
//
// when a new published message arrives
case 'SR_MSG':
// handle server-published messages
case 'SR_PUBLISH':
if (onChannelMessages.hasOwnProperty(para.channel)) {
if (typeof onChannelMessages[para.channel] !== 'function')
SR.Error('channel [' + para.channel + '] handler is not a function');
else
onChannelMessages[para.channel](para.msg, para.channel);
}
else
SR.Error('cannot find channel [' + para.channel + '] to publish');
return true;
// when a list of messages arrive (in array)
case 'SR_MSGLIST':
var msg_list = para.msgs;
if (msg_list && msg_list.length > 0 && onChannelMessages.hasOwnProperty(para.channel)) {
for (var i=0; i < msg_list.length; i++)
onChannelMessages[para.channel](msg_list[i], para.channel);
}
return true;
// redirect to another webpage
case 'SR_REDIRECT':
window.location.href = para.url;
return true;
case "SR_NOTIFY" :
SR.Warn('SR_NOTIFY para: ');
SR.Warn(para);
console.log(onChannelMessages);
if (onChannelMessages.hasOwnProperty('notify'))
onChannelMessages['notify'](para, 'notify');
return true;
//
// login related
//
case "SR_LOGIN_RESPONSE":
case "SR_LOGOUT_RESPONSE":
replyLogin(para);
return true;
case "SR_MESSAGE":
alert('SR_MESSAGE: ' + para.msg);
return true;
case "SR_WARNING":
alert('SR_WARNING: ' + para.msg);
return true;
case "SR_ERROR":
alert('SR_ERROR: ' + para.msg);
return true;
default:
// check if custom handlers exist and can handle it
if (responseHandlers.hasOwnProperty(type)) {
var callbacks = responseHandlers[type];
// extract rid if available
var rid = undefined;
if (para.hasOwnProperty('_rid') === true) {
rid = para['_rid'];
delete para['_rid'];
}
if (rid) {
callbacks[rid](para, type);
// remove callback once done
if (rid !== 'keep') {
delete callbacks[rid];
}
}
// otherwise ALL registered callbacks will be called
else {
if (Object.keys(callbacks).length > 1)
SR.Warn('[' + type + '] no rid in update, dispatching to first of ' + Object.keys(callbacks).length + ' callbacks');
// call the first in callbacks then remove it
// so only one callback is called unless it's registered via the 'keep_callback' flag
for (var key in callbacks) {
callbacks[key](para, type);
if (key !== 'keep') {
delete callbacks[key];
break;
}
}
}
return true;
}
// still un-handled
console.error('onResponse: unrecongized type: ' + type);
return false;
}
} | [
"function",
"(",
"type",
",",
"para",
")",
"{",
"SR",
".",
"Log",
"(",
"'['",
"+",
"type",
"+",
"'] received'",
")",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'SR_MSG'",
":",
"case",
"'SR_PUBLISH'",
":",
"if",
"(",
"onChannelMessages",
".",
"hasOwnProperty",
"(",
"para",
".",
"channel",
")",
")",
"{",
"if",
"(",
"typeof",
"onChannelMessages",
"[",
"para",
".",
"channel",
"]",
"!==",
"'function'",
")",
"SR",
".",
"Error",
"(",
"'channel ['",
"+",
"para",
".",
"channel",
"+",
"'] handler is not a function'",
")",
";",
"else",
"onChannelMessages",
"[",
"para",
".",
"channel",
"]",
"(",
"para",
".",
"msg",
",",
"para",
".",
"channel",
")",
";",
"}",
"else",
"SR",
".",
"Error",
"(",
"'cannot find channel ['",
"+",
"para",
".",
"channel",
"+",
"'] to publish'",
")",
";",
"return",
"true",
";",
"case",
"'SR_MSGLIST'",
":",
"var",
"msg_list",
"=",
"para",
".",
"msgs",
";",
"if",
"(",
"msg_list",
"&&",
"msg_list",
".",
"length",
">",
"0",
"&&",
"onChannelMessages",
".",
"hasOwnProperty",
"(",
"para",
".",
"channel",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"msg_list",
".",
"length",
";",
"i",
"++",
")",
"onChannelMessages",
"[",
"para",
".",
"channel",
"]",
"(",
"msg_list",
"[",
"i",
"]",
",",
"para",
".",
"channel",
")",
";",
"}",
"return",
"true",
";",
"case",
"'SR_REDIRECT'",
":",
"window",
".",
"location",
".",
"href",
"=",
"para",
".",
"url",
";",
"return",
"true",
";",
"case",
"\"SR_NOTIFY\"",
":",
"SR",
".",
"Warn",
"(",
"'SR_NOTIFY para: '",
")",
";",
"SR",
".",
"Warn",
"(",
"para",
")",
";",
"console",
".",
"log",
"(",
"onChannelMessages",
")",
";",
"if",
"(",
"onChannelMessages",
".",
"hasOwnProperty",
"(",
"'notify'",
")",
")",
"onChannelMessages",
"[",
"'notify'",
"]",
"(",
"para",
",",
"'notify'",
")",
";",
"return",
"true",
";",
"case",
"\"SR_LOGIN_RESPONSE\"",
":",
"case",
"\"SR_LOGOUT_RESPONSE\"",
":",
"replyLogin",
"(",
"para",
")",
";",
"return",
"true",
";",
"case",
"\"SR_MESSAGE\"",
":",
"alert",
"(",
"'SR_MESSAGE: '",
"+",
"para",
".",
"msg",
")",
";",
"return",
"true",
";",
"case",
"\"SR_WARNING\"",
":",
"alert",
"(",
"'SR_WARNING: '",
"+",
"para",
".",
"msg",
")",
";",
"return",
"true",
";",
"case",
"\"SR_ERROR\"",
":",
"alert",
"(",
"'SR_ERROR: '",
"+",
"para",
".",
"msg",
")",
";",
"return",
"true",
";",
"default",
":",
"if",
"(",
"responseHandlers",
".",
"hasOwnProperty",
"(",
"type",
")",
")",
"{",
"var",
"callbacks",
"=",
"responseHandlers",
"[",
"type",
"]",
";",
"var",
"rid",
"=",
"undefined",
";",
"if",
"(",
"para",
".",
"hasOwnProperty",
"(",
"'_rid'",
")",
"===",
"true",
")",
"{",
"rid",
"=",
"para",
"[",
"'_rid'",
"]",
";",
"delete",
"para",
"[",
"'_rid'",
"]",
";",
"}",
"if",
"(",
"rid",
")",
"{",
"callbacks",
"[",
"rid",
"]",
"(",
"para",
",",
"type",
")",
";",
"if",
"(",
"rid",
"!==",
"'keep'",
")",
"{",
"delete",
"callbacks",
"[",
"rid",
"]",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"callbacks",
")",
".",
"length",
">",
"1",
")",
"SR",
".",
"Warn",
"(",
"'['",
"+",
"type",
"+",
"'] no rid in update, dispatching to first of '",
"+",
"Object",
".",
"keys",
"(",
"callbacks",
")",
".",
"length",
"+",
"' callbacks'",
")",
";",
"for",
"(",
"var",
"key",
"in",
"callbacks",
")",
"{",
"callbacks",
"[",
"key",
"]",
"(",
"para",
",",
"type",
")",
";",
"if",
"(",
"key",
"!==",
"'keep'",
")",
"{",
"delete",
"callbacks",
"[",
"key",
"]",
";",
"break",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}",
"console",
".",
"error",
"(",
"'onResponse: unrecongized type: '",
"+",
"type",
")",
";",
"return",
"false",
";",
"}",
"}"
] | generic response callback for system-defined messages | [
"generic",
"response",
"callback",
"for",
"system",
"-",
"defined",
"messages"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/lib/SR_REST.js#L283-L387 | train |
|
imonology/scalra | lib/SR_REST.js | function (entry) {
if (typeof entry === 'number' && entry < entryServers.length) {
entryServers.splice(entry, 1);
return true;
}
else if (typeof entry === 'string') {
for (var i=0; i < entryServers.length; i++) {
if (entryServers[i] === entry) {
entryServers.splice(i, 1);
SR.Log('remove entry: ' + entry + '. entries left: ' + entryServers.length);
return true;
}
}
}
return false;
} | javascript | function (entry) {
if (typeof entry === 'number' && entry < entryServers.length) {
entryServers.splice(entry, 1);
return true;
}
else if (typeof entry === 'string') {
for (var i=0; i < entryServers.length; i++) {
if (entryServers[i] === entry) {
entryServers.splice(i, 1);
SR.Log('remove entry: ' + entry + '. entries left: ' + entryServers.length);
return true;
}
}
}
return false;
} | [
"function",
"(",
"entry",
")",
"{",
"if",
"(",
"typeof",
"entry",
"===",
"'number'",
"&&",
"entry",
"<",
"entryServers",
".",
"length",
")",
"{",
"entryServers",
".",
"splice",
"(",
"entry",
",",
"1",
")",
";",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"typeof",
"entry",
"===",
"'string'",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"entryServers",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"entryServers",
"[",
"i",
"]",
"===",
"entry",
")",
"{",
"entryServers",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"SR",
".",
"Log",
"(",
"'remove entry: '",
"+",
"entry",
"+",
"'. entries left: '",
"+",
"entryServers",
".",
"length",
")",
";",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | remove a given entry server | [
"remove",
"a",
"given",
"entry",
"server"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/lib/SR_REST.js#L401-L416 | train |
|
imonology/scalra | lib/SR_REST.js | function (name) {
return function (args, onDone) {
if (typeof args === 'function') {
onDone = args;
args = {};
}
console.log('calling API [' + name + ']...');
// NOTE: by default callbacks are always kept
SR.sendEvent(name, args, function (result) {
if (result.err) {
console.error(result.err);
return SR.safeCall(onDone, result.err);
}
SR.safeCall(onDone, null, result.result);
}, undefined, true);
}
} | javascript | function (name) {
return function (args, onDone) {
if (typeof args === 'function') {
onDone = args;
args = {};
}
console.log('calling API [' + name + ']...');
// NOTE: by default callbacks are always kept
SR.sendEvent(name, args, function (result) {
if (result.err) {
console.error(result.err);
return SR.safeCall(onDone, result.err);
}
SR.safeCall(onDone, null, result.result);
}, undefined, true);
}
} | [
"function",
"(",
"name",
")",
"{",
"return",
"function",
"(",
"args",
",",
"onDone",
")",
"{",
"if",
"(",
"typeof",
"args",
"===",
"'function'",
")",
"{",
"onDone",
"=",
"args",
";",
"args",
"=",
"{",
"}",
";",
"}",
"console",
".",
"log",
"(",
"'calling API ['",
"+",
"name",
"+",
"']...'",
")",
";",
"SR",
".",
"sendEvent",
"(",
"name",
",",
"args",
",",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"result",
".",
"err",
")",
"{",
"console",
".",
"error",
"(",
"result",
".",
"err",
")",
";",
"return",
"SR",
".",
"safeCall",
"(",
"onDone",
",",
"result",
".",
"err",
")",
";",
"}",
"SR",
".",
"safeCall",
"(",
"onDone",
",",
"null",
",",
"result",
".",
"result",
")",
";",
"}",
",",
"undefined",
",",
"true",
")",
";",
"}",
"}"
] | build a specific API | [
"build",
"a",
"specific",
"API"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/lib/SR_REST.js#L996-L1016 | train |
|
imonology/scalra | core/frontier.js | function (root_path, default_prefix) {
var arr = SR.Settings.SR_PATH.split(SR.path.sep);
var prefix = arr[arr.length-1] + '-';
var dirs = UTIL.getDirectoriesSync(root_path);
if (default_prefix)
prefix = default_prefix;
//LOG.warn('default_prefix: ' + default_prefix + ' prefix: ' + prefix + ' paths to check:');
for (var i in dirs) {
//LOG.warn(dirs[i]);
if (dirs[i].startsWith(prefix)) {
SR.Settings.MOD_PATHS.push(SR.path.resolve(root_path, dirs[i]));
}
}
} | javascript | function (root_path, default_prefix) {
var arr = SR.Settings.SR_PATH.split(SR.path.sep);
var prefix = arr[arr.length-1] + '-';
var dirs = UTIL.getDirectoriesSync(root_path);
if (default_prefix)
prefix = default_prefix;
//LOG.warn('default_prefix: ' + default_prefix + ' prefix: ' + prefix + ' paths to check:');
for (var i in dirs) {
//LOG.warn(dirs[i]);
if (dirs[i].startsWith(prefix)) {
SR.Settings.MOD_PATHS.push(SR.path.resolve(root_path, dirs[i]));
}
}
} | [
"function",
"(",
"root_path",
",",
"default_prefix",
")",
"{",
"var",
"arr",
"=",
"SR",
".",
"Settings",
".",
"SR_PATH",
".",
"split",
"(",
"SR",
".",
"path",
".",
"sep",
")",
";",
"var",
"prefix",
"=",
"arr",
"[",
"arr",
".",
"length",
"-",
"1",
"]",
"+",
"'-'",
";",
"var",
"dirs",
"=",
"UTIL",
".",
"getDirectoriesSync",
"(",
"root_path",
")",
";",
"if",
"(",
"default_prefix",
")",
"prefix",
"=",
"default_prefix",
";",
"for",
"(",
"var",
"i",
"in",
"dirs",
")",
"{",
"if",
"(",
"dirs",
"[",
"i",
"]",
".",
"startsWith",
"(",
"prefix",
")",
")",
"{",
"SR",
".",
"Settings",
".",
"MOD_PATHS",
".",
"push",
"(",
"SR",
".",
"path",
".",
"resolve",
"(",
"root_path",
",",
"dirs",
"[",
"i",
"]",
")",
")",
";",
"}",
"}",
"}"
] | build module path from a root path | [
"build",
"module",
"path",
"from",
"a",
"root",
"path"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/frontier.js#L130-L145 | train |
|
imonology/scalra | core/script.js | function (fullpath, publname) {
var curr_time = new Date();
// store script if modified for first time
if (fullpath !== undefined && publname !== undefined) {
if (l_modified_scripts.hasOwnProperty(fullpath) === false) {
LOG.warn('script modified: ' + fullpath, l_name);
l_modified_scripts[fullpath] = {
time: new Date(curr_time.getTime() + l_reloadTime * 1000),
name: publname
};
}
// if already stored, ignore this request
else
return;
}
else {
// check queue for scripts that can be safely reloaded
for (var path in l_modified_scripts) {
// check if wait time has expired
if (curr_time - l_modified_scripts[path].time > 0) {
// get public name
var name = l_modified_scripts[path].name;
var notify_msg = 'reloading [' + name + '] from: ' + path;
LOG.warn(notify_msg, l_name);
// send e-mail notify to project admin (only if specified)
if (SR.Settings.NOTIFY_SCRIPT_RELOAD === true)
UTIL.notifyAdmin('script reloading', notify_msg);
// save current script in cache as backup
var backup_script = require.cache[path];
// NOTE: if 'path' is incorrect, may not delete successfully, and new script won't load
delete require.cache[path];
// NOTE: this will show false
//LOG.warn('after delete, has path: ' + require.cache.hasOwnProperty(path), l_name);
// NOTE: something can go wrong if the script is corrupt
try {
// re-require
if (l_args.hasOwnProperty(path)) {
LOG.warn('args exist..', l_name);
require(path)(l_args[path]);
l_loaded[name] = require.cache[path];
}
else {
l_loaded[name] = require(path);
SR.Handler.add(l_loaded[name]);
}
}
catch (e) {
LOG.error('reload error: ', l_name);
LOG.error(UTIL.dumpError(e), l_name);
LOG.warn('restoring old script...', l_name);
require.cache[path] = backup_script;
l_loaded[name] = require.cache[path];
// this will show 'true'
//LOG.warn('after restore, has path: ' + require.cache.hasOwnProperty(path), l_name);
}
// remove file record
delete l_modified_scripts[path];
}
}
}
// reload myself to check later if there are scripts to be loaded
if (Object.keys(l_modified_scripts).length > 0) {
var timeout = l_reloadTime * 1.5 * 1000;
LOG.sys('automatic reloading after: ' + timeout + ' ms', l_name);
setTimeout(l_loadScript, timeout);
}
} | javascript | function (fullpath, publname) {
var curr_time = new Date();
// store script if modified for first time
if (fullpath !== undefined && publname !== undefined) {
if (l_modified_scripts.hasOwnProperty(fullpath) === false) {
LOG.warn('script modified: ' + fullpath, l_name);
l_modified_scripts[fullpath] = {
time: new Date(curr_time.getTime() + l_reloadTime * 1000),
name: publname
};
}
// if already stored, ignore this request
else
return;
}
else {
// check queue for scripts that can be safely reloaded
for (var path in l_modified_scripts) {
// check if wait time has expired
if (curr_time - l_modified_scripts[path].time > 0) {
// get public name
var name = l_modified_scripts[path].name;
var notify_msg = 'reloading [' + name + '] from: ' + path;
LOG.warn(notify_msg, l_name);
// send e-mail notify to project admin (only if specified)
if (SR.Settings.NOTIFY_SCRIPT_RELOAD === true)
UTIL.notifyAdmin('script reloading', notify_msg);
// save current script in cache as backup
var backup_script = require.cache[path];
// NOTE: if 'path' is incorrect, may not delete successfully, and new script won't load
delete require.cache[path];
// NOTE: this will show false
//LOG.warn('after delete, has path: ' + require.cache.hasOwnProperty(path), l_name);
// NOTE: something can go wrong if the script is corrupt
try {
// re-require
if (l_args.hasOwnProperty(path)) {
LOG.warn('args exist..', l_name);
require(path)(l_args[path]);
l_loaded[name] = require.cache[path];
}
else {
l_loaded[name] = require(path);
SR.Handler.add(l_loaded[name]);
}
}
catch (e) {
LOG.error('reload error: ', l_name);
LOG.error(UTIL.dumpError(e), l_name);
LOG.warn('restoring old script...', l_name);
require.cache[path] = backup_script;
l_loaded[name] = require.cache[path];
// this will show 'true'
//LOG.warn('after restore, has path: ' + require.cache.hasOwnProperty(path), l_name);
}
// remove file record
delete l_modified_scripts[path];
}
}
}
// reload myself to check later if there are scripts to be loaded
if (Object.keys(l_modified_scripts).length > 0) {
var timeout = l_reloadTime * 1.5 * 1000;
LOG.sys('automatic reloading after: ' + timeout + ' ms', l_name);
setTimeout(l_loadScript, timeout);
}
} | [
"function",
"(",
"fullpath",
",",
"publname",
")",
"{",
"var",
"curr_time",
"=",
"new",
"Date",
"(",
")",
";",
"if",
"(",
"fullpath",
"!==",
"undefined",
"&&",
"publname",
"!==",
"undefined",
")",
"{",
"if",
"(",
"l_modified_scripts",
".",
"hasOwnProperty",
"(",
"fullpath",
")",
"===",
"false",
")",
"{",
"LOG",
".",
"warn",
"(",
"'script modified: '",
"+",
"fullpath",
",",
"l_name",
")",
";",
"l_modified_scripts",
"[",
"fullpath",
"]",
"=",
"{",
"time",
":",
"new",
"Date",
"(",
"curr_time",
".",
"getTime",
"(",
")",
"+",
"l_reloadTime",
"*",
"1000",
")",
",",
"name",
":",
"publname",
"}",
";",
"}",
"else",
"return",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"path",
"in",
"l_modified_scripts",
")",
"{",
"if",
"(",
"curr_time",
"-",
"l_modified_scripts",
"[",
"path",
"]",
".",
"time",
">",
"0",
")",
"{",
"var",
"name",
"=",
"l_modified_scripts",
"[",
"path",
"]",
".",
"name",
";",
"var",
"notify_msg",
"=",
"'reloading ['",
"+",
"name",
"+",
"'] from: '",
"+",
"path",
";",
"LOG",
".",
"warn",
"(",
"notify_msg",
",",
"l_name",
")",
";",
"if",
"(",
"SR",
".",
"Settings",
".",
"NOTIFY_SCRIPT_RELOAD",
"===",
"true",
")",
"UTIL",
".",
"notifyAdmin",
"(",
"'script reloading'",
",",
"notify_msg",
")",
";",
"var",
"backup_script",
"=",
"require",
".",
"cache",
"[",
"path",
"]",
";",
"delete",
"require",
".",
"cache",
"[",
"path",
"]",
";",
"try",
"{",
"if",
"(",
"l_args",
".",
"hasOwnProperty",
"(",
"path",
")",
")",
"{",
"LOG",
".",
"warn",
"(",
"'args exist..'",
",",
"l_name",
")",
";",
"require",
"(",
"path",
")",
"(",
"l_args",
"[",
"path",
"]",
")",
";",
"l_loaded",
"[",
"name",
"]",
"=",
"require",
".",
"cache",
"[",
"path",
"]",
";",
"}",
"else",
"{",
"l_loaded",
"[",
"name",
"]",
"=",
"require",
"(",
"path",
")",
";",
"SR",
".",
"Handler",
".",
"add",
"(",
"l_loaded",
"[",
"name",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"'reload error: '",
",",
"l_name",
")",
";",
"LOG",
".",
"error",
"(",
"UTIL",
".",
"dumpError",
"(",
"e",
")",
",",
"l_name",
")",
";",
"LOG",
".",
"warn",
"(",
"'restoring old script...'",
",",
"l_name",
")",
";",
"require",
".",
"cache",
"[",
"path",
"]",
"=",
"backup_script",
";",
"l_loaded",
"[",
"name",
"]",
"=",
"require",
".",
"cache",
"[",
"path",
"]",
";",
"}",
"delete",
"l_modified_scripts",
"[",
"path",
"]",
";",
"}",
"}",
"}",
"if",
"(",
"Object",
".",
"keys",
"(",
"l_modified_scripts",
")",
".",
"length",
">",
"0",
")",
"{",
"var",
"timeout",
"=",
"l_reloadTime",
"*",
"1.5",
"*",
"1000",
";",
"LOG",
".",
"sys",
"(",
"'automatic reloading after: '",
"+",
"timeout",
"+",
"' ms'",
",",
"l_name",
")",
";",
"setTimeout",
"(",
"l_loadScript",
",",
"timeout",
")",
";",
"}",
"}"
] | script loader, will check periodically if modified script queue is non-empty | [
"script",
"loader",
"will",
"check",
"periodically",
"if",
"modified",
"script",
"queue",
"is",
"non",
"-",
"empty"
] | 0cf7377d02bf1e6beb90d6821c144eefb89feaa9 | https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/script.js#L26-L108 | train |
|
doowb/sma | index.js | sma | function sma(arr, range, format) {
if (!Array.isArray(arr)) {
throw TypeError('expected first argument to be an array');
}
var fn = typeof format === 'function' ? format : toFixed;
var num = range || arr.length;
var res = [];
var len = arr.length + 1;
var idx = num - 1;
while (++idx < len) {
res.push(fn(avg(arr, idx, num)));
}
return res;
} | javascript | function sma(arr, range, format) {
if (!Array.isArray(arr)) {
throw TypeError('expected first argument to be an array');
}
var fn = typeof format === 'function' ? format : toFixed;
var num = range || arr.length;
var res = [];
var len = arr.length + 1;
var idx = num - 1;
while (++idx < len) {
res.push(fn(avg(arr, idx, num)));
}
return res;
} | [
"function",
"sma",
"(",
"arr",
",",
"range",
",",
"format",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"arr",
")",
")",
"{",
"throw",
"TypeError",
"(",
"'expected first argument to be an array'",
")",
";",
"}",
"var",
"fn",
"=",
"typeof",
"format",
"===",
"'function'",
"?",
"format",
":",
"toFixed",
";",
"var",
"num",
"=",
"range",
"||",
"arr",
".",
"length",
";",
"var",
"res",
"=",
"[",
"]",
";",
"var",
"len",
"=",
"arr",
".",
"length",
"+",
"1",
";",
"var",
"idx",
"=",
"num",
"-",
"1",
";",
"while",
"(",
"++",
"idx",
"<",
"len",
")",
"{",
"res",
".",
"push",
"(",
"fn",
"(",
"avg",
"(",
"arr",
",",
"idx",
",",
"num",
")",
")",
")",
";",
"}",
"return",
"res",
";",
"}"
] | Calculate the simple moving average of an array. A new array is returned with the average
of each range of elements. A range will only be calculated when it contains enough elements to fill the range.
```js
console.log(sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4));
//=> [ '2.50', '3.50', '4.50', '5.50', '6.50', '7.50' ]
//=> │ │ │ │ │ └─(6+7+8+9)/4
//=> │ │ │ │ └─(5+6+7+8)/4
//=> │ │ │ └─(4+5+6+7)/4
//=> │ │ └─(3+4+5+6)/4
//=> │ └─(2+3+4+5)/4
//=> └─(1+2+3+4)/4
```
@param {Array} `arr` Array of numbers to calculate.
@param {Number} `range` Size of the window to use to when calculating the average for each range. Defaults to array length.
@param {Function} `format` Custom format function called on each calculated average. Defaults to `n.toFixed(2)`.
@return {Array} Resulting array of averages.
@api public | [
"Calculate",
"the",
"simple",
"moving",
"average",
"of",
"an",
"array",
".",
"A",
"new",
"array",
"is",
"returned",
"with",
"the",
"average",
"of",
"each",
"range",
"of",
"elements",
".",
"A",
"range",
"will",
"only",
"be",
"calculated",
"when",
"it",
"contains",
"enough",
"elements",
"to",
"fill",
"the",
"range",
"."
] | 4c419042c0377bf6c78a8c94832f3d2a59e11a72 | https://github.com/doowb/sma/blob/4c419042c0377bf6c78a8c94832f3d2a59e11a72/index.js#L24-L38 | train |
doowb/sma | index.js | avg | function avg(arr, idx, range) {
return sum(arr.slice(idx - range, idx)) / range;
} | javascript | function avg(arr, idx, range) {
return sum(arr.slice(idx - range, idx)) / range;
} | [
"function",
"avg",
"(",
"arr",
",",
"idx",
",",
"range",
")",
"{",
"return",
"sum",
"(",
"arr",
".",
"slice",
"(",
"idx",
"-",
"range",
",",
"idx",
")",
")",
"/",
"range",
";",
"}"
] | Create an average for the specified range.
```js
console.log(avg([1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 4));
//=> 3.5
```
@param {Array} `arr` Array to pull the range from.
@param {Number} `idx` Index of element being calculated
@param {Number} `range` Size of range to calculate.
@return {Number} Average of range. | [
"Create",
"an",
"average",
"for",
"the",
"specified",
"range",
"."
] | 4c419042c0377bf6c78a8c94832f3d2a59e11a72 | https://github.com/doowb/sma/blob/4c419042c0377bf6c78a8c94832f3d2a59e11a72/index.js#L53-L55 | train |
doowb/sma | index.js | sum | function sum(arr) {
var len = arr.length;
var num = 0;
while (len--) num += Number(arr[len]);
return num;
} | javascript | function sum(arr) {
var len = arr.length;
var num = 0;
while (len--) num += Number(arr[len]);
return num;
} | [
"function",
"sum",
"(",
"arr",
")",
"{",
"var",
"len",
"=",
"arr",
".",
"length",
";",
"var",
"num",
"=",
"0",
";",
"while",
"(",
"len",
"--",
")",
"num",
"+=",
"Number",
"(",
"arr",
"[",
"len",
"]",
")",
";",
"return",
"num",
";",
"}"
] | Calculate the sum of an array.
@param {Array} `arr` Array
@return {Number} Sum | [
"Calculate",
"the",
"sum",
"of",
"an",
"array",
"."
] | 4c419042c0377bf6c78a8c94832f3d2a59e11a72 | https://github.com/doowb/sma/blob/4c419042c0377bf6c78a8c94832f3d2a59e11a72/index.js#L63-L68 | train |
protacon/ng-virtual-keyboard | dist/layouts.js | isSpecial | function isSpecial(key) {
if (key.length > 1) {
return !!exports.specialKeys.filter(function (specialKey) {
var pattern = new RegExp("^(" + specialKey + ")(:(\\d+(\\.\\d+)?))?$", 'g');
return pattern.test(key);
}).length;
}
return false;
} | javascript | function isSpecial(key) {
if (key.length > 1) {
return !!exports.specialKeys.filter(function (specialKey) {
var pattern = new RegExp("^(" + specialKey + ")(:(\\d+(\\.\\d+)?))?$", 'g');
return pattern.test(key);
}).length;
}
return false;
} | [
"function",
"isSpecial",
"(",
"key",
")",
"{",
"if",
"(",
"key",
".",
"length",
">",
"1",
")",
"{",
"return",
"!",
"!",
"exports",
".",
"specialKeys",
".",
"filter",
"(",
"function",
"(",
"specialKey",
")",
"{",
"var",
"pattern",
"=",
"new",
"RegExp",
"(",
"\"^(\"",
"+",
"specialKey",
"+",
"\")(:(\\\\d+(\\\\.\\\\d+)?))?$\"",
",",
"\\\\",
")",
";",
"\\\\",
"}",
")",
".",
"\\\\",
";",
"}",
"'g'",
"}"
] | Helper function to determine if given key is special or not.
@param {string} key
@returns {boolean} | [
"Helper",
"function",
"to",
"determine",
"if",
"given",
"key",
"is",
"special",
"or",
"not",
"."
] | cb55c5bbbb85e5a7e47eb8b84e90748a0b7fd9a8 | https://github.com/protacon/ng-virtual-keyboard/blob/cb55c5bbbb85e5a7e47eb8b84e90748a0b7fd9a8/dist/layouts.js#L84-L92 | train |
protacon/ng-virtual-keyboard | dist/layouts.js | keyboardCapsLockLayout | function keyboardCapsLockLayout(layout, caps) {
return layout.map(function (row) {
return row.map(function (key) {
return isSpecial(key) ? key : (caps ? key.toUpperCase() : key.toLowerCase());
});
});
} | javascript | function keyboardCapsLockLayout(layout, caps) {
return layout.map(function (row) {
return row.map(function (key) {
return isSpecial(key) ? key : (caps ? key.toUpperCase() : key.toLowerCase());
});
});
} | [
"function",
"keyboardCapsLockLayout",
"(",
"layout",
",",
"caps",
")",
"{",
"return",
"layout",
".",
"map",
"(",
"function",
"(",
"row",
")",
"{",
"return",
"row",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"isSpecial",
"(",
"key",
")",
"?",
"key",
":",
"(",
"caps",
"?",
"key",
".",
"toUpperCase",
"(",
")",
":",
"key",
".",
"toLowerCase",
"(",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Function to change specified layout to CapsLock layout.
@param {KeyboardLayout} layout
@param {boolean} caps
@returns {KeyboardLayout} | [
"Function",
"to",
"change",
"specified",
"layout",
"to",
"CapsLock",
"layout",
"."
] | cb55c5bbbb85e5a7e47eb8b84e90748a0b7fd9a8 | https://github.com/protacon/ng-virtual-keyboard/blob/cb55c5bbbb85e5a7e47eb8b84e90748a0b7fd9a8/dist/layouts.js#L101-L107 | train |
nolanlawson/node-websql | lib/websql/WebSQLDatabase.js | TransactionTask | function TransactionTask(readOnly, txnCallback, errorCallback, successCallback) {
this.readOnly = readOnly;
this.txnCallback = txnCallback;
this.errorCallback = errorCallback;
this.successCallback = successCallback;
} | javascript | function TransactionTask(readOnly, txnCallback, errorCallback, successCallback) {
this.readOnly = readOnly;
this.txnCallback = txnCallback;
this.errorCallback = errorCallback;
this.successCallback = successCallback;
} | [
"function",
"TransactionTask",
"(",
"readOnly",
",",
"txnCallback",
",",
"errorCallback",
",",
"successCallback",
")",
"{",
"this",
".",
"readOnly",
"=",
"readOnly",
";",
"this",
".",
"txnCallback",
"=",
"txnCallback",
";",
"this",
".",
"errorCallback",
"=",
"errorCallback",
";",
"this",
".",
"successCallback",
"=",
"successCallback",
";",
"}"
] | v8 likes predictable objects | [
"v8",
"likes",
"predictable",
"objects"
] | ab6d7e06e00909046b98250da71248802935a284 | https://github.com/nolanlawson/node-websql/blob/ab6d7e06e00909046b98250da71248802935a284/lib/websql/WebSQLDatabase.js#L18-L23 | train |
typicode/pinst | index.js | renameKey | function renameKey(obj, prevKey, nextKey) {
return mapKeys(obj, (_, key) => (key === prevKey ? nextKey : key))
} | javascript | function renameKey(obj, prevKey, nextKey) {
return mapKeys(obj, (_, key) => (key === prevKey ? nextKey : key))
} | [
"function",
"renameKey",
"(",
"obj",
",",
"prevKey",
",",
"nextKey",
")",
"{",
"return",
"mapKeys",
"(",
"obj",
",",
"(",
"_",
",",
"key",
")",
"=>",
"(",
"key",
"===",
"prevKey",
"?",
"nextKey",
":",
"key",
")",
")",
"}"
] | Rename key in object without changing its position | [
"Rename",
"key",
"in",
"object",
"without",
"changing",
"its",
"position"
] | 719b1046c7d65ba445b171561b492e38c2791148 | https://github.com/typicode/pinst/blob/719b1046c7d65ba445b171561b492e38c2791148/index.js#L8-L10 | train |
obliquid/jslardo | public/javascripts/jslardo.js | openModal | function openModal(src, width) {
if ( !width ) width = 680;
//var elementId = 'orcodio';
var originalYScroll = window.pageYOffset;
//var modalFrame = $.modal('<iframe id="'+ elementId +'" src="' + src + '" width="' + width + '" onload="centerModal(this,' + originalYScroll + ')" style="border:0">', {
var modalFrame = $.modal('<iframe src="' + src + '" width="' + width + '" onload="centerModal(this,' + originalYScroll + ')" style="border:0">', {
closeHTML:'',
containerCss:{
backgroundColor:"#fff",
borderColor:"#fff",
width:width,
padding:0,
margin:0
},
overlayClose:true,
autoPosition:false,
modal:true,
opacity:70
});
} | javascript | function openModal(src, width) {
if ( !width ) width = 680;
//var elementId = 'orcodio';
var originalYScroll = window.pageYOffset;
//var modalFrame = $.modal('<iframe id="'+ elementId +'" src="' + src + '" width="' + width + '" onload="centerModal(this,' + originalYScroll + ')" style="border:0">', {
var modalFrame = $.modal('<iframe src="' + src + '" width="' + width + '" onload="centerModal(this,' + originalYScroll + ')" style="border:0">', {
closeHTML:'',
containerCss:{
backgroundColor:"#fff",
borderColor:"#fff",
width:width,
padding:0,
margin:0
},
overlayClose:true,
autoPosition:false,
modal:true,
opacity:70
});
} | [
"function",
"openModal",
"(",
"src",
",",
"width",
")",
"{",
"if",
"(",
"!",
"width",
")",
"width",
"=",
"680",
";",
"var",
"originalYScroll",
"=",
"window",
".",
"pageYOffset",
";",
"var",
"modalFrame",
"=",
"$",
".",
"modal",
"(",
"'<iframe src=\"'",
"+",
"src",
"+",
"'\" width=\"'",
"+",
"width",
"+",
"'\" onload=\"centerModal(this,'",
"+",
"originalYScroll",
"+",
"')\" style=\"border:0\">'",
",",
"{",
"closeHTML",
":",
"''",
",",
"containerCss",
":",
"{",
"backgroundColor",
":",
"\"#fff\"",
",",
"borderColor",
":",
"\"#fff\"",
",",
"width",
":",
"width",
",",
"padding",
":",
"0",
",",
"margin",
":",
"0",
"}",
",",
"overlayClose",
":",
"true",
",",
"autoPosition",
":",
"false",
",",
"modal",
":",
"true",
",",
"opacity",
":",
"70",
"}",
")",
";",
"}"
] | open modal iframe popup | [
"open",
"modal",
"iframe",
"popup"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/public/javascripts/jslardo.js#L68-L87 | train |
obliquid/jslardo | public/javascripts/jslardo.js | selectTab | function selectTab(tab,content) {
//deseleziono tutti i tab
$('#'+tab).parent().children().removeClass('tabButtonSelected');
//seleziono il tab cliccato
$('#'+tab).addClass('tabButtonSelected');
//nascondo tutti i content
$('#'+content).parent().children().fadeOut('fast');
//seleziono il tab cliccato
$('#'+content).delay(200).fadeIn('fast');
} | javascript | function selectTab(tab,content) {
//deseleziono tutti i tab
$('#'+tab).parent().children().removeClass('tabButtonSelected');
//seleziono il tab cliccato
$('#'+tab).addClass('tabButtonSelected');
//nascondo tutti i content
$('#'+content).parent().children().fadeOut('fast');
//seleziono il tab cliccato
$('#'+content).delay(200).fadeIn('fast');
} | [
"function",
"selectTab",
"(",
"tab",
",",
"content",
")",
"{",
"$",
"(",
"'#'",
"+",
"tab",
")",
".",
"parent",
"(",
")",
".",
"children",
"(",
")",
".",
"removeClass",
"(",
"'tabButtonSelected'",
")",
";",
"$",
"(",
"'#'",
"+",
"tab",
")",
".",
"addClass",
"(",
"'tabButtonSelected'",
")",
";",
"$",
"(",
"'#'",
"+",
"content",
")",
".",
"parent",
"(",
")",
".",
"children",
"(",
")",
".",
"fadeOut",
"(",
"'fast'",
")",
";",
"$",
"(",
"'#'",
"+",
"content",
")",
".",
"delay",
"(",
"200",
")",
".",
"fadeIn",
"(",
"'fast'",
")",
";",
"}"
] | select a tab, displaying its content | [
"select",
"a",
"tab",
"displaying",
"its",
"content"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/public/javascripts/jslardo.js#L161-L170 | train |
GruntBlanketMocha/grunt-blanket-mocha | support/grunt-reporter.js | function( data ) {
var ret = {
coverage: 0,
hits: 0,
misses: 0,
sloc: 0
};
for (var i = 0; i < data.source.length; i++) {
var line = data.source[i];
var num = i + 1;
if (data[num] === 0) {
ret.misses++;
ret.sloc++;
} else if (data[num] !== undefined) {
ret.hits++;
ret.sloc++;
}
}
ret.coverage = ret.hits / ret.sloc * 100;
return [ret.hits,ret.sloc];
} | javascript | function( data ) {
var ret = {
coverage: 0,
hits: 0,
misses: 0,
sloc: 0
};
for (var i = 0; i < data.source.length; i++) {
var line = data.source[i];
var num = i + 1;
if (data[num] === 0) {
ret.misses++;
ret.sloc++;
} else if (data[num] !== undefined) {
ret.hits++;
ret.sloc++;
}
}
ret.coverage = ret.hits / ret.sloc * 100;
return [ret.hits,ret.sloc];
} | [
"function",
"(",
"data",
")",
"{",
"var",
"ret",
"=",
"{",
"coverage",
":",
"0",
",",
"hits",
":",
"0",
",",
"misses",
":",
"0",
",",
"sloc",
":",
"0",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"source",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"line",
"=",
"data",
".",
"source",
"[",
"i",
"]",
";",
"var",
"num",
"=",
"i",
"+",
"1",
";",
"if",
"(",
"data",
"[",
"num",
"]",
"===",
"0",
")",
"{",
"ret",
".",
"misses",
"++",
";",
"ret",
".",
"sloc",
"++",
";",
"}",
"else",
"if",
"(",
"data",
"[",
"num",
"]",
"!==",
"undefined",
")",
"{",
"ret",
".",
"hits",
"++",
";",
"ret",
".",
"sloc",
"++",
";",
"}",
"}",
"ret",
".",
"coverage",
"=",
"ret",
".",
"hits",
"/",
"ret",
".",
"sloc",
"*",
"100",
";",
"return",
"[",
"ret",
".",
"hits",
",",
"ret",
".",
"sloc",
"]",
";",
"}"
] | helper function for computing coverage info for a particular file | [
"helper",
"function",
"for",
"computing",
"coverage",
"info",
"for",
"a",
"particular",
"file"
] | c210fc13d9d4df73b10de0439940140a70768020 | https://github.com/GruntBlanketMocha/grunt-blanket-mocha/blob/c210fc13d9d4df73b10de0439940140a70768020/support/grunt-reporter.js#L23-L45 | train |
|
GruntBlanketMocha/grunt-blanket-mocha | support/grunt-reporter.js | function(cov){
cov = window._$blanket;
var sortedFileNames = [];
var totals =[];
for (var filename in cov) {
if (cov.hasOwnProperty(filename)) {
sortedFileNames.push(filename);
}
}
sortedFileNames.sort();
for (var i = 0; i < sortedFileNames.length; i++) {
var thisFile = sortedFileNames[i];
var data = cov[thisFile];
var thisTotal= reportFile( data );
sendMessage("blanket:fileDone", thisTotal, thisFile);
}
sendMessage("blanket:done");
} | javascript | function(cov){
cov = window._$blanket;
var sortedFileNames = [];
var totals =[];
for (var filename in cov) {
if (cov.hasOwnProperty(filename)) {
sortedFileNames.push(filename);
}
}
sortedFileNames.sort();
for (var i = 0; i < sortedFileNames.length; i++) {
var thisFile = sortedFileNames[i];
var data = cov[thisFile];
var thisTotal= reportFile( data );
sendMessage("blanket:fileDone", thisTotal, thisFile);
}
sendMessage("blanket:done");
} | [
"function",
"(",
"cov",
")",
"{",
"cov",
"=",
"window",
".",
"_$blanket",
";",
"var",
"sortedFileNames",
"=",
"[",
"]",
";",
"var",
"totals",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"filename",
"in",
"cov",
")",
"{",
"if",
"(",
"cov",
".",
"hasOwnProperty",
"(",
"filename",
")",
")",
"{",
"sortedFileNames",
".",
"push",
"(",
"filename",
")",
";",
"}",
"}",
"sortedFileNames",
".",
"sort",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"sortedFileNames",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"thisFile",
"=",
"sortedFileNames",
"[",
"i",
"]",
";",
"var",
"data",
"=",
"cov",
"[",
"thisFile",
"]",
";",
"var",
"thisTotal",
"=",
"reportFile",
"(",
"data",
")",
";",
"sendMessage",
"(",
"\"blanket:fileDone\"",
",",
"thisTotal",
",",
"thisFile",
")",
";",
"}",
"sendMessage",
"(",
"\"blanket:done\"",
")",
";",
"}"
] | this function is invoked by blanket.js when the coverage data is ready. it will compute per-file coverage info, and send a message to the parent phantomjs process for each file, which the grunt task will use to report passes & failures. | [
"this",
"function",
"is",
"invoked",
"by",
"blanket",
".",
"js",
"when",
"the",
"coverage",
"data",
"is",
"ready",
".",
"it",
"will",
"compute",
"per",
"-",
"file",
"coverage",
"info",
"and",
"send",
"a",
"message",
"to",
"the",
"parent",
"phantomjs",
"process",
"for",
"each",
"file",
"which",
"the",
"grunt",
"task",
"will",
"use",
"to",
"report",
"passes",
"&",
"failures",
"."
] | c210fc13d9d4df73b10de0439940140a70768020 | https://github.com/GruntBlanketMocha/grunt-blanket-mocha/blob/c210fc13d9d4df73b10de0439940140a70768020/support/grunt-reporter.js#L50-L74 | train |
|
ajay2507/lasso-unpack | lib/lasso-unpack.js | extractLiterals | function extractLiterals(stats, args) {
if (stats.getType() != null && (stats.getType() === "installed" || stats.getType() === "builtin")) {
extractLiteralFromInstalled(stats, args);
}
if (stats.getType() != null && stats.getType() === "def") {
extractLiteralFromDef(stats, args[0]);
}
if (stats.getType() != null && (stats.getType() === "main" || stats.getType() === "remap")) {
extractLiteralFromMain(stats, args[0]);
}
} | javascript | function extractLiterals(stats, args) {
if (stats.getType() != null && (stats.getType() === "installed" || stats.getType() === "builtin")) {
extractLiteralFromInstalled(stats, args);
}
if (stats.getType() != null && stats.getType() === "def") {
extractLiteralFromDef(stats, args[0]);
}
if (stats.getType() != null && (stats.getType() === "main" || stats.getType() === "remap")) {
extractLiteralFromMain(stats, args[0]);
}
} | [
"function",
"extractLiterals",
"(",
"stats",
",",
"args",
")",
"{",
"if",
"(",
"stats",
".",
"getType",
"(",
")",
"!=",
"null",
"&&",
"(",
"stats",
".",
"getType",
"(",
")",
"===",
"\"installed\"",
"||",
"stats",
".",
"getType",
"(",
")",
"===",
"\"builtin\"",
")",
")",
"{",
"extractLiteralFromInstalled",
"(",
"stats",
",",
"args",
")",
";",
"}",
"if",
"(",
"stats",
".",
"getType",
"(",
")",
"!=",
"null",
"&&",
"stats",
".",
"getType",
"(",
")",
"===",
"\"def\"",
")",
"{",
"extractLiteralFromDef",
"(",
"stats",
",",
"args",
"[",
"0",
"]",
")",
";",
"}",
"if",
"(",
"stats",
".",
"getType",
"(",
")",
"!=",
"null",
"&&",
"(",
"stats",
".",
"getType",
"(",
")",
"===",
"\"main\"",
"||",
"stats",
".",
"getType",
"(",
")",
"===",
"\"remap\"",
")",
")",
"{",
"extractLiteralFromMain",
"(",
"stats",
",",
"args",
"[",
"0",
"]",
")",
";",
"}",
"}"
] | extract literal from AST tree. | [
"extract",
"literal",
"from",
"AST",
"tree",
"."
] | fb228b00a549eedfafec7e8eaf9999d69db82a0c | https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/lasso-unpack.js#L74-L86 | train |
obliquid/jslardo | public/javascripts/jq/jstree/jquery.jstree.js | function () {
if(this.is_focused()) { return; }
var f = $.jstree._focused();
if(f) { f.unset_focus(); }
this.get_container().addClass("jstree-focused");
focused_instance = this.get_index();
this.__callback();
} | javascript | function () {
if(this.is_focused()) { return; }
var f = $.jstree._focused();
if(f) { f.unset_focus(); }
this.get_container().addClass("jstree-focused");
focused_instance = this.get_index();
this.__callback();
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"is_focused",
"(",
")",
")",
"{",
"return",
";",
"}",
"var",
"f",
"=",
"$",
".",
"jstree",
".",
"_focused",
"(",
")",
";",
"if",
"(",
"f",
")",
"{",
"f",
".",
"unset_focus",
"(",
")",
";",
"}",
"this",
".",
"get_container",
"(",
")",
".",
"addClass",
"(",
"\"jstree-focused\"",
")",
";",
"focused_instance",
"=",
"this",
".",
"get_index",
"(",
")",
";",
"this",
".",
"__callback",
"(",
")",
";",
"}"
] | deal with focus | [
"deal",
"with",
"focus"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/public/javascripts/jq/jstree/jquery.jstree.js#L552-L560 | train |
|
KenanY/trigger-event | index.js | triggerEvent | function triggerEvent(el, type, options) {
if (isString(el)) {
options = type;
type = el;
el = document;
}
var e = createEvent(type, options);
el.dispatchEvent
? el.dispatchEvent(e)
: el.fireEvent('on' + type, e);
} | javascript | function triggerEvent(el, type, options) {
if (isString(el)) {
options = type;
type = el;
el = document;
}
var e = createEvent(type, options);
el.dispatchEvent
? el.dispatchEvent(e)
: el.fireEvent('on' + type, e);
} | [
"function",
"triggerEvent",
"(",
"el",
",",
"type",
",",
"options",
")",
"{",
"if",
"(",
"isString",
"(",
"el",
")",
")",
"{",
"options",
"=",
"type",
";",
"type",
"=",
"el",
";",
"el",
"=",
"document",
";",
"}",
"var",
"e",
"=",
"createEvent",
"(",
"type",
",",
"options",
")",
";",
"el",
".",
"dispatchEvent",
"?",
"el",
".",
"dispatchEvent",
"(",
"e",
")",
":",
"el",
".",
"fireEvent",
"(",
"'on'",
"+",
"type",
",",
"e",
")",
";",
"}"
] | Trigger an event of `type` on an `el` with `options`.
@param {Element} el
@param {String} type
@param {Object} options | [
"Trigger",
"an",
"event",
"of",
"type",
"on",
"an",
"el",
"with",
"options",
"."
] | f7f4f539a76eb04c5ebca9411f64d03edc9ee96d | https://github.com/KenanY/trigger-event/blob/f7f4f539a76eb04c5ebca9411f64d03edc9ee96d/index.js#L12-L24 | train |
bytbil/sauce-test-runner | src/WrapperError.js | WrapperError | function WrapperError(message, innerError) {
// supports instantiating the object without the new keyword
if (!(this instanceof WrapperError)) {
return new WrapperError(message, innerError);
}
Error.call(this);
Error.captureStackTrace(this, WrapperError);
this.message = message;
this.innerError = innerError;
} | javascript | function WrapperError(message, innerError) {
// supports instantiating the object without the new keyword
if (!(this instanceof WrapperError)) {
return new WrapperError(message, innerError);
}
Error.call(this);
Error.captureStackTrace(this, WrapperError);
this.message = message;
this.innerError = innerError;
} | [
"function",
"WrapperError",
"(",
"message",
",",
"innerError",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"WrapperError",
")",
")",
"{",
"return",
"new",
"WrapperError",
"(",
"message",
",",
"innerError",
")",
";",
"}",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"WrapperError",
")",
";",
"this",
".",
"message",
"=",
"message",
";",
"this",
".",
"innerError",
"=",
"innerError",
";",
"}"
] | An Error object which wraps another Error instance.
@constructor
@extends Error
@param {String} message - Error message.
@param {Error} innerError - The Error instance to wrap. | [
"An",
"Error",
"object",
"which",
"wraps",
"another",
"Error",
"instance",
"."
] | db0304a31a5fe7b4e6ab5f496cbca52a012d1b6e | https://github.com/bytbil/sauce-test-runner/blob/db0304a31a5fe7b4e6ab5f496cbca52a012d1b6e/src/WrapperError.js#L11-L22 | train |
bytbil/sauce-test-runner | src/WrapperError.js | formatError | function formatError(error, stack) {
if (origPrepareStackTrace) {
return origPrepareStackTrace(error, stack);
}
return [
error.toString(),
stack
.map(function (frame) {
return 'at ' + frame.toString();
})
.map(padLeft)
.join('\n')
].join('\n');
} | javascript | function formatError(error, stack) {
if (origPrepareStackTrace) {
return origPrepareStackTrace(error, stack);
}
return [
error.toString(),
stack
.map(function (frame) {
return 'at ' + frame.toString();
})
.map(padLeft)
.join('\n')
].join('\n');
} | [
"function",
"formatError",
"(",
"error",
",",
"stack",
")",
"{",
"if",
"(",
"origPrepareStackTrace",
")",
"{",
"return",
"origPrepareStackTrace",
"(",
"error",
",",
"stack",
")",
";",
"}",
"return",
"[",
"error",
".",
"toString",
"(",
")",
",",
"stack",
".",
"map",
"(",
"function",
"(",
"frame",
")",
"{",
"return",
"'at '",
"+",
"frame",
".",
"toString",
"(",
")",
";",
"}",
")",
".",
"map",
"(",
"padLeft",
")",
".",
"join",
"(",
"'\\n'",
")",
"]",
".",
"\\n",
"join",
";",
"}"
] | Creates and returns a string representation of an error.
@param {Error} error - The error.
@returns {String} - A string representation of the error. | [
"Creates",
"and",
"returns",
"a",
"string",
"representation",
"of",
"an",
"error",
"."
] | db0304a31a5fe7b4e6ab5f496cbca52a012d1b6e | https://github.com/bytbil/sauce-test-runner/blob/db0304a31a5fe7b4e6ab5f496cbca52a012d1b6e/src/WrapperError.js#L45-L58 | train |
syntaxhighlighter/syntaxhighlighter-regex | xregexp.js | isQuantifierNext | function isQuantifierNext(pattern, pos, flags) {
return nativ.test.call(
flags.indexOf('x') > -1 ?
// Ignore any leading whitespace, line comments, and inline comments
/^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/ :
// Ignore any leading inline comments
/^(?:\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/,
pattern.slice(pos)
);
} | javascript | function isQuantifierNext(pattern, pos, flags) {
return nativ.test.call(
flags.indexOf('x') > -1 ?
// Ignore any leading whitespace, line comments, and inline comments
/^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/ :
// Ignore any leading inline comments
/^(?:\(\?#[^)]*\))*(?:[?*+]|{\d+(?:,\d*)?})/,
pattern.slice(pos)
);
} | [
"function",
"isQuantifierNext",
"(",
"pattern",
",",
"pos",
",",
"flags",
")",
"{",
"return",
"nativ",
".",
"test",
".",
"call",
"(",
"flags",
".",
"indexOf",
"(",
"'x'",
")",
">",
"-",
"1",
"?",
"/",
"^(?:\\s+|#.*|\\(\\?#[^)]*\\))*(?:[?*+]|{\\d+(?:,\\d*)?})",
"/",
":",
"/",
"^(?:\\(\\?#[^)]*\\))*(?:[?*+]|{\\d+(?:,\\d*)?})",
"/",
",",
"pattern",
".",
"slice",
"(",
"pos",
")",
")",
";",
"}"
] | Checks whether the next nonignorable token after the specified position is a quantifier.
@private
@param {String} pattern Pattern to search within.
@param {Number} pos Index in `pattern` to search at.
@param {String} flags Flags used by the pattern.
@returns {Boolean} Whether the next token is a quantifier. | [
"Checks",
"whether",
"the",
"next",
"nonignorable",
"token",
"after",
"the",
"specified",
"position",
"is",
"a",
"quantifier",
"."
] | a20b8bc52097774bf49e01a6554c904683c03878 | https://github.com/syntaxhighlighter/syntaxhighlighter-regex/blob/a20b8bc52097774bf49e01a6554c904683c03878/xregexp.js#L309-L318 | train |
syntaxhighlighter/syntaxhighlighter-regex | xregexp.js | prepareOptions | function prepareOptions(value) {
var options = {};
if (isType(value, 'String')) {
XRegExp.forEach(value, /[^\s,]+/, function(match) {
options[match] = true;
});
return options;
}
return value;
} | javascript | function prepareOptions(value) {
var options = {};
if (isType(value, 'String')) {
XRegExp.forEach(value, /[^\s,]+/, function(match) {
options[match] = true;
});
return options;
}
return value;
} | [
"function",
"prepareOptions",
"(",
"value",
")",
"{",
"var",
"options",
"=",
"{",
"}",
";",
"if",
"(",
"isType",
"(",
"value",
",",
"'String'",
")",
")",
"{",
"XRegExp",
".",
"forEach",
"(",
"value",
",",
"/",
"[^\\s,]+",
"/",
",",
"function",
"(",
"match",
")",
"{",
"options",
"[",
"match",
"]",
"=",
"true",
";",
"}",
")",
";",
"return",
"options",
";",
"}",
"return",
"value",
";",
"}"
] | Prepares an options object from the given value.
@private
@param {String|Object} value Value to convert to an options object.
@returns {Object} Options object. | [
"Prepares",
"an",
"options",
"object",
"from",
"the",
"given",
"value",
"."
] | a20b8bc52097774bf49e01a6554c904683c03878 | https://github.com/syntaxhighlighter/syntaxhighlighter-regex/blob/a20b8bc52097774bf49e01a6554c904683c03878/xregexp.js#L382-L394 | train |
fraserxu/babel-jsxgettext | index.js | parser | function parser (inputs, output, plugins, cb) {
var data = {
charset: 'UTF-8',
headers: DEFAULT_HEADERS,
translations: {
context: {}
}
}
var defaultContext = data.translations.context
var headers = data.headers
headers['plural-forms'] = headers['plural-forms'] || DEFAULT_HEADERS['plural-forms']
headers['content-type'] = headers['content-type'] || DEFAULT_HEADERS['content-type']
var nplurals = /nplurals ?= ?(\d)/.exec(headers['plural-forms'])[1]
inputs
.forEach(function (file) {
var resolvedFilePath = path.join(process.cwd(), file)
var src = fs.readFileSync(resolvedFilePath, 'utf8')
try {
var ast = babelParser.parse(src, {
sourceType: 'module',
plugins: ['jsx'].concat(plugins)
})
} catch (e) {
console.error(`SyntaxError in ${file} (line: ${e.loc.line}, column: ${e.loc.column})`)
process.exit(1)
}
walk.simple(ast.program, {
CallExpression: function (node) {
if (functionNames.hasOwnProperty(node.callee.name) ||
node.callee.property && functionNames.hasOwnProperty(node.callee.property.name)) {
var functionName = functionNames[node.callee.name] || functionNames[node.callee.property.name]
var translate = {}
var args = node.arguments
for (var i = 0, l = args.length; i < l; i++) {
var name = functionName[i]
if (name && name !== 'count' && name !== 'domain') {
var arg = args[i]
var value = arg.value
if (value) {
var line = node.loc.start.line
translate[name] = value
translate['comments'] = {
reference: file + ':' + line
}
}
if (name === 'msgid_plural') {
translate.msgstr = []
for (var p = 0; p < nplurals; p++) {
translate.msgstr[p] = ''
}
}
}
}
var context = defaultContext
var msgctxt = translate.msgctxt
if (msgctxt) {
data.translations[msgctxt] = data.translations[msgctxt] || {}
context = data.translations[msgctxt]
}
context[translate.msgid] = translate
}
}
})
})
fs.writeFile(output, gettextParser.po.compile(data), function (err) {
if (err) {
cb(err)
}
cb(null)
})
} | javascript | function parser (inputs, output, plugins, cb) {
var data = {
charset: 'UTF-8',
headers: DEFAULT_HEADERS,
translations: {
context: {}
}
}
var defaultContext = data.translations.context
var headers = data.headers
headers['plural-forms'] = headers['plural-forms'] || DEFAULT_HEADERS['plural-forms']
headers['content-type'] = headers['content-type'] || DEFAULT_HEADERS['content-type']
var nplurals = /nplurals ?= ?(\d)/.exec(headers['plural-forms'])[1]
inputs
.forEach(function (file) {
var resolvedFilePath = path.join(process.cwd(), file)
var src = fs.readFileSync(resolvedFilePath, 'utf8')
try {
var ast = babelParser.parse(src, {
sourceType: 'module',
plugins: ['jsx'].concat(plugins)
})
} catch (e) {
console.error(`SyntaxError in ${file} (line: ${e.loc.line}, column: ${e.loc.column})`)
process.exit(1)
}
walk.simple(ast.program, {
CallExpression: function (node) {
if (functionNames.hasOwnProperty(node.callee.name) ||
node.callee.property && functionNames.hasOwnProperty(node.callee.property.name)) {
var functionName = functionNames[node.callee.name] || functionNames[node.callee.property.name]
var translate = {}
var args = node.arguments
for (var i = 0, l = args.length; i < l; i++) {
var name = functionName[i]
if (name && name !== 'count' && name !== 'domain') {
var arg = args[i]
var value = arg.value
if (value) {
var line = node.loc.start.line
translate[name] = value
translate['comments'] = {
reference: file + ':' + line
}
}
if (name === 'msgid_plural') {
translate.msgstr = []
for (var p = 0; p < nplurals; p++) {
translate.msgstr[p] = ''
}
}
}
}
var context = defaultContext
var msgctxt = translate.msgctxt
if (msgctxt) {
data.translations[msgctxt] = data.translations[msgctxt] || {}
context = data.translations[msgctxt]
}
context[translate.msgid] = translate
}
}
})
})
fs.writeFile(output, gettextParser.po.compile(data), function (err) {
if (err) {
cb(err)
}
cb(null)
})
} | [
"function",
"parser",
"(",
"inputs",
",",
"output",
",",
"plugins",
",",
"cb",
")",
"{",
"var",
"data",
"=",
"{",
"charset",
":",
"'UTF-8'",
",",
"headers",
":",
"DEFAULT_HEADERS",
",",
"translations",
":",
"{",
"context",
":",
"{",
"}",
"}",
"}",
"var",
"defaultContext",
"=",
"data",
".",
"translations",
".",
"context",
"var",
"headers",
"=",
"data",
".",
"headers",
"headers",
"[",
"'plural-forms'",
"]",
"=",
"headers",
"[",
"'plural-forms'",
"]",
"||",
"DEFAULT_HEADERS",
"[",
"'plural-forms'",
"]",
"headers",
"[",
"'content-type'",
"]",
"=",
"headers",
"[",
"'content-type'",
"]",
"||",
"DEFAULT_HEADERS",
"[",
"'content-type'",
"]",
"var",
"nplurals",
"=",
"/",
"nplurals ?= ?(\\d)",
"/",
".",
"exec",
"(",
"headers",
"[",
"'plural-forms'",
"]",
")",
"[",
"1",
"]",
"inputs",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"resolvedFilePath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"file",
")",
"var",
"src",
"=",
"fs",
".",
"readFileSync",
"(",
"resolvedFilePath",
",",
"'utf8'",
")",
"try",
"{",
"var",
"ast",
"=",
"babelParser",
".",
"parse",
"(",
"src",
",",
"{",
"sourceType",
":",
"'module'",
",",
"plugins",
":",
"[",
"'jsx'",
"]",
".",
"concat",
"(",
"plugins",
")",
"}",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"file",
"}",
"${",
"e",
".",
"loc",
".",
"line",
"}",
"${",
"e",
".",
"loc",
".",
"column",
"}",
"`",
")",
"process",
".",
"exit",
"(",
"1",
")",
"}",
"walk",
".",
"simple",
"(",
"ast",
".",
"program",
",",
"{",
"CallExpression",
":",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"functionNames",
".",
"hasOwnProperty",
"(",
"node",
".",
"callee",
".",
"name",
")",
"||",
"node",
".",
"callee",
".",
"property",
"&&",
"functionNames",
".",
"hasOwnProperty",
"(",
"node",
".",
"callee",
".",
"property",
".",
"name",
")",
")",
"{",
"var",
"functionName",
"=",
"functionNames",
"[",
"node",
".",
"callee",
".",
"name",
"]",
"||",
"functionNames",
"[",
"node",
".",
"callee",
".",
"property",
".",
"name",
"]",
"var",
"translate",
"=",
"{",
"}",
"var",
"args",
"=",
"node",
".",
"arguments",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"args",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"var",
"name",
"=",
"functionName",
"[",
"i",
"]",
"if",
"(",
"name",
"&&",
"name",
"!==",
"'count'",
"&&",
"name",
"!==",
"'domain'",
")",
"{",
"var",
"arg",
"=",
"args",
"[",
"i",
"]",
"var",
"value",
"=",
"arg",
".",
"value",
"if",
"(",
"value",
")",
"{",
"var",
"line",
"=",
"node",
".",
"loc",
".",
"start",
".",
"line",
"translate",
"[",
"name",
"]",
"=",
"value",
"translate",
"[",
"'comments'",
"]",
"=",
"{",
"reference",
":",
"file",
"+",
"':'",
"+",
"line",
"}",
"}",
"if",
"(",
"name",
"===",
"'msgid_plural'",
")",
"{",
"translate",
".",
"msgstr",
"=",
"[",
"]",
"for",
"(",
"var",
"p",
"=",
"0",
";",
"p",
"<",
"nplurals",
";",
"p",
"++",
")",
"{",
"translate",
".",
"msgstr",
"[",
"p",
"]",
"=",
"''",
"}",
"}",
"}",
"}",
"var",
"context",
"=",
"defaultContext",
"var",
"msgctxt",
"=",
"translate",
".",
"msgctxt",
"if",
"(",
"msgctxt",
")",
"{",
"data",
".",
"translations",
"[",
"msgctxt",
"]",
"=",
"data",
".",
"translations",
"[",
"msgctxt",
"]",
"||",
"{",
"}",
"context",
"=",
"data",
".",
"translations",
"[",
"msgctxt",
"]",
"}",
"context",
"[",
"translate",
".",
"msgid",
"]",
"=",
"translate",
"}",
"}",
"}",
")",
"}",
")",
"fs",
".",
"writeFile",
"(",
"output",
",",
"gettextParser",
".",
"po",
".",
"compile",
"(",
"data",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
"}",
"cb",
"(",
"null",
")",
"}",
")",
"}"
] | The parser function
@param {String} input The path to soure JavaScript file
@param {String} output The path of the output PO file
@param {Function} cb The callback function | [
"The",
"parser",
"function"
] | aa51718017879069bf93571958a9e86d2d3a8646 | https://github.com/fraserxu/babel-jsxgettext/blob/aa51718017879069bf93571958a9e86d2d3a8646/index.js#L16-L100 | train |
storj/service-storage-models | index.js | Storage | function Storage(mongoURI, mongoOptions, storageOptions) {
if (!(this instanceof Storage)) {
return new Storage(mongoURI, mongoOptions, storageOptions);
}
assert(typeof mongoOptions === 'object', 'Invalid mongo options supplied');
this._uri = mongoURI;
this._options = mongoOptions;
const defaultLogger = {
info: console.log,
debug: console.log,
error: console.error,
warn: console.warn
};
this._log = defaultLogger;
if (storageOptions && storageOptions.logger) {
this._log = storageOptions.logger;
}
// connect to the database
this._connect();
} | javascript | function Storage(mongoURI, mongoOptions, storageOptions) {
if (!(this instanceof Storage)) {
return new Storage(mongoURI, mongoOptions, storageOptions);
}
assert(typeof mongoOptions === 'object', 'Invalid mongo options supplied');
this._uri = mongoURI;
this._options = mongoOptions;
const defaultLogger = {
info: console.log,
debug: console.log,
error: console.error,
warn: console.warn
};
this._log = defaultLogger;
if (storageOptions && storageOptions.logger) {
this._log = storageOptions.logger;
}
// connect to the database
this._connect();
} | [
"function",
"Storage",
"(",
"mongoURI",
",",
"mongoOptions",
",",
"storageOptions",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Storage",
")",
")",
"{",
"return",
"new",
"Storage",
"(",
"mongoURI",
",",
"mongoOptions",
",",
"storageOptions",
")",
";",
"}",
"assert",
"(",
"typeof",
"mongoOptions",
"===",
"'object'",
",",
"'Invalid mongo options supplied'",
")",
";",
"this",
".",
"_uri",
"=",
"mongoURI",
";",
"this",
".",
"_options",
"=",
"mongoOptions",
";",
"const",
"defaultLogger",
"=",
"{",
"info",
":",
"console",
".",
"log",
",",
"debug",
":",
"console",
".",
"log",
",",
"error",
":",
"console",
".",
"error",
",",
"warn",
":",
"console",
".",
"warn",
"}",
";",
"this",
".",
"_log",
"=",
"defaultLogger",
";",
"if",
"(",
"storageOptions",
"&&",
"storageOptions",
".",
"logger",
")",
"{",
"this",
".",
"_log",
"=",
"storageOptions",
".",
"logger",
";",
"}",
"this",
".",
"_connect",
"(",
")",
";",
"}"
] | MongoDB storage interface
@constructor
@param {Object} mongoConf
@param {Object} options | [
"MongoDB",
"storage",
"interface"
] | 1271354451bb410bdf1ecc6285f40918d4bc861d | https://github.com/storj/service-storage-models/blob/1271354451bb410bdf1ecc6285f40918d4bc861d/index.js#L18-L41 | train |
neekey/connected-domain | lib/connected-domain.js | addPointToDomain | function addPointToDomain( point, x, y, domainId ){
var domain = domains[ domainId ];
var newPoint = {
value: point,
x: x,
y: y,
identifier: domain.identifier,
domainId: domainId
};
pointsHash[ x + '_' + y ] = {
value: point,
identifier: domain.identifier,
domainId: domainId
};
domain.points.push( newPoint );
} | javascript | function addPointToDomain( point, x, y, domainId ){
var domain = domains[ domainId ];
var newPoint = {
value: point,
x: x,
y: y,
identifier: domain.identifier,
domainId: domainId
};
pointsHash[ x + '_' + y ] = {
value: point,
identifier: domain.identifier,
domainId: domainId
};
domain.points.push( newPoint );
} | [
"function",
"addPointToDomain",
"(",
"point",
",",
"x",
",",
"y",
",",
"domainId",
")",
"{",
"var",
"domain",
"=",
"domains",
"[",
"domainId",
"]",
";",
"var",
"newPoint",
"=",
"{",
"value",
":",
"point",
",",
"x",
":",
"x",
",",
"y",
":",
"y",
",",
"identifier",
":",
"domain",
".",
"identifier",
",",
"domainId",
":",
"domainId",
"}",
";",
"pointsHash",
"[",
"x",
"+",
"'_'",
"+",
"y",
"]",
"=",
"{",
"value",
":",
"point",
",",
"identifier",
":",
"domain",
".",
"identifier",
",",
"domainId",
":",
"domainId",
"}",
";",
"domain",
".",
"points",
".",
"push",
"(",
"newPoint",
")",
";",
"}"
] | add a point to a existing domain, and attach properties domainId and identifier to point.
@param point
@param x
@param y
@param domainId | [
"add",
"a",
"point",
"to",
"a",
"existing",
"domain",
"and",
"attach",
"properties",
"domainId",
"and",
"identifier",
"to",
"point",
"."
] | ecb49662ddab7a5bc26d6ec94701a5129bc914f3 | https://github.com/neekey/connected-domain/blob/ecb49662ddab7a5bc26d6ec94701a5129bc914f3/lib/connected-domain.js#L208-L226 | train |
Manabu-GT/grunt-auto-install | tasks/auto_install.js | function(dir) {
var results = [];
var list = fs.readdirSync(dir);
list.forEach(function(file) {
// Check for every given pattern, regardless of whether it is an array or a string
var matchesSomeExclude = [].concat(options.exclude).some(function(regexp) {
return file.match(regexp) != null;
});
if(!matchesSomeExclude) {
var matchesSomePattern = [].concat(options.match).some(function(regexp) {
return file.match(regexp) != null;
});
file = path.resolve(dir, file);
var stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
if(matchesSomePattern) {
results = results.concat(file);
}
results = results.concat(walk(file));
}
}
});
return results;
} | javascript | function(dir) {
var results = [];
var list = fs.readdirSync(dir);
list.forEach(function(file) {
// Check for every given pattern, regardless of whether it is an array or a string
var matchesSomeExclude = [].concat(options.exclude).some(function(regexp) {
return file.match(regexp) != null;
});
if(!matchesSomeExclude) {
var matchesSomePattern = [].concat(options.match).some(function(regexp) {
return file.match(regexp) != null;
});
file = path.resolve(dir, file);
var stat = fs.statSync(file);
if (stat && stat.isDirectory()) {
if(matchesSomePattern) {
results = results.concat(file);
}
results = results.concat(walk(file));
}
}
});
return results;
} | [
"function",
"(",
"dir",
")",
"{",
"var",
"results",
"=",
"[",
"]",
";",
"var",
"list",
"=",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
";",
"list",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"matchesSomeExclude",
"=",
"[",
"]",
".",
"concat",
"(",
"options",
".",
"exclude",
")",
".",
"some",
"(",
"function",
"(",
"regexp",
")",
"{",
"return",
"file",
".",
"match",
"(",
"regexp",
")",
"!=",
"null",
";",
"}",
")",
";",
"if",
"(",
"!",
"matchesSomeExclude",
")",
"{",
"var",
"matchesSomePattern",
"=",
"[",
"]",
".",
"concat",
"(",
"options",
".",
"match",
")",
".",
"some",
"(",
"function",
"(",
"regexp",
")",
"{",
"return",
"file",
".",
"match",
"(",
"regexp",
")",
"!=",
"null",
";",
"}",
")",
";",
"file",
"=",
"path",
".",
"resolve",
"(",
"dir",
",",
"file",
")",
";",
"var",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"file",
")",
";",
"if",
"(",
"stat",
"&&",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"if",
"(",
"matchesSomePattern",
")",
"{",
"results",
"=",
"results",
".",
"concat",
"(",
"file",
")",
";",
"}",
"results",
"=",
"results",
".",
"concat",
"(",
"walk",
"(",
"file",
")",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"results",
";",
"}"
] | Synchronously walks the directory
and returns an array of every subdirectory that
matches the patterns, and doesn't match any exclude pattern | [
"Synchronously",
"walks",
"the",
"directory",
"and",
"returns",
"an",
"array",
"of",
"every",
"subdirectory",
"that",
"matches",
"the",
"patterns",
"and",
"doesn",
"t",
"match",
"any",
"exclude",
"pattern"
] | e0d394a047f5364a00340112a8090c86ebf3b469 | https://github.com/Manabu-GT/grunt-auto-install/blob/e0d394a047f5364a00340112a8090c86ebf3b469/tasks/auto_install.js#L59-L88 | train |
|
Alhadis/Atom-Mocha | bin/post-install.js | die | function die(reason = "", error = null, exitCode = 0){
reason = (reason || "").trim();
// ANSI escape sequences (disabled if output is redirected)
const [reset,, underline,, noUnderline, red] = process.stderr.isTTY
? [0, 1, 4, 22, 24, [31, 9, 38]].map(s => `\x1B[${ Array.isArray(s) ? s.join(";") : s}m`)
: Array.of("", 40);
if(error){
const {inspect} = require("util");
process.stderr.write(red + inspect(error) + reset + "\n\n");
}
// Underline all occurrences of target-file's name
const target = underline + file + noUnderline;
// "Not found" -> "package.json not found"
if(reason && !reason.match(file))
reason = (file + " ")
+ reason[0].toLowerCase()
+ reason.substr(1);
// Pedantic polishes
reason = reason
.replace(/(?:\r\n|\s)+/g, " ")
.replace(/^\s+|[.!]*\s*$/g, "")
.replace(/^(?!\.$)/, ": ")
.replace(file, target);
const output = `${red}Unable to finish installing Atom-Mocha${reason}${reset}
The following field must be added to your project's ${target} file:
"${key}": "${value}"
See ${underline}README.md${reset} for setup instructions.
`.replace(/^\t/gm, "");
process.stderr.write(output);
process.exit(exitCode);
} | javascript | function die(reason = "", error = null, exitCode = 0){
reason = (reason || "").trim();
// ANSI escape sequences (disabled if output is redirected)
const [reset,, underline,, noUnderline, red] = process.stderr.isTTY
? [0, 1, 4, 22, 24, [31, 9, 38]].map(s => `\x1B[${ Array.isArray(s) ? s.join(";") : s}m`)
: Array.of("", 40);
if(error){
const {inspect} = require("util");
process.stderr.write(red + inspect(error) + reset + "\n\n");
}
// Underline all occurrences of target-file's name
const target = underline + file + noUnderline;
// "Not found" -> "package.json not found"
if(reason && !reason.match(file))
reason = (file + " ")
+ reason[0].toLowerCase()
+ reason.substr(1);
// Pedantic polishes
reason = reason
.replace(/(?:\r\n|\s)+/g, " ")
.replace(/^\s+|[.!]*\s*$/g, "")
.replace(/^(?!\.$)/, ": ")
.replace(file, target);
const output = `${red}Unable to finish installing Atom-Mocha${reason}${reset}
The following field must be added to your project's ${target} file:
"${key}": "${value}"
See ${underline}README.md${reset} for setup instructions.
`.replace(/^\t/gm, "");
process.stderr.write(output);
process.exit(exitCode);
} | [
"function",
"die",
"(",
"reason",
"=",
"\"\"",
",",
"error",
"=",
"null",
",",
"exitCode",
"=",
"0",
")",
"{",
"reason",
"=",
"(",
"reason",
"||",
"\"\"",
")",
".",
"trim",
"(",
")",
";",
"const",
"[",
"reset",
",",
",",
"underline",
",",
",",
"noUnderline",
",",
"red",
"]",
"=",
"process",
".",
"stderr",
".",
"isTTY",
"?",
"[",
"0",
",",
"1",
",",
"4",
",",
"22",
",",
"24",
",",
"[",
"31",
",",
"9",
",",
"38",
"]",
"]",
".",
"map",
"(",
"s",
"=>",
"`",
"\\x1B",
"${",
"Array",
".",
"isArray",
"(",
"s",
")",
"?",
"s",
".",
"join",
"(",
"\";\"",
")",
":",
"s",
"}",
"`",
")",
":",
"Array",
".",
"of",
"(",
"\"\"",
",",
"40",
")",
";",
"if",
"(",
"error",
")",
"{",
"const",
"{",
"inspect",
"}",
"=",
"require",
"(",
"\"util\"",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"red",
"+",
"inspect",
"(",
"error",
")",
"+",
"reset",
"+",
"\"\\n\\n\"",
")",
";",
"}",
"\\n",
"\\n",
"const",
"target",
"=",
"underline",
"+",
"file",
"+",
"noUnderline",
";",
"if",
"(",
"reason",
"&&",
"!",
"reason",
".",
"match",
"(",
"file",
")",
")",
"reason",
"=",
"(",
"file",
"+",
"\" \"",
")",
"+",
"reason",
"[",
"0",
"]",
".",
"toLowerCase",
"(",
")",
"+",
"reason",
".",
"substr",
"(",
"1",
")",
";",
"reason",
"=",
"reason",
".",
"replace",
"(",
"/",
"(?:\\r\\n|\\s)+",
"/",
"g",
",",
"\" \"",
")",
".",
"replace",
"(",
"/",
"^\\s+|[.!]*\\s*$",
"/",
"g",
",",
"\"\"",
")",
".",
"replace",
"(",
"/",
"^(?!\\.$)",
"/",
",",
"\": \"",
")",
".",
"replace",
"(",
"file",
",",
"target",
")",
";",
"const",
"output",
"=",
"`",
"${",
"red",
"}",
"${",
"reason",
"}",
"${",
"reset",
"}",
"${",
"target",
"}",
"${",
"key",
"}",
"${",
"value",
"}",
"${",
"underline",
"}",
"${",
"reset",
"}",
"`",
".",
"replace",
"(",
"/",
"^\\t",
"/",
"gm",
",",
"\"\"",
")",
";",
"}"
] | Print an error message to the standard error stream, then quit.
@param {String} [reason=""] - Brief description of the error.
@param {Error} [error=null] - Possible error object preceding output
@param {Number} [exitCode=1] - Error code to exit with.
@private | [
"Print",
"an",
"error",
"message",
"to",
"the",
"standard",
"error",
"stream",
"then",
"quit",
"."
] | fa784a52905957dcf9e9cb6fec095f79972bfbc4 | https://github.com/Alhadis/Atom-Mocha/blob/fa784a52905957dcf9e9cb6fec095f79972bfbc4/bin/post-install.js#L78-L118 | train |
Alhadis/Atom-Mocha | bin/post-install.js | read | function read(filePath, options){
return new Promise((resolve, reject) => {
fs.readFile(filePath, options, (error, data) => {
error
? reject(error)
: resolve(data.toString());
});
});
} | javascript | function read(filePath, options){
return new Promise((resolve, reject) => {
fs.readFile(filePath, options, (error, data) => {
error
? reject(error)
: resolve(data.toString());
});
});
} | [
"function",
"read",
"(",
"filePath",
",",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"readFile",
"(",
"filePath",
",",
"options",
",",
"(",
"error",
",",
"data",
")",
"=>",
"{",
"error",
"?",
"reject",
"(",
"error",
")",
":",
"resolve",
"(",
"data",
".",
"toString",
"(",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Promise-aware version of `fs.readFile`.
@param {String} filePath - File to read
@param {Object} [options] - Options passed to `fs.readFile`
@return {Promise} Resolves with stringified data.
@see {@link https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback|`fs.readFile`} | [
"Promise",
"-",
"aware",
"version",
"of",
"fs",
".",
"readFile",
"."
] | fa784a52905957dcf9e9cb6fec095f79972bfbc4 | https://github.com/Alhadis/Atom-Mocha/blob/fa784a52905957dcf9e9cb6fec095f79972bfbc4/bin/post-install.js#L129-L137 | train |
Alhadis/Atom-Mocha | bin/post-install.js | write | function write(filePath, fileData, options){
return new Promise((resolve, reject) => {
fs.writeFile(filePath, fileData, options, error => {
error
? reject(error)
: resolve(fileData);
});
});
} | javascript | function write(filePath, fileData, options){
return new Promise((resolve, reject) => {
fs.writeFile(filePath, fileData, options, error => {
error
? reject(error)
: resolve(fileData);
});
});
} | [
"function",
"write",
"(",
"filePath",
",",
"fileData",
",",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"writeFile",
"(",
"filePath",
",",
"fileData",
",",
"options",
",",
"error",
"=>",
"{",
"error",
"?",
"reject",
"(",
"error",
")",
":",
"resolve",
"(",
"fileData",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Promise-aware version of `fs.writeFile`.
@param {String} filePath - File to write to
@param {String} fileData - Data to be written
@param {Object} [options] - Options passed to `fs.writeFile`
@return {Promise} Resolves with input parameter for easier chaining
@see {@link https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback|`fs.writeFile`} | [
"Promise",
"-",
"aware",
"version",
"of",
"fs",
".",
"writeFile",
"."
] | fa784a52905957dcf9e9cb6fec095f79972bfbc4 | https://github.com/Alhadis/Atom-Mocha/blob/fa784a52905957dcf9e9cb6fec095f79972bfbc4/bin/post-install.js#L149-L157 | train |
kevinoid/nodecat | index.js | combineErrors | function combineErrors(errPrev, errNew) {
if (!errPrev) {
return errNew;
}
let errCombined;
if (errPrev instanceof AggregateError) {
errCombined = errPrev;
} else {
errCombined = new AggregateError();
errCombined.push(errPrev);
}
errCombined.push(errNew);
return errCombined;
} | javascript | function combineErrors(errPrev, errNew) {
if (!errPrev) {
return errNew;
}
let errCombined;
if (errPrev instanceof AggregateError) {
errCombined = errPrev;
} else {
errCombined = new AggregateError();
errCombined.push(errPrev);
}
errCombined.push(errNew);
return errCombined;
} | [
"function",
"combineErrors",
"(",
"errPrev",
",",
"errNew",
")",
"{",
"if",
"(",
"!",
"errPrev",
")",
"{",
"return",
"errNew",
";",
"}",
"let",
"errCombined",
";",
"if",
"(",
"errPrev",
"instanceof",
"AggregateError",
")",
"{",
"errCombined",
"=",
"errPrev",
";",
"}",
"else",
"{",
"errCombined",
"=",
"new",
"AggregateError",
"(",
")",
";",
"errCombined",
".",
"push",
"(",
"errPrev",
")",
";",
"}",
"errCombined",
".",
"push",
"(",
"errNew",
")",
";",
"return",
"errCombined",
";",
"}"
] | Combines one or more errors into a single error.
@param {AggregateError|Error} errPrev Previous errors, if any.
@param {!Error} errNew New error.
@return {!AggregateError|!Error} Error which represents all errors that have
occurred. If only one error has occurred, it will be returned. Otherwise
an {@link AggregateError} including all previous errors will be returned.
@private | [
"Combines",
"one",
"or",
"more",
"errors",
"into",
"a",
"single",
"error",
"."
] | 333f9710bbe7ceac5ec3f6171b2e8446ab2f3973 | https://github.com/kevinoid/nodecat/blob/333f9710bbe7ceac5ec3f6171b2e8446ab2f3973/index.js#L21-L36 | train |
Alhadis/Atom-Mocha | lib/extensions.js | addToChai | function addToChai(names, fn){
for(const name of names)
Chai.Assertion.addMethod(name, fn);
} | javascript | function addToChai(names, fn){
for(const name of names)
Chai.Assertion.addMethod(name, fn);
} | [
"function",
"addToChai",
"(",
"names",
",",
"fn",
")",
"{",
"for",
"(",
"const",
"name",
"of",
"names",
")",
"Chai",
".",
"Assertion",
".",
"addMethod",
"(",
"name",
",",
"fn",
")",
";",
"}"
] | Thin wrapper around Chai.Assertion.addMethod to permit plugin aliases | [
"Thin",
"wrapper",
"around",
"Chai",
".",
"Assertion",
".",
"addMethod",
"to",
"permit",
"plugin",
"aliases"
] | fa784a52905957dcf9e9cb6fec095f79972bfbc4 | https://github.com/Alhadis/Atom-Mocha/blob/fa784a52905957dcf9e9cb6fec095f79972bfbc4/lib/extensions.js#L184-L187 | train |
xiara-io/xiara-mongo | dist/Definitions/Decorators.js | FieldReference | function FieldReference(typeFunction, fieldOptions = {}) {
return function (target, key) {
let fieldType = Reflect.getMetadata("design:type", target, key);
let schema = MongoSchemaRegistry_1.MongoSchemaRegistry.getSchema(target.constructor.name);
if (!schema) {
schema = new MongoSchema_1.MongoSchema(target.constructor);
MongoSchemaRegistry_1.MongoSchemaRegistry.register(target.constructor.name, schema);
}
if (!typeFunction) {
typeFunction = type => {
return fieldOptions.type || Reflect.getMetadata("design:type", target, key).name;
};
}
fieldOptions.foreignField = fieldOptions.foreignField || "_id";
if (!fieldType || fieldType.name != "Array") {
fieldOptions.relationType = MongoSchema_1.ERelationType.SingleObjectId;
}
if (fieldType && fieldType.name == "Array") {
fieldOptions.relationType = MongoSchema_1.ERelationType.ArrayObjectId;
}
schema.addField(key, typeFunction, fieldOptions);
};
} | javascript | function FieldReference(typeFunction, fieldOptions = {}) {
return function (target, key) {
let fieldType = Reflect.getMetadata("design:type", target, key);
let schema = MongoSchemaRegistry_1.MongoSchemaRegistry.getSchema(target.constructor.name);
if (!schema) {
schema = new MongoSchema_1.MongoSchema(target.constructor);
MongoSchemaRegistry_1.MongoSchemaRegistry.register(target.constructor.name, schema);
}
if (!typeFunction) {
typeFunction = type => {
return fieldOptions.type || Reflect.getMetadata("design:type", target, key).name;
};
}
fieldOptions.foreignField = fieldOptions.foreignField || "_id";
if (!fieldType || fieldType.name != "Array") {
fieldOptions.relationType = MongoSchema_1.ERelationType.SingleObjectId;
}
if (fieldType && fieldType.name == "Array") {
fieldOptions.relationType = MongoSchema_1.ERelationType.ArrayObjectId;
}
schema.addField(key, typeFunction, fieldOptions);
};
} | [
"function",
"FieldReference",
"(",
"typeFunction",
",",
"fieldOptions",
"=",
"{",
"}",
")",
"{",
"return",
"function",
"(",
"target",
",",
"key",
")",
"{",
"let",
"fieldType",
"=",
"Reflect",
".",
"getMetadata",
"(",
"\"design:type\"",
",",
"target",
",",
"key",
")",
";",
"let",
"schema",
"=",
"MongoSchemaRegistry_1",
".",
"MongoSchemaRegistry",
".",
"getSchema",
"(",
"target",
".",
"constructor",
".",
"name",
")",
";",
"if",
"(",
"!",
"schema",
")",
"{",
"schema",
"=",
"new",
"MongoSchema_1",
".",
"MongoSchema",
"(",
"target",
".",
"constructor",
")",
";",
"MongoSchemaRegistry_1",
".",
"MongoSchemaRegistry",
".",
"register",
"(",
"target",
".",
"constructor",
".",
"name",
",",
"schema",
")",
";",
"}",
"if",
"(",
"!",
"typeFunction",
")",
"{",
"typeFunction",
"=",
"type",
"=>",
"{",
"return",
"fieldOptions",
".",
"type",
"||",
"Reflect",
".",
"getMetadata",
"(",
"\"design:type\"",
",",
"target",
",",
"key",
")",
".",
"name",
";",
"}",
";",
"}",
"fieldOptions",
".",
"foreignField",
"=",
"fieldOptions",
".",
"foreignField",
"||",
"\"_id\"",
";",
"if",
"(",
"!",
"fieldType",
"||",
"fieldType",
".",
"name",
"!=",
"\"Array\"",
")",
"{",
"fieldOptions",
".",
"relationType",
"=",
"MongoSchema_1",
".",
"ERelationType",
".",
"SingleObjectId",
";",
"}",
"if",
"(",
"fieldType",
"&&",
"fieldType",
".",
"name",
"==",
"\"Array\"",
")",
"{",
"fieldOptions",
".",
"relationType",
"=",
"MongoSchema_1",
".",
"ERelationType",
".",
"ArrayObjectId",
";",
"}",
"schema",
".",
"addField",
"(",
"key",
",",
"typeFunction",
",",
"fieldOptions",
")",
";",
"}",
";",
"}"
] | Single field representing a singl object | [
"Single",
"field",
"representing",
"a",
"singl",
"object"
] | cd816e9fce11b0739a0859c4f462bcbe72c729a9 | https://github.com/xiara-io/xiara-mongo/blob/cd816e9fce11b0739a0859c4f462bcbe72c729a9/dist/Definitions/Decorators.js#L80-L102 | train |
timmywil/grunt-npmcopy | tasks/npmcopy.js | getNumTargets | function getNumTargets() {
if (numTargets) {
return numTargets
}
var targets = grunt.config('npmcopy')
if (targets) {
delete targets.options
numTargets = Object.keys(targets).length
}
return numTargets
} | javascript | function getNumTargets() {
if (numTargets) {
return numTargets
}
var targets = grunt.config('npmcopy')
if (targets) {
delete targets.options
numTargets = Object.keys(targets).length
}
return numTargets
} | [
"function",
"getNumTargets",
"(",
")",
"{",
"if",
"(",
"numTargets",
")",
"{",
"return",
"numTargets",
"}",
"var",
"targets",
"=",
"grunt",
".",
"config",
"(",
"'npmcopy'",
")",
"if",
"(",
"targets",
")",
"{",
"delete",
"targets",
".",
"options",
"numTargets",
"=",
"Object",
".",
"keys",
"(",
"targets",
")",
".",
"length",
"}",
"return",
"numTargets",
"}"
] | Retrieve the number of targets from the grunt config
@returns {number|undefined} Returns the number of targets,
or undefined if the npmcopy config could not be found | [
"Retrieve",
"the",
"number",
"of",
"targets",
"from",
"the",
"grunt",
"config"
] | bd7ebdfd043437ac52e123ee007cb174d94e2565 | https://github.com/timmywil/grunt-npmcopy/blob/bd7ebdfd043437ac52e123ee007cb174d94e2565/tasks/npmcopy.js#L42-L52 | train |
timmywil/grunt-npmcopy | tasks/npmcopy.js | convert | function convert(files) {
var converted = []
files.forEach(function(file) {
// We need originals as the destinations may not yet exist
file = file.orig
var dest = file.dest
// Use destination for source if no source is available
if (!file.src.length) {
converted.push({
src: dest,
dest: dest
})
return
}
file.src.forEach(function(source) {
converted.push({
src: source,
dest: dest
})
})
})
return converted
} | javascript | function convert(files) {
var converted = []
files.forEach(function(file) {
// We need originals as the destinations may not yet exist
file = file.orig
var dest = file.dest
// Use destination for source if no source is available
if (!file.src.length) {
converted.push({
src: dest,
dest: dest
})
return
}
file.src.forEach(function(source) {
converted.push({
src: source,
dest: dest
})
})
})
return converted
} | [
"function",
"convert",
"(",
"files",
")",
"{",
"var",
"converted",
"=",
"[",
"]",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"file",
"=",
"file",
".",
"orig",
"var",
"dest",
"=",
"file",
".",
"dest",
"if",
"(",
"!",
"file",
".",
"src",
".",
"length",
")",
"{",
"converted",
".",
"push",
"(",
"{",
"src",
":",
"dest",
",",
"dest",
":",
"dest",
"}",
")",
"return",
"}",
"file",
".",
"src",
".",
"forEach",
"(",
"function",
"(",
"source",
")",
"{",
"converted",
".",
"push",
"(",
"{",
"src",
":",
"source",
",",
"dest",
":",
"dest",
"}",
")",
"}",
")",
"}",
")",
"return",
"converted",
"}"
] | Convert from grunt to a cleaner format
@param {Array} files | [
"Convert",
"from",
"grunt",
"to",
"a",
"cleaner",
"format"
] | bd7ebdfd043437ac52e123ee007cb174d94e2565 | https://github.com/timmywil/grunt-npmcopy/blob/bd7ebdfd043437ac52e123ee007cb174d94e2565/tasks/npmcopy.js#L58-L82 | train |
timmywil/grunt-npmcopy | tasks/npmcopy.js | filterRepresented | function filterRepresented(modules, files, options) {
return _.filter(modules, function(module) {
return !_.some(files, function(file) {
// Look for the module name somewhere in the source path
return (
path
.join(sep, options.srcPrefix, file.src.replace(rmain, '$1'), sep)
.indexOf(sep + module + sep) > -1
)
})
})
} | javascript | function filterRepresented(modules, files, options) {
return _.filter(modules, function(module) {
return !_.some(files, function(file) {
// Look for the module name somewhere in the source path
return (
path
.join(sep, options.srcPrefix, file.src.replace(rmain, '$1'), sep)
.indexOf(sep + module + sep) > -1
)
})
})
} | [
"function",
"filterRepresented",
"(",
"modules",
",",
"files",
",",
"options",
")",
"{",
"return",
"_",
".",
"filter",
"(",
"modules",
",",
"function",
"(",
"module",
")",
"{",
"return",
"!",
"_",
".",
"some",
"(",
"files",
",",
"function",
"(",
"file",
")",
"{",
"return",
"(",
"path",
".",
"join",
"(",
"sep",
",",
"options",
".",
"srcPrefix",
",",
"file",
".",
"src",
".",
"replace",
"(",
"rmain",
",",
"'$1'",
")",
",",
"sep",
")",
".",
"indexOf",
"(",
"sep",
"+",
"module",
"+",
"sep",
")",
">",
"-",
"1",
")",
"}",
")",
"}",
")",
"}"
] | Filter out all of the modules represented in the filesSrc array
@param {Array} modules
@param {Array} files
@param {Object} options | [
"Filter",
"out",
"all",
"of",
"the",
"modules",
"represented",
"in",
"the",
"filesSrc",
"array"
] | bd7ebdfd043437ac52e123ee007cb174d94e2565 | https://github.com/timmywil/grunt-npmcopy/blob/bd7ebdfd043437ac52e123ee007cb174d94e2565/tasks/npmcopy.js#L90-L101 | train |
timmywil/grunt-npmcopy | tasks/npmcopy.js | ensure | function ensure(files, options) {
// Update the global array of represented modules
unused = filterRepresented(unused, files, options)
verbose.writeln('Unrepresented modules list currently at ', unused)
// Only print message when all targets have been run
if (++numRuns === getNumTargets()) {
if (unused.length) {
if (options.report) {
log.writeln('\nPackages left out:')
log.writeln(unused.join('\n'))
}
} else if (options.report) {
log.ok('All modules have something copied.')
}
}
} | javascript | function ensure(files, options) {
// Update the global array of represented modules
unused = filterRepresented(unused, files, options)
verbose.writeln('Unrepresented modules list currently at ', unused)
// Only print message when all targets have been run
if (++numRuns === getNumTargets()) {
if (unused.length) {
if (options.report) {
log.writeln('\nPackages left out:')
log.writeln(unused.join('\n'))
}
} else if (options.report) {
log.ok('All modules have something copied.')
}
}
} | [
"function",
"ensure",
"(",
"files",
",",
"options",
")",
"{",
"unused",
"=",
"filterRepresented",
"(",
"unused",
",",
"files",
",",
"options",
")",
"verbose",
".",
"writeln",
"(",
"'Unrepresented modules list currently at '",
",",
"unused",
")",
"if",
"(",
"++",
"numRuns",
"===",
"getNumTargets",
"(",
")",
")",
"{",
"if",
"(",
"unused",
".",
"length",
")",
"{",
"if",
"(",
"options",
".",
"report",
")",
"{",
"log",
".",
"writeln",
"(",
"'\\nPackages left out:'",
")",
"\\n",
"}",
"}",
"else",
"log",
".",
"writeln",
"(",
"unused",
".",
"join",
"(",
"'\\n'",
")",
")",
"}",
"}"
] | Ensure all npm dependencies are accounted for
@param {Array} files Files property from the task
@param {Object} options
@returns {boolean} Returns whether all dependencies are accounted for | [
"Ensure",
"all",
"npm",
"dependencies",
"are",
"accounted",
"for"
] | bd7ebdfd043437ac52e123ee007cb174d94e2565 | https://github.com/timmywil/grunt-npmcopy/blob/bd7ebdfd043437ac52e123ee007cb174d94e2565/tasks/npmcopy.js#L109-L126 | train |
timmywil/grunt-npmcopy | tasks/npmcopy.js | convertMatches | function convertMatches(files, options, dest) {
return files.map(function(source) {
return {
src: source,
dest: path.join(
// Build a destination from the new source if no dest
// was specified
dest != null ? dest : path.dirname(source).replace(options.srcPrefix + sep, ''),
path.basename(source)
)
}
})
} | javascript | function convertMatches(files, options, dest) {
return files.map(function(source) {
return {
src: source,
dest: path.join(
// Build a destination from the new source if no dest
// was specified
dest != null ? dest : path.dirname(source).replace(options.srcPrefix + sep, ''),
path.basename(source)
)
}
})
} | [
"function",
"convertMatches",
"(",
"files",
",",
"options",
",",
"dest",
")",
"{",
"return",
"files",
".",
"map",
"(",
"function",
"(",
"source",
")",
"{",
"return",
"{",
"src",
":",
"source",
",",
"dest",
":",
"path",
".",
"join",
"(",
"dest",
"!=",
"null",
"?",
"dest",
":",
"path",
".",
"dirname",
"(",
"source",
")",
".",
"replace",
"(",
"options",
".",
"srcPrefix",
"+",
"sep",
",",
"''",
")",
",",
"path",
".",
"basename",
"(",
"source",
")",
")",
"}",
"}",
")",
"}"
] | Convert an array of files sources to our format
@param {Array} files
@param {Object} options
@param {String} [dest] A folder destination for all of these sources | [
"Convert",
"an",
"array",
"of",
"files",
"sources",
"to",
"our",
"format"
] | bd7ebdfd043437ac52e123ee007cb174d94e2565 | https://github.com/timmywil/grunt-npmcopy/blob/bd7ebdfd043437ac52e123ee007cb174d94e2565/tasks/npmcopy.js#L134-L146 | train |
timmywil/grunt-npmcopy | tasks/npmcopy.js | getMain | function getMain(src, options, dest) {
var meta = grunt.file.readJSON(path.join(src, 'package.json'))
if (!meta.main) {
fail.fatal(
'No main property specified by ' + path.normalize(src.replace(options.srcPrefix, ''))
)
}
var files = typeof meta.main === 'string' ? [meta.main] : meta.main
return files.map(function(source) {
return {
src: path.join(src, source),
dest: dest
}
})
} | javascript | function getMain(src, options, dest) {
var meta = grunt.file.readJSON(path.join(src, 'package.json'))
if (!meta.main) {
fail.fatal(
'No main property specified by ' + path.normalize(src.replace(options.srcPrefix, ''))
)
}
var files = typeof meta.main === 'string' ? [meta.main] : meta.main
return files.map(function(source) {
return {
src: path.join(src, source),
dest: dest
}
})
} | [
"function",
"getMain",
"(",
"src",
",",
"options",
",",
"dest",
")",
"{",
"var",
"meta",
"=",
"grunt",
".",
"file",
".",
"readJSON",
"(",
"path",
".",
"join",
"(",
"src",
",",
"'package.json'",
")",
")",
"if",
"(",
"!",
"meta",
".",
"main",
")",
"{",
"fail",
".",
"fatal",
"(",
"'No main property specified by '",
"+",
"path",
".",
"normalize",
"(",
"src",
".",
"replace",
"(",
"options",
".",
"srcPrefix",
",",
"''",
")",
")",
")",
"}",
"var",
"files",
"=",
"typeof",
"meta",
".",
"main",
"===",
"'string'",
"?",
"[",
"meta",
".",
"main",
"]",
":",
"meta",
".",
"main",
"return",
"files",
".",
"map",
"(",
"function",
"(",
"source",
")",
"{",
"return",
"{",
"src",
":",
"path",
".",
"join",
"(",
"src",
",",
"source",
")",
",",
"dest",
":",
"dest",
"}",
"}",
")",
"}"
] | Get the main files for a particular package
@param {string} src
@param {Object} options
@param {string} dest
@returns {Array} Returns an array of file locations from the main property | [
"Get",
"the",
"main",
"files",
"for",
"a",
"particular",
"package"
] | bd7ebdfd043437ac52e123ee007cb174d94e2565 | https://github.com/timmywil/grunt-npmcopy/blob/bd7ebdfd043437ac52e123ee007cb174d94e2565/tasks/npmcopy.js#L155-L169 | train |
obliquid/jslardo | core/permissions.js | readStrucPerm | function readStrucPerm(on, req, res, next) {
//console.log('readStrucPerm: req.session.user_id = ' + req.session.user_id);
//solo nel caso di favicon.ico non ha le session impostate, non so perchè,
//quindi bypasso il controllo, perchè su favicon non ho nessuna restrizione
if ( !req.session )
{
next();
}
else
{
//azzero i permessi
req.session.loggedIn = false;
req.session.canCreate = false;
req.session.canModify = false;
req.session.canModifyMyself = false; //questo è un permesso che vale solo per l'elemento "users"
//controllo se sono loggato
if (req.session.user_id) {
//l'utente risulta loggato
//controllo se i suoi dati di login sono validi
//(questo controllo va fatto ogni volta, perchè se dall'ultimo conrollo l'utente fosse stato cancellato, non me ne accorgerei senza controllo
req.app.jsl.sess.checkValidUser(req, function(result, user_id) {
if ( result )
{
//i dati di login sono validi
req.session.loggedIn = true;
if ( user_id == 'superadmin' )
{
//se sono super admin, ho sempre permesso di modify su tutti i contenuti, ma non ho il create (a parte sugli users)
//questo perchè quando si crea un contenuto, questo è strettamente legato all'utente che lo crea, e il superadmin
//non è un utente vero è proprio (non è presente nel db, non ha id). il super admin serve solo per poter vedere e modificare tutto, ma non può creare nulla
req.session.canModify = true;
req.session.canModifyMyself = true; //questo serve per permettere al super admin di modificare gli utenti (il form di modifica lo richiede)
//solo nel caso degli users, il superadmin ha il create, anche se usersCanRegister = false
if ( on == 'user' )
{
req.session.canCreate = true;
}
//la request puo essere processata
next();
}
else
{
//non sono superadmin
//siccome si tratta di permessi su elementi della struttura, chiunque (loggato) ha sempre il permesso di create nuovi elementi
//(tranne per il caso degli "user" in cui si creano altri utenti con il bottone "registrati", che però non prevede di essere loggati)
if ( on != 'user' )
{
req.session.canCreate = true;
}
//differenzio i permessi di modify in base all'oggetto trattato
switch (on)
{
case 'user':
//user è un elemento della struttura particolare, perchè, a differenza di tutti gli altri elementi di struttura, ogni utente può solo modificare
//se stesso. inoltre user non ha un "author" poichè un utente è creato da se stesso tramite il bottone "register"
//nel caso di modifica di users, ho modify solo per modificare me stesso
if ( req.params.id == req.session.user_id ) //controllo se l'id dell'utente da modificare è quello dell'utente loggato, cioè se modifico me stesso
{
//lo user id nella route richiesta corrisponde al mio, quindi posso modificare me stesso (il mio profilo)
req.session.canModifyMyself = true;
}
break;
default:
//ora come ora per tutti gli altri elementi della struttura chiunque ha permesso di modify, ma solo sui propri elementi
req.session.canModify = true;
break;
}
//continuo
next();
}
}
else
{
//i dati di login non sono validi
//console.log('readStrucPerm: login NON valido');
//forzo un logout (potrebbe verificarsi il caso in cui un utente è loggato, e viene cancellato dal db. in quel caso deve avvenire anche il suo logout)
setSignedOut(req);
//vengo mandato in home
res.redirect('/');
}
});
} else {
//console.log('readStrucPerm: utente non loggato');
//non sono loggato. l'unica cosa che posso fare è di registrarmi, ovvero creare un nuovo user
//ma solo se è stato previsto nel config
if ( on == 'user' && req.app.jsl.config.usersCanRegister )
{
req.session.canCreate = true;
}
//non ho nessun permesso, continuo
next();
}
}
} | javascript | function readStrucPerm(on, req, res, next) {
//console.log('readStrucPerm: req.session.user_id = ' + req.session.user_id);
//solo nel caso di favicon.ico non ha le session impostate, non so perchè,
//quindi bypasso il controllo, perchè su favicon non ho nessuna restrizione
if ( !req.session )
{
next();
}
else
{
//azzero i permessi
req.session.loggedIn = false;
req.session.canCreate = false;
req.session.canModify = false;
req.session.canModifyMyself = false; //questo è un permesso che vale solo per l'elemento "users"
//controllo se sono loggato
if (req.session.user_id) {
//l'utente risulta loggato
//controllo se i suoi dati di login sono validi
//(questo controllo va fatto ogni volta, perchè se dall'ultimo conrollo l'utente fosse stato cancellato, non me ne accorgerei senza controllo
req.app.jsl.sess.checkValidUser(req, function(result, user_id) {
if ( result )
{
//i dati di login sono validi
req.session.loggedIn = true;
if ( user_id == 'superadmin' )
{
//se sono super admin, ho sempre permesso di modify su tutti i contenuti, ma non ho il create (a parte sugli users)
//questo perchè quando si crea un contenuto, questo è strettamente legato all'utente che lo crea, e il superadmin
//non è un utente vero è proprio (non è presente nel db, non ha id). il super admin serve solo per poter vedere e modificare tutto, ma non può creare nulla
req.session.canModify = true;
req.session.canModifyMyself = true; //questo serve per permettere al super admin di modificare gli utenti (il form di modifica lo richiede)
//solo nel caso degli users, il superadmin ha il create, anche se usersCanRegister = false
if ( on == 'user' )
{
req.session.canCreate = true;
}
//la request puo essere processata
next();
}
else
{
//non sono superadmin
//siccome si tratta di permessi su elementi della struttura, chiunque (loggato) ha sempre il permesso di create nuovi elementi
//(tranne per il caso degli "user" in cui si creano altri utenti con il bottone "registrati", che però non prevede di essere loggati)
if ( on != 'user' )
{
req.session.canCreate = true;
}
//differenzio i permessi di modify in base all'oggetto trattato
switch (on)
{
case 'user':
//user è un elemento della struttura particolare, perchè, a differenza di tutti gli altri elementi di struttura, ogni utente può solo modificare
//se stesso. inoltre user non ha un "author" poichè un utente è creato da se stesso tramite il bottone "register"
//nel caso di modifica di users, ho modify solo per modificare me stesso
if ( req.params.id == req.session.user_id ) //controllo se l'id dell'utente da modificare è quello dell'utente loggato, cioè se modifico me stesso
{
//lo user id nella route richiesta corrisponde al mio, quindi posso modificare me stesso (il mio profilo)
req.session.canModifyMyself = true;
}
break;
default:
//ora come ora per tutti gli altri elementi della struttura chiunque ha permesso di modify, ma solo sui propri elementi
req.session.canModify = true;
break;
}
//continuo
next();
}
}
else
{
//i dati di login non sono validi
//console.log('readStrucPerm: login NON valido');
//forzo un logout (potrebbe verificarsi il caso in cui un utente è loggato, e viene cancellato dal db. in quel caso deve avvenire anche il suo logout)
setSignedOut(req);
//vengo mandato in home
res.redirect('/');
}
});
} else {
//console.log('readStrucPerm: utente non loggato');
//non sono loggato. l'unica cosa che posso fare è di registrarmi, ovvero creare un nuovo user
//ma solo se è stato previsto nel config
if ( on == 'user' && req.app.jsl.config.usersCanRegister )
{
req.session.canCreate = true;
}
//non ho nessun permesso, continuo
next();
}
}
} | [
"function",
"readStrucPerm",
"(",
"on",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"!",
"req",
".",
"session",
")",
"{",
"next",
"(",
")",
";",
"}",
"else",
"{",
"req",
".",
"session",
".",
"loggedIn",
"=",
"false",
";",
"req",
".",
"session",
".",
"canCreate",
"=",
"false",
";",
"req",
".",
"session",
".",
"canModify",
"=",
"false",
";",
"req",
".",
"session",
".",
"canModifyMyself",
"=",
"false",
";",
"if",
"(",
"req",
".",
"session",
".",
"user_id",
")",
"{",
"req",
".",
"app",
".",
"jsl",
".",
"sess",
".",
"checkValidUser",
"(",
"req",
",",
"function",
"(",
"result",
",",
"user_id",
")",
"{",
"if",
"(",
"result",
")",
"{",
"req",
".",
"session",
".",
"loggedIn",
"=",
"true",
";",
"if",
"(",
"user_id",
"==",
"'superadmin'",
")",
"{",
"req",
".",
"session",
".",
"canModify",
"=",
"true",
";",
"req",
".",
"session",
".",
"canModifyMyself",
"=",
"true",
";",
"if",
"(",
"on",
"==",
"'user'",
")",
"{",
"req",
".",
"session",
".",
"canCreate",
"=",
"true",
";",
"}",
"next",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"on",
"!=",
"'user'",
")",
"{",
"req",
".",
"session",
".",
"canCreate",
"=",
"true",
";",
"}",
"switch",
"(",
"on",
")",
"{",
"case",
"'user'",
":",
"if",
"(",
"req",
".",
"params",
".",
"id",
"==",
"req",
".",
"session",
".",
"user_id",
")",
"{",
"req",
".",
"session",
".",
"canModifyMyself",
"=",
"true",
";",
"}",
"break",
";",
"default",
":",
"req",
".",
"session",
".",
"canModify",
"=",
"true",
";",
"break",
";",
"}",
"next",
"(",
")",
";",
"}",
"}",
"else",
"{",
"setSignedOut",
"(",
"req",
")",
";",
"res",
".",
"redirect",
"(",
"'/'",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"on",
"==",
"'user'",
"&&",
"req",
".",
"app",
".",
"jsl",
".",
"config",
".",
"usersCanRegister",
")",
"{",
"req",
".",
"session",
".",
"canCreate",
"=",
"true",
";",
"}",
"next",
"(",
")",
";",
"}",
"}",
"}"
] | questo metodo viene richiamato prima di eseguire ogni request che lo richiede in qualunque controller di qualunque oggetto | [
"questo",
"metodo",
"viene",
"richiamato",
"prima",
"di",
"eseguire",
"ogni",
"request",
"che",
"lo",
"richiede",
"in",
"qualunque",
"controller",
"di",
"qualunque",
"oggetto"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/core/permissions.js#L179-L274 | train |
feedhenry/fh-gridfs | lib/gridFileManager.js | getFileDetails | function getFileDetails(db, fileSelectionCriteria, fileOptions, cb) {
defaultLogger.debug("In getFileDetails ");
var selectionQuery = undefined;
if (fileSelectionCriteria.groupId) {
selectionQuery= {"metadata.groupId": fileSelectionCriteria.groupId};
} else if (fileSelectionCriteria.hash) {
selectionQuery= {"md5": fileSelectionCriteria.hash};
}
var gridStore = new GridStore(db, null, "r", {"root": constants.ROOT_COLLECTION});
var fileOfInterest = undefined;
gridStore.collection(function(err, collection) {
collection.find(selectionQuery, { "sort": {"metadata.version":-1}}, function(err, files) {
if (err) {
defaultLogger.error(err); return cb(err);
}
files.toArray(function(err, filesArray) {
if (err) {
defaultLogger.error(err); return cb(err);
}
if (!(filesArray && Array.isArray(filesArray) && filesArray.length > 0)) {
return cb(new Error("No files exist for groupId " + fileSelectionCriteria.groupId));
}
//If the file details are needed for all files in the groupId, then an array containing all of the file details is returned.
if (fileOptions.allMatchingFiles == true) { // eslint-disable-line eqeqeq
fileOfInterest = filesArray;
} else {// Just want the details of a single file.
//If there is no version, get the latest version
//If no version is found or we have a hash query, just want the first entry of the array.
if (!fileSelectionCriteria.version || fileSelectionCriteria.hash) {
fileOfInterest = filesArray[0];
} else {
fileOfInterest = filesArray.filter(function(file) {
return file.metadata.version === fileSelectionCriteria.version;
});
if (fileOfInterest.length === 1) {
fileOfInterest = fileOfInterest[0];
} else {
return cb(new Error("Unexpected number of files returned for groupId " + fileSelectionCriteria.groupId, fileOfInterest.length));
}
}
}
if (!Array.isArray(fileOfInterest)) {
//Actually want the thumbnail for the file, return the details for that file instead.
if (fileOptions.thumbnail) {
if (fileOfInterest.metadata.thumbnail) {
getThumbnailFileDetails(db, fileOfInterest.metadata.thumbnail, function(err, thumbFileDetails) {
if (err) {
defaultLogger.error(err); return cb(err);
}
fileOfInterest = thumbFileDetails;
gridStore.close(function(err) {
return cb(err, fileOfInterest);
});
});
} else {
return cb(new Error("Thumbnail for file " + JSON.stringify(fileSelectionCriteria) + " does not exist."));
}
} else {
gridStore.close(function(err) {
return cb(err, fileOfInterest);
});
}
} else {
gridStore.close(function(err) {
return cb(err, fileOfInterest);
});
}
});
});
});
} | javascript | function getFileDetails(db, fileSelectionCriteria, fileOptions, cb) {
defaultLogger.debug("In getFileDetails ");
var selectionQuery = undefined;
if (fileSelectionCriteria.groupId) {
selectionQuery= {"metadata.groupId": fileSelectionCriteria.groupId};
} else if (fileSelectionCriteria.hash) {
selectionQuery= {"md5": fileSelectionCriteria.hash};
}
var gridStore = new GridStore(db, null, "r", {"root": constants.ROOT_COLLECTION});
var fileOfInterest = undefined;
gridStore.collection(function(err, collection) {
collection.find(selectionQuery, { "sort": {"metadata.version":-1}}, function(err, files) {
if (err) {
defaultLogger.error(err); return cb(err);
}
files.toArray(function(err, filesArray) {
if (err) {
defaultLogger.error(err); return cb(err);
}
if (!(filesArray && Array.isArray(filesArray) && filesArray.length > 0)) {
return cb(new Error("No files exist for groupId " + fileSelectionCriteria.groupId));
}
//If the file details are needed for all files in the groupId, then an array containing all of the file details is returned.
if (fileOptions.allMatchingFiles == true) { // eslint-disable-line eqeqeq
fileOfInterest = filesArray;
} else {// Just want the details of a single file.
//If there is no version, get the latest version
//If no version is found or we have a hash query, just want the first entry of the array.
if (!fileSelectionCriteria.version || fileSelectionCriteria.hash) {
fileOfInterest = filesArray[0];
} else {
fileOfInterest = filesArray.filter(function(file) {
return file.metadata.version === fileSelectionCriteria.version;
});
if (fileOfInterest.length === 1) {
fileOfInterest = fileOfInterest[0];
} else {
return cb(new Error("Unexpected number of files returned for groupId " + fileSelectionCriteria.groupId, fileOfInterest.length));
}
}
}
if (!Array.isArray(fileOfInterest)) {
//Actually want the thumbnail for the file, return the details for that file instead.
if (fileOptions.thumbnail) {
if (fileOfInterest.metadata.thumbnail) {
getThumbnailFileDetails(db, fileOfInterest.metadata.thumbnail, function(err, thumbFileDetails) {
if (err) {
defaultLogger.error(err); return cb(err);
}
fileOfInterest = thumbFileDetails;
gridStore.close(function(err) {
return cb(err, fileOfInterest);
});
});
} else {
return cb(new Error("Thumbnail for file " + JSON.stringify(fileSelectionCriteria) + " does not exist."));
}
} else {
gridStore.close(function(err) {
return cb(err, fileOfInterest);
});
}
} else {
gridStore.close(function(err) {
return cb(err, fileOfInterest);
});
}
});
});
});
} | [
"function",
"getFileDetails",
"(",
"db",
",",
"fileSelectionCriteria",
",",
"fileOptions",
",",
"cb",
")",
"{",
"defaultLogger",
".",
"debug",
"(",
"\"In getFileDetails \"",
")",
";",
"var",
"selectionQuery",
"=",
"undefined",
";",
"if",
"(",
"fileSelectionCriteria",
".",
"groupId",
")",
"{",
"selectionQuery",
"=",
"{",
"\"metadata.groupId\"",
":",
"fileSelectionCriteria",
".",
"groupId",
"}",
";",
"}",
"else",
"if",
"(",
"fileSelectionCriteria",
".",
"hash",
")",
"{",
"selectionQuery",
"=",
"{",
"\"md5\"",
":",
"fileSelectionCriteria",
".",
"hash",
"}",
";",
"}",
"var",
"gridStore",
"=",
"new",
"GridStore",
"(",
"db",
",",
"null",
",",
"\"r\"",
",",
"{",
"\"root\"",
":",
"constants",
".",
"ROOT_COLLECTION",
"}",
")",
";",
"var",
"fileOfInterest",
"=",
"undefined",
";",
"gridStore",
".",
"collection",
"(",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"collection",
".",
"find",
"(",
"selectionQuery",
",",
"{",
"\"sort\"",
":",
"{",
"\"metadata.version\"",
":",
"-",
"1",
"}",
"}",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"{",
"defaultLogger",
".",
"error",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"files",
".",
"toArray",
"(",
"function",
"(",
"err",
",",
"filesArray",
")",
"{",
"if",
"(",
"err",
")",
"{",
"defaultLogger",
".",
"error",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"(",
"filesArray",
"&&",
"Array",
".",
"isArray",
"(",
"filesArray",
")",
"&&",
"filesArray",
".",
"length",
">",
"0",
")",
")",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"No files exist for groupId \"",
"+",
"fileSelectionCriteria",
".",
"groupId",
")",
")",
";",
"}",
"if",
"(",
"fileOptions",
".",
"allMatchingFiles",
"==",
"true",
")",
"{",
"fileOfInterest",
"=",
"filesArray",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"fileSelectionCriteria",
".",
"version",
"||",
"fileSelectionCriteria",
".",
"hash",
")",
"{",
"fileOfInterest",
"=",
"filesArray",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"fileOfInterest",
"=",
"filesArray",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"return",
"file",
".",
"metadata",
".",
"version",
"===",
"fileSelectionCriteria",
".",
"version",
";",
"}",
")",
";",
"if",
"(",
"fileOfInterest",
".",
"length",
"===",
"1",
")",
"{",
"fileOfInterest",
"=",
"fileOfInterest",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"Unexpected number of files returned for groupId \"",
"+",
"fileSelectionCriteria",
".",
"groupId",
",",
"fileOfInterest",
".",
"length",
")",
")",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"fileOfInterest",
")",
")",
"{",
"if",
"(",
"fileOptions",
".",
"thumbnail",
")",
"{",
"if",
"(",
"fileOfInterest",
".",
"metadata",
".",
"thumbnail",
")",
"{",
"getThumbnailFileDetails",
"(",
"db",
",",
"fileOfInterest",
".",
"metadata",
".",
"thumbnail",
",",
"function",
"(",
"err",
",",
"thumbFileDetails",
")",
"{",
"if",
"(",
"err",
")",
"{",
"defaultLogger",
".",
"error",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"fileOfInterest",
"=",
"thumbFileDetails",
";",
"gridStore",
".",
"close",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"fileOfInterest",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"Thumbnail for file \"",
"+",
"JSON",
".",
"stringify",
"(",
"fileSelectionCriteria",
")",
"+",
"\" does not exist.\"",
")",
")",
";",
"}",
"}",
"else",
"{",
"gridStore",
".",
"close",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"fileOfInterest",
")",
";",
"}",
")",
";",
"}",
"}",
"else",
"{",
"gridStore",
".",
"close",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"fileOfInterest",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Utility function to search for files in the database. | [
"Utility",
"function",
"to",
"search",
"for",
"files",
"in",
"the",
"database",
"."
] | 6ca85b1cd5c5a7426708a2657725f3a9bda91fff | https://github.com/feedhenry/fh-gridfs/blob/6ca85b1cd5c5a7426708a2657725f3a9bda91fff/lib/gridFileManager.js#L636-L719 | train |
feedhenry/fh-gridfs | lib/gridFileManager.js | updateExistingFile | function updateExistingFile(db, fileName, fileReadStream, options, cb) {
defaultLogger.debug("In updateExistingFile");
getFileDetails(db, {"groupId": options.groupId}, {}, function(err, fileInfo) {
if (err) {
defaultLogger.error(err); return cb(err);
}
var latestFileVersion = fileInfo.metadata.version;
incrementFileVersion(latestFileVersion, function(newFileVersion) {
if (!newFileVersion) {
return cb(new Error("File version was not incremented for file " + fileName));
}
defaultLogger.debug("New File Version ", newFileVersion);
createFileWithVersion(db, fileName, fileReadStream, newFileVersion, options, cb);
});
});
} | javascript | function updateExistingFile(db, fileName, fileReadStream, options, cb) {
defaultLogger.debug("In updateExistingFile");
getFileDetails(db, {"groupId": options.groupId}, {}, function(err, fileInfo) {
if (err) {
defaultLogger.error(err); return cb(err);
}
var latestFileVersion = fileInfo.metadata.version;
incrementFileVersion(latestFileVersion, function(newFileVersion) {
if (!newFileVersion) {
return cb(new Error("File version was not incremented for file " + fileName));
}
defaultLogger.debug("New File Version ", newFileVersion);
createFileWithVersion(db, fileName, fileReadStream, newFileVersion, options, cb);
});
});
} | [
"function",
"updateExistingFile",
"(",
"db",
",",
"fileName",
",",
"fileReadStream",
",",
"options",
",",
"cb",
")",
"{",
"defaultLogger",
".",
"debug",
"(",
"\"In updateExistingFile\"",
")",
";",
"getFileDetails",
"(",
"db",
",",
"{",
"\"groupId\"",
":",
"options",
".",
"groupId",
"}",
",",
"{",
"}",
",",
"function",
"(",
"err",
",",
"fileInfo",
")",
"{",
"if",
"(",
"err",
")",
"{",
"defaultLogger",
".",
"error",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"var",
"latestFileVersion",
"=",
"fileInfo",
".",
"metadata",
".",
"version",
";",
"incrementFileVersion",
"(",
"latestFileVersion",
",",
"function",
"(",
"newFileVersion",
")",
"{",
"if",
"(",
"!",
"newFileVersion",
")",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"\"File version was not incremented for file \"",
"+",
"fileName",
")",
")",
";",
"}",
"defaultLogger",
".",
"debug",
"(",
"\"New File Version \"",
",",
"newFileVersion",
")",
";",
"createFileWithVersion",
"(",
"db",
",",
"fileName",
",",
"fileReadStream",
",",
"newFileVersion",
",",
"options",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Updating an existing file means that the new file is saved with the same name with an incremented version. | [
"Updating",
"an",
"existing",
"file",
"means",
"that",
"the",
"new",
"file",
"is",
"saved",
"with",
"the",
"same",
"name",
"with",
"an",
"incremented",
"version",
"."
] | 6ca85b1cd5c5a7426708a2657725f3a9bda91fff | https://github.com/feedhenry/fh-gridfs/blob/6ca85b1cd5c5a7426708a2657725f3a9bda91fff/lib/gridFileManager.js#L757-L773 | train |
feedhenry/fh-gridfs | lib/gridFileManager.js | createNewFile | function createNewFile(db, fileName, fileReadStream, options, cb) {
defaultLogger.debug("In createNewFile");
createFileWithVersion(db, fileName, fileReadStream, constants.LOWEST_VERSION, options, cb);
} | javascript | function createNewFile(db, fileName, fileReadStream, options, cb) {
defaultLogger.debug("In createNewFile");
createFileWithVersion(db, fileName, fileReadStream, constants.LOWEST_VERSION, options, cb);
} | [
"function",
"createNewFile",
"(",
"db",
",",
"fileName",
",",
"fileReadStream",
",",
"options",
",",
"cb",
")",
"{",
"defaultLogger",
".",
"debug",
"(",
"\"In createNewFile\"",
")",
";",
"createFileWithVersion",
"(",
"db",
",",
"fileName",
",",
"fileReadStream",
",",
"constants",
".",
"LOWEST_VERSION",
",",
"options",
",",
"cb",
")",
";",
"}"
] | Creating a new file means creating a new file with fileName with version 0; | [
"Creating",
"a",
"new",
"file",
"means",
"creating",
"a",
"new",
"file",
"with",
"fileName",
"with",
"version",
"0",
";"
] | 6ca85b1cd5c5a7426708a2657725f3a9bda91fff | https://github.com/feedhenry/fh-gridfs/blob/6ca85b1cd5c5a7426708a2657725f3a9bda91fff/lib/gridFileManager.js#L776-L779 | train |
CactusTechnologies/cactus-utils | packages/logger/lib/serializers.js | errorSerializer | function errorSerializer (err) {
if (!err || !err.stack) return err
const obj = {
message: err.message,
name: err.name,
code: err.code,
stack: getErrorStack(err)
}
return obj
} | javascript | function errorSerializer (err) {
if (!err || !err.stack) return err
const obj = {
message: err.message,
name: err.name,
code: err.code,
stack: getErrorStack(err)
}
return obj
} | [
"function",
"errorSerializer",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"err",
"||",
"!",
"err",
".",
"stack",
")",
"return",
"err",
"const",
"obj",
"=",
"{",
"message",
":",
"err",
".",
"message",
",",
"name",
":",
"err",
".",
"name",
",",
"code",
":",
"err",
".",
"code",
",",
"stack",
":",
"getErrorStack",
"(",
"err",
")",
"}",
"return",
"obj",
"}"
] | Serializes Error Objects
@type {import("pino").SerializerFn}
@param {any} err | [
"Serializes",
"Error",
"Objects"
] | 0a827dbd755766309a4bc0f0a47c9e8dc4eb8d17 | https://github.com/CactusTechnologies/cactus-utils/blob/0a827dbd755766309a4bc0f0a47c9e8dc4eb8d17/packages/logger/lib/serializers.js#L14-L23 | train |
CactusTechnologies/cactus-utils | packages/logger/lib/serializers.js | getCleanUrl | function getCleanUrl (url) {
try {
const parsed = new URL(url)
return parsed.pathname || url
} catch (err) {
return url
}
} | javascript | function getCleanUrl (url) {
try {
const parsed = new URL(url)
return parsed.pathname || url
} catch (err) {
return url
}
} | [
"function",
"getCleanUrl",
"(",
"url",
")",
"{",
"try",
"{",
"const",
"parsed",
"=",
"new",
"URL",
"(",
"url",
")",
"return",
"parsed",
".",
"pathname",
"||",
"url",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"url",
"}",
"}"
] | Returns the pathname part of the given url
@param {String} url
@return {String} | [
"Returns",
"the",
"pathname",
"part",
"of",
"the",
"given",
"url"
] | 0a827dbd755766309a4bc0f0a47c9e8dc4eb8d17 | https://github.com/CactusTechnologies/cactus-utils/blob/0a827dbd755766309a4bc0f0a47c9e8dc4eb8d17/packages/logger/lib/serializers.js#L90-L97 | train |
Allenice/madoka | index.js | function(str, index) {
// replace {{ xxx }}
var obj = this
str = str.replace(interpolateReg, function(match, interpolate) {
try {
/*jslint evil: true */
var funcNames = ['','index'].concat(fakerFuncNames).concat(['return ' + interpolate + ';']),
func = new (Function.prototype.bind.apply(Function, funcNames)),
funcs = [function(){return index}].concat(fakerFuncs);
return func.apply(obj, funcs);
} catch(e) {
return e.message;
}
});
// if result is true or false, parse it to boolean
if(/^(true|false)$/.test(str)) {
str = str === 'true';
}
// if result is digit, parse it to float
if(/^[-+]?\d*\.?\d+$/.test(str)) {
str = parseFloat(str);
}
return str;
} | javascript | function(str, index) {
// replace {{ xxx }}
var obj = this
str = str.replace(interpolateReg, function(match, interpolate) {
try {
/*jslint evil: true */
var funcNames = ['','index'].concat(fakerFuncNames).concat(['return ' + interpolate + ';']),
func = new (Function.prototype.bind.apply(Function, funcNames)),
funcs = [function(){return index}].concat(fakerFuncs);
return func.apply(obj, funcs);
} catch(e) {
return e.message;
}
});
// if result is true or false, parse it to boolean
if(/^(true|false)$/.test(str)) {
str = str === 'true';
}
// if result is digit, parse it to float
if(/^[-+]?\d*\.?\d+$/.test(str)) {
str = parseFloat(str);
}
return str;
} | [
"function",
"(",
"str",
",",
"index",
")",
"{",
"var",
"obj",
"=",
"this",
"str",
"=",
"str",
".",
"replace",
"(",
"interpolateReg",
",",
"function",
"(",
"match",
",",
"interpolate",
")",
"{",
"try",
"{",
"var",
"funcNames",
"=",
"[",
"''",
",",
"'index'",
"]",
".",
"concat",
"(",
"fakerFuncNames",
")",
".",
"concat",
"(",
"[",
"'return '",
"+",
"interpolate",
"+",
"';'",
"]",
")",
",",
"func",
"=",
"new",
"(",
"Function",
".",
"prototype",
".",
"bind",
".",
"apply",
"(",
"Function",
",",
"funcNames",
")",
")",
",",
"funcs",
"=",
"[",
"function",
"(",
")",
"{",
"return",
"index",
"}",
"]",
".",
"concat",
"(",
"fakerFuncs",
")",
";",
"return",
"func",
".",
"apply",
"(",
"obj",
",",
"funcs",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"e",
".",
"message",
";",
"}",
"}",
")",
";",
"if",
"(",
"/",
"^(true|false)$",
"/",
".",
"test",
"(",
"str",
")",
")",
"{",
"str",
"=",
"str",
"===",
"'true'",
";",
"}",
"if",
"(",
"/",
"^[-+]?\\d*\\.?\\d+$",
"/",
".",
"test",
"(",
"str",
")",
")",
"{",
"str",
"=",
"parseFloat",
"(",
"str",
")",
";",
"}",
"return",
"str",
";",
"}"
] | parse string template, if the parent template is an array, it will pass the index value to the child template | [
"parse",
"string",
"template",
"if",
"the",
"parent",
"template",
"is",
"an",
"array",
"it",
"will",
"pass",
"the",
"index",
"value",
"to",
"the",
"child",
"template"
] | 1d8ffca8cff4ce96980c0f30af0e38aadbd1fe1b | https://github.com/Allenice/madoka/blob/1d8ffca8cff4ce96980c0f30af0e38aadbd1fe1b/index.js#L46-L74 | train |
|
Allenice/madoka | index.js | function(obj, index) {
var funcKey = [];
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
// If this is a function, generate it later.
if(typeof obj[key] === 'function') {
funcKey.push(key);
continue;
}
obj[key] = generate.call(obj, obj[key], index);
}
}
// parse function
funcKey.forEach(function(key) {
obj[key] = generate.call(obj, obj[key], index);
});
return obj;
} | javascript | function(obj, index) {
var funcKey = [];
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
// If this is a function, generate it later.
if(typeof obj[key] === 'function') {
funcKey.push(key);
continue;
}
obj[key] = generate.call(obj, obj[key], index);
}
}
// parse function
funcKey.forEach(function(key) {
obj[key] = generate.call(obj, obj[key], index);
});
return obj;
} | [
"function",
"(",
"obj",
",",
"index",
")",
"{",
"var",
"funcKey",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"obj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"if",
"(",
"typeof",
"obj",
"[",
"key",
"]",
"===",
"'function'",
")",
"{",
"funcKey",
".",
"push",
"(",
"key",
")",
";",
"continue",
";",
"}",
"obj",
"[",
"key",
"]",
"=",
"generate",
".",
"call",
"(",
"obj",
",",
"obj",
"[",
"key",
"]",
",",
"index",
")",
";",
"}",
"}",
"funcKey",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"obj",
"[",
"key",
"]",
"=",
"generate",
".",
"call",
"(",
"obj",
",",
"obj",
"[",
"key",
"]",
",",
"index",
")",
";",
"}",
")",
";",
"return",
"obj",
";",
"}"
] | parse object, it will generate each property | [
"parse",
"object",
"it",
"will",
"generate",
"each",
"property"
] | 1d8ffca8cff4ce96980c0f30af0e38aadbd1fe1b | https://github.com/Allenice/madoka/blob/1d8ffca8cff4ce96980c0f30af0e38aadbd1fe1b/index.js#L77-L98 | train |
|
Allenice/madoka | index.js | save | function save(template, distpath) {
var data = generate(template);
var dir = path.dirname(distpath);
mkdirp(dir, function(err) {
if(err) {
console.log(err.message);
return;
}
fs.writeFile(distpath, JSON.stringify(data, null, 2), function(err) {
if(err) {
console.log(err.message);
return;
}
});
});
} | javascript | function save(template, distpath) {
var data = generate(template);
var dir = path.dirname(distpath);
mkdirp(dir, function(err) {
if(err) {
console.log(err.message);
return;
}
fs.writeFile(distpath, JSON.stringify(data, null, 2), function(err) {
if(err) {
console.log(err.message);
return;
}
});
});
} | [
"function",
"save",
"(",
"template",
",",
"distpath",
")",
"{",
"var",
"data",
"=",
"generate",
"(",
"template",
")",
";",
"var",
"dir",
"=",
"path",
".",
"dirname",
"(",
"distpath",
")",
";",
"mkdirp",
"(",
"dir",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
".",
"message",
")",
";",
"return",
";",
"}",
"fs",
".",
"writeFile",
"(",
"distpath",
",",
"JSON",
".",
"stringify",
"(",
"data",
",",
"null",
",",
"2",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
".",
"message",
")",
";",
"return",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | save as json file
@param template - json scheme
@param path - path to save file | [
"save",
"as",
"json",
"file"
] | 1d8ffca8cff4ce96980c0f30af0e38aadbd1fe1b | https://github.com/Allenice/madoka/blob/1d8ffca8cff4ce96980c0f30af0e38aadbd1fe1b/index.js#L170-L189 | train |
comapi/comapi-sdk-js | specs/server.js | setConversationEtagHeader | function setConversationEtagHeader(res, conversationInfo) {
var copy = JSON.parse(JSON.stringify(conversationInfo));
delete copy.participants;
delete copy.createdOn;
delete copy.updatedOn;
setEtagHeader(res, copy);
} | javascript | function setConversationEtagHeader(res, conversationInfo) {
var copy = JSON.parse(JSON.stringify(conversationInfo));
delete copy.participants;
delete copy.createdOn;
delete copy.updatedOn;
setEtagHeader(res, copy);
} | [
"function",
"setConversationEtagHeader",
"(",
"res",
",",
"conversationInfo",
")",
"{",
"var",
"copy",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"conversationInfo",
")",
")",
";",
"delete",
"copy",
".",
"participants",
";",
"delete",
"copy",
".",
"createdOn",
";",
"delete",
"copy",
".",
"updatedOn",
";",
"setEtagHeader",
"(",
"res",
",",
"copy",
")",
";",
"}"
] | Copy the conversation info and lose the participants prior to setting the ETag ;-) | [
"Copy",
"the",
"conversation",
"info",
"and",
"lose",
"the",
"participants",
"prior",
"to",
"setting",
"the",
"ETag",
";",
"-",
")"
] | fd39d098f6d4ae4bfba2d06bf0b42b70c45c418d | https://github.com/comapi/comapi-sdk-js/blob/fd39d098f6d4ae4bfba2d06bf0b42b70c45c418d/specs/server.js#L195-L201 | train |
obliquid/jslardo | core/i18n.js | translate | function translate(singular, plural) {
if (!locales[currentLocale]) {
read(currentLocale);
}
if (plural) {
if (!locales[currentLocale][singular]) {
locales[currentLocale][singular] = {
'one': singular,
'other': plural
};
write(currentLocale);
}
}
if (!locales[currentLocale][singular]) {
locales[currentLocale][singular] = singular;
write(currentLocale);
}
return locales[currentLocale][singular];
} | javascript | function translate(singular, plural) {
if (!locales[currentLocale]) {
read(currentLocale);
}
if (plural) {
if (!locales[currentLocale][singular]) {
locales[currentLocale][singular] = {
'one': singular,
'other': plural
};
write(currentLocale);
}
}
if (!locales[currentLocale][singular]) {
locales[currentLocale][singular] = singular;
write(currentLocale);
}
return locales[currentLocale][singular];
} | [
"function",
"translate",
"(",
"singular",
",",
"plural",
")",
"{",
"if",
"(",
"!",
"locales",
"[",
"currentLocale",
"]",
")",
"{",
"read",
"(",
"currentLocale",
")",
";",
"}",
"if",
"(",
"plural",
")",
"{",
"if",
"(",
"!",
"locales",
"[",
"currentLocale",
"]",
"[",
"singular",
"]",
")",
"{",
"locales",
"[",
"currentLocale",
"]",
"[",
"singular",
"]",
"=",
"{",
"'one'",
":",
"singular",
",",
"'other'",
":",
"plural",
"}",
";",
"write",
"(",
"currentLocale",
")",
";",
"}",
"}",
"if",
"(",
"!",
"locales",
"[",
"currentLocale",
"]",
"[",
"singular",
"]",
")",
"{",
"locales",
"[",
"currentLocale",
"]",
"[",
"singular",
"]",
"=",
"singular",
";",
"write",
"(",
"currentLocale",
")",
";",
"}",
"return",
"locales",
"[",
"currentLocale",
"]",
"[",
"singular",
"]",
";",
"}"
] | read currentLocale file, translate a msg and write to fs if new QUI!!! metodo che usa currentLocale globale | [
"read",
"currentLocale",
"file",
"translate",
"a",
"msg",
"and",
"write",
"to",
"fs",
"if",
"new",
"QUI!!!",
"metodo",
"che",
"usa",
"currentLocale",
"globale"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/core/i18n.js#L164-L184 | train |
obliquid/jslardo | core/i18n.js | read | function read(myLocale) {
locales[myLocale] = {};
try {
locales[myLocale] = JSON.parse(fs.readFileSync(locate(myLocale)));
} catch(e) {
console.log('initializing ' + locate(myLocale));
write(myLocale);
}
} | javascript | function read(myLocale) {
locales[myLocale] = {};
try {
locales[myLocale] = JSON.parse(fs.readFileSync(locate(myLocale)));
} catch(e) {
console.log('initializing ' + locate(myLocale));
write(myLocale);
}
} | [
"function",
"read",
"(",
"myLocale",
")",
"{",
"locales",
"[",
"myLocale",
"]",
"=",
"{",
"}",
";",
"try",
"{",
"locales",
"[",
"myLocale",
"]",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"locate",
"(",
"myLocale",
")",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"'initializing '",
"+",
"locate",
"(",
"myLocale",
")",
")",
";",
"write",
"(",
"myLocale",
")",
";",
"}",
"}"
] | try reading a file | [
"try",
"reading",
"a",
"file"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/core/i18n.js#L187-L195 | train |
obliquid/jslardo | core/i18n.js | write | function write(myLocale) {
try {
stats = fs.lstatSync(directory);
} catch(e) {
fs.mkdirSync(directory, 0755);
}
fs.writeFile(locate(myLocale), JSON.stringify(locales[myLocale], null, "\t"));
} | javascript | function write(myLocale) {
try {
stats = fs.lstatSync(directory);
} catch(e) {
fs.mkdirSync(directory, 0755);
}
fs.writeFile(locate(myLocale), JSON.stringify(locales[myLocale], null, "\t"));
} | [
"function",
"write",
"(",
"myLocale",
")",
"{",
"try",
"{",
"stats",
"=",
"fs",
".",
"lstatSync",
"(",
"directory",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"directory",
",",
"0755",
")",
";",
"}",
"fs",
".",
"writeFile",
"(",
"locate",
"(",
"myLocale",
")",
",",
"JSON",
".",
"stringify",
"(",
"locales",
"[",
"myLocale",
"]",
",",
"null",
",",
"\"\\t\"",
")",
")",
";",
"}"
] | try writing a file in a created directory | [
"try",
"writing",
"a",
"file",
"in",
"a",
"created",
"directory"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/core/i18n.js#L198-L205 | train |
obliquid/jslardo | core/i18n.js | guessLanguage | function guessLanguage(request){
//console.log("guessLanguage");
if(typeof request === 'object'){
var language_header = request.headers['accept-language'],
languages = [];
regions = [];
request.languages = [currentLocale];
/*
for (x in request.languages)
{
console.log(request.languages[x] + x);
}
*/
request.regions = [currentLocale];
request.language = currentLocale;
request.region = currentLocale;
if (language_header) {
language_header.split(',').forEach(function(l) {
header = l.split(';', 1)[0];
lr = header.split('-', 2);
if (lr[0]) {
languages.push(lr[0].toLowerCase());
}
if (lr[1]) {
regions.push(lr[1].toLowerCase());
}
});
if (languages.length > 0) {
request.languages = languages;
request.language = languages[0];
}
if (regions.length > 0) {
request.regions = regions;
request.region = regions[0];
}
}
i18n.setLocale(request.language);
}
} | javascript | function guessLanguage(request){
//console.log("guessLanguage");
if(typeof request === 'object'){
var language_header = request.headers['accept-language'],
languages = [];
regions = [];
request.languages = [currentLocale];
/*
for (x in request.languages)
{
console.log(request.languages[x] + x);
}
*/
request.regions = [currentLocale];
request.language = currentLocale;
request.region = currentLocale;
if (language_header) {
language_header.split(',').forEach(function(l) {
header = l.split(';', 1)[0];
lr = header.split('-', 2);
if (lr[0]) {
languages.push(lr[0].toLowerCase());
}
if (lr[1]) {
regions.push(lr[1].toLowerCase());
}
});
if (languages.length > 0) {
request.languages = languages;
request.language = languages[0];
}
if (regions.length > 0) {
request.regions = regions;
request.region = regions[0];
}
}
i18n.setLocale(request.language);
}
} | [
"function",
"guessLanguage",
"(",
"request",
")",
"{",
"if",
"(",
"typeof",
"request",
"===",
"'object'",
")",
"{",
"var",
"language_header",
"=",
"request",
".",
"headers",
"[",
"'accept-language'",
"]",
",",
"languages",
"=",
"[",
"]",
";",
"regions",
"=",
"[",
"]",
";",
"request",
".",
"languages",
"=",
"[",
"currentLocale",
"]",
";",
"request",
".",
"regions",
"=",
"[",
"currentLocale",
"]",
";",
"request",
".",
"language",
"=",
"currentLocale",
";",
"request",
".",
"region",
"=",
"currentLocale",
";",
"if",
"(",
"language_header",
")",
"{",
"language_header",
".",
"split",
"(",
"','",
")",
".",
"forEach",
"(",
"function",
"(",
"l",
")",
"{",
"header",
"=",
"l",
".",
"split",
"(",
"';'",
",",
"1",
")",
"[",
"0",
"]",
";",
"lr",
"=",
"header",
".",
"split",
"(",
"'-'",
",",
"2",
")",
";",
"if",
"(",
"lr",
"[",
"0",
"]",
")",
"{",
"languages",
".",
"push",
"(",
"lr",
"[",
"0",
"]",
".",
"toLowerCase",
"(",
")",
")",
";",
"}",
"if",
"(",
"lr",
"[",
"1",
"]",
")",
"{",
"regions",
".",
"push",
"(",
"lr",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"languages",
".",
"length",
">",
"0",
")",
"{",
"request",
".",
"languages",
"=",
"languages",
";",
"request",
".",
"language",
"=",
"languages",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"regions",
".",
"length",
">",
"0",
")",
"{",
"request",
".",
"regions",
"=",
"regions",
";",
"request",
".",
"region",
"=",
"regions",
"[",
"0",
"]",
";",
"}",
"}",
"i18n",
".",
"setLocale",
"(",
"request",
".",
"language",
")",
";",
"}",
"}"
] | guess language setting based on http headers | [
"guess",
"language",
"setting",
"based",
"on",
"http",
"headers"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/core/i18n.js#L216-L257 | train |
happyplan/happyplan | grunt_tasks/config/connect.js | function(connect, options) {
return [
require('connect-livereload')(),
// Default middlewares
// Serve static files.
connect.static(options.base),
// Make empty directories browsable.
connect.directory(options.base)
];
} | javascript | function(connect, options) {
return [
require('connect-livereload')(),
// Default middlewares
// Serve static files.
connect.static(options.base),
// Make empty directories browsable.
connect.directory(options.base)
];
} | [
"function",
"(",
"connect",
",",
"options",
")",
"{",
"return",
"[",
"require",
"(",
"'connect-livereload'",
")",
"(",
")",
",",
"connect",
".",
"static",
"(",
"options",
".",
"base",
")",
",",
"connect",
".",
"directory",
"(",
"options",
".",
"base",
")",
"]",
";",
"}"
] | Must be empty to be accessible everywhere and not only "localhost" | [
"Must",
"be",
"empty",
"to",
"be",
"accessible",
"everywhere",
"and",
"not",
"only",
"localhost"
] | 38d0bce566a1864881b5867227348ff187e46999 | https://github.com/happyplan/happyplan/blob/38d0bce566a1864881b5867227348ff187e46999/grunt_tasks/config/connect.js#L10-L19 | train |
|
Lemurro/client-framework7-core-frontend | dist/lemurro.js | fireCallback | function fireCallback(callbackName) {
var data = [], len = arguments.length - 1;
while ( len-- > 0 ) data[ len ] = arguments[ len + 1 ];
/*
Callbacks:
beforeCreate (options),
beforeOpen (xhr, options),
beforeSend (xhr, options),
error (xhr, status),
complete (xhr, stautus),
success (response, status, xhr),
statusCode ()
*/
var globalCallbackValue;
var optionCallbackValue;
if (globals[callbackName]) {
globalCallbackValue = globals[callbackName].apply(globals, data);
}
if (options[callbackName]) {
optionCallbackValue = options[callbackName].apply(options, data);
}
if (typeof globalCallbackValue !== 'boolean') { globalCallbackValue = true; }
if (typeof optionCallbackValue !== 'boolean') { optionCallbackValue = true; }
return (globalCallbackValue && optionCallbackValue);
} | javascript | function fireCallback(callbackName) {
var data = [], len = arguments.length - 1;
while ( len-- > 0 ) data[ len ] = arguments[ len + 1 ];
/*
Callbacks:
beforeCreate (options),
beforeOpen (xhr, options),
beforeSend (xhr, options),
error (xhr, status),
complete (xhr, stautus),
success (response, status, xhr),
statusCode ()
*/
var globalCallbackValue;
var optionCallbackValue;
if (globals[callbackName]) {
globalCallbackValue = globals[callbackName].apply(globals, data);
}
if (options[callbackName]) {
optionCallbackValue = options[callbackName].apply(options, data);
}
if (typeof globalCallbackValue !== 'boolean') { globalCallbackValue = true; }
if (typeof optionCallbackValue !== 'boolean') { optionCallbackValue = true; }
return (globalCallbackValue && optionCallbackValue);
} | [
"function",
"fireCallback",
"(",
"callbackName",
")",
"{",
"var",
"data",
"=",
"[",
"]",
",",
"len",
"=",
"arguments",
".",
"length",
"-",
"1",
";",
"while",
"(",
"len",
"--",
">",
"0",
")",
"data",
"[",
"len",
"]",
"=",
"arguments",
"[",
"len",
"+",
"1",
"]",
";",
"var",
"globalCallbackValue",
";",
"var",
"optionCallbackValue",
";",
"if",
"(",
"globals",
"[",
"callbackName",
"]",
")",
"{",
"globalCallbackValue",
"=",
"globals",
"[",
"callbackName",
"]",
".",
"apply",
"(",
"globals",
",",
"data",
")",
";",
"}",
"if",
"(",
"options",
"[",
"callbackName",
"]",
")",
"{",
"optionCallbackValue",
"=",
"options",
"[",
"callbackName",
"]",
".",
"apply",
"(",
"options",
",",
"data",
")",
";",
"}",
"if",
"(",
"typeof",
"globalCallbackValue",
"!==",
"'boolean'",
")",
"{",
"globalCallbackValue",
"=",
"true",
";",
"}",
"if",
"(",
"typeof",
"optionCallbackValue",
"!==",
"'boolean'",
")",
"{",
"optionCallbackValue",
"=",
"true",
";",
"}",
"return",
"(",
"globalCallbackValue",
"&&",
"optionCallbackValue",
")",
";",
"}"
] | Function to run XHR callbacks and events | [
"Function",
"to",
"run",
"XHR",
"callbacks",
"and",
"events"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L3887-L3912 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | onTabLoaded | function onTabLoaded(contentEl) {
// Remove theme elements
router.removeThemeElements($newTabEl);
var tabEventTarget = $newTabEl;
if (typeof contentEl !== 'string') { tabEventTarget = $(contentEl); }
tabEventTarget.trigger('tab:init tab:mounted', tabRoute);
router.emit('tabInit tabMounted', $newTabEl[0], tabRoute);
if ($oldTabEl && $oldTabEl.length) {
if (animated) {
onTabsChanged(function () {
router.emit('routeChanged', router.currentRoute, router.previousRoute, router);
if (router.params.unloadTabContent) {
router.tabRemove($oldTabEl, $newTabEl, tabRoute);
}
});
} else {
router.emit('routeChanged', router.currentRoute, router.previousRoute, router);
if (router.params.unloadTabContent) {
router.tabRemove($oldTabEl, $newTabEl, tabRoute);
}
}
}
} | javascript | function onTabLoaded(contentEl) {
// Remove theme elements
router.removeThemeElements($newTabEl);
var tabEventTarget = $newTabEl;
if (typeof contentEl !== 'string') { tabEventTarget = $(contentEl); }
tabEventTarget.trigger('tab:init tab:mounted', tabRoute);
router.emit('tabInit tabMounted', $newTabEl[0], tabRoute);
if ($oldTabEl && $oldTabEl.length) {
if (animated) {
onTabsChanged(function () {
router.emit('routeChanged', router.currentRoute, router.previousRoute, router);
if (router.params.unloadTabContent) {
router.tabRemove($oldTabEl, $newTabEl, tabRoute);
}
});
} else {
router.emit('routeChanged', router.currentRoute, router.previousRoute, router);
if (router.params.unloadTabContent) {
router.tabRemove($oldTabEl, $newTabEl, tabRoute);
}
}
}
} | [
"function",
"onTabLoaded",
"(",
"contentEl",
")",
"{",
"router",
".",
"removeThemeElements",
"(",
"$newTabEl",
")",
";",
"var",
"tabEventTarget",
"=",
"$newTabEl",
";",
"if",
"(",
"typeof",
"contentEl",
"!==",
"'string'",
")",
"{",
"tabEventTarget",
"=",
"$",
"(",
"contentEl",
")",
";",
"}",
"tabEventTarget",
".",
"trigger",
"(",
"'tab:init tab:mounted'",
",",
"tabRoute",
")",
";",
"router",
".",
"emit",
"(",
"'tabInit tabMounted'",
",",
"$newTabEl",
"[",
"0",
"]",
",",
"tabRoute",
")",
";",
"if",
"(",
"$oldTabEl",
"&&",
"$oldTabEl",
".",
"length",
")",
"{",
"if",
"(",
"animated",
")",
"{",
"onTabsChanged",
"(",
"function",
"(",
")",
"{",
"router",
".",
"emit",
"(",
"'routeChanged'",
",",
"router",
".",
"currentRoute",
",",
"router",
".",
"previousRoute",
",",
"router",
")",
";",
"if",
"(",
"router",
".",
"params",
".",
"unloadTabContent",
")",
"{",
"router",
".",
"tabRemove",
"(",
"$oldTabEl",
",",
"$newTabEl",
",",
"tabRoute",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"router",
".",
"emit",
"(",
"'routeChanged'",
",",
"router",
".",
"currentRoute",
",",
"router",
".",
"previousRoute",
",",
"router",
")",
";",
"if",
"(",
"router",
".",
"params",
".",
"unloadTabContent",
")",
"{",
"router",
".",
"tabRemove",
"(",
"$oldTabEl",
",",
"$newTabEl",
",",
"tabRoute",
")",
";",
"}",
"}",
"}",
"}"
] | Tab Content Loaded | [
"Tab",
"Content",
"Loaded"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L7147-L7172 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | loadTab | function loadTab(loadTabParams, loadTabOptions) {
// Load Tab Props
var url = loadTabParams.url;
var content = loadTabParams.content;
var el = loadTabParams.el;
var template = loadTabParams.template;
var templateUrl = loadTabParams.templateUrl;
var component = loadTabParams.component;
var componentUrl = loadTabParams.componentUrl;
// Component/Template Callbacks
function resolve(contentEl) {
router.allowPageChange = true;
if (!contentEl) { return; }
if (typeof contentEl === 'string') {
$newTabEl.html(contentEl);
} else {
$newTabEl.html('');
if (contentEl.f7Component) {
contentEl.f7Component.$mount(function (componentEl) {
$newTabEl.append(componentEl);
});
} else {
$newTabEl.append(contentEl);
}
}
$newTabEl[0].f7RouterTabLoaded = true;
onTabLoaded(contentEl);
}
function reject() {
router.allowPageChange = true;
return router;
}
if (content) {
resolve(content);
} else if (template || templateUrl) {
try {
router.tabTemplateLoader(template, templateUrl, loadTabOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (el) {
resolve(el);
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.tabComponentLoader($newTabEl[0], component, componentUrl, loadTabOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, loadTabOptions)
.then(function (tabContent) {
resolve(tabContent);
})
.catch(function () {
router.allowPageChange = true;
});
}
} | javascript | function loadTab(loadTabParams, loadTabOptions) {
// Load Tab Props
var url = loadTabParams.url;
var content = loadTabParams.content;
var el = loadTabParams.el;
var template = loadTabParams.template;
var templateUrl = loadTabParams.templateUrl;
var component = loadTabParams.component;
var componentUrl = loadTabParams.componentUrl;
// Component/Template Callbacks
function resolve(contentEl) {
router.allowPageChange = true;
if (!contentEl) { return; }
if (typeof contentEl === 'string') {
$newTabEl.html(contentEl);
} else {
$newTabEl.html('');
if (contentEl.f7Component) {
contentEl.f7Component.$mount(function (componentEl) {
$newTabEl.append(componentEl);
});
} else {
$newTabEl.append(contentEl);
}
}
$newTabEl[0].f7RouterTabLoaded = true;
onTabLoaded(contentEl);
}
function reject() {
router.allowPageChange = true;
return router;
}
if (content) {
resolve(content);
} else if (template || templateUrl) {
try {
router.tabTemplateLoader(template, templateUrl, loadTabOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (el) {
resolve(el);
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.tabComponentLoader($newTabEl[0], component, componentUrl, loadTabOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, loadTabOptions)
.then(function (tabContent) {
resolve(tabContent);
})
.catch(function () {
router.allowPageChange = true;
});
}
} | [
"function",
"loadTab",
"(",
"loadTabParams",
",",
"loadTabOptions",
")",
"{",
"var",
"url",
"=",
"loadTabParams",
".",
"url",
";",
"var",
"content",
"=",
"loadTabParams",
".",
"content",
";",
"var",
"el",
"=",
"loadTabParams",
".",
"el",
";",
"var",
"template",
"=",
"loadTabParams",
".",
"template",
";",
"var",
"templateUrl",
"=",
"loadTabParams",
".",
"templateUrl",
";",
"var",
"component",
"=",
"loadTabParams",
".",
"component",
";",
"var",
"componentUrl",
"=",
"loadTabParams",
".",
"componentUrl",
";",
"function",
"resolve",
"(",
"contentEl",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"if",
"(",
"!",
"contentEl",
")",
"{",
"return",
";",
"}",
"if",
"(",
"typeof",
"contentEl",
"===",
"'string'",
")",
"{",
"$newTabEl",
".",
"html",
"(",
"contentEl",
")",
";",
"}",
"else",
"{",
"$newTabEl",
".",
"html",
"(",
"''",
")",
";",
"if",
"(",
"contentEl",
".",
"f7Component",
")",
"{",
"contentEl",
".",
"f7Component",
".",
"$mount",
"(",
"function",
"(",
"componentEl",
")",
"{",
"$newTabEl",
".",
"append",
"(",
"componentEl",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"$newTabEl",
".",
"append",
"(",
"contentEl",
")",
";",
"}",
"}",
"$newTabEl",
"[",
"0",
"]",
".",
"f7RouterTabLoaded",
"=",
"true",
";",
"onTabLoaded",
"(",
"contentEl",
")",
";",
"}",
"function",
"reject",
"(",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"return",
"router",
";",
"}",
"if",
"(",
"content",
")",
"{",
"resolve",
"(",
"content",
")",
";",
"}",
"else",
"if",
"(",
"template",
"||",
"templateUrl",
")",
"{",
"try",
"{",
"router",
".",
"tabTemplateLoader",
"(",
"template",
",",
"templateUrl",
",",
"loadTabOptions",
",",
"resolve",
",",
"reject",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"throw",
"err",
";",
"}",
"}",
"else",
"if",
"(",
"el",
")",
"{",
"resolve",
"(",
"el",
")",
";",
"}",
"else",
"if",
"(",
"component",
"||",
"componentUrl",
")",
"{",
"try",
"{",
"router",
".",
"tabComponentLoader",
"(",
"$newTabEl",
"[",
"0",
"]",
",",
"component",
",",
"componentUrl",
",",
"loadTabOptions",
",",
"resolve",
",",
"reject",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"throw",
"err",
";",
"}",
"}",
"else",
"if",
"(",
"url",
")",
"{",
"if",
"(",
"router",
".",
"xhr",
")",
"{",
"router",
".",
"xhr",
".",
"abort",
"(",
")",
";",
"router",
".",
"xhr",
"=",
"false",
";",
"}",
"router",
".",
"xhrRequest",
"(",
"url",
",",
"loadTabOptions",
")",
".",
"then",
"(",
"function",
"(",
"tabContent",
")",
"{",
"resolve",
"(",
"tabContent",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"}",
")",
";",
"}",
"}"
] | Load Tab Content | [
"Load",
"Tab",
"Content"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L7187-L7253 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | loadModal | function loadModal(loadModalParams, loadModalOptions) {
// Load Modal Props
var url = loadModalParams.url;
var content = loadModalParams.content;
var template = loadModalParams.template;
var templateUrl = loadModalParams.templateUrl;
var component = loadModalParams.component;
var componentUrl = loadModalParams.componentUrl;
// Component/Template Callbacks
function resolve(contentEl) {
if (contentEl) {
if (typeof contentEl === 'string') {
modalParams.content = contentEl;
} else if (contentEl.f7Component) {
contentEl.f7Component.$mount(function (componentEl) {
modalParams.el = componentEl;
app.root.append(componentEl);
});
} else {
modalParams.el = contentEl;
}
onModalLoaded();
}
}
function reject() {
router.allowPageChange = true;
return router;
}
if (content) {
resolve(content);
} else if (template || templateUrl) {
try {
router.modalTemplateLoader(template, templateUrl, loadModalOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.modalComponentLoader(app.root[0], component, componentUrl, loadModalOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, loadModalOptions)
.then(function (modalContent) {
modalParams.content = modalContent;
onModalLoaded();
})
.catch(function () {
router.allowPageChange = true;
});
} else {
onModalLoaded();
}
} | javascript | function loadModal(loadModalParams, loadModalOptions) {
// Load Modal Props
var url = loadModalParams.url;
var content = loadModalParams.content;
var template = loadModalParams.template;
var templateUrl = loadModalParams.templateUrl;
var component = loadModalParams.component;
var componentUrl = loadModalParams.componentUrl;
// Component/Template Callbacks
function resolve(contentEl) {
if (contentEl) {
if (typeof contentEl === 'string') {
modalParams.content = contentEl;
} else if (contentEl.f7Component) {
contentEl.f7Component.$mount(function (componentEl) {
modalParams.el = componentEl;
app.root.append(componentEl);
});
} else {
modalParams.el = contentEl;
}
onModalLoaded();
}
}
function reject() {
router.allowPageChange = true;
return router;
}
if (content) {
resolve(content);
} else if (template || templateUrl) {
try {
router.modalTemplateLoader(template, templateUrl, loadModalOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.modalComponentLoader(app.root[0], component, componentUrl, loadModalOptions, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, loadModalOptions)
.then(function (modalContent) {
modalParams.content = modalContent;
onModalLoaded();
})
.catch(function () {
router.allowPageChange = true;
});
} else {
onModalLoaded();
}
} | [
"function",
"loadModal",
"(",
"loadModalParams",
",",
"loadModalOptions",
")",
"{",
"var",
"url",
"=",
"loadModalParams",
".",
"url",
";",
"var",
"content",
"=",
"loadModalParams",
".",
"content",
";",
"var",
"template",
"=",
"loadModalParams",
".",
"template",
";",
"var",
"templateUrl",
"=",
"loadModalParams",
".",
"templateUrl",
";",
"var",
"component",
"=",
"loadModalParams",
".",
"component",
";",
"var",
"componentUrl",
"=",
"loadModalParams",
".",
"componentUrl",
";",
"function",
"resolve",
"(",
"contentEl",
")",
"{",
"if",
"(",
"contentEl",
")",
"{",
"if",
"(",
"typeof",
"contentEl",
"===",
"'string'",
")",
"{",
"modalParams",
".",
"content",
"=",
"contentEl",
";",
"}",
"else",
"if",
"(",
"contentEl",
".",
"f7Component",
")",
"{",
"contentEl",
".",
"f7Component",
".",
"$mount",
"(",
"function",
"(",
"componentEl",
")",
"{",
"modalParams",
".",
"el",
"=",
"componentEl",
";",
"app",
".",
"root",
".",
"append",
"(",
"componentEl",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"modalParams",
".",
"el",
"=",
"contentEl",
";",
"}",
"onModalLoaded",
"(",
")",
";",
"}",
"}",
"function",
"reject",
"(",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"return",
"router",
";",
"}",
"if",
"(",
"content",
")",
"{",
"resolve",
"(",
"content",
")",
";",
"}",
"else",
"if",
"(",
"template",
"||",
"templateUrl",
")",
"{",
"try",
"{",
"router",
".",
"modalTemplateLoader",
"(",
"template",
",",
"templateUrl",
",",
"loadModalOptions",
",",
"resolve",
",",
"reject",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"throw",
"err",
";",
"}",
"}",
"else",
"if",
"(",
"component",
"||",
"componentUrl",
")",
"{",
"try",
"{",
"router",
".",
"modalComponentLoader",
"(",
"app",
".",
"root",
"[",
"0",
"]",
",",
"component",
",",
"componentUrl",
",",
"loadModalOptions",
",",
"resolve",
",",
"reject",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"throw",
"err",
";",
"}",
"}",
"else",
"if",
"(",
"url",
")",
"{",
"if",
"(",
"router",
".",
"xhr",
")",
"{",
"router",
".",
"xhr",
".",
"abort",
"(",
")",
";",
"router",
".",
"xhr",
"=",
"false",
";",
"}",
"router",
".",
"xhrRequest",
"(",
"url",
",",
"loadModalOptions",
")",
".",
"then",
"(",
"function",
"(",
"modalContent",
")",
"{",
"modalParams",
".",
"content",
"=",
"modalContent",
";",
"onModalLoaded",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
")",
"{",
"router",
".",
"allowPageChange",
"=",
"true",
";",
"}",
")",
";",
"}",
"else",
"{",
"onModalLoaded",
"(",
")",
";",
"}",
"}"
] | Load Modal Content | [
"Load",
"Modal",
"Content"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L7405-L7469 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | isEmpty | function isEmpty(value) {
if (value === null) {
return true;
}
var type = typeof(value);
switch (type) {
case 'undefined':
return true;
case 'number':
return isNaN(value);
case 'string':
return value.trim() === '';
case 'object':
var countKeys = Object.keys(value).length;
return countKeys < 1;
case 'function':
case 'boolean':
return false;
default:
console.log('Unknown value type: "' + type + '"', 'isEmpty.js');
return false;
}
} | javascript | function isEmpty(value) {
if (value === null) {
return true;
}
var type = typeof(value);
switch (type) {
case 'undefined':
return true;
case 'number':
return isNaN(value);
case 'string':
return value.trim() === '';
case 'object':
var countKeys = Object.keys(value).length;
return countKeys < 1;
case 'function':
case 'boolean':
return false;
default:
console.log('Unknown value type: "' + type + '"', 'isEmpty.js');
return false;
}
} | [
"function",
"isEmpty",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"return",
"true",
";",
"}",
"var",
"type",
"=",
"typeof",
"(",
"value",
")",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'undefined'",
":",
"return",
"true",
";",
"case",
"'number'",
":",
"return",
"isNaN",
"(",
"value",
")",
";",
"case",
"'string'",
":",
"return",
"value",
".",
"trim",
"(",
")",
"===",
"''",
";",
"case",
"'object'",
":",
"var",
"countKeys",
"=",
"Object",
".",
"keys",
"(",
"value",
")",
".",
"length",
";",
"return",
"countKeys",
"<",
"1",
";",
"case",
"'function'",
":",
"case",
"'boolean'",
":",
"return",
"false",
";",
"default",
":",
"console",
".",
"log",
"(",
"'Unknown value type: \"'",
"+",
"type",
"+",
"'\"'",
",",
"'isEmpty.js'",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Javascript empty value checker
@param {null|undefined|number|string|object|array|function|boolean} value
@version 07.02.2019
@author DimNS <[email protected]> | [
"Javascript",
"empty",
"value",
"checker"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L36474-L36503 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | _encodeBlob | function _encodeBlob(blob) {
return new Promise$1(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
} | javascript | function _encodeBlob(blob) {
return new Promise$1(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
} | [
"function",
"_encodeBlob",
"(",
"blob",
")",
"{",
"return",
"new",
"Promise$1",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"reader",
".",
"onerror",
"=",
"reject",
";",
"reader",
".",
"onloadend",
"=",
"function",
"(",
"e",
")",
"{",
"var",
"base64",
"=",
"btoa",
"(",
"e",
".",
"target",
".",
"result",
"||",
"''",
")",
";",
"resolve",
"(",
"{",
"__local_forage_encoded_blob",
":",
"true",
",",
"data",
":",
"base64",
",",
"type",
":",
"blob",
".",
"type",
"}",
")",
";",
"}",
";",
"reader",
".",
"readAsBinaryString",
"(",
"blob",
")",
";",
"}",
")",
";",
"}"
] | encode a blob for indexeddb engines that don't support blobs | [
"encode",
"a",
"blob",
"for",
"indexeddb",
"engines",
"that",
"don",
"t",
"support",
"blobs"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L40250-L40264 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | checkIfLocalStorageThrows | function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
} | javascript | function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
localStorage.removeItem(localStorageTestKey);
return false;
} catch (e) {
return true;
}
} | [
"function",
"checkIfLocalStorageThrows",
"(",
")",
"{",
"var",
"localStorageTestKey",
"=",
"'_localforage_support_test'",
";",
"try",
"{",
"localStorage",
".",
"setItem",
"(",
"localStorageTestKey",
",",
"true",
")",
";",
"localStorage",
".",
"removeItem",
"(",
"localStorageTestKey",
")",
";",
"return",
"false",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"true",
";",
"}",
"}"
] | Check if localStorage throws when saving an item | [
"Check",
"if",
"localStorage",
"throws",
"when",
"saving",
"an",
"item"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L41661-L41672 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | uniqueArray | function uniqueArray(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
} | javascript | function uniqueArray(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
} | [
"function",
"uniqueArray",
"(",
"arr",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"result",
".",
"indexOf",
"(",
"arr",
"[",
"i",
"]",
")",
"===",
"-",
"1",
")",
"{",
"result",
".",
"push",
"(",
"arr",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Filter the unique values into a new array
@param arr | [
"Filter",
"the",
"unique",
"values",
"into",
"a",
"new",
"array"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L42526-L42536 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | warnOnce | function warnOnce(message) {
if (!(previousWarnOnceMessages.indexOf(message) !== -1)) {
previousWarnOnceMessages.push(message);
warn(message);
}
} | javascript | function warnOnce(message) {
if (!(previousWarnOnceMessages.indexOf(message) !== -1)) {
previousWarnOnceMessages.push(message);
warn(message);
}
} | [
"function",
"warnOnce",
"(",
"message",
")",
"{",
"if",
"(",
"!",
"(",
"previousWarnOnceMessages",
".",
"indexOf",
"(",
"message",
")",
"!==",
"-",
"1",
")",
")",
"{",
"previousWarnOnceMessages",
".",
"push",
"(",
"message",
")",
";",
"warn",
"(",
"message",
")",
";",
"}",
"}"
] | Show a console warning, but only if it hasn't already been shown
@param message | [
"Show",
"a",
"console",
"warning",
"but",
"only",
"if",
"it",
"hasn",
"t",
"already",
"been",
"shown"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L42593-L42598 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | adaptInputValidator | function adaptInputValidator(legacyValidator) {
return function adaptedInputValidator(inputValue, extraParams) {
return legacyValidator.call(this, inputValue, extraParams).then(function () {
return undefined;
}, function (validationMessage) {
return validationMessage;
});
};
} | javascript | function adaptInputValidator(legacyValidator) {
return function adaptedInputValidator(inputValue, extraParams) {
return legacyValidator.call(this, inputValue, extraParams).then(function () {
return undefined;
}, function (validationMessage) {
return validationMessage;
});
};
} | [
"function",
"adaptInputValidator",
"(",
"legacyValidator",
")",
"{",
"return",
"function",
"adaptedInputValidator",
"(",
"inputValue",
",",
"extraParams",
")",
"{",
"return",
"legacyValidator",
".",
"call",
"(",
"this",
",",
"inputValue",
",",
"extraParams",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"undefined",
";",
"}",
",",
"function",
"(",
"validationMessage",
")",
"{",
"return",
"validationMessage",
";",
"}",
")",
";",
"}",
";",
"}"
] | Adapt a legacy inputValidator for use with expectRejections=false | [
"Adapt",
"a",
"legacy",
"inputValidator",
"for",
"use",
"with",
"expectRejections",
"=",
"false"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L42651-L42659 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | showWarningsForParams | function showWarningsForParams(params) {
for (var param in params) {
if (!isValidParameter(param)) {
warn("Unknown parameter \"".concat(param, "\""));
}
if (params.toast && toastIncompatibleParams.indexOf(param) !== -1) {
warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
}
if (isDeprecatedParameter(param)) {
warnOnce("The parameter \"".concat(param, "\" is deprecated and will be removed in the next major release."));
}
}
} | javascript | function showWarningsForParams(params) {
for (var param in params) {
if (!isValidParameter(param)) {
warn("Unknown parameter \"".concat(param, "\""));
}
if (params.toast && toastIncompatibleParams.indexOf(param) !== -1) {
warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
}
if (isDeprecatedParameter(param)) {
warnOnce("The parameter \"".concat(param, "\" is deprecated and will be removed in the next major release."));
}
}
} | [
"function",
"showWarningsForParams",
"(",
"params",
")",
"{",
"for",
"(",
"var",
"param",
"in",
"params",
")",
"{",
"if",
"(",
"!",
"isValidParameter",
"(",
"param",
")",
")",
"{",
"warn",
"(",
"\"Unknown parameter \\\"\"",
".",
"\\\"",
"concat",
")",
";",
"}",
"(",
"param",
",",
"\"\\\"\"",
")",
"\\\"",
"}",
"}"
] | Show relevant warnings for given params
@param params | [
"Show",
"relevant",
"warnings",
"for",
"given",
"params"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L43502-L43516 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | mixin | function mixin(mixinParams) {
return withNoNewKeyword(
/*#__PURE__*/
function (_this) {
_inherits(MixinSwal, _this);
function MixinSwal() {
_classCallCheck(this, MixinSwal);
return _possibleConstructorReturn(this, _getPrototypeOf(MixinSwal).apply(this, arguments));
}
_createClass(MixinSwal, [{
key: "_main",
value: function _main(params) {
return _get(_getPrototypeOf(MixinSwal.prototype), "_main", this).call(this, _extends({}, mixinParams, params));
}
}]);
return MixinSwal;
}(this));
} | javascript | function mixin(mixinParams) {
return withNoNewKeyword(
/*#__PURE__*/
function (_this) {
_inherits(MixinSwal, _this);
function MixinSwal() {
_classCallCheck(this, MixinSwal);
return _possibleConstructorReturn(this, _getPrototypeOf(MixinSwal).apply(this, arguments));
}
_createClass(MixinSwal, [{
key: "_main",
value: function _main(params) {
return _get(_getPrototypeOf(MixinSwal.prototype), "_main", this).call(this, _extends({}, mixinParams, params));
}
}]);
return MixinSwal;
}(this));
} | [
"function",
"mixin",
"(",
"mixinParams",
")",
"{",
"return",
"withNoNewKeyword",
"(",
"function",
"(",
"_this",
")",
"{",
"_inherits",
"(",
"MixinSwal",
",",
"_this",
")",
";",
"function",
"MixinSwal",
"(",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"MixinSwal",
")",
";",
"return",
"_possibleConstructorReturn",
"(",
"this",
",",
"_getPrototypeOf",
"(",
"MixinSwal",
")",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
")",
";",
"}",
"_createClass",
"(",
"MixinSwal",
",",
"[",
"{",
"key",
":",
"\"_main\"",
",",
"value",
":",
"function",
"_main",
"(",
"params",
")",
"{",
"return",
"_get",
"(",
"_getPrototypeOf",
"(",
"MixinSwal",
".",
"prototype",
")",
",",
"\"_main\"",
",",
"this",
")",
".",
"call",
"(",
"this",
",",
"_extends",
"(",
"{",
"}",
",",
"mixinParams",
",",
"params",
")",
")",
";",
"}",
"}",
"]",
")",
";",
"return",
"MixinSwal",
";",
"}",
"(",
"this",
")",
")",
";",
"}"
] | Returns an extended version of `Swal` containing `params` as defaults.
Useful for reusing Swal configuration.
For example:
Before:
const textPromptOptions = { input: 'text', showCancelButton: true }
const {value: firstName} = await Swal({ ...textPromptOptions, title: 'What is your first name?' })
const {value: lastName} = await Swal({ ...textPromptOptions, title: 'What is your last name?' })
After:
const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
const {value: firstName} = await TextPrompt('What is your first name?')
const {value: lastName} = await TextPrompt('What is your last name?')
@param mixinParams | [
"Returns",
"an",
"extended",
"version",
"of",
"Swal",
"containing",
"params",
"as",
"defaults",
".",
"Useful",
"for",
"reusing",
"Swal",
"configuration",
"."
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L43592-L43613 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | showLoading | function showLoading() {
var popup = getPopup();
if (!popup) {
Swal('');
}
popup = getPopup();
var actions = getActions();
var confirmButton = getConfirmButton();
var cancelButton = getCancelButton();
show(actions);
show(confirmButton);
addClass([popup, actions], swalClasses.loading);
confirmButton.disabled = true;
cancelButton.disabled = true;
popup.setAttribute('data-loading', true);
popup.setAttribute('aria-busy', true);
popup.focus();
} | javascript | function showLoading() {
var popup = getPopup();
if (!popup) {
Swal('');
}
popup = getPopup();
var actions = getActions();
var confirmButton = getConfirmButton();
var cancelButton = getCancelButton();
show(actions);
show(confirmButton);
addClass([popup, actions], swalClasses.loading);
confirmButton.disabled = true;
cancelButton.disabled = true;
popup.setAttribute('data-loading', true);
popup.setAttribute('aria-busy', true);
popup.focus();
} | [
"function",
"showLoading",
"(",
")",
"{",
"var",
"popup",
"=",
"getPopup",
"(",
")",
";",
"if",
"(",
"!",
"popup",
")",
"{",
"Swal",
"(",
"''",
")",
";",
"}",
"popup",
"=",
"getPopup",
"(",
")",
";",
"var",
"actions",
"=",
"getActions",
"(",
")",
";",
"var",
"confirmButton",
"=",
"getConfirmButton",
"(",
")",
";",
"var",
"cancelButton",
"=",
"getCancelButton",
"(",
")",
";",
"show",
"(",
"actions",
")",
";",
"show",
"(",
"confirmButton",
")",
";",
"addClass",
"(",
"[",
"popup",
",",
"actions",
"]",
",",
"swalClasses",
".",
"loading",
")",
";",
"confirmButton",
".",
"disabled",
"=",
"true",
";",
"cancelButton",
".",
"disabled",
"=",
"true",
";",
"popup",
".",
"setAttribute",
"(",
"'data-loading'",
",",
"true",
")",
";",
"popup",
".",
"setAttribute",
"(",
"'aria-busy'",
",",
"true",
")",
";",
"popup",
".",
"focus",
"(",
")",
";",
"}"
] | Show spinner instead of Confirm button and disable Cancel button | [
"Show",
"spinner",
"instead",
"of",
"Confirm",
"button",
"and",
"disable",
"Cancel",
"button"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L43687-L43706 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | hideLoading | function hideLoading() {
var innerParams = privateProps.innerParams.get(this);
var domCache = privateProps.domCache.get(this);
if (!innerParams.showConfirmButton) {
hide(domCache.confirmButton);
if (!innerParams.showCancelButton) {
hide(domCache.actions);
}
}
removeClass([domCache.popup, domCache.actions], swalClasses.loading);
domCache.popup.removeAttribute('aria-busy');
domCache.popup.removeAttribute('data-loading');
domCache.confirmButton.disabled = false;
domCache.cancelButton.disabled = false;
} | javascript | function hideLoading() {
var innerParams = privateProps.innerParams.get(this);
var domCache = privateProps.domCache.get(this);
if (!innerParams.showConfirmButton) {
hide(domCache.confirmButton);
if (!innerParams.showCancelButton) {
hide(domCache.actions);
}
}
removeClass([domCache.popup, domCache.actions], swalClasses.loading);
domCache.popup.removeAttribute('aria-busy');
domCache.popup.removeAttribute('data-loading');
domCache.confirmButton.disabled = false;
domCache.cancelButton.disabled = false;
} | [
"function",
"hideLoading",
"(",
")",
"{",
"var",
"innerParams",
"=",
"privateProps",
".",
"innerParams",
".",
"get",
"(",
"this",
")",
";",
"var",
"domCache",
"=",
"privateProps",
".",
"domCache",
".",
"get",
"(",
"this",
")",
";",
"if",
"(",
"!",
"innerParams",
".",
"showConfirmButton",
")",
"{",
"hide",
"(",
"domCache",
".",
"confirmButton",
")",
";",
"if",
"(",
"!",
"innerParams",
".",
"showCancelButton",
")",
"{",
"hide",
"(",
"domCache",
".",
"actions",
")",
";",
"}",
"}",
"removeClass",
"(",
"[",
"domCache",
".",
"popup",
",",
"domCache",
".",
"actions",
"]",
",",
"swalClasses",
".",
"loading",
")",
";",
"domCache",
".",
"popup",
".",
"removeAttribute",
"(",
"'aria-busy'",
")",
";",
"domCache",
".",
"popup",
".",
"removeAttribute",
"(",
"'data-loading'",
")",
";",
"domCache",
".",
"confirmButton",
".",
"disabled",
"=",
"false",
";",
"domCache",
".",
"cancelButton",
".",
"disabled",
"=",
"false",
";",
"}"
] | Enables buttons and hide loader. | [
"Enables",
"buttons",
"and",
"hide",
"loader",
"."
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L43822-L43839 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | resetValidationMessage | function resetValidationMessage() {
var domCache = privateProps.domCache.get(this);
if (domCache.validationMessage) {
hide(domCache.validationMessage);
}
var input = this.getInput();
if (input) {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedBy');
removeClass(input, swalClasses.inputerror);
}
} | javascript | function resetValidationMessage() {
var domCache = privateProps.domCache.get(this);
if (domCache.validationMessage) {
hide(domCache.validationMessage);
}
var input = this.getInput();
if (input) {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedBy');
removeClass(input, swalClasses.inputerror);
}
} | [
"function",
"resetValidationMessage",
"(",
")",
"{",
"var",
"domCache",
"=",
"privateProps",
".",
"domCache",
".",
"get",
"(",
"this",
")",
";",
"if",
"(",
"domCache",
".",
"validationMessage",
")",
"{",
"hide",
"(",
"domCache",
".",
"validationMessage",
")",
";",
"}",
"var",
"input",
"=",
"this",
".",
"getInput",
"(",
")",
";",
"if",
"(",
"input",
")",
"{",
"input",
".",
"removeAttribute",
"(",
"'aria-invalid'",
")",
";",
"input",
".",
"removeAttribute",
"(",
"'aria-describedBy'",
")",
";",
"removeClass",
"(",
"input",
",",
"swalClasses",
".",
"inputerror",
")",
";",
"}",
"}"
] | Hide block with validation message | [
"Hide",
"block",
"with",
"validation",
"message"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L43942-L43956 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | openPopup | function openPopup(params) {
var container = getContainer();
var popup = getPopup();
if (params.onBeforeOpen !== null && typeof params.onBeforeOpen === 'function') {
params.onBeforeOpen(popup);
}
if (params.animation) {
addClass(popup, swalClasses.show);
addClass(container, swalClasses.fade);
removeClass(popup, swalClasses.hide);
} else {
removeClass(popup, swalClasses.fade);
}
show(popup); // scrolling is 'hidden' until animation is done, after that 'auto'
container.style.overflowY = 'hidden';
if (animationEndEvent && !hasClass(popup, swalClasses.noanimation)) {
popup.addEventListener(animationEndEvent, function swalCloseEventFinished() {
popup.removeEventListener(animationEndEvent, swalCloseEventFinished);
container.style.overflowY = 'auto';
});
} else {
container.style.overflowY = 'auto';
}
addClass([document.documentElement, document.body, container], swalClasses.shown);
if (params.heightAuto && params.backdrop && !params.toast) {
addClass([document.documentElement, document.body], swalClasses['height-auto']);
}
if (isModal()) {
fixScrollbar();
iOSfix();
IEfix();
setAriaHidden(); // sweetalert2/issues/1247
setTimeout(function () {
container.scrollTop = 0;
});
}
if (!isToast() && !globalState.previousActiveElement) {
globalState.previousActiveElement = document.activeElement;
}
if (params.onOpen !== null && typeof params.onOpen === 'function') {
setTimeout(function () {
params.onOpen(popup);
});
}
} | javascript | function openPopup(params) {
var container = getContainer();
var popup = getPopup();
if (params.onBeforeOpen !== null && typeof params.onBeforeOpen === 'function') {
params.onBeforeOpen(popup);
}
if (params.animation) {
addClass(popup, swalClasses.show);
addClass(container, swalClasses.fade);
removeClass(popup, swalClasses.hide);
} else {
removeClass(popup, swalClasses.fade);
}
show(popup); // scrolling is 'hidden' until animation is done, after that 'auto'
container.style.overflowY = 'hidden';
if (animationEndEvent && !hasClass(popup, swalClasses.noanimation)) {
popup.addEventListener(animationEndEvent, function swalCloseEventFinished() {
popup.removeEventListener(animationEndEvent, swalCloseEventFinished);
container.style.overflowY = 'auto';
});
} else {
container.style.overflowY = 'auto';
}
addClass([document.documentElement, document.body, container], swalClasses.shown);
if (params.heightAuto && params.backdrop && !params.toast) {
addClass([document.documentElement, document.body], swalClasses['height-auto']);
}
if (isModal()) {
fixScrollbar();
iOSfix();
IEfix();
setAriaHidden(); // sweetalert2/issues/1247
setTimeout(function () {
container.scrollTop = 0;
});
}
if (!isToast() && !globalState.previousActiveElement) {
globalState.previousActiveElement = document.activeElement;
}
if (params.onOpen !== null && typeof params.onOpen === 'function') {
setTimeout(function () {
params.onOpen(popup);
});
}
} | [
"function",
"openPopup",
"(",
"params",
")",
"{",
"var",
"container",
"=",
"getContainer",
"(",
")",
";",
"var",
"popup",
"=",
"getPopup",
"(",
")",
";",
"if",
"(",
"params",
".",
"onBeforeOpen",
"!==",
"null",
"&&",
"typeof",
"params",
".",
"onBeforeOpen",
"===",
"'function'",
")",
"{",
"params",
".",
"onBeforeOpen",
"(",
"popup",
")",
";",
"}",
"if",
"(",
"params",
".",
"animation",
")",
"{",
"addClass",
"(",
"popup",
",",
"swalClasses",
".",
"show",
")",
";",
"addClass",
"(",
"container",
",",
"swalClasses",
".",
"fade",
")",
";",
"removeClass",
"(",
"popup",
",",
"swalClasses",
".",
"hide",
")",
";",
"}",
"else",
"{",
"removeClass",
"(",
"popup",
",",
"swalClasses",
".",
"fade",
")",
";",
"}",
"show",
"(",
"popup",
")",
";",
"container",
".",
"style",
".",
"overflowY",
"=",
"'hidden'",
";",
"if",
"(",
"animationEndEvent",
"&&",
"!",
"hasClass",
"(",
"popup",
",",
"swalClasses",
".",
"noanimation",
")",
")",
"{",
"popup",
".",
"addEventListener",
"(",
"animationEndEvent",
",",
"function",
"swalCloseEventFinished",
"(",
")",
"{",
"popup",
".",
"removeEventListener",
"(",
"animationEndEvent",
",",
"swalCloseEventFinished",
")",
";",
"container",
".",
"style",
".",
"overflowY",
"=",
"'auto'",
";",
"}",
")",
";",
"}",
"else",
"{",
"container",
".",
"style",
".",
"overflowY",
"=",
"'auto'",
";",
"}",
"addClass",
"(",
"[",
"document",
".",
"documentElement",
",",
"document",
".",
"body",
",",
"container",
"]",
",",
"swalClasses",
".",
"shown",
")",
";",
"if",
"(",
"params",
".",
"heightAuto",
"&&",
"params",
".",
"backdrop",
"&&",
"!",
"params",
".",
"toast",
")",
"{",
"addClass",
"(",
"[",
"document",
".",
"documentElement",
",",
"document",
".",
"body",
"]",
",",
"swalClasses",
"[",
"'height-auto'",
"]",
")",
";",
"}",
"if",
"(",
"isModal",
"(",
")",
")",
"{",
"fixScrollbar",
"(",
")",
";",
"iOSfix",
"(",
")",
";",
"IEfix",
"(",
")",
";",
"setAriaHidden",
"(",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"container",
".",
"scrollTop",
"=",
"0",
";",
"}",
")",
";",
"}",
"if",
"(",
"!",
"isToast",
"(",
")",
"&&",
"!",
"globalState",
".",
"previousActiveElement",
")",
"{",
"globalState",
".",
"previousActiveElement",
"=",
"document",
".",
"activeElement",
";",
"}",
"if",
"(",
"params",
".",
"onOpen",
"!==",
"null",
"&&",
"typeof",
"params",
".",
"onOpen",
"===",
"'function'",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"params",
".",
"onOpen",
"(",
"popup",
")",
";",
"}",
")",
";",
"}",
"}"
] | Open popup, add necessary classes and styles, fix scrollbar
@param {Array} params | [
"Open",
"popup",
"add",
"necessary",
"classes",
"and",
"styles",
"fix",
"scrollbar"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L44191-L44246 | train |
Lemurro/client-framework7-core-frontend | dist/lemurro.js | getInputValue | function getInputValue() {
var input = _this.getInput();
if (!input) {
return null;
}
switch (innerParams.input) {
case 'checkbox':
return input.checked ? 1 : 0;
case 'radio':
return input.checked ? input.value : null;
case 'file':
return input.files.length ? input.files[0] : null;
default:
return innerParams.inputAutoTrim ? input.value.trim() : input.value;
}
} | javascript | function getInputValue() {
var input = _this.getInput();
if (!input) {
return null;
}
switch (innerParams.input) {
case 'checkbox':
return input.checked ? 1 : 0;
case 'radio':
return input.checked ? input.value : null;
case 'file':
return input.files.length ? input.files[0] : null;
default:
return innerParams.inputAutoTrim ? input.value.trim() : input.value;
}
} | [
"function",
"getInputValue",
"(",
")",
"{",
"var",
"input",
"=",
"_this",
".",
"getInput",
"(",
")",
";",
"if",
"(",
"!",
"input",
")",
"{",
"return",
"null",
";",
"}",
"switch",
"(",
"innerParams",
".",
"input",
")",
"{",
"case",
"'checkbox'",
":",
"return",
"input",
".",
"checked",
"?",
"1",
":",
"0",
";",
"case",
"'radio'",
":",
"return",
"input",
".",
"checked",
"?",
"input",
".",
"value",
":",
"null",
";",
"case",
"'file'",
":",
"return",
"input",
".",
"files",
".",
"length",
"?",
"input",
".",
"files",
"[",
"0",
"]",
":",
"null",
";",
"default",
":",
"return",
"innerParams",
".",
"inputAutoTrim",
"?",
"input",
".",
"value",
".",
"trim",
"(",
")",
":",
"input",
".",
"value",
";",
"}",
"}"
] | Get the value of the popup input | [
"Get",
"the",
"value",
"of",
"the",
"popup",
"input"
] | 119985cb1d00b92b4400504e1c46f54dc36bcd77 | https://github.com/Lemurro/client-framework7-core-frontend/blob/119985cb1d00b92b4400504e1c46f54dc36bcd77/dist/lemurro.js#L44319-L44339 | train |
bytbil/sauce-test-runner | src/Job.js | function (runner, url, browser) {
this.id = null;
this.taskId = null;
this.user = runner.user;
this.key = runner.key;
this.framework = runner.framework;
this.pollInterval = runner.pollInterval;
this.statusCheckAttempts = runner.statusCheckAttempts;
this.url = url;
this.platform = _.isArray(browser) ? browser : [browser.platform || '', browser.browserName || '', browser.version || ''];
this.build = runner.build;
this.public = browser.public || runner.public || "team";
this.tags = browser.tags || runner.tags;
this.testName = browser.name || runner.testName;
this.sauceConfig = runner.sauceConfig;
this.tunneled = runner.tunneled;
this.tunnelId = runner.tunnelId;
} | javascript | function (runner, url, browser) {
this.id = null;
this.taskId = null;
this.user = runner.user;
this.key = runner.key;
this.framework = runner.framework;
this.pollInterval = runner.pollInterval;
this.statusCheckAttempts = runner.statusCheckAttempts;
this.url = url;
this.platform = _.isArray(browser) ? browser : [browser.platform || '', browser.browserName || '', browser.version || ''];
this.build = runner.build;
this.public = browser.public || runner.public || "team";
this.tags = browser.tags || runner.tags;
this.testName = browser.name || runner.testName;
this.sauceConfig = runner.sauceConfig;
this.tunneled = runner.tunneled;
this.tunnelId = runner.tunnelId;
} | [
"function",
"(",
"runner",
",",
"url",
",",
"browser",
")",
"{",
"this",
".",
"id",
"=",
"null",
";",
"this",
".",
"taskId",
"=",
"null",
";",
"this",
".",
"user",
"=",
"runner",
".",
"user",
";",
"this",
".",
"key",
"=",
"runner",
".",
"key",
";",
"this",
".",
"framework",
"=",
"runner",
".",
"framework",
";",
"this",
".",
"pollInterval",
"=",
"runner",
".",
"pollInterval",
";",
"this",
".",
"statusCheckAttempts",
"=",
"runner",
".",
"statusCheckAttempts",
";",
"this",
".",
"url",
"=",
"url",
";",
"this",
".",
"platform",
"=",
"_",
".",
"isArray",
"(",
"browser",
")",
"?",
"browser",
":",
"[",
"browser",
".",
"platform",
"||",
"''",
",",
"browser",
".",
"browserName",
"||",
"''",
",",
"browser",
".",
"version",
"||",
"''",
"]",
";",
"this",
".",
"build",
"=",
"runner",
".",
"build",
";",
"this",
".",
"public",
"=",
"browser",
".",
"public",
"||",
"runner",
".",
"public",
"||",
"\"team\"",
";",
"this",
".",
"tags",
"=",
"browser",
".",
"tags",
"||",
"runner",
".",
"tags",
";",
"this",
".",
"testName",
"=",
"browser",
".",
"name",
"||",
"runner",
".",
"testName",
";",
"this",
".",
"sauceConfig",
"=",
"runner",
".",
"sauceConfig",
";",
"this",
".",
"tunneled",
"=",
"runner",
".",
"tunneled",
";",
"this",
".",
"tunnelId",
"=",
"runner",
".",
"tunnelId",
";",
"}"
] | Represents a Sauce Labs job.
@constructor
@param {Object} runner - TestRunner instance.
@param {String} url - The test runner page's URL.
@param {Object} browser - Object describing the platform to run the test on. | [
"Represents",
"a",
"Sauce",
"Labs",
"job",
"."
] | db0304a31a5fe7b4e6ab5f496cbca52a012d1b6e | https://github.com/bytbil/sauce-test-runner/blob/db0304a31a5fe7b4e6ab5f496cbca52a012d1b6e/src/Job.js#L38-L55 | train |
|
kevinoid/nodecat | lib/aggregate-error.js | AggregateError | function AggregateError(message) {
if (!(this instanceof AggregateError)) {
return new AggregateError(message);
}
Error.captureStackTrace(this, AggregateError);
// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
if (message !== undefined) {
Object.defineProperty(this, 'message', {
value: String(message),
configurable: true,
writable: true
});
}
} | javascript | function AggregateError(message) {
if (!(this instanceof AggregateError)) {
return new AggregateError(message);
}
Error.captureStackTrace(this, AggregateError);
// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
if (message !== undefined) {
Object.defineProperty(this, 'message', {
value: String(message),
configurable: true,
writable: true
});
}
} | [
"function",
"AggregateError",
"(",
"message",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"AggregateError",
")",
")",
"{",
"return",
"new",
"AggregateError",
"(",
"message",
")",
";",
"}",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"AggregateError",
")",
";",
"if",
"(",
"message",
"!==",
"undefined",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'message'",
",",
"{",
"value",
":",
"String",
"(",
"message",
")",
",",
"configurable",
":",
"true",
",",
"writable",
":",
"true",
"}",
")",
";",
"}",
"}"
] | Constructs an AggregateError.
Based on the AggregateError class from bluebird.
@class Represents a collection of errors.
@constructor
@extends Error
@extends Array
@param {string=} message Human-readable description of the error. | [
"Constructs",
"an",
"AggregateError",
"."
] | 333f9710bbe7ceac5ec3f6171b2e8446ab2f3973 | https://github.com/kevinoid/nodecat/blob/333f9710bbe7ceac5ec3f6171b2e8446ab2f3973/lib/aggregate-error.js#L21-L35 | train |
brainshave/sharpvg | split.js | split | function split (data, w, h) {
var colors = {};
var pos = 0;
for (var y = 0; y < h; ++y) {
for (var x = 0; x < w; ++x) {
pos = (y * w + x) * 4;
if (data[pos + 3] > 0) {
set(x, y, data[pos], data[pos + 1], data[pos + 2]);
}
}
}
return {
w: w,
h: h,
colors: colors
};
function set (x, y, r, g, b) {
var hex = "#" + [r, g, b].map(hexaze).join("");
if (!colors[hex]) {
colors[hex] = new Array(h);
for (var i = 0; i < h; ++i) {
colors[hex][i] = new Uint8Array(w);
}
}
colors[hex][y][x] = 1;
}
} | javascript | function split (data, w, h) {
var colors = {};
var pos = 0;
for (var y = 0; y < h; ++y) {
for (var x = 0; x < w; ++x) {
pos = (y * w + x) * 4;
if (data[pos + 3] > 0) {
set(x, y, data[pos], data[pos + 1], data[pos + 2]);
}
}
}
return {
w: w,
h: h,
colors: colors
};
function set (x, y, r, g, b) {
var hex = "#" + [r, g, b].map(hexaze).join("");
if (!colors[hex]) {
colors[hex] = new Array(h);
for (var i = 0; i < h; ++i) {
colors[hex][i] = new Uint8Array(w);
}
}
colors[hex][y][x] = 1;
}
} | [
"function",
"split",
"(",
"data",
",",
"w",
",",
"h",
")",
"{",
"var",
"colors",
"=",
"{",
"}",
";",
"var",
"pos",
"=",
"0",
";",
"for",
"(",
"var",
"y",
"=",
"0",
";",
"y",
"<",
"h",
";",
"++",
"y",
")",
"{",
"for",
"(",
"var",
"x",
"=",
"0",
";",
"x",
"<",
"w",
";",
"++",
"x",
")",
"{",
"pos",
"=",
"(",
"y",
"*",
"w",
"+",
"x",
")",
"*",
"4",
";",
"if",
"(",
"data",
"[",
"pos",
"+",
"3",
"]",
">",
"0",
")",
"{",
"set",
"(",
"x",
",",
"y",
",",
"data",
"[",
"pos",
"]",
",",
"data",
"[",
"pos",
"+",
"1",
"]",
",",
"data",
"[",
"pos",
"+",
"2",
"]",
")",
";",
"}",
"}",
"}",
"return",
"{",
"w",
":",
"w",
",",
"h",
":",
"h",
",",
"colors",
":",
"colors",
"}",
";",
"function",
"set",
"(",
"x",
",",
"y",
",",
"r",
",",
"g",
",",
"b",
")",
"{",
"var",
"hex",
"=",
"\"#\"",
"+",
"[",
"r",
",",
"g",
",",
"b",
"]",
".",
"map",
"(",
"hexaze",
")",
".",
"join",
"(",
"\"\"",
")",
";",
"if",
"(",
"!",
"colors",
"[",
"hex",
"]",
")",
"{",
"colors",
"[",
"hex",
"]",
"=",
"new",
"Array",
"(",
"h",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"h",
";",
"++",
"i",
")",
"{",
"colors",
"[",
"hex",
"]",
"[",
"i",
"]",
"=",
"new",
"Uint8Array",
"(",
"w",
")",
";",
"}",
"}",
"colors",
"[",
"hex",
"]",
"[",
"y",
"]",
"[",
"x",
"]",
"=",
"1",
";",
"}",
"}"
] | Split colors of RGBA data to separate 2d arrays. | [
"Split",
"colors",
"of",
"RGBA",
"data",
"to",
"separate",
"2d",
"arrays",
"."
] | c3bfe9d8566f149bc3ffd50a9ad2b26b01b3d08e | https://github.com/brainshave/sharpvg/blob/c3bfe9d8566f149bc3ffd50a9ad2b26b01b3d08e/split.js#L7-L40 | train |
sinnerschrader/boilerplate-server | source/library/utilities/execute.js | handleError | function handleError(error) {
console.log(`${options.entry} failed.`);
console.trace(error);
setTimeout(() => {
throw error;
});
} | javascript | function handleError(error) {
console.log(`${options.entry} failed.`);
console.trace(error);
setTimeout(() => {
throw error;
});
} | [
"function",
"handleError",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"options",
".",
"entry",
"}",
"`",
")",
";",
"console",
".",
"trace",
"(",
"error",
")",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"throw",
"error",
";",
"}",
")",
";",
"}"
] | Handles and escalates top level Promise errors causing the process to crash if uncatched
@param {object} error - Error object to print and escalete
@private | [
"Handles",
"and",
"escalates",
"top",
"level",
"Promise",
"errors",
"causing",
"the",
"process",
"to",
"crash",
"if",
"uncatched"
] | 5a16535af5d5a39d3d8301eeaaa5065f04307bd5 | https://github.com/sinnerschrader/boilerplate-server/blob/5a16535af5d5a39d3d8301eeaaa5065f04307bd5/source/library/utilities/execute.js#L32-L39 | train |
ajay2507/lasso-unpack | lib/utils.js | getArguments | function getArguments(node) {
if (node && node.arguments && node.arguments.length > 0) {
return node.arguments;
}
return [];
} | javascript | function getArguments(node) {
if (node && node.arguments && node.arguments.length > 0) {
return node.arguments;
}
return [];
} | [
"function",
"getArguments",
"(",
"node",
")",
"{",
"if",
"(",
"node",
"&&",
"node",
".",
"arguments",
"&&",
"node",
".",
"arguments",
".",
"length",
">",
"0",
")",
"{",
"return",
"node",
".",
"arguments",
";",
"}",
"return",
"[",
"]",
";",
"}"
] | get Arguments from the AST tree. | [
"get",
"Arguments",
"from",
"the",
"AST",
"tree",
"."
] | fb228b00a549eedfafec7e8eaf9999d69db82a0c | https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L10-L15 | train |
ajay2507/lasso-unpack | lib/utils.js | extractLiteralFromInstalled | function extractLiteralFromInstalled(stats, element) {
if (element.length === 0) return stats;
let value = "";
if (validLiteral(element[0])) {
value = element[0].value;
// let array = value.split('$');
// if (array.length == 0) {
// stats.setPackageName(value);
// } else {
// stats.setPackageName(array[0]);
// stats.setPackageVersion(array[1]);
// }
stats.setPackageName(value);
}
if (validLiteral(element[1])) {
value = element[1].value;
stats.setFileName(value);
}
if (validLiteral(element[2])) {
value = element[2].value;
stats.setVersion(value);
}
return stats;
} | javascript | function extractLiteralFromInstalled(stats, element) {
if (element.length === 0) return stats;
let value = "";
if (validLiteral(element[0])) {
value = element[0].value;
// let array = value.split('$');
// if (array.length == 0) {
// stats.setPackageName(value);
// } else {
// stats.setPackageName(array[0]);
// stats.setPackageVersion(array[1]);
// }
stats.setPackageName(value);
}
if (validLiteral(element[1])) {
value = element[1].value;
stats.setFileName(value);
}
if (validLiteral(element[2])) {
value = element[2].value;
stats.setVersion(value);
}
return stats;
} | [
"function",
"extractLiteralFromInstalled",
"(",
"stats",
",",
"element",
")",
"{",
"if",
"(",
"element",
".",
"length",
"===",
"0",
")",
"return",
"stats",
";",
"let",
"value",
"=",
"\"\"",
";",
"if",
"(",
"validLiteral",
"(",
"element",
"[",
"0",
"]",
")",
")",
"{",
"value",
"=",
"element",
"[",
"0",
"]",
".",
"value",
";",
"stats",
".",
"setPackageName",
"(",
"value",
")",
";",
"}",
"if",
"(",
"validLiteral",
"(",
"element",
"[",
"1",
"]",
")",
")",
"{",
"value",
"=",
"element",
"[",
"1",
"]",
".",
"value",
";",
"stats",
".",
"setFileName",
"(",
"value",
")",
";",
"}",
"if",
"(",
"validLiteral",
"(",
"element",
"[",
"2",
"]",
")",
")",
"{",
"value",
"=",
"element",
"[",
"2",
"]",
".",
"value",
";",
"stats",
".",
"setVersion",
"(",
"value",
")",
";",
"}",
"return",
"stats",
";",
"}"
] | Extract packageName, version and fileName from given literal if type = "installed". | [
"Extract",
"packageName",
"version",
"and",
"fileName",
"from",
"given",
"literal",
"if",
"type",
"=",
"installed",
"."
] | fb228b00a549eedfafec7e8eaf9999d69db82a0c | https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L18-L41 | train |
ajay2507/lasso-unpack | lib/utils.js | extractLiteralFromDef | function extractLiteralFromDef(stats, element) {
if (validLiteral(element)) {
stats.setPath(element.value);
let arrayLiteral = element.value.split('/');
let length = arrayLiteral.length;
if (length > 0) {
const index = validIndex(arrayLiteral);
stats.setPackageName(arrayLiteral[index].split("$")[0]);
stats.setVersion(arrayLiteral[index].split("$")[1] || '');
stats.setFileName(arrayLiteral.splice(index + 1, length).join('/'));
}
}
return stats;
} | javascript | function extractLiteralFromDef(stats, element) {
if (validLiteral(element)) {
stats.setPath(element.value);
let arrayLiteral = element.value.split('/');
let length = arrayLiteral.length;
if (length > 0) {
const index = validIndex(arrayLiteral);
stats.setPackageName(arrayLiteral[index].split("$")[0]);
stats.setVersion(arrayLiteral[index].split("$")[1] || '');
stats.setFileName(arrayLiteral.splice(index + 1, length).join('/'));
}
}
return stats;
} | [
"function",
"extractLiteralFromDef",
"(",
"stats",
",",
"element",
")",
"{",
"if",
"(",
"validLiteral",
"(",
"element",
")",
")",
"{",
"stats",
".",
"setPath",
"(",
"element",
".",
"value",
")",
";",
"let",
"arrayLiteral",
"=",
"element",
".",
"value",
".",
"split",
"(",
"'/'",
")",
";",
"let",
"length",
"=",
"arrayLiteral",
".",
"length",
";",
"if",
"(",
"length",
">",
"0",
")",
"{",
"const",
"index",
"=",
"validIndex",
"(",
"arrayLiteral",
")",
";",
"stats",
".",
"setPackageName",
"(",
"arrayLiteral",
"[",
"index",
"]",
".",
"split",
"(",
"\"$\"",
")",
"[",
"0",
"]",
")",
";",
"stats",
".",
"setVersion",
"(",
"arrayLiteral",
"[",
"index",
"]",
".",
"split",
"(",
"\"$\"",
")",
"[",
"1",
"]",
"||",
"''",
")",
";",
"stats",
".",
"setFileName",
"(",
"arrayLiteral",
".",
"splice",
"(",
"index",
"+",
"1",
",",
"length",
")",
".",
"join",
"(",
"'/'",
")",
")",
";",
"}",
"}",
"return",
"stats",
";",
"}"
] | Extract packageName, version and fileName from given literal if type = "def". | [
"Extract",
"packageName",
"version",
"and",
"fileName",
"from",
"given",
"literal",
"if",
"type",
"=",
"def",
"."
] | fb228b00a549eedfafec7e8eaf9999d69db82a0c | https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L63-L76 | train |
ajay2507/lasso-unpack | lib/utils.js | isFunctionExpression | function isFunctionExpression(node) {
if (node && node.callee && node.callee.type === 'FunctionExpression') {
return true;
}
return false;
} | javascript | function isFunctionExpression(node) {
if (node && node.callee && node.callee.type === 'FunctionExpression') {
return true;
}
return false;
} | [
"function",
"isFunctionExpression",
"(",
"node",
")",
"{",
"if",
"(",
"node",
"&&",
"node",
".",
"callee",
"&&",
"node",
".",
"callee",
".",
"type",
"===",
"'FunctionExpression'",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | check valid function expression or not. | [
"check",
"valid",
"function",
"expression",
"or",
"not",
"."
] | fb228b00a549eedfafec7e8eaf9999d69db82a0c | https://github.com/ajay2507/lasso-unpack/blob/fb228b00a549eedfafec7e8eaf9999d69db82a0c/lib/utils.js#L111-L116 | train |
mmacmillan/grunt-jsdox | tasks/jsdox.js | publish | function publish(target, data, done) {
if(data.enabled !== true)
return grunt.fail.fatal('publishing is disabled; set "publish.enabled" to true to enable');
if(!data.path)
return grunt.fail.fatal('the "publish.path" attribute must be provided for the publish task');
if(!data.message)
return grunt.fail.fatal('the "publish.message" attribute must be provided for the publish task');
/**
* provide the defaults for the git commands. by default, we are assuming the markdown repo is stored
* in a separate directory, so our git commands need to support that...provide the git-dir and work-tree
* paths. the standard publish process is:
*
* git add .
* git commit -m <configured commit message>
* git push <remoteName> <remoteBranch> (defaults to upstream master)
*
*/
_.defaults(data, {
addCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'add', '.'],
commitCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'commit', '-m', data.message],
pushCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'push', data.remoteName || 'upstream', data.remoteBranch || 'master']
});
//run the git commands, using promises to handle when complete
function cmd(args) {
var def = Q.defer();
grunt.util.spawn({ cmd: 'git', args: args }, def.resolve);
return def.promise;
}
//add, commit, and publish the doc repository
cmd(data.addCmd)
.then(cmd.bind(this, data.commitCmd))
.then(cmd.bind(this, data.pushCmd))
.then(done);
} | javascript | function publish(target, data, done) {
if(data.enabled !== true)
return grunt.fail.fatal('publishing is disabled; set "publish.enabled" to true to enable');
if(!data.path)
return grunt.fail.fatal('the "publish.path" attribute must be provided for the publish task');
if(!data.message)
return grunt.fail.fatal('the "publish.message" attribute must be provided for the publish task');
/**
* provide the defaults for the git commands. by default, we are assuming the markdown repo is stored
* in a separate directory, so our git commands need to support that...provide the git-dir and work-tree
* paths. the standard publish process is:
*
* git add .
* git commit -m <configured commit message>
* git push <remoteName> <remoteBranch> (defaults to upstream master)
*
*/
_.defaults(data, {
addCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'add', '.'],
commitCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'commit', '-m', data.message],
pushCmd: ['--git-dir='+ data.path +'/.git', '--work-tree='+ data.path, 'push', data.remoteName || 'upstream', data.remoteBranch || 'master']
});
//run the git commands, using promises to handle when complete
function cmd(args) {
var def = Q.defer();
grunt.util.spawn({ cmd: 'git', args: args }, def.resolve);
return def.promise;
}
//add, commit, and publish the doc repository
cmd(data.addCmd)
.then(cmd.bind(this, data.commitCmd))
.then(cmd.bind(this, data.pushCmd))
.then(done);
} | [
"function",
"publish",
"(",
"target",
",",
"data",
",",
"done",
")",
"{",
"if",
"(",
"data",
".",
"enabled",
"!==",
"true",
")",
"return",
"grunt",
".",
"fail",
".",
"fatal",
"(",
"'publishing is disabled; set \"publish.enabled\" to true to enable'",
")",
";",
"if",
"(",
"!",
"data",
".",
"path",
")",
"return",
"grunt",
".",
"fail",
".",
"fatal",
"(",
"'the \"publish.path\" attribute must be provided for the publish task'",
")",
";",
"if",
"(",
"!",
"data",
".",
"message",
")",
"return",
"grunt",
".",
"fail",
".",
"fatal",
"(",
"'the \"publish.message\" attribute must be provided for the publish task'",
")",
";",
"_",
".",
"defaults",
"(",
"data",
",",
"{",
"addCmd",
":",
"[",
"'--git-dir='",
"+",
"data",
".",
"path",
"+",
"'/.git'",
",",
"'--work-tree='",
"+",
"data",
".",
"path",
",",
"'add'",
",",
"'.'",
"]",
",",
"commitCmd",
":",
"[",
"'--git-dir='",
"+",
"data",
".",
"path",
"+",
"'/.git'",
",",
"'--work-tree='",
"+",
"data",
".",
"path",
",",
"'commit'",
",",
"'-m'",
",",
"data",
".",
"message",
"]",
",",
"pushCmd",
":",
"[",
"'--git-dir='",
"+",
"data",
".",
"path",
"+",
"'/.git'",
",",
"'--work-tree='",
"+",
"data",
".",
"path",
",",
"'push'",
",",
"data",
".",
"remoteName",
"||",
"'upstream'",
",",
"data",
".",
"remoteBranch",
"||",
"'master'",
"]",
"}",
")",
";",
"function",
"cmd",
"(",
"args",
")",
"{",
"var",
"def",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"grunt",
".",
"util",
".",
"spawn",
"(",
"{",
"cmd",
":",
"'git'",
",",
"args",
":",
"args",
"}",
",",
"def",
".",
"resolve",
")",
";",
"return",
"def",
".",
"promise",
";",
"}",
"cmd",
"(",
"data",
".",
"addCmd",
")",
".",
"then",
"(",
"cmd",
".",
"bind",
"(",
"this",
",",
"data",
".",
"commitCmd",
")",
")",
".",
"then",
"(",
"cmd",
".",
"bind",
"(",
"this",
",",
"data",
".",
"pushCmd",
")",
")",
".",
"then",
"(",
"done",
")",
";",
"}"
] | publishes the 'dest' folder to the git repo it is currently configured for. this code only
issues git commands; it doesn't target any specific repo...setting up the markdown repo ahead of time is
necessary.
@param target the target action, which is always 'publish'; ignore
@param data the data for the publish action
@param done the handler to end the async operation
@returns {*} | [
"publishes",
"the",
"dest",
"folder",
"to",
"the",
"git",
"repo",
"it",
"is",
"currently",
"configured",
"for",
".",
"this",
"code",
"only",
"issues",
"git",
"commands",
";",
"it",
"doesn",
"t",
"target",
"any",
"specific",
"repo",
"...",
"setting",
"up",
"the",
"markdown",
"repo",
"ahead",
"of",
"time",
"is",
"necessary",
"."
] | bafce5b121ba25ba2509eca1fa3351f957e9733d | https://github.com/mmacmillan/grunt-jsdox/blob/bafce5b121ba25ba2509eca1fa3351f957e9733d/tasks/jsdox.js#L29-L67 | train |
mmacmillan/grunt-jsdox | tasks/jsdox.js | cmd | function cmd(args) {
var def = Q.defer();
grunt.util.spawn({ cmd: 'git', args: args }, def.resolve);
return def.promise;
} | javascript | function cmd(args) {
var def = Q.defer();
grunt.util.spawn({ cmd: 'git', args: args }, def.resolve);
return def.promise;
} | [
"function",
"cmd",
"(",
"args",
")",
"{",
"var",
"def",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"grunt",
".",
"util",
".",
"spawn",
"(",
"{",
"cmd",
":",
"'git'",
",",
"args",
":",
"args",
"}",
",",
"def",
".",
"resolve",
")",
";",
"return",
"def",
".",
"promise",
";",
"}"
] | run the git commands, using promises to handle when complete | [
"run",
"the",
"git",
"commands",
"using",
"promises",
"to",
"handle",
"when",
"complete"
] | bafce5b121ba25ba2509eca1fa3351f957e9733d | https://github.com/mmacmillan/grunt-jsdox/blob/bafce5b121ba25ba2509eca1fa3351f957e9733d/tasks/jsdox.js#L56-L60 | train |
vineyard-bloom/vineyard-lawn | src/api.js | getArguments | function getArguments(req) {
const result = req.body || {};
for (let i in req.query) {
result[i] = req.query[i];
}
return result;
} | javascript | function getArguments(req) {
const result = req.body || {};
for (let i in req.query) {
result[i] = req.query[i];
}
return result;
} | [
"function",
"getArguments",
"(",
"req",
")",
"{",
"const",
"result",
"=",
"req",
".",
"body",
"||",
"{",
"}",
";",
"for",
"(",
"let",
"i",
"in",
"req",
".",
"query",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"req",
".",
"query",
"[",
"i",
"]",
";",
"}",
"return",
"result",
";",
"}"
] | This function is currently modifying req.body for performance though could be changed if it ever caused problems. | [
"This",
"function",
"is",
"currently",
"modifying",
"req",
".",
"body",
"for",
"performance",
"though",
"could",
"be",
"changed",
"if",
"it",
"ever",
"caused",
"problems",
"."
] | f36000716befa9bf467b8f29c3f0568368d4854e | https://github.com/vineyard-bloom/vineyard-lawn/blob/f36000716befa9bf467b8f29c3f0568368d4854e/src/api.js#L38-L44 | train |
maxrimue/node-autostart | index.js | isAutostartEnabled | function isAutostartEnabled(key, callback) {
if (arguments.length < 1) {
throw new Error('Not enough arguments passed to isAutostartEnabled()');
} else if (typeof key !== 'string') {
throw new TypeError('Passed "key" to disableAutostart() is not a string.');
}
if (typeof callback !== 'function') {
return new Promise((resolve, reject) => {
autostart.isAutostartEnabled(key, (error, isEnabled) => {
if (error) {
reject(error);
} else {
resolve(isEnabled);
}
});
});
}
autostart.isAutostartEnabled(key, (error, isEnabled) => {
callback(error, isEnabled);
});
} | javascript | function isAutostartEnabled(key, callback) {
if (arguments.length < 1) {
throw new Error('Not enough arguments passed to isAutostartEnabled()');
} else if (typeof key !== 'string') {
throw new TypeError('Passed "key" to disableAutostart() is not a string.');
}
if (typeof callback !== 'function') {
return new Promise((resolve, reject) => {
autostart.isAutostartEnabled(key, (error, isEnabled) => {
if (error) {
reject(error);
} else {
resolve(isEnabled);
}
});
});
}
autostart.isAutostartEnabled(key, (error, isEnabled) => {
callback(error, isEnabled);
});
} | [
"function",
"isAutostartEnabled",
"(",
"key",
",",
"callback",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"<",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Not enough arguments passed to isAutostartEnabled()'",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"key",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Passed \"key\" to disableAutostart() is not a string.'",
")",
";",
"}",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"autostart",
".",
"isAutostartEnabled",
"(",
"key",
",",
"(",
"error",
",",
"isEnabled",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"isEnabled",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"autostart",
".",
"isAutostartEnabled",
"(",
"key",
",",
"(",
"error",
",",
"isEnabled",
")",
"=>",
"{",
"callback",
"(",
"error",
",",
"isEnabled",
")",
";",
"}",
")",
";",
"}"
] | Checks if autostart is enabled
@param {String} key
@param {Function} callback | [
"Checks",
"if",
"autostart",
"is",
"enabled"
] | 486d4476c78f646fabf43988d3f460cc9142f438 | https://github.com/maxrimue/node-autostart/blob/486d4476c78f646fabf43988d3f460cc9142f438/index.js#L77-L99 | train |
obliquid/jslardo | public/javascripts/jq/jquery.ui.touch.js | iPadTouchStart | function iPadTouchStart(event) {
var touches = event.changedTouches,
first = touches[0],
type = "mouseover",
simulatedEvent = document.createEvent("MouseEvent");
//
// Mouse over first - I have live events attached on mouse over
//
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0, null);
first.target.dispatchEvent(simulatedEvent);
type = "mousedown";
simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0, null);
first.target.dispatchEvent(simulatedEvent);
if (!tapValid) {
lastTap = first.target;
tapValid = true;
tapTimeout = window.setTimeout("cancelTap();", 600);
startHold(event);
}
else {
window.clearTimeout(tapTimeout);
//
// If a double tap is still a possibility and the elements are the same
// Then perform a double click
//
if (first.target == lastTap) {
lastTap = null;
tapValid = false;
type = "click";
simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
type = "dblclick";
simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
}
else {
lastTap = first.target;
tapValid = true;
tapTimeout = window.setTimeout("cancelTap();", 600);
startHold(event);
}
}
} | javascript | function iPadTouchStart(event) {
var touches = event.changedTouches,
first = touches[0],
type = "mouseover",
simulatedEvent = document.createEvent("MouseEvent");
//
// Mouse over first - I have live events attached on mouse over
//
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0, null);
first.target.dispatchEvent(simulatedEvent);
type = "mousedown";
simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0, null);
first.target.dispatchEvent(simulatedEvent);
if (!tapValid) {
lastTap = first.target;
tapValid = true;
tapTimeout = window.setTimeout("cancelTap();", 600);
startHold(event);
}
else {
window.clearTimeout(tapTimeout);
//
// If a double tap is still a possibility and the elements are the same
// Then perform a double click
//
if (first.target == lastTap) {
lastTap = null;
tapValid = false;
type = "click";
simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
type = "dblclick";
simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY,
false, false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
}
else {
lastTap = first.target;
tapValid = true;
tapTimeout = window.setTimeout("cancelTap();", 600);
startHold(event);
}
}
} | [
"function",
"iPadTouchStart",
"(",
"event",
")",
"{",
"var",
"touches",
"=",
"event",
".",
"changedTouches",
",",
"first",
"=",
"touches",
"[",
"0",
"]",
",",
"type",
"=",
"\"mouseover\"",
",",
"simulatedEvent",
"=",
"document",
".",
"createEvent",
"(",
"\"MouseEvent\"",
")",
";",
"simulatedEvent",
".",
"initMouseEvent",
"(",
"type",
",",
"true",
",",
"true",
",",
"window",
",",
"1",
",",
"first",
".",
"screenX",
",",
"first",
".",
"screenY",
",",
"first",
".",
"clientX",
",",
"first",
".",
"clientY",
",",
"false",
",",
"false",
",",
"false",
",",
"false",
",",
"0",
",",
"null",
")",
";",
"first",
".",
"target",
".",
"dispatchEvent",
"(",
"simulatedEvent",
")",
";",
"type",
"=",
"\"mousedown\"",
";",
"simulatedEvent",
"=",
"document",
".",
"createEvent",
"(",
"\"MouseEvent\"",
")",
";",
"simulatedEvent",
".",
"initMouseEvent",
"(",
"type",
",",
"true",
",",
"true",
",",
"window",
",",
"1",
",",
"first",
".",
"screenX",
",",
"first",
".",
"screenY",
",",
"first",
".",
"clientX",
",",
"first",
".",
"clientY",
",",
"false",
",",
"false",
",",
"false",
",",
"false",
",",
"0",
",",
"null",
")",
";",
"first",
".",
"target",
".",
"dispatchEvent",
"(",
"simulatedEvent",
")",
";",
"if",
"(",
"!",
"tapValid",
")",
"{",
"lastTap",
"=",
"first",
".",
"target",
";",
"tapValid",
"=",
"true",
";",
"tapTimeout",
"=",
"window",
".",
"setTimeout",
"(",
"\"cancelTap();\"",
",",
"600",
")",
";",
"startHold",
"(",
"event",
")",
";",
"}",
"else",
"{",
"window",
".",
"clearTimeout",
"(",
"tapTimeout",
")",
";",
"if",
"(",
"first",
".",
"target",
"==",
"lastTap",
")",
"{",
"lastTap",
"=",
"null",
";",
"tapValid",
"=",
"false",
";",
"type",
"=",
"\"click\"",
";",
"simulatedEvent",
"=",
"document",
".",
"createEvent",
"(",
"\"MouseEvent\"",
")",
";",
"simulatedEvent",
".",
"initMouseEvent",
"(",
"type",
",",
"true",
",",
"true",
",",
"window",
",",
"1",
",",
"first",
".",
"screenX",
",",
"first",
".",
"screenY",
",",
"first",
".",
"clientX",
",",
"first",
".",
"clientY",
",",
"false",
",",
"false",
",",
"false",
",",
"false",
",",
"0",
",",
"null",
")",
";",
"first",
".",
"target",
".",
"dispatchEvent",
"(",
"simulatedEvent",
")",
";",
"type",
"=",
"\"dblclick\"",
";",
"simulatedEvent",
"=",
"document",
".",
"createEvent",
"(",
"\"MouseEvent\"",
")",
";",
"simulatedEvent",
".",
"initMouseEvent",
"(",
"type",
",",
"true",
",",
"true",
",",
"window",
",",
"1",
",",
"first",
".",
"screenX",
",",
"first",
".",
"screenY",
",",
"first",
".",
"clientX",
",",
"first",
".",
"clientY",
",",
"false",
",",
"false",
",",
"false",
",",
"false",
",",
"0",
",",
"null",
")",
";",
"first",
".",
"target",
".",
"dispatchEvent",
"(",
"simulatedEvent",
")",
";",
"}",
"else",
"{",
"lastTap",
"=",
"first",
".",
"target",
";",
"tapValid",
"=",
"true",
";",
"tapTimeout",
"=",
"window",
".",
"setTimeout",
"(",
"\"cancelTap();\"",
",",
"600",
")",
";",
"startHold",
"(",
"event",
")",
";",
"}",
"}",
"}"
] | mouse over event then mouse down | [
"mouse",
"over",
"event",
"then",
"mouse",
"down"
] | 84225f280e0cce8d46bff8cc2d16f2c8f9633fac | https://github.com/obliquid/jslardo/blob/84225f280e0cce8d46bff8cc2d16f2c8f9633fac/public/javascripts/jq/jquery.ui.touch.js#L108-L166 | train |
seebees/ironmq | libs/index.js | parseResponse | function parseResponse(cb) {
return function parse(err, response, body) {
// TODO Handel the errors
cb(err, JSON.parse(body))
}
} | javascript | function parseResponse(cb) {
return function parse(err, response, body) {
// TODO Handel the errors
cb(err, JSON.parse(body))
}
} | [
"function",
"parseResponse",
"(",
"cb",
")",
"{",
"return",
"function",
"parse",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"cb",
"(",
"err",
",",
"JSON",
".",
"parse",
"(",
"body",
")",
")",
"}",
"}"
] | one function to handle all the return errors | [
"one",
"function",
"to",
"handle",
"all",
"the",
"return",
"errors"
] | 28661aa21a43a28f80d341049b42f1b05cfc6870 | https://github.com/seebees/ironmq/blob/28661aa21a43a28f80d341049b42f1b05cfc6870/libs/index.js#L243-L248 | train |
amida-tech/rxnorm-js | lib/rxnorm.js | query | function query(base, q, callback) {
// Added unescape to fix URI errors resulting from hexadecimal escape sequences
var url = util.format("%s?%s", base, querystring.unescape(querystring.stringify(q)));
request(url, function (err, response) {
if (err) return callback(err);
callback(null, response.body);
});
} | javascript | function query(base, q, callback) {
// Added unescape to fix URI errors resulting from hexadecimal escape sequences
var url = util.format("%s?%s", base, querystring.unescape(querystring.stringify(q)));
request(url, function (err, response) {
if (err) return callback(err);
callback(null, response.body);
});
} | [
"function",
"query",
"(",
"base",
",",
"q",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"util",
".",
"format",
"(",
"\"%s?%s\"",
",",
"base",
",",
"querystring",
".",
"unescape",
"(",
"querystring",
".",
"stringify",
"(",
"q",
")",
")",
")",
";",
"request",
"(",
"url",
",",
"function",
"(",
"err",
",",
"response",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
",",
"response",
".",
"body",
")",
";",
"}",
")",
";",
"}"
] | generic GET query with any endpoint | [
"generic",
"GET",
"query",
"with",
"any",
"endpoint"
] | 967682eef73c531ea14e43bb01af99015a1989eb | https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L10-L17 | train |
amida-tech/rxnorm-js | lib/rxnorm.js | queryRxNormApproximate | function queryRxNormApproximate(medname, maxEntries, callback) {
// maxEntries is optional
if (!callback) {
callback = maxEntries;
maxEntries = 5;
}
query("http://rxnav.nlm.nih.gov/REST/approximateTerm.json", {
term: medname,
maxEntries: maxEntries
}, callback);
} | javascript | function queryRxNormApproximate(medname, maxEntries, callback) {
// maxEntries is optional
if (!callback) {
callback = maxEntries;
maxEntries = 5;
}
query("http://rxnav.nlm.nih.gov/REST/approximateTerm.json", {
term: medname,
maxEntries: maxEntries
}, callback);
} | [
"function",
"queryRxNormApproximate",
"(",
"medname",
",",
"maxEntries",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"callback",
")",
"{",
"callback",
"=",
"maxEntries",
";",
"maxEntries",
"=",
"5",
";",
"}",
"query",
"(",
"\"http://rxnav.nlm.nih.gov/REST/approximateTerm.json\"",
",",
"{",
"term",
":",
"medname",
",",
"maxEntries",
":",
"maxEntries",
"}",
",",
"callback",
")",
";",
"}"
] | find a medication by approximate name | [
"find",
"a",
"medication",
"by",
"approximate",
"name"
] | 967682eef73c531ea14e43bb01af99015a1989eb | https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L63-L74 | train |
amida-tech/rxnorm-js | lib/rxnorm.js | function (cb) {
fs.readFile(path.resolve(__dirname, "dose_form_groups.txt"), "UTF-8", function (err, doseForms) {
if (err) return cb(err);
// each group is a new line in the file
doseFormGroups = doseForms.toString().split("\n").filter(function (form) {
// ignore empty lines
return form.length > 0;
});
cb();
});
} | javascript | function (cb) {
fs.readFile(path.resolve(__dirname, "dose_form_groups.txt"), "UTF-8", function (err, doseForms) {
if (err) return cb(err);
// each group is a new line in the file
doseFormGroups = doseForms.toString().split("\n").filter(function (form) {
// ignore empty lines
return form.length > 0;
});
cb();
});
} | [
"function",
"(",
"cb",
")",
"{",
"fs",
".",
"readFile",
"(",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"\"dose_form_groups.txt\"",
")",
",",
"\"UTF-8\"",
",",
"function",
"(",
"err",
",",
"doseForms",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"doseFormGroups",
"=",
"doseForms",
".",
"toString",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"\\n",
"filter",
";",
"(",
"function",
"(",
"form",
")",
"{",
"return",
"form",
".",
"length",
">",
"0",
";",
"}",
")",
"}",
")",
";",
"}"
] | read in doseFormGroups from text file | [
"read",
"in",
"doseFormGroups",
"from",
"text",
"file"
] | 967682eef73c531ea14e43bb01af99015a1989eb | https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L104-L114 | train |
|
amida-tech/rxnorm-js | lib/rxnorm.js | queryRxNormGroup | function queryRxNormGroup(medname, callback) {
query("http://rxnav.nlm.nih.gov/REST/drugs.json", {
name: medname
}, function (err, body) {
if (err) return callback(err);
drugFormList(JSON.parse(body), callback);
});
} | javascript | function queryRxNormGroup(medname, callback) {
query("http://rxnav.nlm.nih.gov/REST/drugs.json", {
name: medname
}, function (err, body) {
if (err) return callback(err);
drugFormList(JSON.parse(body), callback);
});
} | [
"function",
"queryRxNormGroup",
"(",
"medname",
",",
"callback",
")",
"{",
"query",
"(",
"\"http://rxnav.nlm.nih.gov/REST/drugs.json\"",
",",
"{",
"name",
":",
"medname",
"}",
",",
"function",
"(",
"err",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"drugFormList",
"(",
"JSON",
".",
"parse",
"(",
"body",
")",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | query dose form groups | [
"query",
"dose",
"form",
"groups"
] | 967682eef73c531ea14e43bb01af99015a1989eb | https://github.com/amida-tech/rxnorm-js/blob/967682eef73c531ea14e43bb01af99015a1989eb/lib/rxnorm.js#L251-L258 | train |
mziccard/node-timsort | src/timsort.js | minRunLength | function minRunLength(n) {
let r = 0;
while (n >= DEFAULT_MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
} | javascript | function minRunLength(n) {
let r = 0;
while (n >= DEFAULT_MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
} | [
"function",
"minRunLength",
"(",
"n",
")",
"{",
"let",
"r",
"=",
"0",
";",
"while",
"(",
"n",
">=",
"DEFAULT_MIN_MERGE",
")",
"{",
"r",
"|=",
"(",
"n",
"&",
"1",
")",
";",
"n",
">>=",
"1",
";",
"}",
"return",
"n",
"+",
"r",
";",
"}"
] | Compute minimum run length for TimSort
@param {number} n - The size of the array to sort. | [
"Compute",
"minimum",
"run",
"length",
"for",
"TimSort"
] | f8acc9e336117356d354ccb15133d10c92444322 | https://github.com/mziccard/node-timsort/blob/f8acc9e336117356d354ccb15133d10c92444322/src/timsort.js#L121-L130 | train |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.