_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q50400
|
isBuiltinPlugin
|
train
|
function isBuiltinPlugin(name) {
var isNpmPluginName = /^(?:babel-plugin-)/;
var availablePlugins = babel.availablePlugins;
// if the full npm plugin name was set in `babelOptions.plugins`, use the
// shorthand to check whether the plugin is included in babel-standalone;
// shorthand plugin names are used internally by babel-standalone
var shorthand = isNpmPluginName.test(name) ?
name.replace("babel-plugin-", "") :
name;
return !!availablePlugins[shorthand];
}
|
javascript
|
{
"resource": ""
}
|
q50401
|
rebuild
|
train
|
function rebuild(moduleNames){
moduleName = moduleNames[0] || "";
moduleNames.forEach(function(moduleName){
graphStream.write(moduleName);
});
}
|
javascript
|
{
"resource": ""
}
|
q50402
|
flagCircularDependencies
|
train
|
function flagCircularDependencies(graph) {
var includes = require("lodash/includes");
var nodes = Array.isArray(graph) ? graph : require("lodash/values")(graph);
for (var i = 0; i < nodes.length; i += 1) {
var curr = nodes[i];
for (var j = i + 1; j < nodes.length; j += 1) {
var next = nodes[j];
if (
includes(curr.dependencies, next.load.name) &&
includes(next.dependencies, curr.load.name)
) {
curr.load.circular = true;
next.load.circular = true;
}
}
}
return graph;
}
|
javascript
|
{
"resource": ""
}
|
q50403
|
getRelativeBundlePath
|
train
|
function getRelativeBundlePath(target, bundle) {
var baseUrl = options.baseUrl.replace("file:", "");
return target !== "web" ?
getBundleFileName(bundle) :
path.join(
path.relative(baseUrl, options.bundlesPath),
getBundleFileName(bundle)
);
}
|
javascript
|
{
"resource": ""
}
|
q50404
|
train
|
function(results) {
var value;
if (targets.length) {
value = {};
results.forEach(function(result, index) {
value[targets[index]] = result;
});
} else {
value = results[0];
}
slimDfd.resolve(value);
}
|
javascript
|
{
"resource": ""
}
|
|
q50405
|
getUniqueName
|
train
|
function getUniqueName(dirName, shortened, buildTypeSuffix) {
if (!usedBundleNames[dirName + shortened + buildTypeSuffix]) {
return dirName + shortened + buildTypeSuffix + "";
}else {
return dirName + shortened + "-" + (bundleCounter++) + buildTypeSuffix + "";
}
}
|
javascript
|
{
"resource": ""
}
|
q50406
|
log
|
train
|
function log(message, level) {
var prefix = "[" + colors.cyan("gulp-tslint") + "]";
if (level === "error") {
fancyLog(prefix, colors.red("error"), message);
}
else {
fancyLog(prefix, message);
}
}
|
javascript
|
{
"resource": ""
}
|
q50407
|
train
|
function (pluginOptions) {
// If user options are undefined, set an empty options object
if (!pluginOptions) {
pluginOptions = {};
}
// Save off pluginOptions so we can get it in `report()`
tslintPlugin.pluginOptions = pluginOptions;
// TSLint default options
var options = {
fix: pluginOptions.fix || false,
formatter: pluginOptions.formatter || "prose",
formattersDirectory: pluginOptions.formattersDirectory || null,
rulesDirectory: pluginOptions.rulesDirectory || null
};
var linter = getTslint(pluginOptions);
var tslint = new linter.Linter(options, pluginOptions.program);
return map(function (file, cb) {
// Skip
if (file.isNull()) {
return cb(null, file);
}
// Stream is not supported
if (file.isStream()) {
return cb(new PluginError("gulp-tslint", "Streaming not supported"));
}
var configuration = (pluginOptions.configuration === null ||
pluginOptions.configuration === undefined ||
isString(pluginOptions.configuration))
// Configuration can be a file path or null, if it's unknown
? linter.Configuration.findConfiguration(pluginOptions.configuration || null, file.path).results
: pluginOptions.configuration;
tslint.lint(file.path, file.contents.toString("utf8"), configuration);
file.tslint = tslint.getResult();
// Clear all results for current file from tslint
tslint.failures = [];
tslint.fixes = [];
// Pass file
cb(null, file);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50408
|
train
|
function (file) {
if (file.tslint) {
// Version 5.0.0 of tslint no longer has a failureCount member
// It was renamed to errorCount. See tslint issue #2439
var failureCount = file.tslint.errorCount;
if (!options.allowWarnings) {
failureCount += file.tslint.warningCount;
}
if (failureCount > 0) {
errorFiles.push(file);
Array.prototype.push.apply(allFailures, file.tslint.failures);
if (options.reportLimit <= 0 || (options.reportLimit && options.reportLimit > totalReported)) {
if (file.tslint.output !== undefined) {
// If any errors were found, print all warnings and errors
console.log(file.tslint.output);
}
totalReported += failureCount;
if (options.reportLimit > 0 &&
options.reportLimit <= totalReported) {
log("More than " + options.reportLimit
+ " failures reported. Turning off reporter.");
}
}
}
else if (options.allowWarnings && file.tslint.warningCount > 0) {
// Íf only warnings were emitted, format and print them
// Figure out which formatter the user requested in `tslintPlugin()` and construct one
var formatterConstructor = TSLint.findFormatter(tslintPlugin.pluginOptions.formatter);
var formatter = new formatterConstructor();
// Get just the warnings
var warnings = file.tslint.failures.filter(function (failure) { return failure.getRuleSeverity() === "warning"; });
// Print the output of those
console.log(formatter.format(warnings));
}
}
// Pass file
this.emit("data", file);
}
|
javascript
|
{
"resource": ""
}
|
|
q50409
|
train
|
function () {
// Throw error
if (options && errorFiles.length > 0) {
var failuresToOutput = allFailures;
var ignoreFailureCount = 0;
// If error count is limited, calculate number of errors not shown and slice reportLimit
// number of errors to be included in the error.
if (options.reportLimit > 0) {
ignoreFailureCount = allFailures.length - options.reportLimit;
failuresToOutput = allFailures.slice(0, options.reportLimit);
}
// Always use the proseErrorFormat for the error.
var failureOutput = failuresToOutput.map(function (failure) {
return proseErrorFormat(failure);
}).join(", ");
var errorOutput = "Failed to lint: ";
if (options.summarizeFailureOutput) {
errorOutput += failuresToOutput.length + " errors.";
}
else {
errorOutput += failureOutput + ".";
}
if (ignoreFailureCount > 0) {
errorOutput += " (" + ignoreFailureCount + " other errors not shown.)";
}
if (options.emitError === true) {
return this.emit("error", new PluginError("gulp-tslint", errorOutput));
}
else if (options.summarizeFailureOutput) {
log(errorOutput);
}
}
// Notify through that we're done
this.emit("end");
}
|
javascript
|
{
"resource": ""
}
|
|
q50410
|
touchend
|
train
|
function touchend(e) {
if (isDown) {
isDown = false;
var touch;
if (e.type == 'touchend') //Check for touch event or mousemove
touch = getTouch(e);
else
touch = e;
$(window).off('mousemove touchmove', mousemove); //Stop listening for the mousemove event
//Check if vertical panning (swipe out) or horizontal panning (carousel swipe)
//Vertical PANNING
if (vertical_pan && options.swipe_out) {
//HAPPENS WHEN SWIPEOUT
vertical_pan = false; //Back to false for mousewheel (Vertical pan has finished so enable mousewheel scrolling)
swipeOut();
return;
} //Veritcal Pan
else if ($el.end_animation && !options.disable_slide) { //if finished animation of sliding and swiping is not disabled
//Calculate deltaTime for calculation of velocity
var deltaTime = (Date.now() - swipeStartTime);
//Verify delta is > 0 to avoid divide by 0 error
deltaTime++;
vars.velocity = -(touch.pageX - startPointX) / deltaTime;
if (vars.velocity > 0) { //Set direction
vars.direction = 1; //PAN LEFT
} else {
vars.direction = -1;
}
vars.distanceFromStart = (touch.pageX - startPointX) * vars.direction * -1; //Yaaa SOOO
var landingSlideIndex = anim.getLandingSlideIndex(vars.velocity * options.swipe_sensitivity - $el.translate3d().x);
//TAP is when deltaX is less or equal to 12px
if (vars.distanceFromStart > 6) {
anim.gotoSlideByIndex(landingSlideIndex);
return;
}
} //Regular horizontal pan until here
//TAP - click to slide
$el.trigger({
type: "clickSlide",
slide: $el.savedSlideIndex
});
if ($el.savedSlideIndex != vars.currentIndex && !options.disable_clicktoslide) { //If this occurs then its a tap
e.preventDefault();
anim.gotoSlideByIndex($el.savedSlideIndex);
}
//TAP until here
}
}
|
javascript
|
{
"resource": ""
}
|
q50411
|
train
|
function (map) {
this._parts = [];
var startAngle = 0;
var stopAngle = 0;
this.addTo(map);
for (var i = 0; i < this.count(); i++) {
var normalized = this._normalize(this._data[i].num);
stopAngle = normalized * 360 + startAngle;
// set start/stop Angle and color for semicircle
var options = L.extend({
startAngle: startAngle,
stopAngle: stopAngle,
radius: this.options.radius,
fillColor: this._color(i),
color: this._color(i)
}, this.options.sliceOptions);
this._data[i].slice = L.semiCircle(
this._latlng,
L.Util.extend({}, options, this.options.pathOptions)
).addTo(this);
if (this.options.labels) {
this._createLabel(normalized, this._data[i].label, this._data[i].slice);
}
startAngle = stopAngle;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q50412
|
complete
|
train
|
function complete(e) {
clearTimeout(doneTimeout);
if (!done) { return; }
var d = done;
done = null;
if (e) {
// test failure
if (!(e instanceof Error)) {
e = new Error(e);
}
d(e);
} else {
// test passed
d();
}
}
|
javascript
|
{
"resource": ""
}
|
q50413
|
parseConnectAddress
|
train
|
function parseConnectAddress(address)
{
var url = address.trim();
if (!url.match('^https?://[A-Z0-9\.]*.*$'))
{
// Add protocol.
url = 'http://' + url;
}
if (url.match('^https?://[0-9\.]*$') &&
!url.match('^https?://[0-9\.]*:[0-9]*$'))
{
// Add port to numeric ip address.
url = url + ':4042';
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
q50414
|
helper_createTriggerObject
|
train
|
function helper_createTriggerObject(trigger)
{
var triggerObject = {};
triggerObject.triggerIdentifier = trigger.identifier;
triggerObject.rules = [];
for (var i = 0; i < trigger.rules.length; ++i)
{
var rule = trigger.rules[i];
triggerObject.rules.push({
ruleType: rule.ruleType,
ruleIdentifier: rule.ruleIdentifier,
nearableIdentifier: rule.nearableIdentifier,
nearableType: rule.nearableType });
}
return triggerObject;
}
|
javascript
|
{
"resource": ""
}
|
q50415
|
helper_updateTriggerRule
|
train
|
function helper_updateTriggerRule(trigger, event)
{
var rule = trigger.ruleTable[event.ruleIdentifier];
if (rule && rule.ruleUpdateFunction)
{
rule.ruleUpdateFunction(rule, event.nearable, event);
helper_updateRuleState(
event.triggerIdentifier,
event.ruleIdentifier,
rule.state);
}
}
|
javascript
|
{
"resource": ""
}
|
q50416
|
helper_updateRuleState
|
train
|
function helper_updateRuleState(triggerIdentifier, ruleIdentifier, state)
{
exec(null,
null,
'EstimoteBeacons',
'triggers_updateRuleState',
[triggerIdentifier, ruleIdentifier, state]
);
}
|
javascript
|
{
"resource": ""
}
|
q50417
|
train
|
function(model, attrs) {
attrs = attrs || _.keys(_.result(model, 'validation') || {});
return _.reduce(attrs, function(memo, key) {
memo[key] = void 0;
return memo;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
|
q50418
|
train
|
function(attr, value) {
var self = this,
result = {},
error;
if(_.isObject(attr)){
_.each(attr, function(value, key) {
error = self.preValidate(key, value);
if(error){
result[key] = error;
}
});
return _.isEmpty(result) ? undefined : result;
}
else {
return validateAttr(this, attr, value, _.extend({}, this.attributes));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50419
|
train
|
function(view, model, options) {
if (model.associatedViews) {
model.associatedViews.push(view);
} else {
model.associatedViews = [view];
}
_.extend(model, mixin(view, options));
}
|
javascript
|
{
"resource": ""
}
|
|
q50420
|
train
|
function(model, view) {
if (view && model.associatedViews && model.associatedViews.length > 1){
model.associatedViews = _.without(model.associatedViews, view);
} else {
delete model.validate;
delete model.preValidate;
delete model.isValid;
delete model.associatedViews;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50421
|
train
|
function(view, options) {
options = _.extend({}, defaultOptions, defaultCallbacks, options);
var model = options.model || view.model,
collection = options.collection || view.collection;
if(typeof model === 'undefined' && typeof collection === 'undefined'){
throw 'Before you execute the binding your view must have a model or a collection.\n' +
'See http://thedersen.com/projects/backbone-validation/#using-form-model-validation for more information.';
}
if(model) {
bindModel(view, model, options);
}
else if(collection) {
collection.each(function(model){
bindModel(view, model, options);
});
collection.bind('add', collectionAdd, {view: view, options: options});
collection.bind('remove', collectionRemove);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50422
|
train
|
function(view, options) {
options = _.extend({}, options);
var model = options.model || view.model,
collection = options.collection || view.collection;
if(model) {
unbindModel(model, view);
}
else if(collection) {
collection.each(function(model){
unbindModel(model, view);
});
collection.unbind('add', collectionAdd);
collection.unbind('remove', collectionRemove);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50423
|
train
|
function(view, attr, error, selector) {
view.$('[' + selector + '~="' + attr + '"]')
.addClass('invalid')
.attr('data-error', error);
}
|
javascript
|
{
"resource": ""
}
|
|
q50424
|
train
|
function(attrName) {
return attrName.replace(/(?:^\w|[A-Z]|\b\w)/g, function(match, index) {
return index === 0 ? match.toUpperCase() : ' ' + match.toLowerCase();
}).replace(/_/g, ' ');
}
|
javascript
|
{
"resource": ""
}
|
|
q50425
|
train
|
function(value){
return _.isNumber(value) || (_.isString(value) && value.match(defaultPatterns.number));
}
|
javascript
|
{
"resource": ""
}
|
|
q50426
|
train
|
function(value, attr, fn, model, computed) {
if(_.isString(fn)){
fn = model[fn];
}
return fn.call(model, value, attr, computed);
}
|
javascript
|
{
"resource": ""
}
|
|
q50427
|
train
|
function(value, attr, minValue, model) {
if (!isNumber(value) || value < minValue) {
return this.format(defaultMessages.min, this.formatLabel(attr, model), minValue);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50428
|
train
|
function(value, attr, length, model) {
if (!_.isString(value) || value.length !== length) {
return this.format(defaultMessages.length, this.formatLabel(attr, model), length);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50429
|
train
|
function(value, attr, values, model) {
if(!_.include(values, value)){
return this.format(defaultMessages.oneOf, this.formatLabel(attr, model), values.join(', '));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50430
|
train
|
function(value, attr, equalTo, model, computed) {
if(value !== computed[equalTo]) {
return this.format(defaultMessages.equalTo, this.formatLabel(attr, model), this.formatLabel(equalTo, model));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50431
|
MemcachedStore
|
train
|
function MemcachedStore(options) {
options = options || {};
Store.call(this, options);
this.prefix = options.prefix || "";
this.ttl = options.ttl;
if (!options.client) {
if (!options.hosts) {
options.hosts = "127.0.0.1:11211";
}
if (options.secret) {
(this.crypto = require("crypto")), (this.secret = options.secret);
}
if (options.algorithm) {
this.algorithm = options.algorithm;
}
options.client = new Memcached(options.hosts, options);
}
this.client = options.client;
}
|
javascript
|
{
"resource": ""
}
|
q50432
|
consumeWord
|
train
|
function consumeWord (css, start) {
let next = start;
let code;
do {
code = css.charCodeAt(next);
if (wordDelimiters[code]) {
return next - 1;
} else if (code === t.backslash) {
next = consumeEscape(css, next) + 1;
} else {
// All other characters are part of the word
next++;
}
} while (next < css.length);
return next - 1;
}
|
javascript
|
{
"resource": ""
}
|
q50433
|
consumeEscape
|
train
|
function consumeEscape (css, start) {
let next = start;
let code = css.charCodeAt(next + 1);
if (unescapable[code]) {
// just consume the escape char
} else if (hex[code]) {
let hexDigits = 0;
// consume up to 6 hex chars
do {
next++;
hexDigits++;
code = css.charCodeAt(next + 1);
} while (hex[code] && hexDigits < 6);
// if fewer than 6 hex chars, a trailing space ends the escape
if (hexDigits < 6 && code === t.space) {
next++;
}
} else {
// the next char is part of the current word
next++;
}
return next;
}
|
javascript
|
{
"resource": ""
}
|
q50434
|
findMatchingBucket
|
train
|
function findMatchingBucket(mod, ignore, bucketsContext) {
var match = null;
if (!mod.resource) {
return match;
}
var resourcePath = mod.resource;
for (var i in ignore) {
if (ignore[i].test(resourcePath)) {
return match;
}
}
bucketsContext.some(function (bucket) {
return bucket.path.some(function (path) {
if (path.test(resourcePath)) {
match = bucket;
return true;
}
});
});
return match;
}
|
javascript
|
{
"resource": ""
}
|
q50435
|
train
|
function () {
if (job.pull_requests < worker_count) {
return false;
}
for (var i = 0; i < worker_count; i++) {
if (!job.worker_complete[i]) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q50436
|
train
|
function () {
//Check if any input was added dynamically
if (job.input.length > 0) {
job.is_complete = false;
return false;
}
//Wait for workers or instances that are still working
return worker_count > 0 ? areWorkersComplete() : job.instances <= 0;
}
|
javascript
|
{
"resource": ""
}
|
|
q50437
|
train
|
function (options, start_as_slave) {
isSlave = start_as_slave && !process.env._CHILD_ID_;
isMaster = !start_as_slave && !process.env._CHILD_ID_;
this.options = options || {};
this.jobs = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q50438
|
train
|
function (job_name, job_obj) {
//If we're capturing output, we need to explicitly override job.output()
if (isMaster && capture_output) {
var output = [];
job_obj.output = function (out) {
if (out instanceof Array && job_obj.options.flatten) {
for (var i = 0, l = out.length; i < l; i++) {
output.push(out[i]);
}
} else {
output.push(out);
}
};
var old_callback = callback;
callback = function (err) {
old_callback(err, output);
};
}
//Are we distributing work?
fork = job_obj.options.fork;
//Initialise the processor
processor.init(function () {
//Start the job
if (isMaster) {
processor.startJob(job_name, job_obj, callback);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q50439
|
train
|
function (path) {
if (path[path.length - 1] === '/') {
path = path.substr(0, path.length - 1);
}
return path;
}
|
javascript
|
{
"resource": ""
}
|
|
q50440
|
train
|
function (msg, type) {
var cmd = type;
switch (type) {
case 'info':
msg = '\x1B[33mINFO\x1B[0m: ' + msg;
break;
case 'debug':
cmd = 'info';
msg = '\x1B[36mDEBUG\x1B[0m: ' + msg;
break;
case 'error':
case 'fatal':
cmd = 'error';
msg = '\x1B[31mERROR\x1B[0m: ' + msg;
break;
case 'ok':
cmd = 'info';
msg = '\x1B[32mOK\x1B[0m: ' + msg;
break;
case 'bold':
cmd = 'info';
msg = '\x1B[33mINFO\x1B[0m: \x1B[1m' + msg + '\x1B[0m';
break;
}
console[cmd](msg); //Write output according to status severity
if (type === 'fatal') {
process.exit(1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50441
|
train
|
function (output, options) {
this.output = output;
this.options = options;
// Set sane defaults for any options.
this.options.rootAssetPath = options.rootAssetPath || './';
this.options.ignorePaths = options.ignorePaths || [];
this.options.extensionsRegex = options.extensionsRegex || null;
this.options.format = options.format || 'general';
}
|
javascript
|
{
"resource": ""
}
|
|
q50442
|
createDeployTasks
|
train
|
function createDeployTasks(depolyConfs, files, flaten){
var tasks = flaten ? [] : {};
fis.util.map(files, function(subpath, file) {
fis.util.map(depolyConfs, function(name, depolyConf) {
var target = flaten? tasks : (tasks[name] = tasks[name] || []);
depolyConf.forEach(function(d) {
if(
file.release &&
file.release.indexOf(d.from) === 0 && //relate to replaceFrom
fis.util.filter(file.release, d.include, d.exclude)
) {
target.push({dest : d, file : file });
}
});
});
});
return tasks;
}
|
javascript
|
{
"resource": ""
}
|
q50443
|
flattenList
|
train
|
function flattenList(list) {
// Make a copy, so the original tensor is not modified.
list = [].concat(list);
// Note that i must be checked against the length of the list each time through the loop, as the
// list is modified within the iterations.
for (let i = 0; i < list.length; i++) {
if (Array.isArray(list[i])) {
// Replace the item with the flattened version of the item (using the ... operator).
// Replace with the items and backtrack 1 position
list.splice(i, 1, ...list[i]);
// Decrement i to look at the element again; we'll keep looking at this i index, until
// the most deeply nested item has been flattened.
i--;
}
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
q50444
|
upsertDocumentController
|
train
|
function upsertDocumentController(req, res) {
var modelName = req.params.modelName,
id = req.params.documentId,
user = req.admin_user,
data = _.extend({}, req.body, req.files),
modelConfig = registry.models[modelName],
form;
polymorphGetDocument(modelConfig.model, modelConfig.is_single, id).then(
function createTheForm(document) {
var action = document ? 'update' : 'create';
var docType = document && document._doc.__t;
if (docType) modelConfig = registry.models[docType];
var FormType = modelConfig.options.form;
if (!user.hasPermissions(modelConfig.modelName, action)) throw new Error('unauthorized');
form = new FormType(modelConfig.options, modelConfig.model, document, data);
return form.save();
}
).then(
function (document) {
modelConfig.options.post(document);
return form;
},
function (err) {
err.modelConfig = modelConfig;
err.form = form;
if (!form) throw err;
form.errors = form.errors || {};
if (err.name == 'ValidationError') {
form.errors = _.merge(form.errors, err.errors);
} else if (err.name === 'MongoError' && err.code == 11000) {
form.errors.exception = err;
err.name = "Duplicate";
var msg = '{' + err.err.split('$').pop().split('{').pop();
var ObjectID = /ObjectId\(\'(\w+)\'\)/.exec(msg);
err.fields = '\n<br />';
err.fields += (ObjectID.length == 2) ? '<a href="' + ObjectID[1] + '" target="_blank">Click to open duplicate document</a>' :
msg;
} else {
form.errors.exception = err;
}
if (_.isEmpty(form.errors)) return form;
throw err;
}
).then(
function (form) {
res._debug_form = form;
var response = form.instance.toJSON();
response.id = response.id || form.instance._id;
response.label = response.label || form.instance.name || form.instance.title || form.instance.toString();
return response;
}
).then(
function (response) {
res.json(200, response);
},
function (err) {
err.form = res._debug_form;
res.json(422, err);
}
).end();
}
|
javascript
|
{
"resource": ""
}
|
q50445
|
train
|
function (pathOrRequestMatcher, type) {
if (type) {
var typeEnum = ['EXPECTATIONS', 'LOG', 'ALL'];
if (typeEnum.indexOf(type) === -1) {
throw new Error("\"" + (type || "undefined") + "\" is not a supported value for \"type\" parameter only " + typeEnum + " are allowed values");
}
}
return makeRequest(host, port, "/clear" + (type ? "?type=" + type : ""), addDefaultRequestMatcherHeaders(pathOrRequestMatcher));
}
|
javascript
|
{
"resource": ""
}
|
|
q50446
|
train
|
function (ports) {
if (!Array.isArray(ports)) {
throw new Error("ports parameter must be an array but found: " + JSON.stringify(ports));
}
return makeRequest(host, port, "/bind", {ports: ports});
}
|
javascript
|
{
"resource": ""
}
|
|
q50447
|
train
|
function (data, legacy) {
if (!data) { return; }
var head,
headers = [],
statusValue = !legacy,
match = regexes.header.exec(data),
property = legacy ? 'enabled' : 'disabled';
data = data.toString().replace(regexes.fold, '$1');
while (match) {
head = {
key: match[1],
value: match[3].replace(regexes.trim, '$1')
};
if (_.startsWith(head.key, headersCommentPrefix)) {
head[property] = statusValue;
head.key = head.key.replace(headersCommentPrefix, '').trim();
}
headers.push(head);
match = regexes.header.exec(data);
}
return headers;
}
|
javascript
|
{
"resource": ""
}
|
|
q50448
|
train
|
function (collection, options, callback) {
if (!options.outputVersion || !semver.valid(options.outputVersion, true)) {
return callback(new Error('Output version not specified or invalid: ' + options.outputVersion));
}
if (!options.inputVersion || !semver.valid(options.inputVersion, true)) {
return callback(new Error('Input version not specified or invalid: ' + options.inputVersion));
}
return converter.convert(collection, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q50449
|
train
|
function (object, options, callback) {
if (!options.outputVersion || !semver.valid(options.outputVersion, true)) {
return callback(new Error('Output version not specified or invalid: ' + options.outputVersion));
}
if (!options.inputVersion || !semver.valid(options.inputVersion, true)) {
return callback(new Error('Input version not specified or invalid: ' + options.inputVersion));
}
return converter.convertSingle(object, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q50450
|
train
|
function (entityV1, options) {
if (!entityV1) { return; }
var auth,
params,
mapper,
currentHelper,
helperAttributes,
prioritizeV2 = this.options.prioritizeV2;
// if prioritize v2 is true, use auth as the source of truth
if (util.notLegacy(entityV1, 'auth') || (entityV1.auth && prioritizeV2)) {
return util.sanitizeAuthArray(entityV1, options);
}
if ((entityV1.currentHelper === null) || (entityV1.currentHelper === 'normal')) { return null; }
currentHelper = entityV1.currentHelper;
helperAttributes = entityV1.helperAttributes;
// if noDefaults is false and there is no currentHelper, bail out
if (!(currentHelper || this.options.noDefaults)) { return; }
// if there is a currentHelper without helperAttributes, bail out.
if (currentHelper && !helperAttributes) { return this.options.noDefaults ? undefined : null; }
!currentHelper && (currentHelper = authIdMap[helperAttributes && helperAttributes.id]);
auth = { type: v1Common.authMap[currentHelper] };
mapper = util.authMappersFromLegacy[currentHelper];
// @todo: Change this to support custom auth helpers
mapper && helperAttributes && (params = mapper(helperAttributes)) && (auth[auth.type] = params);
return util.authMapToArray({ auth: auth }, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q50451
|
train
|
function (requestV1) {
if (!requestV1) { return; }
var mode = requestV1.dataMode,
noDefaults = this.options.noDefaults,
retainEmptyValues = this.options.retainEmptyValues;
if ((!mode || mode === 'binary') && !noDefaults) {
return retainEmptyValues ? [] : undefined;
}
if (!requestV1.data) { return; }
_.isArray(requestV1.data) && _.forEach(requestV1.data, function (datum) {
if (datum.type === 'file' && (_.has(datum, 'value') || !noDefaults)) {
datum.value = (_.isString(datum.value) || _.isArray(datum.value)) ? datum.value : null;
}
util.cleanEmptyValue(datum, 'description', retainEmptyValues);
});
return requestV1.data;
}
|
javascript
|
{
"resource": ""
}
|
|
q50452
|
train
|
function (requestV1) {
if (!requestV1) { return; }
if (requestV1.headers && _.isEmpty(requestV1.headerData)) {
// this converts a newline concatenated string of headers to an array, so there are no descriptions
return v1Common.parseHeaders(requestV1.headers, true);
}
// however, if non empty headerData already exists, sanitize it.
return normalizeEntities(requestV1.headerData, this.options);
}
|
javascript
|
{
"resource": ""
}
|
|
q50453
|
train
|
function (responseV1) {
var self = this;
// if noDefaults is true, do not replace the id
// else
// if id is falsy, replace the id
// if retainIds is false, replace the id
!((self.options.retainIds && responseV1.id) || self.options.noDefaults) && (responseV1.id = util.uid());
// the true in the next line ensures that we don't recursively go on processing responses in a request.
responseV1.request = self.request(responseV1.request, undefined, true);
!responseV1.language && (responseV1.language = 'Text');
!responseV1.previewType && (responseV1.previewType = 'html');
_.isEmpty(responseV1.cookies) && (delete responseV1.cookies);
return responseV1;
}
|
javascript
|
{
"resource": ""
}
|
|
q50454
|
train
|
function (collectionV1) {
if (_.isEmpty(collectionV1 && collectionV1.folders)) { return; }
var auth,
events,
variables,
self = this,
order,
foldersOrder,
retainEmpty = self.options.retainEmptyValues,
varOpts = { noDefaults: self.options.noDefaults };
_.forEach(collectionV1.folders, function (folder) {
if (!folder) { return; }
// if noDefaults is true, do not replace the id
// else
// if id is falsy, replace the id
// if retainIds is false, replace the id
!((self.options.retainIds && folder.id) || self.options.noDefaults) && (folder.id = util.uid());
util.cleanEmptyValue(folder, 'description', retainEmpty);
auth = self.auth(folder);
!_.isEmpty((order = self.order(folder))) && (folder.order = order);
!_.isEmpty((foldersOrder = self.folders_order(folder))) && (folder.folders_order = foldersOrder);
(auth || (auth === null)) && (folder.auth = auth);
(events = self.events(folder)) && (folder.events = events);
(variables = self.variables(folder, varOpts)) && (folder.variables = variables);
});
return _.compact(collectionV1.folders);
}
|
javascript
|
{
"resource": ""
}
|
|
q50455
|
train
|
function (request, options, callback) {
var err,
normalized,
builders = new Builders(options);
// At this stage, mutate will not be passed ordinarily. Hence, the falsy nature of options.mutate can be used
// to selectively clone the request.
options && !options.mutate && (request = _.cloneDeep(request));
try { normalized = builders.request(request); }
catch (e) { err = e; }
if (callback) { return callback(err, normalized); }
if (err) { throw err; }
return normalized;
}
|
javascript
|
{
"resource": ""
}
|
|
q50456
|
train
|
function (inputVersion, outputVersion) {
var converter;
inputVersion = semver.clean(inputVersion);
outputVersion = semver.clean(outputVersion);
for (converter in this.converters) {
// eslint-disable-next-line no-prototype-builtins
converter = this.converters.hasOwnProperty(converter) && this.converters[converter];
if (converter && semver.eq(converter.input, inputVersion) && semver.eq(converter.output, outputVersion)) {
return generateConverter(converter);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50457
|
train
|
function (collection, options, callback) {
var chosenConverter = this.getConverter(options.inputVersion, options.outputVersion);
if (!chosenConverter) {
return callback(new Error('no conversion path found'));
}
return chosenConverter.convert(collection, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q50458
|
train
|
function (object, options, callback) {
var chosenConverter = this.getConverter(options.inputVersion, options.outputVersion);
if (!chosenConverter) {
return callback(new Error('no conversion path found'));
}
return chosenConverter.convertSingle(object, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q50459
|
train
|
function (options) {
var chosenConverter = this.getConverter(options.inputVersion, options.outputVersion);
return chosenConverter.create(options);
}
|
javascript
|
{
"resource": ""
}
|
|
q50460
|
train
|
function (collection, options, callback) {
var version;
if (!options || !(version = semver.valid(options.normalizeVersion, true)) || !normalizers[version]) {
return callback(new Error('Version not specified or invalid: ' + options.normalizeVersion));
}
return normalizers[version].normalize(collection, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q50461
|
train
|
function (object, options, callback) {
var version;
if (!options || !(version = semver.valid(options.normalizeVersion, true)) || !normalizers[version]) {
return callback(new Error('Version not specified or invalid: ' + options.normalizeVersion));
}
return normalizers[version].normalizeSingle(object, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q50462
|
train
|
function (response, options, callback) {
var version;
if (!options || !(version = semver.valid(options.normalizeVersion, true)) || !normalizers[version]) {
return callback(new Error('Version not specified or invalid: ' + options.normalizeVersion));
}
return normalizers[version].normalizeResponse(response, options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q50463
|
train
|
function () {
var n,
r,
E = '',
H = '-'; // r = result , n = numeric variable for positional checks
// if "n" is not 9 or 14 or 19 or 24 return a random number or 4
// if "n" is not 15 generate a random number from 0 to 15
// `(n ^ 20 ? 16 : 4)` := unless "n" is 20, in which case a random number from 8 to 11 otherwise 4
//
// in other cases (if "n" is 9,14,19,24) insert "-"
// eslint-disable-next-line curly
for (r = n = E; n++ < 36; r += n * 51 & 52 ? (n ^ 15 ? 8 ^ rnd() * (n ^ 20 ? 16 : 4) : 4).toString(16) : H);
return r;
}
|
javascript
|
{
"resource": ""
}
|
|
q50464
|
train
|
function (entity, options, modifiers) {
!options && (options = {});
var self = this,
noDefaults = options.noDefaults,
isV1 = modifiers && modifiers.isV1,
retainEmpty = options.retainEmptyValues,
source = entity && (entity.variables || entity.variable || (isV1 && entity.pathVariableData)),
fallback = options.fallback && options.fallback.values,
result = _.map(source || fallback, function (item) {
var result = {
id: (noDefaults || item.id) ? item.id : self.uid(),
key: item.key || item.id,
value: item.value,
type: (item.type === 'text' ? 'string' : item.type) || self.typeMap[typeof item.value] || 'any'
};
item.disabled && (result.disabled = true);
if (item.description) { result.description = item.description; }
else if (retainEmpty) { result.description = null; }
return result;
});
if (result.length) { return result; }
}
|
javascript
|
{
"resource": ""
}
|
|
q50465
|
train
|
function (entity, options) {
!options && (options = {});
var auth = entity && entity.auth;
if (auth === null) { return null; } // eslint-disable-line security/detect-possible-timing-attacks
if (!(auth && auth.type)) { return; }
if (auth.type === 'noauth') {
return options.excludeNoauth ? null : { type: 'noauth' };
}
return auth;
}
|
javascript
|
{
"resource": ""
}
|
|
q50466
|
train
|
function (entity, options) {
var type,
result,
self = this,
auth = self.cleanAuth(entity, options);
if (!auth) { return auth; }
result = { type: (type = auth.type) };
if (type !== 'noauth') {
result[type] = _.transform(auth[type], function (result, param) {
result[param.key] = param.value;
}, {});
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q50467
|
train
|
function (entity, options) {
var type,
params,
result,
self = this,
auth = self.cleanAuth(entity, options);
if (!auth) { return auth; }
result = { type: (type = auth.type) };
if (type !== 'noauth') {
// @todo: Handle all non _ prefixed properties, ala request bodies
params = _.map(auth[type], function (value, key) {
return {
key: key,
value: value,
type: self.typeMap[typeof value] || 'any'
};
});
params.length && (result[type] = params);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q50468
|
train
|
function (entity, options) {
var type,
result,
self = this,
auth = self.cleanAuth(entity, options);
if (!auth) { return auth; }
result = { type: (type = auth.type) };
if (type !== 'noauth') {
result[type] = _.map(auth[type], function (param) {
return {
key: param.key,
value: param.value,
type: (param.type === 'text' ? 'string' : param.type) || self.typeMap[typeof param.value] || 'any'
};
});
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q50469
|
train
|
function (entityV1, type) {
if (!entityV1) { return; }
switch (type) {
case 'event':
return !(entityV1.tests || entityV1.preRequestScript);
case 'auth':
return _.has(entityV1, 'auth') && !(_.has(entityV1, 'currentHelper') || entityV1.helperAttributes);
default:
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q50470
|
train
|
function (source, destination) {
var behavior = source && source.protocolProfileBehavior;
if (!(behavior && typeof behavior === 'object')) { return false; }
destination && (destination.protocolProfileBehavior = behavior);
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q50471
|
train
|
function (collectionV1) {
var info = {
_postman_id: collectionV1.id || util.uid(),
name: collectionV1.name
};
if (collectionV1.description) { info.description = collectionV1.description; }
else if (this.options.retainEmptyValues) { info.description = null; }
info.schema = constants.SCHEMA_V2_URL;
return info;
}
|
javascript
|
{
"resource": ""
}
|
|
q50472
|
train
|
function (requestV1) {
var queryParams = [],
pathVariables = [],
traversedVars = {},
queryParamAltered,
traversedQueryParams = {},
parsed = util.urlparse(requestV1.url),
retainEmpty = this.options.retainEmptyValues;
// Merge query params
_.forEach(requestV1.queryParams, function (queryParam) {
(queryParam.enabled === false) && (queryParam.disabled = true);
delete queryParam.enabled;
util.cleanEmptyValue(queryParam, 'description', retainEmpty);
if (_.has(queryParam, 'equals')) {
if (queryParam.equals) {
(queryParam.value === null) && (queryParam.value = '');
queryParamAltered = true;
}
else {
// = is not appended when the value is null
(queryParam.value === '') && (queryParam.value = null);
queryParamAltered = true;
}
delete queryParam.equals;
}
queryParams.push(queryParam);
traversedQueryParams[queryParam.key] = true;
});
// parsed query params are taken from the url, so no descriptions are available from them
_.forEach(parsed.query, function (queryParam) {
!traversedQueryParams[queryParam.key] && queryParams.push(queryParam);
});
// Merge path variables
_.forEach(requestV1.pathVariableData, function (pathVariable) {
pathVariable = _.clone(pathVariable);
util.cleanEmptyValue(pathVariable, 'description', retainEmpty);
pathVariables.push(pathVariable);
traversedVars[pathVariable.key] = true;
});
// pathVariables in v1 are of the form {foo: bar}, so no descriptions can be obtained from them
_.forEach(requestV1.pathVariables, function (value, id) {
!traversedVars[id] && pathVariables.push({
value: value,
id: id
});
});
!_.isEmpty(queryParams) && (parsed.query = queryParams);
!_.isEmpty(pathVariables) && (parsed.variable = pathVariables);
// If the query params have been altered, update the raw stringified URL
queryParamAltered && (parsed.raw = util.urlunparse(parsed));
// return the objectified URL only if query param or path variable descriptions are present, string otherwise
return (parsed.query || parsed.variable) ? parsed : (parsed.raw || requestV1.url);
}
|
javascript
|
{
"resource": ""
}
|
|
q50473
|
train
|
function (requestV1) {
if (_.isArray(requestV1.headers)) {
return requestV1.headers;
}
var headers = [],
traversed = {},
headerData = requestV1.headerData || [],
retainEmpty = this.options.retainEmptyValues;
_.forEach(headerData, function (header) {
if (_.startsWith(header.key, headersCommentPrefix) || (header.enabled === false)) {
header.disabled = true;
header.key = header.key.replace(headersCommentPrefix, '').trim();
}
// prevent empty header descriptions from showing up in converted results. This keeps the collections clean
util.cleanEmptyValue(header, 'description', retainEmpty);
delete header.enabled;
headers.push(header); // @todo Improve this sequence to account for multi-valued headers
traversed[header.key] = true;
});
// requestV1.headers is a string, so no descriptions can be obtained from it
_.forEach(v1Common.parseHeaders(requestV1.headers), function (header) {
!traversed[header.key] && headers.push(header);
});
return headers;
}
|
javascript
|
{
"resource": ""
}
|
|
q50474
|
train
|
function (requestV1) {
var modes = {
urlencoded: 'urlencoded',
params: 'formdata',
raw: 'raw',
binary: 'file'
},
data = {},
rawModeData,
dataMode = modes[requestV1.dataMode],
retainEmpty = this.options.retainEmptyValues;
// set null body if neither data|rawModeData nor dataMode is set, or if the dataMode is explicitly set to null
// The explicit null check is added to ensure that body is not set in case the dataMode was set to null by the
// app, but `data` or `rawModeData` was not empty
if ((!dataMode && _.isEmpty(requestV1.data) && _.isEmpty(requestV1.rawModeData)) ||
requestV1.dataMode === null) {
return retainEmpty ? null : undefined;
}
// set `rawModeData` if its a string
if (_.isString(requestV1.rawModeData)) {
rawModeData = requestV1.rawModeData;
}
// check if `rawModeData` is an array like: ['rawModeData']
else if (Array.isArray(requestV1.rawModeData) &&
requestV1.rawModeData.length === 1 &&
_.isString(requestV1.rawModeData[0])) {
rawModeData = requestV1.rawModeData[0];
}
// set data.mode.
// if dataMode is not set, infer from data or rawModeData
// at this point either data or rawModeData is set
if (dataMode) {
data.mode = dataMode;
}
// set `formdata` if rawModeData is not set and data is an array
// `data` takes higher precedence over `rawModeData`.
else if (!rawModeData && Array.isArray(requestV1.data || requestV1.rawModeData)) {
data.mode = 'formdata';
}
// set `raw` mode as default
else {
data.mode = 'raw';
}
if (data.mode === 'raw') {
if (rawModeData) {
data[data.mode] = rawModeData;
}
else if (_.isString(requestV1.data)) {
data[data.mode] = requestV1.data;
}
else {
data[data.mode] = ''; // empty string instead of retainEmpty check to have parity with other modes.
}
}
else if (data.mode === 'file') {
data[data.mode] = { src: rawModeData }; // rawModeData can be string or undefined.
}
else {
// parse data for formdata or urlencoded data modes.
// `rawModeData` is checked in case its of type `data`.
data[data.mode] = parseFormData(requestV1.data || requestV1.rawModeData, retainEmpty);
}
if (requestV1.dataDisabled) { data.disabled = true; }
else if (retainEmpty) { data.disabled = false; }
return data;
}
|
javascript
|
{
"resource": ""
}
|
|
q50475
|
train
|
function (entityV1) {
if (!entityV1) { return; }
// if prioritizeV2 is true, events is used as the source of truth
if ((util.notLegacy(entityV1, 'event') || this.options.prioritizeV2) && !_.isEmpty(entityV1.events)) {
// in v1, `events` is regarded as the source of truth if it exists, so handle that first and bail out.
// @todo: Improve this to order prerequest events before test events
_.forEach(entityV1.events, function (event) {
!event.listen && (event.listen = 'test');
if (event.script) {
!event.script.type && (event.script.type = 'text/javascript');
// @todo: Add support for src
_.isString(event.script.exec) && (event.script.exec = event.script.exec.split('\n'));
}
});
return entityV1.events;
}
var events = [];
// @todo: Extract both flows below into a common method
if (entityV1.tests) {
events.push({
listen: 'test',
script: {
type: 'text/javascript',
exec: _.isString(entityV1.tests) ?
entityV1.tests.split('\n') :
entityV1.tests
}
});
}
if (entityV1.preRequestScript) {
events.push({
listen: 'prerequest',
script: {
type: 'text/javascript',
exec: _.isString(entityV1.preRequestScript) ?
entityV1.preRequestScript.split('\n') :
entityV1.preRequestScript
}
});
}
return events.length ? events : undefined;
}
|
javascript
|
{
"resource": ""
}
|
|
q50476
|
train
|
function (requestV1) {
var self = this,
request = {},
retainEmpty = self.options.retainEmptyValues,
units = ['auth', 'method', 'header', 'body', 'url'];
units.forEach(function (unit) {
request[unit] = self[unit](requestV1);
});
if (requestV1.description) { request.description = requestV1.description; }
else if (retainEmpty) { request.description = null; }
return request;
}
|
javascript
|
{
"resource": ""
}
|
|
q50477
|
train
|
function (cookieV1) {
return {
expires: (new Date(cookieV1.expirationDate * 1000)).toString(),
hostOnly: cookieV1.hostOnly,
httpOnly: cookieV1.httpOnly,
domain: cookieV1.domain,
path: cookieV1.path,
secure: cookieV1.secure,
session: cookieV1.session,
value: cookieV1.value,
key: cookieV1.name
};
}
|
javascript
|
{
"resource": ""
}
|
|
q50478
|
train
|
function (responseV1) {
var self = this,
associatedRequestId;
if (responseV1.requestObject) {
if (_.isString(responseV1.requestObject)) {
try {
return JSON.parse(responseV1.requestObject);
}
catch (e) {
// if there was an error parsing it as JSON, it's probably an ID, so store it in the ID variable
associatedRequestId = responseV1.requestObject;
}
}
else {
return responseV1.requestObject;
}
}
if (responseV1.request) {
if (_.isString(responseV1.request)) {
try {
return JSON.parse(responseV1.request);
}
catch (e) {
// if there was an error parsing it as JSON, it's probably an ID, so store it in the ID variable
associatedRequestId = responseV1.request;
}
}
else {
return responseV1.request;
}
}
// we have a request ID
return associatedRequestId && _.get(self, ['cache', associatedRequestId]);
}
|
javascript
|
{
"resource": ""
}
|
|
q50479
|
train
|
function (responseV1) {
var response = {},
self = this,
originalRequest;
originalRequest = self.savedRequest(responseV1);
// add ids to the v2 result only if both: the id and retainIds are truthy.
// this prevents successive exports to v2 from being overwhelmed by id diffs
self.options.retainIds && (response.id = responseV1.id || util.uid());
response.name = responseV1.name || 'response';
response.originalRequest = originalRequest ? self.request(originalRequest) : undefined;
response.status = responseV1.responseCode && responseV1.responseCode.name || undefined;
response.code = responseV1.responseCode && responseV1.responseCode.code || undefined;
response._postman_previewlanguage = responseV1.language;
response._postman_previewtype = responseV1.previewType;
response.header = responseV1.headers;
response.cookie = _.map(responseV1.cookies, function (cookie) {
return self.cookie(cookie);
});
response.responseTime = responseV1.time;
response.body = responseV1.text;
return response;
}
|
javascript
|
{
"resource": ""
}
|
|
q50480
|
train
|
function (requestV1) {
if (!requestV1) { return; }
var self = this,
units = ['request', 'response'],
variable = self.variable(requestV1),
item = {
name: requestV1.name || '', // Inline building to avoid additional function call
event: self.event(requestV1)
};
self.options.retainIds && (item._postman_id = requestV1.id || util.uid());
// add protocolProfileBehavior property from requestV1 to the item
util.addProtocolProfileBehavior(requestV1, item);
units.forEach(function (unit) {
item[unit] = self[unit](requestV1);
});
variable && variable.length && (item.variable = variable);
return item;
}
|
javascript
|
{
"resource": ""
}
|
|
q50481
|
train
|
function (collectionV1) {
var self = this,
items = [],
itemGroupCache = {},
retainEmpty = self.options.retainEmptyValues;
// Read all folder data, and prep it so that we can throw subfolders in the right places
itemGroupCache = _.reduce(collectionV1.folders, function (accumulator, folder) {
if (!folder) { return accumulator; }
var auth = self.auth(folder),
event = self.event(folder),
variable = self.variable(folder),
result = {
name: folder.name,
item: []
};
self.options.retainIds && (result._postman_id = folder.id || util.uid());
if (folder.description) { result.description = folder.description; }
else if (retainEmpty) { result.description = null; }
(auth || (auth === null)) && (result.auth = auth);
event && (result.event = event);
variable && variable.length && (result.variable = variable);
accumulator[folder.id] = result;
return accumulator;
}, {});
// Populate each ItemGroup with subfolders
_.forEach(collectionV1.folders, function (folderV1) {
if (!folderV1) { return; }
var itemGroup = itemGroupCache[folderV1.id],
hasSubfolders = folderV1.folders_order && folderV1.folders_order.length,
hasRequests = folderV1.order && folderV1.order.length;
// Add subfolders
hasSubfolders && _.forEach(folderV1.folders_order, function (subFolderId) {
if (!itemGroupCache[subFolderId]) {
// todo: figure out what to do when a collection contains a subfolder ID,
// but the subfolder is not actually there.
return;
}
itemGroupCache[subFolderId]._postman_isSubFolder = true;
itemGroup.item.push(itemGroupCache[subFolderId]);
});
// Add items
hasRequests && _.forEach(folderV1.order, function (requestId) {
if (!self.cache[requestId]) {
// todo: what do we do here??
return;
}
itemGroup.item.push(self.singleItem(self.cache[requestId]));
});
});
// This compromises some self-healing, which was originally present, but the performance cost of
// doing self-healing the right way is high, so we directly rely on collectionV1.folders_order
// The self-healing way would be to iterate over itemGroupCache directly, but preserving the right order
// becomes a pain in that case.
_.forEach(_.uniq(collectionV1.folders_order || _.map(collectionV1.folders, 'id')), function (folderId) {
var itemGroup = itemGroupCache[folderId];
itemGroup && !_.get(itemGroup, '_postman_isSubFolder') && items.push(itemGroup);
});
// This is useful later
self.itemGroupCache = itemGroupCache;
return _.compact(items);
}
|
javascript
|
{
"resource": ""
}
|
|
q50482
|
train
|
function (collectionV1) {
var self = this,
requestsCache = _.keyBy(collectionV1.requests, 'id'),
allRequests = _.map(collectionV1.requests, 'id'),
result;
self.cache = requestsCache;
result = self.itemGroups(collectionV1);
_.forEach(_.intersection(collectionV1.order, allRequests), function (requestId) {
var request = self.singleItem(requestsCache[requestId]);
request && (result.push(request));
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q50483
|
train
|
function (request, options, callback) {
var builders = new Builders(options),
converted,
err;
try {
converted = builders.singleItem(_.cloneDeep(request));
}
catch (e) {
err = e;
}
if (callback) {
return callback(err, converted);
}
if (err) {
throw err;
}
return converted;
}
|
javascript
|
{
"resource": ""
}
|
|
q50484
|
train
|
function (response, options, callback) {
var builders = new Builders(options),
converted,
err;
try {
converted = builders.singleResponse(_.cloneDeep(response));
}
catch (e) {
err = e;
}
if (callback) {
return callback(err, converted);
}
if (err) {
throw err;
}
return converted;
}
|
javascript
|
{
"resource": ""
}
|
|
q50485
|
train
|
function (collectionV1) {
var info = Builders.super_.prototype.info.call(this, collectionV1);
info.schema = constants.SCHEMA_V2_1_0_URL;
return info;
}
|
javascript
|
{
"resource": ""
}
|
|
q50486
|
train
|
function (requestV1) {
var v21Url = Builders.super_.prototype.url.call(this, requestV1);
return _.isString(v21Url) ? url.parse(v21Url) : v21Url;
}
|
javascript
|
{
"resource": ""
}
|
|
q50487
|
PingppResource
|
train
|
function PingppResource(pingpp, urlData) {
this._pingpp = pingpp;
this._urlData = urlData || {};
this.basePath = utils.makeURLInterpolator(pingpp.getApiField('basePath'));
this.path = utils.makeURLInterpolator(this.path);
if (this.includeBasic) {
this.includeBasic.forEach(function(methodName) {
this[methodName] = PingppResource.BASIC_METHODS[methodName];
}, this);
}
this.initialize.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q50488
|
merge
|
train
|
function merge (dest, src, redefine) {
if (!dest) {
throw new TypeError('argument dest is required')
}
if (!src) {
throw new TypeError('argument src is required')
}
if (redefine === undefined) {
// Default to true
redefine = true
}
Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName (name) {
if (!redefine && hasOwnProperty.call(dest, name)) {
// Skip descriptor
return
}
// Copy descriptor
var descriptor = Object.getOwnPropertyDescriptor(src, name)
Object.defineProperty(dest, name, descriptor)
})
return dest
}
|
javascript
|
{
"resource": ""
}
|
q50489
|
getTimings
|
train
|
function getTimings (eventTimes) {
return {
// There is no DNS lookup with IP address, can be null
dnsLookup: getHrTimeDurationInMs(
eventTimes.startAt,
eventTimes.dnsLookupAt
),
tcpConnection: getHrTimeDurationInMs(
eventTimes.dnsLookupAt || eventTimes.startAt,
eventTimes.tcpConnectionAt
),
// There is no TLS handshake without https, can be null
tlsHandshake: getHrTimeDurationInMs(
eventTimes.tcpConnectionAt,
eventTimes.tlsHandshakeAt
),
firstByte: getHrTimeDurationInMs((
// There is no TLS/TCP Connection with keep-alive connection
eventTimes.tlsHandshakeAt || eventTimes.tcpConnectionAt ||
eventTimes.startAt),
eventTimes.firstByteAt
),
contentTransfer: getHrTimeDurationInMs(
eventTimes.firstByteAt,
eventTimes.endAt
),
total: getHrTimeDurationInMs(eventTimes.startAt, eventTimes.endAt)
};
}
|
javascript
|
{
"resource": ""
}
|
q50490
|
normalizeOptions
|
train
|
function normalizeOptions(options) {
var opts = {};
if (typeof options === 'string') {
opts = {
url: options
};
} else if (_.isPlainObject(options)) {
opts = _.clone(options);
}
return opts;
}
|
javascript
|
{
"resource": ""
}
|
q50491
|
clientReq
|
train
|
function clientReq(req) {
if (!req) {
return (req);
}
var host;
try {
host = req.host.split(':')[0];
} catch (e) {
host = false;
}
return ({
method: req ? req.method : false,
url: req ? req.path : false,
address: host,
port: req ? req.port : false,
headers: req ? req.headers : false
});
}
|
javascript
|
{
"resource": ""
}
|
q50492
|
clientRes
|
train
|
function clientRes(res) {
if (!res || !res.statusCode) {
return (res);
}
return ({
statusCode: res.statusCode,
headers: res.headers
});
}
|
javascript
|
{
"resource": ""
}
|
q50493
|
createLogger
|
train
|
function createLogger(name) {
return (bunyan.createLogger({
name: name,
serializers: SERIALIZERS,
streams: [
{
level: 'warn',
stream: process.stderr
},
{
level: 'debug',
type: 'raw',
stream: new RequestCaptureStream({
stream: process.stderr
})
}
]
}));
}
|
javascript
|
{
"resource": ""
}
|
q50494
|
isProxyForURL
|
train
|
function isProxyForURL(noProxy, address) {
// wildcard
if (noProxy === '*') {
return (null);
}
// otherwise, parse the noProxy value to see if it applies to the URL
if (noProxy !== null) {
var noProxyItem, hostname, port, noProxyItemParts,
noProxyHost, noProxyPort, noProxyList;
// canonicalize the hostname
/* JSSTYLED */
hostname = address.hostname.replace(/^\.*/, '.').toLowerCase();
noProxyList = noProxy.split(',');
for (var i = 0, len = noProxyList.length; i < len; i++) {
noProxyItem = noProxyList[i].trim().toLowerCase();
// no_proxy can be granular at the port level
if (noProxyItem.indexOf(':') > -1) {
noProxyItemParts = noProxyItem.split(':', 2);
/* JSSTYLED */
noProxyHost = noProxyItemParts[0].replace(/^\.*/, '.');
noProxyPort = noProxyItemParts[1];
port = address.port ||
(address.protocol === 'https:' ? '443' : '80');
// match - ports are same and host ends with no_proxy entry.
if (port === noProxyPort &&
hostname.indexOf(noProxyHost) ===
hostname.length - noProxyHost.length) {
return (null);
}
} else {
/* JSSTYLED */
noProxyItem = noProxyItem.replace(/^\.*/, '.');
var isMatchedAt = hostname.indexOf(noProxyItem);
if (isMatchedAt > -1 &&
isMatchedAt === hostname.length - noProxyItem.length) {
return (null);
}
}
}
}
return (true);
}
|
javascript
|
{
"resource": ""
}
|
q50495
|
createHttpErr
|
train
|
function createHttpErr(statusCode, opts, req) {
assert.number(statusCode, 'statusCode');
assert.object(opts, 'opts');
assert.object(req, 'req');
var errInfo = createErrInfo(opts, req);
return restifyErrors.makeErrFromCode(statusCode, {
info: errInfo
});
}
|
javascript
|
{
"resource": ""
}
|
q50496
|
createRequestTimeoutErr
|
train
|
function createRequestTimeoutErr(opts, req) {
assert.object(opts, 'opts');
assert.object(req, 'req');
var errInfo = createErrInfo(opts, req);
var errMsg = [
opts.method,
'request to',
errInfo.fullUrl,
'failed to complete within',
opts.requestTimeout + 'ms'
].join(' ');
return new ERR_CTOR.RequestTimeoutError({
info: _.assign(errInfo, {
requestTimeout: opts.requestTimeout
})
}, '%s', errMsg);
}
|
javascript
|
{
"resource": ""
}
|
q50497
|
createTooManyRedirectsErr
|
train
|
function createTooManyRedirectsErr(opts, req) {
assert.object(opts, 'opts');
assert.object(req, 'req');
var errInfo = createErrInfo(opts, req);
var errMsg = [
'aborted',
opts.method,
'request to',
errInfo.fullUrl,
'after',
opts.redirects,
'redirects'
].join(' ');
return new ERR_CTOR.TooManyRedirectsError({
info: _.assign(errInfo, {
// add additional context relevant for redirects
numRedirects: opts.redirects,
maxRedirects: opts.maxRedirects
})
}, '%s', errMsg);
}
|
javascript
|
{
"resource": ""
}
|
q50498
|
createErrInfo
|
train
|
function createErrInfo(opts, req) {
assert.object(opts, 'opts');
assert.object(req, 'req');
return {
// port and address can both be unpopulated - fall back on null so
// that they can both be null (instead of req.remoteAddress
// defaulting to undefined)
address: req.remoteAddress || null,
fullUrl: fullRequestUrl(opts),
method: opts.method,
port: opts.port
};
}
|
javascript
|
{
"resource": ""
}
|
q50499
|
Writer
|
train
|
function Writer (props, current) {
var self = this
if (typeof props === 'string') {
props = { path: props }
}
// polymorphism.
// call fstream.Writer(dir) to get a DirWriter object, etc.
var type = getType(props)
var ClassType = Writer
switch (type) {
case 'Directory':
ClassType = DirWriter
break
case 'File':
ClassType = FileWriter
break
case 'Link':
case 'SymbolicLink':
ClassType = LinkWriter
break
case null:
default:
// Don't know yet what type to create, so we wrap in a proxy.
ClassType = ProxyWriter
break
}
if (!(self instanceof ClassType)) return new ClassType(props)
// now get down to business.
Abstract.call(self)
if (!props.path) self.error('Must provide a path', null, true)
// props is what we want to set.
// set some convenience properties as well.
self.type = props.type
self.props = props
self.depth = props.depth || 0
self.clobber = props.clobber === false ? props.clobber : true
self.parent = props.parent || null
self.root = props.root || (props.parent && props.parent.root) || self
self._path = self.path = path.resolve(props.path)
if (process.platform === 'win32') {
self.path = self._path = self.path.replace(/\?/g, '_')
if (self._path.length >= 260) {
self._swallowErrors = true
self._path = '\\\\?\\' + self.path.replace(/\//g, '\\')
}
}
self.basename = path.basename(props.path)
self.dirname = path.dirname(props.path)
self.linkpath = props.linkpath || null
props.parent = props.root = null
// console.error("\n\n\n%s setting size to", props.path, props.size)
self.size = props.size
if (typeof props.mode === 'string') {
props.mode = parseInt(props.mode, 8)
}
self.readable = false
self.writable = true
// buffer until ready, or while handling another entry
self._buffer = []
self.ready = false
self.filter = typeof props.filter === 'function' ? props.filter : null
// start the ball rolling.
// this checks what's there already, and then calls
// self._create() to call the impl-specific creation stuff.
self._stat(current)
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.