_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2800
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2801
|
train
|
function (port, parent_port) {
// check if the port wasn't reported
if (l_ports.hasOwnProperty(port) === false) {
LOG.warn('recording
|
javascript
|
{
"resource": ""
}
|
|
q2802
|
train
|
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;
|
javascript
|
{
"resource": ""
}
|
|
q2803
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2804
|
train
|
function(req) {
return ((req.headers.origin
|
javascript
|
{
"resource": ""
}
|
|
q2805
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q2806
|
train
|
function() {
var origin = _getOrigin(req);
|
javascript
|
{
"resource": ""
}
|
|
q2807
|
train
|
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') {
|
javascript
|
{
"resource": ""
}
|
|
q2808
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2809
|
nameVersionInstallStrategy
|
train
|
function nameVersionInstallStrategy(baseDir) {
return (name, version) => {
if (!version) {
throw Error('hey I need a version!');
|
javascript
|
{
"resource": ""
}
|
q2810
|
train
|
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:
|
javascript
|
{
"resource": ""
}
|
|
q2811
|
train
|
function (entry) {
if (typeof entry === 'number' && entry < entryServers.length) {
entryServers.splice(entry, 1);
return true;
}
else if (typeof entry === 'string') {
|
javascript
|
{
"resource": ""
}
|
|
q2812
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
|
q2813
|
train
|
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)
|
javascript
|
{
"resource": ""
}
|
|
q2814
|
train
|
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);
//
|
javascript
|
{
"resource": ""
}
|
|
q2815
|
sma
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2816
|
avg
|
train
|
function avg(arr, idx, range) {
return sum(arr.slice(idx
|
javascript
|
{
"resource": ""
}
|
q2817
|
sum
|
train
|
function sum(arr) {
var len = arr.length;
var
|
javascript
|
{
"resource": ""
}
|
q2818
|
isSpecial
|
train
|
function isSpecial(key) {
if (key.length > 1) {
return !!exports.specialKeys.filter(function (specialKey) {
var pattern = new RegExp("^("
|
javascript
|
{
"resource": ""
}
|
q2819
|
keyboardCapsLockLayout
|
train
|
function keyboardCapsLockLayout(layout, caps) {
return layout.map(function (row) {
return row.map(function (key) {
return isSpecial(key) ?
|
javascript
|
{
"resource": ""
}
|
q2820
|
TransactionTask
|
train
|
function TransactionTask(readOnly, txnCallback, errorCallback, successCallback) {
this.readOnly = readOnly;
this.txnCallback = txnCallback;
|
javascript
|
{
"resource": ""
}
|
q2821
|
renameKey
|
train
|
function renameKey(obj, prevKey, nextKey) {
return mapKeys(obj, (_, key)
|
javascript
|
{
"resource": ""
}
|
q2822
|
openModal
|
train
|
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 +
|
javascript
|
{
"resource": ""
}
|
q2823
|
selectTab
|
train
|
function selectTab(tab,content) {
//deseleziono tutti i tab
$('#'+tab).parent().children().removeClass('tabButtonSelected');
//seleziono il tab cliccato
$('#'+tab).addClass('tabButtonSelected');
//nascondo tutti i content
|
javascript
|
{
"resource": ""
}
|
q2824
|
train
|
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++;
|
javascript
|
{
"resource": ""
}
|
|
q2825
|
train
|
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];
|
javascript
|
{
"resource": ""
}
|
|
q2826
|
extractLiterals
|
train
|
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]);
}
|
javascript
|
{
"resource": ""
}
|
q2827
|
train
|
function () {
if(this.is_focused()) { return; }
var f = $.jstree._focused();
if(f) {
|
javascript
|
{
"resource": ""
}
|
|
q2828
|
triggerEvent
|
train
|
function triggerEvent(el, type, options) {
if (isString(el)) {
options = type;
type = el;
el = document;
}
var e = createEvent(type, options);
|
javascript
|
{
"resource": ""
}
|
q2829
|
WrapperError
|
train
|
function WrapperError(message, innerError) {
// supports instantiating the object without the new keyword
if (!(this instanceof WrapperError)) {
return new WrapperError(message, innerError);
}
Error.call(this);
|
javascript
|
{
"resource": ""
}
|
q2830
|
formatError
|
train
|
function formatError(error, stack) {
if (origPrepareStackTrace) {
return origPrepareStackTrace(error, stack);
}
|
javascript
|
{
"resource": ""
}
|
q2831
|
isQuantifierNext
|
train
|
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*)?})/ :
|
javascript
|
{
"resource": ""
}
|
q2832
|
prepareOptions
|
train
|
function prepareOptions(value) {
var options = {};
if (isType(value, 'String')) {
XRegExp.forEach(value, /[^\s,]+/, function(match) {
|
javascript
|
{
"resource": ""
}
|
q2833
|
parser
|
train
|
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))
|
javascript
|
{
"resource": ""
}
|
q2834
|
Storage
|
train
|
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,
|
javascript
|
{
"resource": ""
}
|
q2835
|
addPointToDomain
|
train
|
function addPointToDomain( point, x, y, domainId ){
var domain = domains[ domainId ];
var newPoint = {
value: point,
x: x,
y: y,
|
javascript
|
{
"resource": ""
}
|
q2836
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
|
q2837
|
die
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2838
|
read
|
train
|
function read(filePath, options){
return new Promise((resolve, reject) => {
fs.readFile(filePath, options, (error, data) => {
error
|
javascript
|
{
"resource": ""
}
|
q2839
|
write
|
train
|
function write(filePath, fileData, options){
return new Promise((resolve, reject) => {
fs.writeFile(filePath, fileData, options, error => {
|
javascript
|
{
"resource": ""
}
|
q2840
|
combineErrors
|
train
|
function combineErrors(errPrev, errNew) {
if (!errPrev) {
return errNew;
}
let errCombined;
if (errPrev instanceof AggregateError) {
errCombined = errPrev;
} else {
|
javascript
|
{
"resource": ""
}
|
q2841
|
addToChai
|
train
|
function addToChai(names, fn){
for(const name of names)
|
javascript
|
{
"resource": ""
}
|
q2842
|
FieldReference
|
train
|
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;
};
|
javascript
|
{
"resource": ""
}
|
q2843
|
getNumTargets
|
train
|
function getNumTargets() {
if (numTargets) {
return numTargets
}
var targets = grunt.config('npmcopy')
if (targets) {
delete targets.options
|
javascript
|
{
"resource": ""
}
|
q2844
|
convert
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2845
|
filterRepresented
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2846
|
ensure
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q2847
|
convertMatches
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2848
|
getMain
|
train
|
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, ''))
)
}
|
javascript
|
{
"resource": ""
}
|
q2849
|
readStrucPerm
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2850
|
getFileDetails
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2851
|
updateExistingFile
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2852
|
createNewFile
|
train
|
function createNewFile(db, fileName, fileReadStream, options, cb) {
defaultLogger.debug("In createNewFile");
createFileWithVersion(db,
|
javascript
|
{
"resource": ""
}
|
q2853
|
errorSerializer
|
train
|
function errorSerializer (err) {
if (!err || !err.stack) return err
const obj = {
message: err.message,
name: err.name,
|
javascript
|
{
"resource": ""
}
|
q2854
|
getCleanUrl
|
train
|
function getCleanUrl (url) {
try {
const parsed = new
|
javascript
|
{
"resource": ""
}
|
q2855
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
|
q2856
|
train
|
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;
}
|
javascript
|
{
"resource": ""
}
|
|
q2857
|
save
|
train
|
function save(template, distpath) {
var data = generate(template);
var dir = path.dirname(distpath);
mkdirp(dir, function(err) {
if(err) {
console.log(err.message);
return;
|
javascript
|
{
"resource": ""
}
|
q2858
|
setConversationEtagHeader
|
train
|
function setConversationEtagHeader(res, conversationInfo) {
var copy = JSON.parse(JSON.stringify(conversationInfo));
delete copy.participants;
|
javascript
|
{
"resource": ""
}
|
q2859
|
translate
|
train
|
function translate(singular, plural) {
if (!locales[currentLocale]) {
read(currentLocale);
}
if (plural) {
if (!locales[currentLocale][singular]) {
locales[currentLocale][singular] = {
'one': singular,
'other': plural
};
write(currentLocale);
}
|
javascript
|
{
"resource": ""
}
|
q2860
|
read
|
train
|
function read(myLocale) {
locales[myLocale] = {};
try {
locales[myLocale] = JSON.parse(fs.readFileSync(locate(myLocale)));
|
javascript
|
{
"resource": ""
}
|
q2861
|
write
|
train
|
function write(myLocale) {
try {
stats = fs.lstatSync(directory);
} catch(e) {
fs.mkdirSync(directory, 0755);
}
|
javascript
|
{
"resource": ""
}
|
q2862
|
guessLanguage
|
train
|
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]) {
|
javascript
|
{
"resource": ""
}
|
q2863
|
train
|
function(connect, options) {
return [
require('connect-livereload')(),
// Default middlewares
// Serve static files.
connect.static(options.base),
|
javascript
|
{
"resource": ""
}
|
|
q2864
|
fireCallback
|
train
|
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]) {
|
javascript
|
{
"resource": ""
}
|
q2865
|
onTabLoaded
|
train
|
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,
|
javascript
|
{
"resource": ""
}
|
q2866
|
loadTab
|
train
|
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,
|
javascript
|
{
"resource": ""
}
|
q2867
|
loadModal
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q2868
|
isEmpty
|
train
|
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;
|
javascript
|
{
"resource": ""
}
|
q2869
|
_encodeBlob
|
train
|
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({
|
javascript
|
{
"resource": ""
}
|
q2870
|
checkIfLocalStorageThrows
|
train
|
function checkIfLocalStorageThrows() {
var localStorageTestKey = '_localforage_support_test';
try {
localStorage.setItem(localStorageTestKey, true);
|
javascript
|
{
"resource": ""
}
|
q2871
|
uniqueArray
|
train
|
function uniqueArray(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) ===
|
javascript
|
{
"resource": ""
}
|
q2872
|
warnOnce
|
train
|
function warnOnce(message) {
if (!(previousWarnOnceMessages.indexOf(message)
|
javascript
|
{
"resource": ""
}
|
q2873
|
adaptInputValidator
|
train
|
function adaptInputValidator(legacyValidator) {
return function adaptedInputValidator(inputValue, extraParams) {
return legacyValidator.call(this, inputValue, extraParams).then(function () {
|
javascript
|
{
"resource": ""
}
|
q2874
|
showWarningsForParams
|
train
|
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"));
|
javascript
|
{
"resource": ""
}
|
q2875
|
mixin
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q2876
|
showLoading
|
train
|
function showLoading() {
var popup = getPopup();
if (!popup) {
Swal('');
}
popup = getPopup();
var actions = getActions();
var confirmButton = getConfirmButton();
var cancelButton =
|
javascript
|
{
"resource": ""
}
|
q2877
|
hideLoading
|
train
|
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);
}
}
|
javascript
|
{
"resource": ""
}
|
q2878
|
resetValidationMessage
|
train
|
function resetValidationMessage() {
var domCache = privateProps.domCache.get(this);
if (domCache.validationMessage) {
hide(domCache.validationMessage);
}
var input = this.getInput();
if (input) {
|
javascript
|
{
"resource": ""
}
|
q2879
|
openPopup
|
train
|
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() {
|
javascript
|
{
"resource": ""
}
|
q2880
|
getInputValue
|
train
|
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;
|
javascript
|
{
"resource": ""
}
|
q2881
|
train
|
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 ||
|
javascript
|
{
"resource": ""
}
|
|
q2882
|
AggregateError
|
train
|
function AggregateError(message) {
if (!(this instanceof AggregateError)) {
return new AggregateError(message);
}
Error.captureStackTrace(this, AggregateError);
|
javascript
|
{
"resource": ""
}
|
q2883
|
split
|
train
|
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]);
|
javascript
|
{
"resource": ""
}
|
q2884
|
handleError
|
train
|
function handleError(error) {
console.log(`${options.entry} failed.`);
console.trace(error);
|
javascript
|
{
"resource": ""
}
|
q2885
|
getArguments
|
train
|
function getArguments(node) {
if (node && node.arguments && node.arguments.length > 0) {
|
javascript
|
{
"resource": ""
}
|
q2886
|
extractLiteralFromInstalled
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
q2887
|
extractLiteralFromDef
|
train
|
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);
|
javascript
|
{
"resource": ""
}
|
q2888
|
isFunctionExpression
|
train
|
function isFunctionExpression(node) {
if (node && node.callee && node.callee.type === 'FunctionExpression')
|
javascript
|
{
"resource": ""
}
|
q2889
|
publish
|
train
|
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
|
javascript
|
{
"resource": ""
}
|
q2890
|
cmd
|
train
|
function cmd(args) {
var def = Q.defer();
grunt.util.spawn({ cmd: 'git', args: args
|
javascript
|
{
"resource": ""
}
|
q2891
|
getArguments
|
train
|
function getArguments(req) {
const result = req.body || {};
for (let i in req.query) {
|
javascript
|
{
"resource": ""
}
|
q2892
|
isAutostartEnabled
|
train
|
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) => {
|
javascript
|
{
"resource": ""
}
|
q2893
|
iPadTouchStart
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
q2894
|
parseResponse
|
train
|
function parseResponse(cb) {
return function parse(err, response, body) {
// TODO
|
javascript
|
{
"resource": ""
}
|
q2895
|
query
|
train
|
function query(base, q, callback) {
// Added unescape to fix URI errors resulting from hexadecimal escape sequences
var url = util.format("%s?%s",
|
javascript
|
{
"resource": ""
}
|
q2896
|
queryRxNormApproximate
|
train
|
function queryRxNormApproximate(medname, maxEntries, callback) {
// maxEntries is optional
if (!callback) {
callback = maxEntries;
maxEntries = 5;
}
|
javascript
|
{
"resource": ""
}
|
q2897
|
train
|
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) {
|
javascript
|
{
"resource": ""
}
|
|
q2898
|
queryRxNormGroup
|
train
|
function queryRxNormGroup(medname, callback) {
query("http://rxnav.nlm.nih.gov/REST/drugs.json", {
name: medname
}, function (err, body)
|
javascript
|
{
"resource": ""
}
|
q2899
|
minRunLength
|
train
|
function minRunLength(n) {
let r = 0;
while (n >= DEFAULT_MIN_MERGE) {
r |=
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.