_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q54300 | train | function (err, pStatus) {
if (err) {
log.error(that._name + " - Could not get player status- " + err);
} else {
that._playerStatus(pStatus);
}
} | javascript | {
"resource": ""
} | |
q54301 | train | function(err, content_name, parsed_content, modified_date) {
if (!err) {
parsed_contents[content_name] = parsed_content;
if (modified_date > last_modified) {
last_modified = modified_date;
}
}
if (content_files.length) {
return parseFile(content_files.pop(), parse_file_callback);... | javascript | {
"resource": ""
} | |
q54302 | train | function(callback) {
var self = this;
var sections = [Path.join("/")];
var paths_to_traverse = [];
var should_exclude = function(entry) {
return entry[0] === "." || entry[0] === "_" || entry === "shared";
};
var traverse_path = function() {
var current_path = paths_to_traverse.shift() || "";
Fs.r... | javascript | {
"resource": ""
} | |
q54303 | train | function(basePath, output_extension, options, callback) {
var self = this;
var collected_contents = {};
var content_options = {};
var last_modified = null;
// treat files with special output extensions
if (output_extension !== ".html") {
basePath = basePath + output_extension;
}
self.getContent(bas... | javascript | {
"resource": ""
} | |
q54304 | start | train | function start(app) {
/**
* Create HTTP server.
*/
const config = require('./config')();
port = normalizePort(config.get('port'));
server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
app.set('port', port);
server.listen(port);
... | javascript | {
"resource": ""
} |
q54305 | estimatedNumberOfRows | train | function estimatedNumberOfRows(node, context, callback) {
var sql = estimatedCountTemplate({
sourceQuery: node.sql()
});
context.runSQL(sql, function(err, resultSet){
var estimated_rows = null;
if (!err) {
if (resultSet.rows) {
estimated_rows = resultSet.r... | javascript | {
"resource": ""
} |
q54306 | numberOfRows | train | function numberOfRows(node, context, callback) {
var sql = exactCountTemplate({
sourceQuery: node.sql()
});
context.runSQL(sql, function(err, resultSet){
var counted_rows = null;
if (!err) {
counted_rows = resultSet.rows[0].result_rows;
}
return callback(e... | javascript | {
"resource": ""
} |
q54307 | numberOfDistinctValues | train | function numberOfDistinctValues(node, context, columnName, callback) {
var sql = countDistinctValuesTemplate({
source: node.sql(),
column: columnName
});
context.runSQL(sql, function(err, resultSet){
var number = null;
if (!err) {
number = resultSet.rows[0].count_... | javascript | {
"resource": ""
} |
q54308 | train | function(parallels = 1) {
this._parallels = parallels || 1;
/**
* _queueCounter
* each lock() increased this number
* each unlock() decreases this number
* If _qC==0, the state is in idle
* @type {Number}
*/
this._qC = 0;
/**
* _idleCalls
* contains all promises... | javascript | {
"resource": ""
} | |
q54309 | _resolveOneIdleCall | train | function _resolveOneIdleCall(idleQueue) {
if (idleQueue._iC.size === 0) return;
const iterator = idleQueue._iC.values();
const oldestPromise = iterator.next().value;
oldestPromise._manRes();
// try to call the next tick
setTimeout(() => _tryIdleCall(idleQueue), 0);
} | javascript | {
"resource": ""
} |
q54310 | _removeIdlePromise | train | function _removeIdlePromise(idleQueue, promise) {
if (!promise) return;
// remove timeout if exists
if (promise._timeoutObj)
clearTimeout(promise._timeoutObj);
// remove handle-nr if exists
if (idleQueue._pHM.has(promise)) {
const handle = idleQueue._pHM.get(promise);
idleQ... | javascript | {
"resource": ""
} |
q54311 | _tryIdleCall | train | function _tryIdleCall(idleQueue) {
// ensure this does not run in parallel
if (idleQueue._tryIR || idleQueue._iC.size === 0)
return;
idleQueue._tryIR = true;
// w8 one tick
setTimeout(() => {
// check if queue empty
if (!idleQueue.isIdle()) {
idleQueue._tryIR = f... | javascript | {
"resource": ""
} |
q54312 | train | function(view, config) {
var formInputs = getForm(view);
formInputs = _.reject(formInputs, function(el) {
var reject;
var myType = getElementType(el);
var extractor = config.keyExtractors.get(myType);
var identifier = extractor($(el));
var foundInIgnored = _.find(config.ignoredTypes, function(... | javascript | {
"resource": ""
} | |
q54313 | train | function(options) {
var config = _.clone(options) || {};
config.ignoredTypes = _.clone(Syphon.ignoredTypes);
config.inputReaders = config.inputReaders || Syphon.InputReaders;
config.inputWriters = config.inputWriters || Syphon.InputWriters;
config.keyExtractors = config.keyExtractors || Syphon.KeyExtractors;... | javascript | {
"resource": ""
} | |
q54314 | getSocketAddressFromURLSafeHostname | train | function getSocketAddressFromURLSafeHostname(hostname) {
return __awaiter(this, void 0, void 0, function* () {
// IPv4 addresses are fine
if (net_1.isIPv4(hostname))
return hostname;
// IPv6 addresses are wrapped in [], which need to be removed
if (/^\[.+\]$/.test(hostnam... | javascript | {
"resource": ""
} |
q54315 | lookupAsync | train | function lookupAsync(hostname) {
return new Promise((resolve, reject) => {
dns.lookup(hostname, { all: true }, (err, addresses) => {
if (err)
return reject(err);
resolve(addresses[0].address);
});
});
} | javascript | {
"resource": ""
} |
q54316 | padStart | train | function padStart(str, targetLen, fill = " ") {
// simply return strings that are long enough to not be padded
if (str != null && str.length >= targetLen)
return str;
// make sure that <fill> isn't empty
if (fill == null || fill.length < 1)
throw new Error("fill must be at least one char... | javascript | {
"resource": ""
} |
q54317 | train | function(dashed) {
var i;
var camel = '';
var nextCap = false;
for (i = 0; i < dashed.length; i++) {
if (dashed[i] !== '-') {
camel += nextCap ? dashed[i].toUpperCase() : dashed[i];
nextCap = false;
} else {
nextCap = true;
}
}
return camel;
} | javascript | {
"resource": ""
} | |
q54318 | train | function(str) {
var deliminator_stack = [];
var length = str.length;
var i;
var parts = [];
var current_part = '';
var opening_index;
var closing_index;
for (i = 0; i < length; i++) {
opening_index = opening_deliminators.indexOf(str[i]);
closing_index = closing_deliminators.indexOf(str[i]);
... | javascript | {
"resource": ""
} | |
q54319 | train | function(value) {
var i;
for (i = value; i < this._length; i++) {
delete this[i];
}
this._length = value;
} | javascript | {
"resource": ""
} | |
q54320 | train | function(cmdfunc) {
var outfunc = function(msg, reply, meta) {
if ('save' !== msg.cmd) {
if (null == msg.q) {
msg.q = {}
if (null != msg.id) {
msg.q.id = msg.id
delete msg.id
}
}
if (null == msg.qent) {
msg.qent = this.m... | javascript | {
"resource": ""
} | |
q54321 | train | function (err) {
//if any error happened in the previous tasks, exit with a code > 0
if (err) {
var exitCode = 2;
console.log('[ERROR] gulp build task failed', err);
console.log('[FAIL] gulp build task failed - exiting with code ' + exitCode);
return proce... | javascript | {
"resource": ""
} | |
q54322 | splitWords | train | function splitWords(str) {
return str
// insert a space between lower & upper
.replace(/([a-z])([A-Z])/g, '$1 $2')
// space before last upper in a sequence followed by lower
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./... | javascript | {
"resource": ""
} |
q54323 | train | function (stream, state) {
var plannedToken = state.plannedTokens.shift();
if (plannedToken === undefined) {
return null;
}
stream.match(plannedToken.value);
var tokens = plannedToken.type.split('.');
return cmTokenFromAceTokens(tokens);
} | javascript | {
"resource": ""
} | |
q54324 | configureConfigFile | train | function configureConfigFile(err, result) {
for (var key in result) {
if (key === 'port' && !result[key] || key === 'port' && result[key] !== result[key]) {
shell.echo('exports.' + key + ' = 8080' + '\n').toEnd(clientFiles.config)
} else {
shell.echo('exports.' + key + ' = ' + JSON.stringify(resul... | javascript | {
"resource": ""
} |
q54325 | train | function (value) {
if (typeof value === 'object' && value !== null) {
if (_.size(value) <= 2
&& _.all(value, function (v, k) {
return typeof k === 'string' && k.substr(0, 1) === '$';
})) {
for (var i = 0; i < builtinConverters.length; i++) {
var converter = builtinConverter... | javascript | {
"resource": ""
} | |
q54326 | SetConfigNodeConnectionListeners | train | function SetConfigNodeConnectionListeners(node) {
node.clientNode.rtmClient.on("connecting", () => {
node.status(statuses.connecting);
});
node.clientNode.rtmClient.on("ready", () => {
node.status(statuses.connected);
});
node.clientNode.rtmClient.on("disconnected", e => {
var st... | javascript | {
"resource": ""
} |
q54327 | SlackState | train | function SlackState(n) {
RED.nodes.createNode(this, n);
var node = this;
this.client = n.client;
this.clientNode = RED.nodes.getNode(this.client);
node.status(statuses.disconnected);
if (node.client) {
SetConfigNodeConnectionListeners(node);
node.on("input", function(msg) {
... | javascript | {
"resource": ""
} |
q54328 | moneyBuyDescriptionHandler | train | function moneyBuyDescriptionHandler(descriptions, position) {
descriptions.each(function (i) {
$(this).removeClass('show-money-buy-copy');
if (position === i + 1) {
$(this).addClass('show-money-buy-copy');
}
})
} | javascript | {
"resource": ""
} |
q54329 | onYouTubePlayerAPIReady | train | function onYouTubePlayerAPIReady() {
// Loop through each iframe video on the page
jQuery( "iframe.copy-video__video").each(function (index) {
// Create IDs dynamically
var iframeID = "js-copy-video-" + index;
var buttonID = "js-copy-video-" + index + "__button";
// Set IDs
jQuery(this).attr('... | javascript | {
"resource": ""
} |
q54330 | getProcessedData | train | async function getProcessedData(url) {
let data;
try {
data = await downloadData(url);
} catch (error) {
data = await downloadFallbackData(url);
}
return processDataInWorker(data);
} | javascript | {
"resource": ""
} |
q54331 | regexpForFunctionCall | train | function regexpForFunctionCall(fnName, args) {
const optionalWhitespace = '\\s*';
const argumentParts = args.map(
arg => optionalWhitespace + arg + optionalWhitespace
);
let parts = [fnName, '\\(', argumentParts.join(','), '\\)'];
return new RegExp(parts.join(''), 'g');
} | javascript | {
"resource": ""
} |
q54332 | stringifyParams | train | function stringifyParams (obj) {
return obj ? arrayMap(objectKeys(obj).sort(), function (key) {
var val = obj[key]
if (angular.isArray(val)) {
return arrayMap(val.sort(), function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2)
}).join('&')
}
... | javascript | {
"resource": ""
} |
q54333 | Thumbnailer | train | function Thumbnailer (opts) {
// for the benefit of testing
// perform dependency injection.
_.extend(this, {
tmp: require('tmp'),
logger: require(config.get('logger'))
}, opts)
} | javascript | {
"resource": ""
} |
q54334 | Worker | train | function Worker (opts) {
_.extend(this, {
grabber: null,
saver: null,
logger: require(config.get('logger'))
}, opts)
this.sqs = new aws.SQS({
accessKeyId: config.get('awsKey'),
secretAccessKey: config.get('awsSecret'),
region: config.get('awsRegion')
})
config.set('sqsQueueUrl', this... | javascript | {
"resource": ""
} |
q54335 | Client | train | function Client (opts) {
// update client instance and config
// with overrides from opts.
_.extend(this, {
Saver: require('./saver').Saver
}, opts)
config.extend(opts)
// allow sqs to be overridden
// in tests.
if (opts && opts.sqs) {
this.sqs = opts.sqs
delete opts.sqs
} else {
thi... | javascript | {
"resource": ""
} |
q54336 | buildOpts | train | function buildOpts (keys) {
var opts = {}
var pairs = _.pairs(keys)
for (var i in pairs) {
var argvKey = pairs[i][0]
var envKey = argvKey.toUpperCase()
var configKey = pairs[i][1]
opts[configKey] = argv[argvKey] || config.get(configKey)
if (opts[configKey] === null) {
throw Error("The en... | javascript | {
"resource": ""
} |
q54337 | SymbolicLinkFinder | train | function SymbolicLinkFinder(options) {
this.scanDirs = options && options.scanDirs || ['.'];
this.extensions = options && options.extensions || ['.js'];
this.ignore = options && options.ignore || null;
} | javascript | {
"resource": ""
} |
q54338 | train | function(buildConfig, path) {
ensureBlacklistsComputed(buildConfig);
var buildConfigBlacklistRE = buildConfig.blacklistRE;
var internalDependenciesBlacklistRE = buildConfig._reactPageBlacklistRE;
if (BLACKLIST_FILE_EXTS_RE.test(path) ||
buildConfig._middlewareBlacklistRE.test(path) ||
internalDepend... | javascript | {
"resource": ""
} | |
q54339 | requireLazy | train | function requireLazy(dependencies, factory, context) {
return define(
dependencies,
factory,
undefined,
REQUIRE_WHEN_READY,
context,
1
);
} | javascript | {
"resource": ""
} |
q54340 | train | function(id, deps, factory, _special) {
define(id, deps, factory, _special || USED_AS_TRANSPORT);
} | javascript | {
"resource": ""
} | |
q54341 | requireUnsee | train | function requireUnsee(module) {
if (window.requirejs.has(module)) {
window.requirejs.unsee(module);
}
} | javascript | {
"resource": ""
} |
q54342 | rm | train | function rm(filepath, callback) {
var killswitch = false;
fs.stat(filepath, function(err, stat) {
if (err) return callback(err);
if (stat.isFile()) return fs.unlink(filepath, callback);
if (!stat.isDirectory()) return callback(new Error('Unrecognized file.'));
Step(function() {
... | javascript | {
"resource": ""
} |
q54343 | forcelink | train | function forcelink(src, dest, options, callback) {
if (!options || !options.cache) throw new Error('options.cache not defined!');
if (!callback) throw new Error('callback not defined!');
// uses relative path if linking to cache dir
if (path.relative) {
src = path.relative(options.cache, dest).s... | javascript | {
"resource": ""
} |
q54344 | localize | train | function localize(url, options, callback) {
existsAsync(options.filepath, function(exists) {
if (exists) {
var re_download = false;
// unideal workaround for frequently corrupt/partially downloaded zips
// https://github.com/mapbox/millstone/issues/85
if (path... | javascript | {
"resource": ""
} |
q54345 | cachepath | train | function cachepath(location) {
var uri = url.parse(location);
if (!uri.protocol) {
throw new Error('Invalid URL: ' + location);
} else {
var hash = crypto.createHash('md5')
.update(location)
.digest('hex')
.substr(0,8) +
'-' + path.basename(uri... | javascript | {
"resource": ""
} |
q54346 | metapath | train | function metapath(filepath) {
return path.join(path.dirname(filepath), '.' + path.basename(filepath));
} | javascript | {
"resource": ""
} |
q54347 | readExtension | train | function readExtension(file, cb) {
fs.readFile(metapath(file), 'utf-8', function(err, data) {
if (err) {
if (err.code === 'ENOENT') return cb(new Error('Metadata file does not exist.'));
return cb(err);
}
try {
var ext = guessExtension(JSON.parse(data));
... | javascript | {
"resource": ""
} |
q54348 | fixSRS | train | function fixSRS(obj) {
if (!obj.srs) return;
var normalized = _(obj.srs.split(' ')).chain()
.select(function(s) { return s.indexOf('=') > 0; })
.sortBy(function(s) { return s; })
.reduce(function(memo, s) {
var key = s.split('=')[0];
var val = s.split('=')[1];
... | javascript | {
"resource": ""
} |
q54349 | localizeCartoURIs | train | function localizeCartoURIs(s,cb) {
// Get all unique URIs in stylesheet
// TODO - avoid finding non url( uris?
var matches = s.data.match(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi);
var URIs = _.uniq(matches || []);
va... | javascript | {
"resource": ""
} |
q54350 | indexOf | train | function indexOf(haystack, needle, i) {
if (!Buffer.isBuffer(needle)) needle = new Buffer(needle);
if (typeof i === 'undefined') i = 0;
var l = haystack.length - needle.length + 1;
while (i<l) {
var good = true;
for (var j=0, n=needle.length; j<n; j++) {
if (haystack[i+j] !== needle[... | javascript | {
"resource": ""
} |
q54351 | hashPassword | train | function hashPassword (passport, next) {
if (passport.password) {
bcrypt.hash(passport.password, 10, function (err, hash) {
passport.password = hash;
next(err, passport);
});
} else {
next(null, passport);
}
} | javascript | {
"resource": ""
} |
q54352 | train | function(target, key, value, receiver) {
// If the receiver is not this observable (the observable might be on the proto chain),
// set the key on the reciever.
if (receiver !== this.proxy) {
return makeObject.setKey(receiver, key, value, this);
}
// If it has a defined property definiition
var computed... | javascript | {
"resource": ""
} | |
q54353 | getStoredToken | train | function getStoredToken (storageLocation) {
var token = readCookie(storageLocation);
if (!token && (window && window.localStorage || window.sessionStorage)) {
token = window.sessionStorage.getItem(storageLocation) || window.localStorage.getItem(storageLocation);
}
return token;
} | javascript | {
"resource": ""
} |
q54354 | hasValidToken | train | function hasValidToken (storageLocation) {
var token = getStoredToken(storageLocation);
if (token) {
try {
var payload = decode(token);
return payloadIsValid(payload);
} catch (error) {
return false;
}
}
return false;
} | javascript | {
"resource": ""
} |
q54355 | toPairs | train | function toPairs (v) {
if (ktypes.isArray(v)) {
var pairs = []
var i
for (i = 0; i < v.length; i++) {
pairs.push([i, v[i]])
}
return pairs
}
return _.toPairs(v)
} | javascript | {
"resource": ""
} |
q54356 | train | function (auth) {
var clientCredentials = Buffer.from(auth.slice('basic '.length), 'base64').toString().split(':')
var clientId = querystring.unescape(clientCredentials[0])
var clientSecret = querystring.unescape(clientCredentials[1])
return { id: clientId, secret: clientSecret }
} | javascript | {
"resource": ""
} | |
q54357 | train | function(x){
if(!x || x.type !== type){
return false;
}
if(value){
return x.src === value;
}
return true;
} | javascript | {
"resource": ""
} | |
q54358 | getPathToDestination | train | function getPathToDestination(pathToSource, pathToDestinationFile) {
var isDestinationDirectory = (/\/$/).test(pathToDestinationFile);
var fileName = path.basename(pathToSource);
var newPathToDestination;
if (typeof pathToDestinationFile === 'undefined') {
newPathToDestination = pathToSource;
} else {
n... | javascript | {
"resource": ""
} |
q54359 | fixHeaders | train | function fixHeaders(contents) {
contents = contents.replace(/x-poedit-keywordslist:/i, 'X-Poedit-KeywordsList:');
contents = contents.replace(/x-poedit-searchpath-/ig, 'X-Poedit-SearchPath-');
contents = contents.replace(/x-poedit-searchpathexcluded-/ig, 'X-Poedit-SearchPathExcluded-');
contents = contents.repl... | javascript | {
"resource": ""
} |
q54360 | normalizeForComparison | train | function normalizeForComparison(pot) {
var clone = _.cloneDeep(pot);
if (!pot) {
return pot;
}
// Normalize the content type case.
clone.headers['content-type'] = clone.headers['content-type'].toLowerCase();
// Blank out the dates.
clone.headers['pot-creation-date'] = '';
clone.headers['po-revisi... | javascript | {
"resource": ""
} |
q54361 | Pot | train | function Pot(filename) {
if (! (this instanceof Pot)) {
return new Pot(filename);
}
this.isOpen = false;
this.filename = filename;
this.contents = '';
this.initialDate = '';
this.fingerprint = '';
} | javascript | {
"resource": ""
} |
q54362 | train | function(file, args) {
return new Promise(function(resolve, reject) {
var child = spawn(file, args, { stdio: 'inherit' });
child.on('error', reject);
child.on('close', resolve);
});
} | javascript | {
"resource": ""
} | |
q54363 | updatePoFiles | train | function updatePoFiles(filename, pattern) {
var merged = [];
var searchPath = path.dirname(filename);
pattern = pattern || '*.po';
glob.sync(pattern, {
cwd: path.dirname(filename)
}).forEach(function(file) {
var poFile = path.join(searchPath, file);
merged.push(mergeFiles(filename, poFile));
}... | javascript | {
"resource": ""
} |
q54364 | guessSlug | train | function guessSlug(wpPackage) {
var directory = wpPackage.getPath();
var slug = path.basename(directory);
var slug2 = path.basename(path.dirname(directory));
if ('trunk' === slug || 'src' === slug) {
slug = slug2;
} else if (-1 !== ['branches', 'tags'].indexOf(slug2)) {
slug = path.basename(path.dirn... | javascript | {
"resource": ""
} |
q54365 | findMainFile | train | function findMainFile(wpPackage) {
if (wpPackage.isType('wp-theme')) {
return 'style.css';
}
var found = '';
var pluginFile = guessSlug(wpPackage) + '.php';
var filename = wpPackage.getPath(pluginFile);
// Check if the main file exists.
if (util.fileExists(filename) && wpPackage.getHeader('Plugin Na... | javascript | {
"resource": ""
} |
q54366 | WPPackage | train | function WPPackage(directory, type) {
if (!(this instanceof WPPackage)) {
return new WPPackage(directory, type);
}
this.directory = null;
this.domainPath = null;
this.mainFile = null;
this.potFile = null;
this.type = 'wp-plugin';
this.initialize(directory, type);
} | javascript | {
"resource": ""
} |
q54367 | train | function(o) {
for (i in o) {
if (!!o[i] && typeof(o[i]) == "object") {
if (!o[i].length && o[i].type === 'tag') {
nodeCount += 1;
o[i]._id = nodeCount;
}
traverseIds(o[i]);
}
}
} | javascript | {
"resource": ""
} | |
q54368 | GitkitClient | train | function GitkitClient(options) {
this.widgetUrl = options.widgetUrl;
this.maxTokenExpiration = 86400 * 30; // 30 days
this.audiences = [];
if (options.projectId !== undefined) {
this.audiences.push(options.projectId);
}
if (options.clientId !== undefined) {
this.audiences.push(options.clientId);
}... | javascript | {
"resource": ""
} |
q54369 | getStudySetup | train | async function getStudySetup() {
// shallow copy
const studySetup = Object.assign({}, baseStudySetup);
studySetup.allowEnroll = await cachingFirstRunShouldAllowEnroll(studySetup);
const testingOverrides = await browser.study.getTestingOverrides();
studySetup.testing = {
variationName: testingOverrides.v... | javascript | {
"resource": ""
} |
q54370 | sendTelemetry | train | async function sendTelemetry(payload) {
utilsLogger.debug("called sendTelemetry payload");
function throwIfInvalid(obj) {
// Check: all keys and values must be strings,
for (const k in obj) {
if (typeof k !== "string")
throw new ExtensionError(`... | javascript | {
"resource": ""
} |
q54371 | onEveryExtensionLoad | train | async function onEveryExtensionLoad() {
new StudyLifeCycleHandler();
const studySetup = await getStudySetup();
await browser.study.logger.log(["Study setup: ", studySetup]);
await browser.study.setup(studySetup);
} | javascript | {
"resource": ""
} |
q54372 | createLogger | train | function createLogger(prefix, maxLogLevelPref, maxLogLevel = "warn") {
const ConsoleAPI = ChromeUtils.import(
"resource://gre/modules/Console.jsm",
{},
).ConsoleAPI;
return new ConsoleAPI({
prefix,
maxLogLevelPref,
maxLogLevel,
});
} | javascript | {
"resource": ""
} |
q54373 | train | function(csv, options) {
// cache settings
var separator = options.separator;
var delimiter = options.delimiter;
// set initial state if it's missing
if(!options.state.rowNum) {
options.state.rowNum = 1;
}
if(!options.state.colNum) {
o... | javascript | {
"resource": ""
} | |
q54374 | train | function(t,i,isOver){
var inc = drag.x-drag.l, c = t.c[i], c2 = t.c[i+1];
var w = c.w + inc; var w2= c2.w- inc; //their new width is obtained
c.width( w + PX); c2.width(w2 + PX); //and set
t.cg.eq(i).width( w + PX); t.cg.eq(i+1).width( w2 + PX);
if(isOver){c.w=w; c2.w=w2;}
} | javascript | {
"resource": ""
} | |
q54375 | train | function(e){
d.unbind('touchend.'+SIGNATURE+' mouseup.'+SIGNATURE).unbind('touchmove.'+SIGNATURE+' mousemove.'+SIGNATURE);
$("head :last-child").remove(); //remove the dragging cursor style
if(!drag) return;
drag.removeClass(drag.t.opt.draggingClass); //remove the grip's dragging css-class
var t = d... | javascript | {
"resource": ""
} | |
q54376 | train | function(){
for(t in tables){
var t = tables[t], i, mw=0;
t.removeClass(SIGNATURE); //firefox doesnt like layout-fixed in some cases
if (t.w != t.width()) { //if the the table's width has changed
t.w = t.width(); //its new value is kept
for(i=0; i<t.ln; i++) mw+= t.c[i].w; //t... | javascript | {
"resource": ""
} | |
q54377 | train | function(oSettings) {
//trick to show row numbers
for (var i = 0; i < oSettings.aiDisplay.length; i++) {
$("td:eq(0)", oSettings.aoData[oSettings.aiDisplay[i]].nTr).html(i + 1);
}
//Hide pagination when we have a single page
var activePaginateButton = false;
$(oSettings.nTab... | javascript | {
"resource": ""
} | |
q54378 | getLayers | train | function getLayers(elements) {
if (elements.length === 0) {
return [[""]];
}
const layers = [];
layers.push(elements);
while (layers[layers.length - 1].length > 1) {
layers.push(getNextLayer(layers[layers.length - 1]));
}
return layers;
} | javascript | {
"resource": ""
} |
q54379 | getProof | train | function getProof(index, layers) {
let i = index;
const proof = layers.reduce((current, layer) => {
const pair = getPair(i, layer);
if (pair) {
current.push(pair);
}
i = Math.floor(i / 2); // finds the index of the parent of the current node
return current;
}, []);
return proof;
} | javascript | {
"resource": ""
} |
q54380 | containsMultipartFormData | train | function containsMultipartFormData(api) {
if (_.includes(api.consumes, 'multipart/form-data')) {
return true;
}
var foundMultipartData = false;
_.forEach(_.keys(api.paths), function (path) {
var pathData = api.paths[path];
_.forEach(_.keys(pathData), function (method) {
... | javascript | {
"resource": ""
} |
q54381 | handleMulterConfig | train | function handleMulterConfig(multerConfig, logger, serviceLoader) {
// Special handling of storage
var storageString = _.get(multerConfig, 'storage');
if (storageString) {
var multerStorage;
if (storageString === MULTER_MEMORY_STORAGE) {
// simple memory storage
logger... | javascript | {
"resource": ""
} |
q54382 | setDefaultQueryParams | train | function setDefaultQueryParams(req, data, logger) {
var parameters = _.toArray(data.parameters);
for (var i = 0; i < parameters.length; i++) {
var parm = parameters[i];
if (parm.in === 'query') {
if (!_.isUndefined(parm.default) && _.isUndefined(req.query[parm.name])) {
... | javascript | {
"resource": ""
} |
q54383 | train | function(callback) {
var toInit = ['config', 'logger'];
loader.loadServices(path.resolve(serverRoot, 'services'));
injectDependencies(loader);
loader.init(toInit, function(err) {
callback(err);
});
} | javascript | {
"resource": ""
} | |
q54384 | injectDependencies | train | function injectDependencies(serviceLoader) {
var EventEmitter = require('events').EventEmitter;
serviceLoader.inject('events', new EventEmitter());
//inject itself so that services can directly use the service loader
serviceLoader.inject('serviceLoader', serviceLoader);
//app will be injected by ... | javascript | {
"resource": ""
} |
q54385 | train | function (err) {
var message = {cmd: 'startupComplete', pid: process.pid};
if (err) {
console.warn(err.stack);
message.error = err.message;
}
process.send(message);
} | javascript | {
"resource": ""
} | |
q54386 | setAuthCodeOnReq | train | function setAuthCodeOnReq(req, res, next) {
if (req.query.code) {
req.code = req.query.code;
debug('Found auth code %s on query param', req.code);
return next();
}
//look for something like {"code": "..."}
if (req.body.code) {
req.code = req.body.code;
debug('Fou... | javascript | {
"resource": ""
} |
q54387 | authCodeCallback | train | function authCodeCallback(req, res, next) {
var code = req.code;
if (!code) {
return res.status(400).send('Missing auth code');
}
var tokenData = {
code: code,
client_id: _cfg.clientId,
client_secret: _cfg.clientSecret,
grant_type: 'authorization_code',
r... | javascript | {
"resource": ""
} |
q54388 | signOutUser | train | function signOutUser(req, res, next) {
debug('Signing out user');
//make a best attempt effort at revoking the tokens
var accessToken = req.session.auth ? req.session.auth.access_token: null;
var refreshToken = req.session.auth ? req.session.auth.refresh_token: null;
if (accessToken) {
debug... | javascript | {
"resource": ""
} |
q54389 | getToken | train | function getToken(data, callback) {
request.post({url: TOKEN_URL, form: data}, function (err, resp, body) {
//this would be something like a connection error
if (err) {
return callback({statusCode: 500, message: err.message});
}
if (resp.statusCode !== 200) { /... | javascript | {
"resource": ""
} |
q54390 | train | function (key, callback) {
return client.get(key, function (err, result) {
return callback(err, result);
});
} | javascript | {
"resource": ""
} | |
q54391 | fetchUnmetDependencies | train | function fetchUnmetDependencies() {
var runAgain = false;
for (var id in dependencyMap) {
_.forEach(dependencyMap[id], function (depId) {
if (!dependencyMap[depId] && !injectedMap[depId]) {
try {
loadExternalModule(id, depId);
... | javascript | {
"resource": ""
} |
q54392 | train | function (dir, failOnDups) {
debug('Loading services from %s', dir);
di.iterateOverJsFiles(dir, function(dir, file) {
var modPath = path.resolve(dir, file);
var mod;
try {
mod = subRequire(modPath); //subRequire inserts the _id ... | javascript | {
"resource": ""
} | |
q54393 | train | function() {
var loader = this;
return {
//callback is optional, but will guarantee module was initialized
get: function(name, callback) {
if (!_.isString(name)) {
debug('To get a registered service, the service name mus... | javascript | {
"resource": ""
} | |
q54394 | loadFromIndividualConfigFile | train | function loadFromIndividualConfigFile(key) {
key = _.replace(key, /\/|\\/g, ''); //forward and backslashes are unsafe when resolving filenames
if (individualKeyCache[key]) {
return individualKeyCache[key];
} else {
var toLoad = path.resolve(global.__appDir, 'config/' + key + '.json');
... | javascript | {
"resource": ""
} |
q54395 | getLocation | train | function getLocation() {
var trace = stackTrace.get();
//trace.forEach(function(e){
// console.log('mytrace: ' + e.getFileName());
//});
//use (start at) index 2 because 0 is the call to getLocation, and 1 is the call to logger
// However, component loggers put an extra level in, so search... | javascript | {
"resource": ""
} |
q54396 | isBlueoakProject | train | function isBlueoakProject() {
if ((path.basename(global.__appDir) !== 'server')) {
return false;
}
try {
return fs.statSync(path.resolve(global.__appDir, '../common/swagger')).isDirectory();
} catch (err) {
return false;
}
} | javascript | {
"resource": ""
} |
q54397 | containsEncryptedData | train | function containsEncryptedData(obj) {
var foundEncrypted = false;
if (_.isString(obj)) {
foundEncrypted = isEncrypted(obj);
} else if (_.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
foundEncrypted = foundEncrypted || containsEncryptedData(obj[i]);
}
} else i... | javascript | {
"resource": ""
} |
q54398 | decryptObject | train | function decryptObject(obj, decryptFunction) {
if (_.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (_.isString(obj[i])) {
if (isEncrypted(obj[i])) {
obj[i] = decryptFunction(obj[i]);
}
} else {
decryptObj... | javascript | {
"resource": ""
} |
q54399 | collectStats | train | function collectStats(callback) {
var serviceStats = {};
var services = loader.listServices();
async.each(services, function(service, callback) {
var mod = loader.get(service);
if (mod.stats) { //does it have a stats function?
invokeStatsOnMod(mod, function(err, data) {
... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.