_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q39000 | train | function () {
var order = [],
el,
children = this.el.children,
i = 0,
n = children.length,
options = this.options;
for (; i < n; i++) {
el = children[i];
if (_closest(el, options.draggable, this.el)) {
order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
}
}
return order;
} | javascript | {
"resource": ""
} | |
q39001 | train | function (order) {
var items = {}, rootEl = this.el;
this.toArray().forEach(function (id, i) {
var el = rootEl.children[i];
if (_closest(el, this.options.draggable, rootEl)) {
items[id] = el;
}
}, this);
order.forEach(function (id) {
if (items[id]) {
rootEl.removeChild(items[id]);
rootEl.appendChild(items[id]);
}
});
} | javascript | {
"resource": ""
} | |
q39002 | _index | train | function _index(/**HTMLElement*/el) {
var index = 0;
while (el && (el = el.previousElementSibling)) {
if (el.nodeName.toUpperCase() !== 'TEMPLATE') {
index++;
}
}
return index;
} | javascript | {
"resource": ""
} |
q39003 | setaddall | train | function setaddall(set, iterable) {
var changed = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = iterable[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var element = _step.value;
changed |= (0, _setadd.default)(set, element);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return changed;
} | javascript | {
"resource": ""
} |
q39004 | getName | train | function getName(name) {
const ext = path.extname(name);
const nameCrypt = crypto.createHash('sha1')
.update(name)
.digest('hex') + ext;
return getDir() + nameCrypt;
} | javascript | {
"resource": ""
} |
q39005 | train | function(password, salt) {
var hash = npm_crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
hash.update(password);
var value = hash.digest('hex');
return {
salt: salt,
passwordHash: value
};
} | javascript | {
"resource": ""
} | |
q39006 | writeFileUtf8 | train | function writeFileUtf8 (filePath, content, callback) {
// Argument callback defaults to throwError.
if (typeof callback !== 'function') callback = throwError
if (typeof content === 'string') {
fs.writeFile(filePath, content, 'utf8', callback)
} else {
throw TypeError(error.contentIsNotString)
}
} | javascript | {
"resource": ""
} |
q39007 | train | function (stream) {
var self = this;
stream.on('data', function (chunk) {
self.push(chunk);
});
stream.on('end', function () {
self.push(null);
});
this.readableUnit = stream;
return this;
} | javascript | {
"resource": ""
} | |
q39008 | buildPushManifest | train | function buildPushManifest (bundles, manifestFilename) {
const manifestableBundles = filter(bundles, bundle => bundle.module);
const bundlesByModuleId = chain(manifestableBundles)
.map(bundle => [ bundle.module.id, bundle ])
.fromPairs()
.value();
const bundleDepGraph = chain(manifestableBundles)
.map(bundle => {
const deepDependencyFilenames = map(bundle.module.deepDependencies,
dependency => bundlesByModuleId[dependency.id].dest
);
return [ bundle.dest, deepDependencyFilenames ];
})
.fromPairs()
.value();
const output = pushManifestPretty ?
JSON.stringify(bundleDepGraph, null, 2) :
JSON.stringify(bundleDepGraph);
return {
raw: output,
dest: manifestFilename
};
} | javascript | {
"resource": ""
} |
q39009 | checkCamelCase | train | function checkCamelCase(idNode) {
var reported = false;
var fakeContext = {
report: function() { reported = true; },
options: []
};
camelcase(fakeContext).Identifier(idNode); // eslint-disable-line new-cap
return !reported;
} | javascript | {
"resource": ""
} |
q39010 | checkSemanticActionName | train | function checkSemanticActionName(node) {
var name = node.name;
var underscoreIdx = name.indexOf('_');
// The underscore should not appear on the ends,
// case names should begin with a lowercase letter,
// and there should be only one underscore in the name.
if ((underscoreIdx > 0 && underscoreIdx < (name.length - 1)) &&
name[underscoreIdx + 1] === name[underscoreIdx + 1].toLowerCase() &&
name.indexOf('_', underscoreIdx + 1) === -1) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q39011 | setAttribute | train | function setAttribute(element, name, value) {
assertType(element, Node, false, 'Invalid element specified');
if (value === undefined || value === null || value === false)
element.removeAttribute(name);
else if (value === true)
element.setAttribute(name, '');
else
element.setAttribute(name, value);
if (name === 'disabled' && element.setDirty)
element.setDirty(DirtyType.STATE);
} | javascript | {
"resource": ""
} |
q39012 | DisplayObject | train | function DisplayObject()
{
EventEmitter.call(this);
/**
* The coordinate of the object relative to the local coordinates of the parent.
*
* @member {Point}
*/
this.position = new math.Point();
/**
* The scale factor of the object.
*
* @member {Point}
*/
this.scale = new math.Point(1, 1);
/**
* The pivot point of the displayObject that it rotates around
*
* @member {Point}
*/
this.pivot = new math.Point(0, 0);
/**
* The rotation of the object in radians.
*
* @member {number}
*/
this.rotation = 0;
/**
* The opacity of the object.
*
* @member {number}
*/
this.alpha = 1;
/**
* The visibility of the object. If false the object will not be drawn, and
* the updateTransform function will not be called.
*
* @member {boolean}
*/
this.visible = true;
/**
* Can this object be rendered, if false the object will not be drawn but the updateTransform
* methods will still be called.
*
* @member {boolean}
*/
this.renderable = true;
/**
* The display object container that contains this display object.
*
* @member {Container}
* @readOnly
*/
this.parent = null;
/**
* The multiplied alpha of the displayObject
*
* @member {number}
* @readOnly
*/
this.worldAlpha = 1;
/**
* Current transform of the object based on world (parent) factors
*
* @member {Matrix}
* @readOnly
*/
this.worldTransform = new math.Matrix();
/**
* The area the filter is applied to. This is used as more of an optimisation
* rather than figuring out the dimensions of the displayObject each frame you can set this rectangle
*
* @member {Rectangle}
*/
this.filterArea = null;
/**
* cached sin rotation
*
* @member {number}
* @private
*/
this._sr = 0;
/**
* cached cos rotation
*
* @member {number}
* @private
*/
this._cr = 1;
/**
* The original, cached bounds of the object
*
* @member {Rectangle}
* @private
*/
this._bounds = new math.Rectangle(0, 0, 1, 1);
/**
* The most up-to-date bounds of the object
*
* @member {Rectangle}
* @private
*/
this._currentBounds = null;
/**
* The original, cached mask of the object
*
* @member {Rectangle}
* @private
*/
this._mask = null;
//TODO rename to _isMask
// this.isMask = false;
/**
* Cached internal flag.
*
* @member {boolean}
* @private
*/
this._cacheAsBitmap = false;
this._cachedObject = null;
} | javascript | {
"resource": ""
} |
q39013 | loadReporter | train | function loadReporter(reporterPath) {
var reporter;
reporterPath = reporterPath || 'checkstyle';
if (!fs.existsSync(path.resolve(reporterPath))) {
try {
reporter = require('./lib/reporters/' + reporterPath);
} catch (e) {
try {
reporter = require('jscs/lib/reporters/' + reporterPath);
}
catch (e) {
reporter = null;
}
}
} else {
try {
reporter = require(path.resolve(reporterPath));
} catch (e) {
reporter = null;
}
}
return reporter;
} | javascript | {
"resource": ""
} |
q39014 | generateRandomString | train | function generateRandomString(length) {
let s = "";
let i = length;
while (length-- > 0) {
let c = Math.floor(Math.random() * (MAX_HEX_SYMBOL - MIN_HEX_SYMBOL + 1)) + MIN_HEX_SYMBOL;
c = c.toString(16).toLowerCase();
s += c;
}
return s;
} | javascript | {
"resource": ""
} |
q39015 | send | train | function send() {
'use strict';
var req = new XMLHttpRequest(),
specs = jsApiReporter.specs(),
payload;
if (specs.length) {
specs.push(logs);
}
payload = JSON.stringify(specs);
req.open('post', 'http://localhost:' + port + '/put', true);
req.onload = function () {
if (this.responseText === 'kill') {
chrome.app.window.current().close();
}
};
req.send(payload);
} | javascript | {
"resource": ""
} |
q39016 | train | function(name) {
// "name" encapsulates some simple options like precision
rgen.random = rgen.algorithms[name].random;
rgen.setSeed = rgen.algorithms[name].setSeed;
return rgen.setRandomSeed();
} | javascript | {
"resource": ""
} | |
q39017 | validate | train | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var value = parseInt('' + args[2]);
if(value !== 0 && value !== 1) throw InvalidBit;
args[2] = value;
} | javascript | {
"resource": ""
} |
q39018 | tokenizeText | train | function tokenizeText(text, callback) {
"use strict";
processTokens(tokenizer.tokenize(text) || [], function (error, tokens) {
process.nextTick(function () {
callback(error, tokens);
});
});
} | javascript | {
"resource": ""
} |
q39019 | load | train | function load(mod) {
var base = path.dirname(mod.filename);
var folders = [].slice.call(arguments, 1);
return function refractory() {
var files = [].slice.call(arguments);
var paths = [];
files
.map(function(file) {
return path.basename(file);
})
.forEach(function(file) {
folders.forEach(function(folder) {
folder = parsePaths(folder);
folder = path.resolve(base, folder);
paths.push(path.join(folder, file));
});
paths.push(file);
});
for (var i = 0, len = paths.length; i < len; i++) {
try {
return require(paths[i]);
} catch (err) {
if (err.code != MODULE_NOT_FOUND) throw err;
}
}
var err = new Error("Couldn't load file(s): \"" + files.join(', ') + '"');
err.code = MODULE_NOT_FOUND;
err.paths = paths;
throw err;
};
} | javascript | {
"resource": ""
} |
q39020 | SpriteMaskFilter | train | function SpriteMaskFilter(sprite)
{
var maskMatrix = new math.Matrix();
AbstractFilter.call(this,
fs.readFileSync(__dirname + '/spriteMaskFilter.vert', 'utf8'),
fs.readFileSync(__dirname + '/spriteMaskFilter.frag', 'utf8'),
{
mask: { type: 'sampler2D', value: sprite._texture },
alpha: { type: 'f', value: 1},
otherMatrix: { type: 'mat3', value: maskMatrix.toArray(true) }
}
);
this.maskSprite = sprite;
this.maskMatrix = maskMatrix;
} | javascript | {
"resource": ""
} |
q39021 | hasPrettier | train | function hasPrettier() {
if (hasPrettierCache === true || hasPrettierCache === false) {
return hasPrettierCache
}
hasPrettierCache = false
try {
const requireOptions = { paths: [getRootPath()] }
const manifestPath = require.resolve('./package.json', requireOptions)
const manifest = JSON.parse(fs.readFileSync(manifestPath).toString())
if ((manifest.devDependencies && manifest.devDependencies.prettier) || (manifest.dependencies && manifest.dependencies.prettier)) {
if (require.resolve('prettier', requireOptions)) {
hasPrettierCache = true
}
}
} catch (e) {
// Ignore error
}
return hasPrettierCache
} | javascript | {
"resource": ""
} |
q39022 | wrapNodeSocket | train | function wrapNodeSocket(ws, reportError) {
// Data traveling from websocket to consumer
var incoming = makeChannel();
// Data traveling from consumer to websocket
var outgoing = makeChannel();
onTake = wrapHandler(onTake, onError);
outgoing.take(onTake);
ws.onerror = onError;
ws.onmessage = wrap(onMessage, onError);
ws.onclose = wrap(onClose, onError);
function onError(err) {
if (reportError) return reportError(err);
console.error(err.stack);
}
function onMessage(evt) {
if (evt.data instanceof ArrayBuffer) {
incoming.put(new Uint8Array(evt.data));
}
}
function onClose(evt) {
incoming.put();
}
function onTake(data) {
// console.log("TAKE", data);
if (data === undefined) {
ws.close();
return;
}
ws.send(data);
outgoing.take(onTake);
}
return {
put: outgoing.put,
drain: outgoing.drain,
take: incoming.take,
};
} | javascript | {
"resource": ""
} |
q39023 | search | train | function search(user, pass, userArray) {
return _.findWhere(userArray, { user: user, pass: pass });
} | javascript | {
"resource": ""
} |
q39024 | ask | train | function ask(question, cbk, skip) {
if (skip) {
cbk(skip);
return;
}
self.prompt(question, function(answ) {
if (String(answ.answer).trim() === "") {
return ask(question, cbk);
} else {
cbk(answ.answer);
}
});
} | javascript | {
"resource": ""
} |
q39025 | gather | train | function gather(cbk) {
ask(questions[0], function(user) {
state.user = user;
ask(questions[1], function(pass){
state.pass = pass;
cbk(state.user, state.pass);
}, state.pass);
}, state.user);
} | javascript | {
"resource": ""
} |
q39026 | attempt | train | function attempt() {
connections[id].attempts++;
if (connections[id].attempts > retry) {
connections[id].attempts = 0;
connections[id].deny++;
self.log(chalk.yellow("Access denied: too many attempts."));
callback("Access denied: too many attempts.", false);
return;
}
if (connections[id].deny >= deny && unlockTime > 0) {
setTimeout(function(){
connections[id].deny = 0;
}, unlockTime);
connections[id].attempts = 0;
self.log(chalk.yellow("Account locked out: too many login attempts."));
callback("Account locked out: too many login attempts.", false);
return;
}
gather(function(user, pass){
user = search(user, pass, users);
if (user) {
connections[id].attempts = 0;
connections[id].deny = 0;
callback("Successfully Authenticated.", true);
} else {
state.pass = void 0;
setTimeout(function(){
if (connections[id].attempts <= retry) {
self.log("Access denied.");
}
attempt();
}, retryTime);
}
});
} | javascript | {
"resource": ""
} |
q39027 | sendAlertEmail | train | function sendAlertEmail(alertEmailData, cb) {
var mongoAlert = alertEmailData.alert;
var eventDetails = alertEmailData.eventDetails;
var emailConfig = config.getConfig().email;
var from = emailConfig ? emailConfig.alert_email_from : 'noreply@feedhenry.com';
fs.readFile(ALERT_EMAIL_TEMPLATE, function(err, data) {
if (err) {
return cb({
'error': 'Could not load email template from "' + ALERT_EMAIL_TEMPLATE + '": ' + err
});
}
var emailBody = data.toString();
emailBody = emailBody.replace(/%appName%/g, eventDetails.appName || "");
emailBody = emailBody.replace(/%appGuid%/g, eventDetails.uid);
emailBody = emailBody.replace(/%appUrl%/g, ' ');
emailBody = emailBody.replace(/%alertName%/g, mongoAlert.alertName);
emailBody = emailBody.replace(/%eventTimestamp%/g, eventDetails.timestamp);
emailBody = emailBody.replace(/%updatedBy%/g, eventDetails.updatedBy);
emailBody = emailBody.replace(/%eventMessage%/g, eventDetails.details.message);
emailBody = emailBody.replace(/%eventCategory%/g, eventDetails.eventClass);
emailBody = emailBody.replace(/%eventName%/g, eventDetails.eventType);
emailBody = emailBody.replace(/%eventSeverity%/g, eventDetails.eventLevel);
emailBody = emailBody.replace(/%eventDetails%/g, JSON.stringify(eventDetails.details));
emailBody = emailBody.replace(/%providerName%/g, from);
getTransport(emailConfig).sendMail({
from: from,
to: mongoAlert.emails,
subject: 'Alert Name: ' + mongoAlert.alertName + ' - Cloud App (' + mongoAlert.uid + ')',
html: emailBody
}, cb);
});
} | javascript | {
"resource": ""
} |
q39028 | createRule | train | function createRule(path, handler) {
if ('*' !== path && 0 != path.indexOf(watch.__base)) {
path = watch.__base + (path == '/' ? '' : path)
}
let rule = pathToRegExp(path)
if (handler instanceof String) {
let target = handler
handler = function() {
watch({
url: target
})
}
}
rule.handler = handler
return rule
} | javascript | {
"resource": ""
} |
q39029 | initialize | train | function initialize(done) {
debug('prepare');
parser(options.index, options, function(err, modules) {
if(err) return done(err)
debug('Parser return, now build the tree...');
tree = buildTree(options, modules, true);
debug('Tree builded');
// Extract from tree as a flatten list of packets to compile
packets = tree.getAllBundles(options);
done(null);
})
} | javascript | {
"resource": ""
} |
q39030 | tokenizeWord | train | function tokenizeWord(word, callback) {
"use strict";
var match, parts = [], stemmedPart, singularPart, singularMetaphones, stemmedMetaphones, token;
// TODO: Improve that. Should be in the stemmer actually
//if (-1 === (match = word.match(/^([#"',;:!?(.\[{])*([a-z0-9]+)+([,;:!?)\]}"'.])*$/i))) {
// return callback(null, []);
//}
//if (!match) {
// return callback(null, []);
//}
//word = match[2] || "";
word = word || "";
if (-1 === word.search(/^[a-z]*$/i) || word.length < 3) {
return callback(null, []);
}
token = word.toUpperCase().trim();
// TODO: Decide which stopwords to use depending on the given language
var stopwordsEn = stopwords.en;
// we skip stopwords
if (stopwordsEn.indexOf(token) >= 0) {
return callback(null, []);
}
parts.push(token);
// TODO: Decide which stemmer to use depending on the given language
stemmedPart = stemmer.stem(token) || "";
if (stemmedPart.length > 2) {
// calc double metaphone of the stemmed word
stemmedMetaphones = doubleMetaphone.process(stemmedPart);
//console.log("stemmed Metaphones for " + token + " " + stemmedMetaphones);
if (stemmedMetaphones[0].length > 1) {
parts.push((stemmedMetaphones[0] || "").trim());
}
if (stemmedMetaphones[1].length > 1) {
parts.push((stemmedMetaphones[1] || "").trim());
}
}
// the last element is the original uppercased stemmed token
parts.push(stemmedPart.toUpperCase().trim());
// Singularize word
singularPart = nounInflector.singularize(token) || "";
if (singularPart.length > 2) {
// calc double metaphone of singular
singularMetaphones = doubleMetaphone.process(singularPart);
//console.log("singular Metaphones for " + token + " " + stemmedMetaphones);
if (singularMetaphones[0].length > 1) {
parts.push((singularMetaphones[0] || "").trim());
}
if (singularMetaphones[1].length > 1) {
parts.push((singularMetaphones[1] || "").trim());
}
}
parts.push(singularPart.toUpperCase().trim());
parts.sort();
parts = underscore.uniq(parts, true);
process.nextTick(function () {
callback(null, parts);
});
} | javascript | {
"resource": ""
} |
q39031 | train | function (ordered) {
var self = this;
if (ordered) {
return self.fetch();
} else {
var results = new LocalCollection._IdMap;
self.forEach(function (doc) {
results.set(doc._id, doc);
});
return results;
}
} | javascript | {
"resource": ""
} | |
q39032 | train | function(arg) {
readOnly(this, ID, COUNT++);
readOnly(this, "_listeners", new Listeners());
readOnly(this, "_links", []);
// An object with the attribute `isContentChangeAware === true`
// can fire a property value changed when its contant has change.
readOnly(this, "isContentChangeAware", true);
if (Array.isArray(arg)) {
readOnly(this, "_array", arg);
} else if (isList(arg)) {
readOnly(this, "_array", arg._array);
this.link(arg);
} else {
readOnly(this, "_array", [arg]);
}
} | javascript | {
"resource": ""
} | |
q39033 | Stats | train | function Stats(state) {
this.state = state;
this.clear();
this.onConnect = onConnect.bind(this);
this.onDisconnect = onDisconnect.bind(this);
this.onRejected = onRejected.bind(this);
this.onHit = onHit.bind(this);
this.onMiss = onMiss.bind(this);
this.onExpired = onExpired.bind(this);
this.onExpired = onExpired.bind(this);
this.addStateListeners();
} | javascript | {
"resource": ""
} |
q39034 | train | function(error) {
if (!error.stack) return error.message;
var stack = error.stack;
var firstLine = stack.substring(0, stack.indexOf('\n'));
if (error.message && firstLine.indexOf(error.message) === -1) stack = error.message + '\n' + stack;
return stack.replace(/\n.+\/adapter(\/lib)?\/hydro.js\?\d*\:.+(?=(\n|$))/g, '');
} | javascript | {
"resource": ""
} | |
q39035 | defaults | train | function defaults(defs,opts) {
if (!opts)
opts = {}
if (opts.context == null)
opts.context = true;
if (opts.coerce == null)
opts.coerce = true;
completeMonad(defs);
if (opts.control === "token")
defs = M.addControlByToken(defs);
if (opts.wrap)
defs = M.wrap(defs,opts.wrap);
if (opts.coerce)
defs = M.addCoerce(defs);
if (opts.context)
defs = M.addContext(defs, opts.context === "run");
if (opts.wrap)
M.completePrototype(defs,opts.wrap.prototype);
return defs;
} | javascript | {
"resource": ""
} |
q39036 | liftContext | train | function liftContext(ctx, func) {
if (!ctx.pure) {
throw new Error("no monad's definition is provided");
}
return function() {
var saved;
saved = context;
context = ctx;
try {
return func.apply(null, arguments);
} finally {
context = saved;
}
};
} | javascript | {
"resource": ""
} |
q39037 | liftContextG | train | function liftContextG(ctx, gen) {
return liftContext(ctx, function() {
return liftContextIterator(ctx, gen.apply(null, arguments));
});
} | javascript | {
"resource": ""
} |
q39038 | Config | train | function Config(options) {
if (!(this instanceof Config)) {
return new Config(options);
}
utils.is(this, 'config');
use(this);
define(this, 'count', 0);
this.options = options || {};
this.targets = {};
this.tasks = {};
if (utils.isConfig(options)) {
this.options = {};
this.expand(options);
return this;
}
} | javascript | {
"resource": ""
} |
q39039 | handler | train | function handler(req, next) {
var conf = this.configure();
var pkg = this.package();
var copyright = conf.copyright || (pkg ? pkg.copyright : null);
var opts = [this._version];
var msg = this._name + ' %s';
// NOTE: allows deferring to this handler from a custom handler
if(arguments.length > 1 && typeof(next) !== 'function') {
opts = opts.concat([].slice.call(arguments, 1));
}
opts.unshift(msg);
// respect vanilla help setting
if(conf.help.vanilla) {
opts = [util.format.apply(util, opts)];
}
console.log.apply(console, opts);
if(copyright) {
console.log();
copyright = '' + copyright;
copyright = wrap(copyright, 0, conf.help.maximum);
console.log(copyright);
}
if(conf.exit && req !== true) process.exit();
return false;
} | javascript | {
"resource": ""
} |
q39040 | _start | train | function _start() {
var now = Date.now();
var config = this._config;
var missing = !config ? required : required.filter(function(key) {
return config[key] === undefined;
});
if (missing.length) {
throw TypeError('Missing config properties: ' + missing.join(', '));
}
if (this._started) {
throw Error('Ticker already started');
}
this._started = now;
this._before = now - config.delay;
this._tick();
return this;
} | javascript | {
"resource": ""
} |
q39041 | _stop | train | function _stop() {
if (!this._started) {
throw Error('Ticker not started');
}
clearTimeout(this._timeout);
delete this._started;
delete this._before;
delete this._count;
if (this._config.stop) {
this._config.stop();
}
return this;
} | javascript | {
"resource": ""
} |
q39042 | _use | train | function _use(config) {
var _config = this._config;
Object.keys(config).forEach(function(key) {
_config[key] = config[key];
});
return this;
} | javascript | {
"resource": ""
} |
q39043 | _tick | train | function _tick() {
var config = this._config;
var now = Date.now();
var dt = now - this._before;
if (!this._started) {
// The ticker has been stopped
return;
}
if (config.async) {
config.task(this._tock, dt);
} else {
config.task(dt);
this._tock();
}
} | javascript | {
"resource": ""
} |
q39044 | _tock | train | function _tock() {
var config = this._config;
var now = Date.now();
var taskTime = now - this._started; // The time it took to finish the last task
var delay = Math.max(0, config.delay - (taskTime)); // Delay until the next task is run
if (config.limit) {
this._count += 1;
if (this._count >= config.limit) {
this.stop();
return;
}
}
this._before = this._started;
this._started = now + delay;
this._timeout = setTimeout(this._tick, delay);
} | javascript | {
"resource": ""
} |
q39045 | indexOfDeepestElement | train | function indexOfDeepestElement (elements) {
var dropzone,
deepestZone = elements[0],
index = deepestZone? 0: -1,
parent,
deepestZoneParents = [],
dropzoneParents = [],
child,
i,
n;
for (i = 1; i < elements.length; i++) {
dropzone = elements[i];
// an element might belong to multiple selector dropzones
if (!dropzone || dropzone === deepestZone) {
continue;
}
if (!deepestZone) {
deepestZone = dropzone;
index = i;
continue;
}
// check if the deepest or current are document.documentElement or document.rootElement
// - if the current dropzone is, do nothing and continue
if (dropzone.parentNode === dropzone.ownerDocument) {
continue;
}
// - if deepest is, update with the current dropzone and continue to next
else if (deepestZone.parentNode === dropzone.ownerDocument) {
deepestZone = dropzone;
index = i;
continue;
}
if (!deepestZoneParents.length) {
parent = deepestZone;
while (parent.parentNode && parent.parentNode !== parent.ownerDocument) {
deepestZoneParents.unshift(parent);
parent = parent.parentNode;
}
}
// if this element is an svg element and the current deepest is
// an HTMLElement
if (deepestZone instanceof HTMLElement
&& dropzone instanceof SVGElement
&& !(dropzone instanceof SVGSVGElement)) {
if (dropzone === deepestZone.parentNode) {
continue;
}
parent = dropzone.ownerSVGElement;
}
else {
parent = dropzone;
}
dropzoneParents = [];
while (parent.parentNode !== parent.ownerDocument) {
dropzoneParents.unshift(parent);
parent = parent.parentNode;
}
n = 0;
// get (position of last common ancestor) + 1
while (dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) {
n++;
}
var parents = [
dropzoneParents[n - 1],
dropzoneParents[n],
deepestZoneParents[n]
];
child = parents[0].lastChild;
while (child) {
if (child === parents[1]) {
deepestZone = dropzone;
index = i;
deepestZoneParents = [];
break;
}
else if (child === parents[2]) {
break;
}
child = child.previousSibling;
}
}
return index;
} | javascript | {
"resource": ""
} |
q39046 | train | function (pointer, event, eventTarget, curEventTarget, matches, matchElements) {
var target = this.target;
if (!this.prepared.name && this.mouse) {
var action;
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, [pointer]);
if (matches) {
action = this.validateSelector(pointer, event, matches, matchElements);
}
else if (target) {
action = validateAction(target.getAction(this.pointers[0], event, this, this.element), this.target);
}
if (target && target.options.styleCursor) {
if (action) {
target._doc.documentElement.style.cursor = getActionCursor(action);
}
else {
target._doc.documentElement.style.cursor = '';
}
}
}
else if (this.prepared.name) {
this.checkAndPreventDefault(event, target, this.element);
}
} | javascript | {
"resource": ""
} | |
q39047 | train | function (dragElement) {
// get dropzones and their elements that could receive the draggable
var possibleDrops = this.collectDrops(dragElement, true);
this.activeDrops.dropzones = possibleDrops.dropzones;
this.activeDrops.elements = possibleDrops.elements;
this.activeDrops.rects = [];
for (var i = 0; i < this.activeDrops.dropzones.length; i++) {
this.activeDrops.rects[i] = this.activeDrops.dropzones[i].getRect(this.activeDrops.elements[i]);
}
} | javascript | {
"resource": ""
} | |
q39048 | validateAction | train | function validateAction (action, interactable) {
if (!isObject(action)) { return null; }
var actionName = action.name,
options = interactable.options;
if (( (actionName === 'resize' && options.resize.enabled )
|| (actionName === 'drag' && options.drag.enabled )
|| (actionName === 'gesture' && options.gesture.enabled))
&& actionIsEnabled[actionName]) {
if (actionName === 'resize' || actionName === 'resizeyx') {
actionName = 'resizexy';
}
return action;
}
return null;
} | javascript | {
"resource": ""
} |
q39049 | delegateListener | train | function delegateListener (event, useCapture) {
var fakeEvent = {},
delegated = delegatedEvents[event.type],
eventTarget = getActualElement(event.path
? event.path[0]
: event.target),
element = eventTarget;
useCapture = useCapture? true: false;
// duplicate the event so that currentTarget can be changed
for (var prop in event) {
fakeEvent[prop] = event[prop];
}
fakeEvent.originalEvent = event;
fakeEvent.preventDefault = preventOriginalDefault;
// climb up document tree looking for selector matches
while (isElement(element)) {
for (var i = 0; i < delegated.selectors.length; i++) {
var selector = delegated.selectors[i],
context = delegated.contexts[i];
if (matchesSelector(element, selector)
&& nodeContains(context, eventTarget)
&& nodeContains(context, element)) {
var listeners = delegated.listeners[i];
fakeEvent.currentTarget = element;
for (var j = 0; j < listeners.length; j++) {
if (listeners[j][1] === useCapture) {
listeners[j][0](fakeEvent);
}
}
}
}
element = parentElement(element);
}
} | javascript | {
"resource": ""
} |
q39050 | modulePathToId | train | function modulePathToId(path) {
// We can only transform if there's no plugin used.
if (path.indexOf('!') === -1) {
// If it ends with ".js", chop it off.
var extension = '.js'
if (path.slice(-extension.length) === '.js') {
path = path.slice(0, path.length - extension.length);
}
}
return path;
} | javascript | {
"resource": ""
} |
q39051 | moduleSize | train | function moduleSize(id, paths) {
var path = id;
var extension = '.js';
// Use `paths:` to resolve an alias.
if (paths[id]) {
path = paths[id];
}
// Does the dependency reference a plugin?
if (path.indexOf('!') !== -1) {
// Split into plugin and path.
var pathParts = path.split('!');
// Often, the plugin maps to the extension it handles.
extension = '.' + pathParts[0];
path = pathParts[1];
}
// Try to get the file at the path.
var stats;
try {
stats = fs.statSync(path);
return stats['size'];
}
catch(e) {}
// Didn't find it? Let's try again with the extension added.
if (path.slice(-extension.length) !== extension) {
path = path + extension;
}
try {
stats = fs.statSync(path);
return stats['size'];
}
catch(e) {}
// Still didn't find the file.
return null;
} | javascript | {
"resource": ""
} |
q39052 | createHandler | train | function createHandler(options) {
/**
* Client request handler
* Data from the incoming request (plus options) is forwarded to the AWS module
*/
return async (ctx) => {
const { credentials, endpoint, region } = options
const { rawBody: body, header: headers, method, url: path } = ctx.request
console.log(chalk.cyan(method, path))
const params = { body, credentials, endpoint, headers, method, path, region }
const req = createSignedAWSRequest(params)
const res = await sendAWSRequest(req)
ctx.status = 200
ctx.type = 'application/json'
ctx.response.header = stripProxyResHeaders(res)
ctx.body = res.body
}
} | javascript | {
"resource": ""
} |
q39053 | getInitOptions | train | async function getInitOptions(args) {
const { debug, endpoint, host, port, profile, region } = args
const options = { debug, host, port, profile, region }
options.endpoint = getAWSEndpoint({ endpoint })
options.credentials = await getAWSCredentials()
return options
} | javascript | {
"resource": ""
} |
q39054 | registerListeners | train | function registerListeners() {
const exit = function exit(signal) {
console.log(chalk.bgBlack.yellow(`Received ${signal} => Exiting`))
process.exit()
}
const SIGABRT = 'SIGABRT'
const SIGHUP = 'SIGHUP'
const SIGINT = 'SIGINT'
const SIGQUIT = 'SIGQUIT'
const SIGTERM = 'SIGTERM'
process.on(SIGABRT, () => exit(SIGABRT))
process.on(SIGHUP, () => exit(SIGHUP))
process.on(SIGINT, () => exit(SIGINT))
process.on(SIGQUIT, () => exit(SIGQUIT))
process.on(SIGTERM, () => exit(SIGTERM))
} | javascript | {
"resource": ""
} |
q39055 | stripProxyResHeaders | train | function stripProxyResHeaders(res) {
return Object.entries(res.headers).reduce((memo, header) => {
const [key, val] = header
const invalid = [undefined, 'connection', 'content-encoding']
if (invalid.indexOf(key) === -1) {
memo[key] = val // eslint-disable-line
}
return memo
}, {})
} | javascript | {
"resource": ""
} |
q39056 | transfer | train | function transfer(xmlFiles, output, dir, needAppend, _callback){
/**
* If needAppend is true, output must be a file but not a directory
*/
Step(
function(){
if(typeof output === 'undefined'){
output = path.dirname(xmlFiles[0]);
}
output = output.indexOf(path.sep) === 0 ? output : path.join(process.cwd(), output);
fs.stat(output, this);
},
function(err, stat){
if(err){
throw err;
}
if(needAppend){
if(!stat.isFile()){
throw new Error('Output must be a file but not a directory when --append is enabled');
}
}else{
if(!stat.isDirectory()){
throw new Error('Output must be a directory');
}
output = path.join(output, 'nproxy-rule.js');
}
return output;
},
function transferBatch(err, outputFile){
var group;
if(err){
throw err;
}
group = this.group();
xmlFiles.forEach(function(xmlFile){
transferSingleFile(xmlFile, dir, group());
});
},
function append(err, rules){
var wrapperTpl;
var result;
var isTargetEmpty = true;
if(err){
throw err;
}
if(needAppend){
wrapperTpl = fs.readFileSync(output, 'utf-8');
isTargetEmpty = false;
}else{
wrapperTpl = [
'module.exports = [/*{{more}}*/',
'];'
].join(EOL);
}
return _append(wrapperTpl, rules, isTargetEmpty);
},
function writeOutput(err, content){
if(err){
throw err;
}
fs.writeFile(output,
content,
'utf-8', function(err){
if(err){ throw err};
log.info('Write output file successfully!');
if(typeof _callback === 'function'){
_callback(null);
}
});
}
);
} | javascript | {
"resource": ""
} |
q39057 | transferSingleFile | train | function transferSingleFile(sfXML, dir, callback){
var xmlParser;
var groups;
var responders = [];
var fileList = [];
var entry;
var responder;
var stat;
if(typeof sfXML === 'undefined'){
throw new Error('No input file specified');
}
if(!/\.xml$/.test(sfXML)){
throw new Error('Input file must be a xml file!');
}
sfXML = sfXML.indexOf(path.sep) === 0 ? sfXML : path.join(process.pwd, sfXML);
xmlParser = new xml2js.Parser();
fs.readFile(sfXML, function(err, xml){
if(err){ throw err; }
xmlParser.parseString(xml, function(err, result){
var groupParser = function(group){
var groupId;
var resources;
if(typeof group['$'] === 'undefined'){
return;
}
groupId = group['$']['id'];
if(typeof groupId !== 'undefined'){
resources = group['resource'];
entry = {
comment: '// pattern for ' + groupId,
pattern: groupId,
responder: {
dir: dir || 'fill the dir',
src: []
}
};
responder = entry.responder;
if(typeof resources === 'object' &&
typeof resources['$'] === 'object' &&
typeof resources['$']['uri'] === 'string'){
responder.src.push(resources['$']['uri']);
}
if(Array.isArray(resources)){
resources.forEach(function(resource){
if(typeof resource['$'] === 'object' &&
typeof resource['$']['uri'] === 'string'){
responder.src.push(resource['$']['uri']);
}
});
}
responders.push(entry);
}
}
groups = result.groupdefinition.groups[0].group;
if(Array.isArray(groups)){
groups.forEach(groupParser);
}else if(typeof groups === 'object'){
groupParser(groups);
}
});
_getRuleAsString(responders, callback);
});
} | javascript | {
"resource": ""
} |
q39058 | _getRuleAsString | train | function _getRuleAsString(responders, callback){
var respondersArr = [];
var respondersLen = responders.length;
var srcLen;
var fileStr;
responders.forEach(function(entry, i){
respondersArr.push(TAP + '{');
respondersArr.push(TAP + TAP + 'pattern: \'' + entry.pattern + '\',' + entry.comment);
respondersArr.push(TAP + TAP + 'responder: {');
respondersArr.push(TAP + TAP + TAP + 'dir: ' + '\'' + entry.responder.dir + '\',');
respondersArr.push(TAP + TAP + TAP + 'src: [');
srcLen = entry.responder.src.length;
entry.responder.src.forEach(function(file, j){
fileStr = TAP + TAP + TAP + TAP + '\'' + file + '\'';
if(j < srcLen - 1){
fileStr += ',';
}
respondersArr.push(fileStr);
});
respondersArr.push(TAP + TAP + TAP + ']');
respondersArr.push(TAP + TAP + '}');
if( i < respondersLen - 1){
respondersArr.push(TAP + '},');
}else{
respondersArr.push(TAP + '}');
}
});
if(typeof callback === 'function'){
callback(null, respondersArr.join(EOL));
}
} | javascript | {
"resource": ""
} |
q39059 | _append | train | function _append(target, rules, isTargetEmpty){
var concatedRules = [];
var rulesContent;
var l = rules.length;
rules.forEach(function(rule, i){
if(i < l - 1){
concatedRules.push(rule + ',');
}else{
concatedRules.push(rule + '/*{{more}}*/');
}
});
if(isTargetEmpty){
rulesContent = EOL + concatedRules.join(EOL);
}else{
rulesContent = ',' + EOL + concatedRules.join(EOL);
}
return target.replace(/\/\*{{more}}\*\//, rulesContent);
} | javascript | {
"resource": ""
} |
q39060 | end | train | function end() {
var group = stack.pop();
if (!requests) return;
var data = JSON.stringify(requests);
var dest = path.join(options.fixtures, group + '.json');
fs.writeFileSync(dest, data, 'utf8');
requests = null;
} | javascript | {
"resource": ""
} |
q39061 | recorder | train | function recorder(opts, fn) {
var group = stack[stack.length - 1];
var response = null;
assert(group, 'please specify copycat group');
recordings = load(group) || [];
recordings.forEach(function(recording) {
if (!deepEqual(recording.opts, opts)) return;
response = recording;
});
if (response) {
return fn(response.err, response.res, response.body);
}
request(opts, function(err, res, body) {
requests = requests || [];
requests.push({ opts: opts, err: err, res: res, body: body });
fn.apply(null, arguments);
});
} | javascript | {
"resource": ""
} |
q39062 | load | train | function load(group) {
var dest = path.join(options.fixtures, group + '.json');
var ret = null;
var json = null;
try {
json = fs.readFileSync(dest, 'utf8');
ret = JSON.parse(json);
} catch (err) {}
return ret;
} | javascript | {
"resource": ""
} |
q39063 | createRunQueue | train | function createRunQueue(modules) {
return modules
.map((mod) => mod._runQueue)
.reduce((acc, res) => acc.concat(res), []);
} | javascript | {
"resource": ""
} |
q39064 | create | train | async function create(options) {
const {
org,
name,
description,
homepage,
license_template,
gitignore_template,
auto_init = false,
} = options
const p = org ? `orgs/${org}` : 'user'
const endpoint = `/${p}/repos`
const { body } = await this._request({
data: {
name,
description,
homepage,
gitignore_template,
license_template,
auto_init,
},
endpoint,
})
/** @type {Repository} */
const r = body
return r
} | javascript | {
"resource": ""
} |
q39065 | TimeoutError | train | function TimeoutError(message) {
// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
if (!(this instanceof TimeoutError)) { return new TimeoutError(message); }
Error.captureStackTrace(this, TimeoutError);
if (message !== undefined) {
Object.defineProperty(this, 'message', {
value: String(message),
configurable: true,
writable: true
});
}
} | javascript | {
"resource": ""
} |
q39066 | parseCoverageResults | train | function parseCoverageResults(src) {
var collector = new istanbul.Collector();
var utils = istanbul.utils;
var results = [];
grunt.file.expand({filter: 'isFile'}, src).forEach(function (file) {
var browser = path.dirname(file).substring(path.dirname(file).lastIndexOf("/")+1)
collector.add(JSON.parse(grunt.file.read(file)));
var summary = utils.summarizeCoverage(collector.getFinalCoverage());
results.push({
browser: browser,
lines: Number(summary.lines.pct),
branches: Number(summary.branches.pct),
functions: Number(summary.functions.pct),
statements: Number(summary.statements.pct)
});
});
return results;
} | javascript | {
"resource": ""
} |
q39067 | parseJshintResults | train | function parseJshintResults(fileName, showDetails) {
var result = {};
if (grunt.file.exists(fileName)) {
var content = grunt.file.read(fileName);
xml2js.parseString(content, {}, function (err, res) {
var consoleStatements = content.match(/(console.*)/g);
result = {
tests: Number(res.testsuite.$.tests),
failures: Number(res.testsuite.$.failures),
errors: Number(res.testsuite.$.errors),
consoleStatements: consoleStatements != null ? consoleStatements.length : 0
};
if (showDetails) {
var details = {};
res.testsuite.testcase.forEach(function (key) {
if(typeof key.failure !== 'undefined') {
var filename = key.$.name.substring(key.$.name.search(/[^\/]+$/g));
var failures = key.failure[0]._.replace(/\n/g, "###").split("###");
failures.shift();
failures.pop();
details[filename] = failures;
}
});
result.failureDetails = details;
}
});
}
return result;
} | javascript | {
"resource": ""
} |
q39068 | parse | train | function parse(obj, options) {
var result = {},
key,
value,
momentValue;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
value = obj[key];
if (typeof value === 'string' || typeof value === 'number') {
momentValue = moment.call(null, value, options.formats, options.strict);
if (momentValue.isValid()) {
result[key] = momentValue.toDate();
}
else {
result[key] = value;
}
}
else if (value.constructor === Object) {
result[key] = parse(value, options);
}
else {
result[key] = value;
}
}
}
return result;
} | javascript | {
"resource": ""
} |
q39069 | main | train | function main(content, callback) {
parser(content, function(error, result) {
if (error) {
callback(error);
} else {
callback(null, result);
}
});
} | javascript | {
"resource": ""
} |
q39070 | toBatchStateItem | train | function toBatchStateItem(batch, context) {
const states = batch.states;
// const messages = batch.allMessages();
const messages = batch.messages;
const rejectedMessages = batch.rejectedMessages;
const unusableRecords = batch.unusableRecords;
// Resolve the messages' states to be saved (if any)
const messageStates = messages && messages.length > 0 ?
messages.map(msg => toStorableMessageState(states.get(msg), msg, context)).filter(s => !!s) : [];
// Resolve the rejected messages' states to be saved (if any)
const rejectedMessageStates = rejectedMessages && rejectedMessages.length > 0 ?
rejectedMessages.map(msg => toStorableMessageState(states.get(msg), msg, context)).filter(s => !!s) : [];
// Resolve the unusable records' states to be saved (if any)
const unusableRecordStates = unusableRecords && unusableRecords.length > 0 ?
unusableRecords.map(uRec => toStorableUnusableRecordState(states.get(uRec), uRec, context)).filter(s => !!s) : [];
const batchState = toStorableBatchState(states.get(batch), batch, context);
return {
streamConsumerId: batch.streamConsumerId, // hash key
shardOrEventID: batch.shardOrEventID, // range key
messageStates: messageStates,
rejectedMessageStates: rejectedMessageStates,
unusableRecordStates: unusableRecordStates,
batchState: batchState || null
};
} | javascript | {
"resource": ""
} |
q39071 | toStorableMessageState | train | function toStorableMessageState(messageState, message, context) {
if (!messageState) {
context.warn(`Skipping save of state for message, since it has no state - message (${JSON.stringify(message)})`);
return undefined;
}
// Convert the message's state into a safely storable object to get a clean, simplified version of its state
const state = dynamoDBUtils.toStorableObject(messageState);
// If state has no message identifier then have no way to identify the message ... so attach a safely storable copy of
// its original message, user record or record (if any) (i.e. without its legacy state, if any, for later matching)!
if (!hasMessageIdentifier(messageState)) {
message = message || messageState.message;
if (message) {
// Make a storable copy of the message & attach it to the storable state
state.message = dynamoDBUtils.toStorableObject(message);
// Remove the message copy's LEGACY state (if any) to get back to the original message
tracking.deleteLegacyState(message, context);
}
else if (messageState.userRecord) {
// If has no message, then attach a copy of its user record
// Make a storable copy of the unusable user record & attach it to the storable state
state.userRecord = dynamoDBUtils.toStorableObject(messageState.userRecord);
// Remove the unusable user record copy's LEGACY state (if any) to get back to the original user record
tracking.deleteLegacyState(state.userRecord, context);
}
else if (messageState.record) {
// If has no message AND no user record, then attach a copy of its record
// Make a storable copy of the unusable record & attach it to the storable state
state.record = dynamoDBUtils.toStorableObject(messageState.record);
// remove the unusable record copy's LEGACY state (if any) to get back to the original record
tracking.deleteLegacyState(state.record, context);
}
}
return state;
} | javascript | {
"resource": ""
} |
q39072 | toStorableUnusableRecordState | train | function toStorableUnusableRecordState(unusableRecordState, unusableRecord, context) {
if (!unusableRecordState) {
context.warn(`Skipping save of state for unusable record, since it has no state - record (${JSON.stringify(unusableRecord)})`);
return undefined;
}
// Convert the record's state into a safely storable object to get a clean, simplified version of its state
const state = dynamoDBUtils.toStorableObject(unusableRecordState);
// If state has no record identifier then have no way to identify the unusable record ... so attach a safely storable
// copy of its original user record or record (if any) (without its legacy state, if any) for later matching!
if (!hasUnusableRecordIdentifier(unusableRecordState)) {
unusableRecord = unusableRecord || unusableRecordState.unusableRecord;
if (unusableRecord) {
// Make a storable copy of the unusable record & attach it to the storable state
state.unusableRecord = dynamoDBUtils.toStorableObject(unusableRecord);
// Remove the unusable record copy's LEGACY state (if any) to get back to the original unusable record
tracking.deleteLegacyState(unusableRecord, context);
}
if (unusableRecordState.userRecord) {
// Make a storable copy of the unusable record's user record & attach it to the storable state
state.userRecord = dynamoDBUtils.toStorableObject(unusableRecordState.userRecord);
// Remove the unusable record's user record copy's LEGACY state (if any) to get back to the original user record
tracking.deleteLegacyState(state.userRecord, context);
}
else if (unusableRecordState.record) {
// Make a storable copy of the unusable record's record & attach it to the storable state
state.record = dynamoDBUtils.toStorableObject(unusableRecordState.record);
// remove the unusable record's record copy's LEGACY state (if any) to get back to the original record
tracking.deleteLegacyState(state.record, context);
}
}
return state;
} | javascript | {
"resource": ""
} |
q39073 | updateBatchWithPriorState | train | function updateBatchWithPriorState(batch, item, context) {
restoreMessageAndRejectedMessageStates(batch, item, context);
restoreUnusableRecordStates(batch, item, context);
} | javascript | {
"resource": ""
} |
q39074 | hasMessageIdentifier | train | function hasMessageIdentifier(msgState) {
const md5s = msgState.md5s;
return isNotBlank(msgState.eventID) || // isNotBlank(msgState.eventSeqNo) || isNotBlank(msgState.eventSubSeqNo) ||
(msgState.idVals && msgState.idVals.some(isNotBlank)) ||
((msgState.keyVals && msgState.keyVals.some(isNotBlank)) &&
(msgState.seqNoVals && msgState.seqNoVals.some(isNotBlank))) ||
(md5s && (isNotBlank(md5s.msg) || isNotBlank(md5s.userRec) || isNotBlank(md5s.rec) || isNotBlank(md5s.data)));
} | javascript | {
"resource": ""
} |
q39075 | hasUnusableRecordIdentifier | train | function hasUnusableRecordIdentifier(recState) {
const md5s = recState.md5s;
return isNotBlank(recState.eventID) || // isNotBlank(recState.eventSeqNo) || isNotBlank(recState.eventSubSeqNo) ||
(md5s && (isNotBlank(md5s.userRec) || isNotBlank(md5s.rec) || isNotBlank(md5s.data)));
} | javascript | {
"resource": ""
} |
q39076 | validate | train | function validate (data, schema) {
if (!data || !schema) {
throw new Error('Trying to validate without passing data and schema')
}
return Joi.validate(data, schema)
} | javascript | {
"resource": ""
} |
q39077 | verifyChain | train | function verifyChain(certificate, chain, trustedCAs) {
if (certificate === null) return Promise.resolve(false);
return Promise.resolve().then(function () {
var certificateChainEngine = new pkijs.CertificateChainValidationEngine({
certs: chain,
trustedCerts: trustedCAs.filter(function (cert) {
return typeof cert !== 'undefined';
})
});
certificateChainEngine.certs.push(certificate);
return certificateChainEngine.verify();
}).then(function (result) {
return result.result;
}, function (result) {
return false;
});
} | javascript | {
"resource": ""
} |
q39078 | getProperties | train | function getProperties (header) {
return header.split(',').map((split) => {
const components = split.replace(/\s+/, '').split(';');
const priorityRegex = /^q=([0-1](\.[0-9]{1,3})?)$/;
/* assign null to priority when invaild quarity values */
return {
lang: components[0],
priority: components[1] ? priorityRegex.test(components[1]) ? parseFloat(components[1].split('=')[1]) : null : 1
}
}).filter((property) => {
return property.priority === null ? false : bcp47.check(property.lang);
}).sort((a, b) => {
return a.priority < b.priority ? 1 : a.priority > b.priority ? -1 : 0;
});
} | javascript | {
"resource": ""
} |
q39079 | matchAccept | train | function matchAccept (properties, langs) {
let match = null;
let priority = 0;
base: for(const lang of langs) {
for (const property of properties) {
if (property.priority === 0) {
break;
}
if (priority < property.priority){
if (lang.lang === property.lang) {
match = lang.raw;
priority = property.priority + 0.001;
break;
}
if (lang.bcp47.language === property.bcp47.language) {
match = lang.raw;
priority = property.priority;
break;
}
}
}
}
return match;
} | javascript | {
"resource": ""
} |
q39080 | train | function() {
var stat = fs.existsSync('/var/run/docker.sock');
if (!stat) {
stat = process.env.DOCKER_HOST || false;
}
return stat;
} | javascript | {
"resource": ""
} | |
q39081 | contents | train | function contents(map, tight) {
var minDepth = Infinity;
var index = -1;
var length = map.length;
var table;
/*
* Find minimum depth.
*/
while (++index < length) {
if (map[index].depth < minDepth) {
minDepth = map[index].depth;
}
}
/*
* Normalize depth.
*/
index = -1;
while (++index < length) {
map[index].depth -= minDepth - 1;
}
/*
* Construct the main list.
*/
table = list();
/*
* Add TOC to list.
*/
index = -1;
while (++index < length) {
insert(map[index], table, tight);
}
return table;
} | javascript | {
"resource": ""
} |
q39082 | train | function() {
var cmdArguments = process.argv.slice(2)
var lookup = {
values: [],
keyValues: {}
};
cmdArguments.forEach(function(cmdArgument) {
var keyValue = cmdArgument.split('=');
//Flag of key value type
if(typeof keyValue[0] === 'string' && keyValue[0].charAt(0) === '-') {
var value = keyValue.length === 2 ? _removeQuotes(keyValue[1]) : true;
var keyName = keyValue[0];
lookup.keyValues[keyName] = value;
//Value type
} else {
lookup.values.push(_removeQuotes(cmdArgument));
}
})
return lookup;
} | javascript | {
"resource": ""
} | |
q39083 | _directoryToStream | train | function _directoryToStream (directory, separator, callback) {
if ("undefined" === typeof directory) {
throw new ReferenceError("missing \"directory\" argument");
}
else if ("string" !== typeof directory) {
throw new TypeError("\"directory\" argument is not a string");
}
else if ("" === directory.trim()) {
throw new Error("\"directory\" argument is empty");
}
else if ("undefined" === typeof callback && "undefined" === typeof separator) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback && "function" !== typeof separator) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
extractFiles(directory, (err, files) => {
const _callback = "undefined" === typeof callback ? separator : callback;
return err ? _callback(err) : filesToStream(files, separator, _callback);
});
}
} | javascript | {
"resource": ""
} |
q39084 | requireLogin | train | function requireLogin (options) {
// merge with default options
options = mergeOptions({
'login': '/login',
'home': '/',
'user': 'user',
'referer': 'referer',
'excepts': []
}, options)
// add login to except page
options.excepts.push(options.login)
return function(req, res, next) {
var url = req.originalUrl
, user = req.session[options.user]
// go to homepage where:
// 1. logged-in, and
// 2. on login page
if (user && url === options.login)
return res.redirect(options.home)
// stay on page wherether:
// 1. logged-in, or
// 2. on login page, or
// 3. on non-required login page
if (user || options.excepts.indexOf(url) > -1)
return next()
// save referer into session
req.session[options.referer] = url
// redirect to login page if not login
return res.redirect(options.login)
}
} | javascript | {
"resource": ""
} |
q39085 | Dispatcher | train | function Dispatcher(req, res, next) {
_classCallCheck(this, Dispatcher);
this.req = req;
this.res = res;
this.next = next;
} | javascript | {
"resource": ""
} |
q39086 | getUrlParameters | train | function getUrlParameters() {
var params = [ "allume" ];
location.search.substr(1).split("&").forEach(function (part) {
if (!part) return;
var item = part.split("=");
params.push(decodeURIComponent(item[0]));
});
return params;
} | javascript | {
"resource": ""
} |
q39087 | getNodeParameters | train | function getNodeParameters() {
return typeof process !== "undefined" && process.argv && process.argv.length > 1 ? process.argv.slice(1) : null;
} | javascript | {
"resource": ""
} |
q39088 | channels | train | function channels(req, res) {
res.send(null, this.state.pubsub.getChannels(req.args[0]));
} | javascript | {
"resource": ""
} |
q39089 | numsub | train | function numsub(req, res) {
res.send(null, this.state.pubsub.getChannelList(req.args));
} | javascript | {
"resource": ""
} |
q39090 | validate | train | function validate(cmd, args, info) {
AbstractCommand.prototype.validate.apply(this, arguments);
var sub = info.command.sub
, cmd = sub.cmd
, args = sub.args
if(('' + cmd) === Constants.SUBCOMMAND.pubsub.channels.name) {
if(args.length > 1) {
throw UnknownSubcommand;
}
}
} | javascript | {
"resource": ""
} |
q39091 | GrayFilter | train | function GrayFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
fs.readFileSync(__dirname + '/gray.frag', 'utf8'),
// set the uniforms
{
gray: { type: '1f', value: 1 }
}
);
} | javascript | {
"resource": ""
} |
q39092 | Texture | train | function Texture(baseTexture, frame, crop, trim, rotate)
{
EventEmitter.call(this);
/**
* Does this Texture have any frame data assigned to it?
*
* @member {boolean}
*/
this.noFrame = false;
if (!frame)
{
this.noFrame = true;
frame = new math.Rectangle(0, 0, 1, 1);
}
if (baseTexture instanceof Texture)
{
baseTexture = baseTexture.baseTexture;
}
// console.log(frame);
/**
* The base texture that this texture uses.
*
* @member {BaseTexture}
*/
this.baseTexture = baseTexture;
/**
* The frame specifies the region of the base texture that this texture uses
*
* @member {Rectangle}
* @private
*/
this._frame = frame;
/**
* The texture trim data.
*
* @member {Rectangle}
*/
this.trim = trim;
/**
* This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
*
* @member {boolean}
*/
this.valid = false;
/**
* This will let a renderer know that a texture has been updated (used mainly for webGL uv updates)
*
* @member {boolean}
*/
this.requiresUpdate = false;
/**
* The WebGL UV data cache.
*
* @member {TextureUvs}
* @private
*/
this._uvs = null;
/**
* The width of the Texture in pixels.
*
* @member {number}
*/
this.width = 0;
/**
* The height of the Texture in pixels.
*
* @member {number}
*/
this.height = 0;
/**
* This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
* irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
*
* @member {Rectangle}
*/
this.crop = crop || frame;//new math.Rectangle(0, 0, 1, 1);
/**
* Indicates whether the texture should be rotated by 90 degrees
*
* @private
* @member {boolean}
*/
this.rotate = !!rotate;
if (baseTexture.hasLoaded)
{
if (this.noFrame)
{
frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height);
// if there is no frame we should monitor for any base texture changes..
baseTexture.on('update', this.onBaseTextureUpdated, this);
}
this.frame = frame;
}
else
{
baseTexture.once('loaded', this.onBaseTextureLoaded, this);
}
} | javascript | {
"resource": ""
} |
q39093 | plugin | train | function plugin(params) {
logger = params.logger;
params.dirname = params.dirname ? _.template(params.dirname)(params) : params.event.dir.resourcesPlatform;
logger.trace("running babel in directory: " + params.dirname);
_.defaults(params, {
options: {},
includes: ["**/*.js", "!backbone.js"]
});
if (params.code) {
params.code = transformCode(params.code, params.options);
} else {
var files = findFiles(params.dirname, params.includes);
_.forEach(files, function(file) {
transformFile(path.join(params.dirname, file), params.options);
});
}
} | javascript | {
"resource": ""
} |
q39094 | transformFile | train | function transformFile(filepath, options) {
logger.trace("transforming file - " + filepath);
var content = fs.readFileSync(filepath, 'utf8');
var result = transformCode(content, options);
fs.writeFileSync(filepath, result);
} | javascript | {
"resource": ""
} |
q39095 | transformCode | train | function transformCode(code, options) {
var result = babel.transform(code, options);
var modified = result.code;
return modified;
} | javascript | {
"resource": ""
} |
q39096 | kwire | train | function kwire(appRoot, globalShadow) {
appRoot = appRoot == null ? {} : appRoot;
globalShadow = globalShadow || window;
if (typeof appRoot !== 'object') {
throw 'root object must be an object.'
}
if (isServerSide() ||
isUsingRequireJS() ||
rootIsAlreadyConfigured(globalShadow)) {
return;
}
globalShadow.module = {
set exports(value) {
if (value === undefined) {
throw 'module not defined.';
}
if (value === null) { // null or undefined.
return;
}
if (!value.hasOwnProperty('_path_')) {
throw '_path_ own-property must be present on modules registered with kwire.';
}
if (typeof value._path_ !== 'string') {
throw '_path_ own-property must be a string.';
}
appRoot[value._path_] = value;
}
};
/**
* cb is optional.
*/
globalShadow.require = function(value, cb) {
var valueIsArray = Array.isArray(value);
if (value == null) {
throw 'value not defined.'
}
if (typeof value !== 'string' && !valueIsArray) {
throw 'value must be a string or an array.'
}
if (cb) {
if (!valueIsArray) {
return cb(appRoot[value]);
}
return cb.apply(null, value.map(function(v) {
return appRoot[v];
}));
}
var result = appRoot[value];
return result === undefined ? globalShadow[camelify(value)] : result;
};
} | javascript | {
"resource": ""
} |
q39097 | getInstance | train | function getInstance(options) {
var bucket = options.bucket;
var upyunInstance = instances[bucket];
// If can not found instance, then new one.
if (!upyunInstance) {
instances[bucket] = upyunInstance = new UPYUN(options.bucket, options.operator, options.password, options.endpoing, options.apiVersion);
}
return upyunInstance;
} | javascript | {
"resource": ""
} |
q39098 | uploadToUpyun | train | function uploadToUpyun(path, file, __newFile, done) {
var options = this.options;
var upyun = getInstance(options);
upyun.uploadFile(path, file, __newFile.headers['content-type'], true, function (err, data) {
if (err) {
return done(err);
}
if (!data) {
return done(new Error('Upload failed!'));
}
if (data && data.statusCode != 200) {
return done(new Error(data.error['message']));
}
__newFile.fd = options.domain + path;
return done();
});
} | javascript | {
"resource": ""
} |
q39099 | buildUpyunReceiverStream | train | function buildUpyunReceiverStream(opts) {
var options = opts || {};
_.defaults(options, {
endpoing: 'v0',
apiVersion: 'legacy',
// Upload limit (in bytes)
// defaults to ~15MB
maxBytes: 15000000,
// Upload limit for per coming file (in bytes)
// falsy means no limit
perMaxBytes: 15000000,
// Upload limit for per file (in content-type)
// falsy means accept all the type
acceptTypes: null,
});
var receiver__ = WritableStream({ objectMode: true });
// if onProgress handler was provided, bind an event automatically:
if (_.isFunction(options.onProgress)) {
receiver__.on('progress', options.onProgress);
}
// Track the progress of all file uploads that pass through this receiver
// through one or more attached Upstream(s).
receiver__._files = [];
// This `_write` method is invoked each time a new file is received
// from the Readable stream (Upstream) which is pumping filestreams
// into this receiver. (filename === `__newFile.filename`).
receiver__._write = onFile.bind({ options });
return receiver__;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.