_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q61600
|
validation
|
function (callback, context) {
SjlMap.prototype.forEach.call(this.sort(), function (value, key, map) {
callback.call(context, this.wrapItems ? value.value : value, key, map);
}, this);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q61601
|
validation
|
function () {
if (this.wrapItems) {
return new Iterator(this.sort()._values.map(function (item) {
return item.value;
}));
}
return new SjlMap.prototype.values.call(this.sort());
}
|
javascript
|
{
"resource": ""
}
|
|
q61602
|
validation
|
function (key, value, priority) {
SjlMap.prototype.set.call(this, key, this.resolveItemWrapping(key, value, priority));
this._sorted = false;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q61603
|
validation
|
function (priority) {
var retVal;
if (sjl.classOfIs(priority, Number)) {
retVal = priority;
}
else {
this._internalPriorities += 1;
retVal = +this._internalPriorities;
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
|
q61604
|
validation
|
function (key, value, priority) {
var normalizedPriority = this.normalizePriority(priority),
serial = this._internalSerialNumbers++;
if (this.wrapItems) {
return new (this.itemWrapperConstructor) (key, value, normalizedPriority, serial);
}
try {
value.key = key;
value.priority = priority;
value.serial = serial;
}
catch (e) {
throw new TypeError('PriorityList can only work in "unwrapped" mode with values/objects' +
' that can have properties created/set on them. Type encountered: `' + sjl.classOf(value) + '`;' +
' Original error: ' + e.message);
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q61605
|
doesSecurityGroupExist
|
validation
|
function doesSecurityGroupExist (ec2, securityGroupName) {
function inspectError (err) {
if (err.code === 'InvalidGroup.NotFound') {
return false
}
return Bluebird.reject(err)
}
return ec2
.describeSecurityGroupsPromised({
GroupNames: [ securityGroupName ]
})
.then(_.constant(true))
.error(inspectError)
}
|
javascript
|
{
"resource": ""
}
|
q61606
|
doesAutoScalingGroupExist
|
validation
|
function doesAutoScalingGroupExist (autoScaling, asgName) {
return autoScaling
.describeAutoScalingGroupsPromised({
AutoScalingGroupNames: [ asgName ]
})
.then(function found (data) {
return !_.isEmpty(data.AutoScalingGroups)
})
}
|
javascript
|
{
"resource": ""
}
|
q61607
|
buildParams
|
validation
|
function buildParams (identifier, instanceState) {
var params = {}
if (instanceState) {
params.Filters = [
{
Name: 'instance-state-name',
Values: [instanceState]
}
]
}
if (isInstanceId(identifier)) {
params.InstanceIds = [identifier]
return params
}
params.Filters = params.Filters || []
params.Filters.push({
Name: 'tag:Name',
Values: [identifier]
})
return params
}
|
javascript
|
{
"resource": ""
}
|
q61608
|
doesInstanceExist
|
validation
|
function doesInstanceExist (ec2, identifier, instanceState) {
var params = buildParams(identifier, instanceState)
function inspectError (err) {
if (err.code === 'InvalidInstanceID.NotFound') {
return false
}
return Bluebird.reject(err)
}
return ec2
.describeInstancesPromised(params)
.then(function checkResult (data) {
return !isEmpty(data.Reservations)
})
.catch(inspectError)
}
|
javascript
|
{
"resource": ""
}
|
q61609
|
EdmundsClient
|
validation
|
function EdmundsClient(config) {
if (!(this instanceof EdmundsClient)) {
return new EdmundsClient(config);
}
var defaultConfig = {};
defaultConfig.responseFormat = 'json';
defaultConfig.baseUrl = 'https://api.edmunds.com';
this.config = extend(defaultConfig, config);
if (!this.config.apiKey) {
throw new Error('API key must be provided');
}
}
|
javascript
|
{
"resource": ""
}
|
q61610
|
addDefinition
|
validation
|
function addDefinition(defName) {
var definition = definitions[defName];
return function(params, done) {
if (!done && typeof params === 'function') {
done = params;
params = {};
}
var url = this.config.baseUrl + definition.url;
var xtraParams = {};
xtraParams.fmt = this.config.responseFormat;
xtraParams.api_key = this.config.apiKey;
try {
Object.keys(definition.params).forEach(function(paramName) {
var paramDef = definition.params[paramName];
if (!params[paramName]) {
if (paramDef.required) {
throw new Error('Parameter ' + paramName + ' is required');
} else {
return;
}
}
if (paramDef.location === 'url') {
url = url.replace(new RegExp('{' + paramName + '}', 'g'), params[paramName]);
} else if (paramDef.location === 'querystring') {
xtraParams[paramName] = params[paramName];
}
});
} catch (e) {
return done(e);
}
return request
.get(url)
.query(xtraParams)
.end(function onEnd(err, res) {
return done(err, res.body);
});
};
}
|
javascript
|
{
"resource": ""
}
|
q61611
|
createClient
|
validation
|
function createClient (host, port, concurrent, frequency, duration, gen, iteration) {
var auth = defaults.auth
var getMessage = defaults.getMessage
emitter.emit('start')
if (typeof gen.authenticate === 'function') {
auth = gen.authenticate
}
if (typeof gen.clientIterateMessage === 'function') {
getMessage = gen.clientIterateMessage
}
/**
* Once auth is complete, this actually initiates the client
* @method postAuth
* @async
* @private
* @param {object} err Error from auth, if any
* @param {object} cookies Any cookies to pass through to the socket object
* @param {string} user The username used to login
* @param {string} pass The password used to login
* @returns {object} undefined
*/
var postAuth = function (err, cookies, user, pass) {
++clientsAttempted
if (err) {
emitter.emit('error', err)
if (clientsAttempted === concurrent && _intervals.length === 0) {
emitter.emit('end')
}
return
}
var socketUrl = gen.getSocketURL(host, port, cookies, user, pass) || host + ':' + port
var socket = io(socketUrl, { multiplex: false })
.on('connect', function () {
emitter.emit('client-connected')
if (typeof gen.events.connect === 'function') {
gen.events.connect('connect', cookies, user, pass, {}, socket, emitter)
}
Object.keys(gen.events).forEach(function (eventName) {
socket.on(eventName, function (data) {
gen.events[eventName].call(null, eventName, cookies, user, pass, data, socket, emitter)
})
})
var sendMessage = function () {
var message = getMessage(cookies, user, pass)
if (!Array.isArray(message)) {
message = [message]
}
for (var i = 0, len = message.length; i < len; i++) {
if (message[i]) {
socket.json.send(message[i])
emitter.emit('message', message[i])
}
}
}
_intervals.push(setInterval(sendMessage, frequency))
setTimeout(function () {
clearInterval(_intervals.pop())
socket.emit('disconnect')
emitter.emit('disconnect')
socket.close()
if (_intervals.length === 0) {
done()
}
}, duration)
})
.on('connect_error', function (err) {
emitter.emit('error', err)
if (clientsAttempted === concurrent && _intervals.length === 0) {
emitter.emit('end')
}
})
}
auth(host, port, iteration, postAuth)
}
|
javascript
|
{
"resource": ""
}
|
q61612
|
validation
|
function(file) {
var xml = file.contents;
var xmlDoc = libxmljs.parseXml(xml);
var rootNode = xmlDoc.root();
var resourceObject = {};
var valueNodes = rootNode.find("data");
valueNodes.forEach(function(element) {
var name = element.attr("name").value();
var value = element.get("value").text();
resourceObject[name] = value;
});
return JSON.stringify(resourceObject);
}
|
javascript
|
{
"resource": ""
}
|
|
q61613
|
doesLaunchConfigurationExist
|
validation
|
function doesLaunchConfigurationExist (autoScaling, launchConfigurationName) {
return autoScaling.
describeLaunchConfigurationsPromised({
LaunchConfigurationNames: [ launchConfigurationName ]
})
.then(function found (data) {
return !_.isEmpty(data.LaunchConfigurations)
})
}
|
javascript
|
{
"resource": ""
}
|
q61614
|
KJU
|
validation
|
function KJU(configuration) {
var self = this
, option;
// defaults
this.limit = 500;
this.ms = 100;
this.interval = 15000;
this.warnings = true;
this.enabled = true;
this.recover = true;
this.dump = true;
this.path = process.cwd() + '/';
this.name = 'node_kju_backup.{sequence}.kju';
// apply the configuration
for (option in configuration)
this[option] = configuration[option];
// these values should not be configured
this.buffer = [];
this.length = 0;
this.drained = 0;
this.processed = 0;
this.since = Date.now();
this.minimum = this.interval / 2;
this.maximum = this.interval * 2;
// initialize the event emitter
EventEmitter2.call(this, { wildcard: true });
if (this.recover) this.recovery();
if (this.enabled) this.enable();
// make sure our backup path exists
fsExists(this.path, function existing(exists) {
if (!exists) {
return self.emit('error', new Error(self.path + ' does not exist.'));
}
if (self.path[self.path.length - 1] !== '/') {
return self.emit('error', new Error(self.path + ' should end with a slash'));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q61615
|
filter
|
validation
|
function filter(err, files) {
if (err) return self.emit('error', err);
var kjud = files.filter(function filterfiles(file) {
return (/(\d)\.kju$/).test(file);
});
// if we don't have any files we don't really need to emit 'recovered' so
// no need to check for the length here. We are only gonna use the length
// if there are files.
processed = kjud.length;
kjud.forEach(read);
}
|
javascript
|
{
"resource": ""
}
|
q61616
|
read
|
validation
|
function read(file, index, files) {
fs.readFile(self.path + file, function readFile(err, contents) {
if (err) return done(), self.emit('error', err);
// try to parse the file as JSON, if that doesn't work we have big issue
// because the file is damaged.
try {
var todo = JSON.parse(contents.toString('utf8'));
// pfew, it worked re-add it to kju and remove the file, I don't really
// care about the clean up process. So I'm not gonna handle the errors
// that could occur there.
self.push.apply(self, todo);
fs.unlink(self.path + file, function ignore(err) {});
} catch (e) {
self.emit('error'
, new Error('Corrupted file, unable to parse contents of ' + file)
);
}
done();
});
}
|
javascript
|
{
"resource": ""
}
|
q61617
|
validation
|
function () {
var s4 = function () {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
return s4() + s4() + '-' + s4();
}
|
javascript
|
{
"resource": ""
}
|
|
q61618
|
validation
|
function (raw) {
if (typeof raw !== 'object' || raw === null || util.isArray( raw )) {
return false;
}
if (raw.wiretree) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q61619
|
validation
|
function (func) {
var fnStr = func.toString().replace( /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '' );
return fnStr.slice( fnStr.indexOf( '(' ) + 1, fnStr.indexOf( ')' )).match(/([^\s,]+)/g) || [];
}
|
javascript
|
{
"resource": ""
}
|
|
q61620
|
validation
|
function (mod) {
self.res = getProcessed( self.processing, mod, self.raw.settings );
self.resolved = true;
callback();
}
|
javascript
|
{
"resource": ""
}
|
|
q61621
|
validation
|
function(width, height, camera) {
var id;
var w = width, h = height;
this.orientation = 'landscape';
this.listeners = {};
if (typeof width !== 'number') {
var image = width;
camera = height;
w = image.videoWidth || image.width;
h = image.videoHeight || image.height;
this.image = image;
}
this.defaultMarkerWidth = 1;
this.patternMarkers = {};
this.barcodeMarkers = {};
this.transform_mat = new Float32Array(16);
this.canvas = document.createElement('canvas');
this.canvas.width = w;
this.canvas.height = h;
this.ctx = this.canvas.getContext('2d');
this.videoWidth = w;
this.videoHeight = h;
if (typeof camera === 'string') {
var self = this;
this.cameraParam = new ARCameraParam(camera, function() {
self._initialize();
}, function(err) {
console.error("ARController: Failed to load ARCameraParam", err);
});
} else {
this.cameraParam = camera;
this._initialize();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61622
|
validation
|
function(src, onload, onerror) {
this.id = -1;
this._src = '';
this.complete = false;
this.onload = onload;
this.onerror = onerror;
if (src) {
this.load(src);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q61623
|
PackageMemberListReadStream
|
validation
|
function PackageMemberListReadStream(dirToScan) {
sjl.throwTypeErrorIfEmpty('PackageMemberListReadStream', 'dirToScan', dirToScan, String);
this._pathToRead = dirToScan;
Readable.call(this, {
encoding: 'utf8',
objectMode: false,
highWaterMark: 100000,
});
}
|
javascript
|
{
"resource": ""
}
|
q61624
|
doesLoadBalancerExist
|
validation
|
function doesLoadBalancerExist (elb, loadBalancerName) {
function inspectError (err) {
if (err.code === 'LoadBalancerNotFound') {
return false
}
return Bluebird.reject(err)
}
return elb
.describeLoadBalancersPromised({
LoadBalancerNames: [ loadBalancerName ]
})
.then(_.constant(true))
.error(inspectError)
}
|
javascript
|
{
"resource": ""
}
|
q61625
|
lint
|
validation
|
function lint(files) {
return gulp.src(files)
.pipe($.plumber())
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failOnError())
.pipe($.jscs())
.pipe($.notify(_jscsNotify));
}
|
javascript
|
{
"resource": ""
}
|
q61626
|
_browserifyBundle
|
validation
|
function _browserifyBundle() {
let bundler = browserifyBundler();
// Watch the bundler, and re-bundle it whenever files change
bundler = watchify(bundler);
bundler.on('update', () => _runBrowserifyBundle(bundler));
return _runBrowserifyBundle(bundler);
}
|
javascript
|
{
"resource": ""
}
|
q61627
|
PauseCommand
|
validation
|
function PauseCommand(args, define) {
if (args.length) {
this.message = new statements.ExpressionStatement(args, define);
if (this.message.error) throw this.message.error;
} else this.message = new statements.StringStatement("[<< Paused, Press RETURN to Continue >>]");
}
|
javascript
|
{
"resource": ""
}
|
q61628
|
ValidationErrors
|
validation
|
function ValidationErrors(errors) {
this.errors = errors ? errors : {};
this.addError = function(field, message) {
if (!this.errors[field]) { this.errors[field] = []; }
this.errors[field].push(util.format(message, field));
};
// omit field for full hash of errors
this.getErrors = function(field) {
if (field) {
return this.errors[field];
} else {
return this.errors;
}
};
this.hasErrors = function() {
return _.keys(this.errors).length > 0;
};
this.isValidationErrors = function() {
return true;
};
}
|
javascript
|
{
"resource": ""
}
|
q61629
|
LineCommand
|
validation
|
function LineCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 4) throw new SyntaxError('LINE command requires 4 arguments');
this.x1 = parsed.args[0];
this.y1 = parsed.args[1];
this.x2 = parsed.args[2];
this.y2 = parsed.args[3];
this.width = parsed.args.length > 4 ? parsed.args[4] : false;
}
|
javascript
|
{
"resource": ""
}
|
q61630
|
PointCommand
|
validation
|
function PointCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 2) throw new SyntaxError('POINT command requires 2 arguments');
this.x = parsed.args[0];
this.y = parsed.args[1];
if (parsed.args.length > 2) this.size = parsed.args[2];
else this.size = false;
}
|
javascript
|
{
"resource": ""
}
|
q61631
|
getRandom
|
validation
|
function getRandom(data) {
var x = Math.sin(data.getPrivate('rnd_seed')) * 10000;
data.setPrivate('rnd_seed', data.getPrivate('rnd_seed') + 1);
return x - Math.floor(x);
}
|
javascript
|
{
"resource": ""
}
|
q61632
|
ForCommand
|
validation
|
function ForCommand(args, define) {
var lowerArgs = args.toLowerCase();
var toIndex = lowerArgs.indexOf(' to ');
if (toIndex === -1) throw new SyntaxError('FOR has no TO');
var assignmentText = args.substring(0, toIndex).trim();
var stepIndex = lowerArgs.indexOf(' step ');
var upperLimitText, stepText;
if (stepIndex === -1) {
upperLimitText = args.substring(toIndex + 4).trim();
stepText = '1';
} else {
upperLimitText = args.substring(toIndex + 4, stepIndex).trim();
stepText = args.substring(stepIndex + 6).trim();
}
var assignmentEquals = assignmentText.indexOf('=');
if (assignmentEquals === -1) throw new SyntaxError('Expected assignment');
var variableName = assignmentText.substring(0, assignmentEquals).trim();
var equalsExpression = assignmentText.substring(assignmentEquals + 1).trim();
var assignmentExpr = new statements.AssignmentStatement(
new statements.VariableStatement(variableName),
new statements.ExpressionStatement(equalsExpression, define)
);
var upperLimitExpr = new statements.ExpressionStatement(upperLimitText, define);
if (upperLimitExpr.error) throw upperLimitExpr.error;
var stepExpr = new statements.ExpressionStatement(stepText, define);
if (stepExpr.error) throw stepExpr.error;
this.assignmentExpr = assignmentExpr;
this.upperLimitExpr = upperLimitExpr;
this.stepExpr = stepExpr;
this.block = define({
start: 'FOR',
end: 'NEXT'
});
this.loopCount = 0;
}
|
javascript
|
{
"resource": ""
}
|
q61633
|
Emitter
|
validation
|
function Emitter(opts) {
Transform.call(this);
this._writableState.objectMode = true;
this._readableState.objectMode = true;
opts = opts || {};
// emit a fixed event name
// rather than the default type
this.name = opts.name;
this.passthrough = opts.passthrough;
}
|
javascript
|
{
"resource": ""
}
|
q61634
|
freeMemory
|
validation
|
function freeMemory (mappedVars /*: Array<SublimeObject>*/, step /*: ?StepObject*/) /*: Promise<any> | void*/ {
if (mappedVars.length > 0) {
let mappedVarsStringify = []
for (let mappedVar /*: Object*/ of mappedVars) {
if (mappedVar.hasOwnProperty("self") && mappedVar.self) {
delete mappedVar.self.code
mappedVarsStringify.push(JSON.stringify(mappedVar.self))
}
}
return simpleEval(`freeMemory(json.loads("""[${mappedVarsStringify.join(',')}]"""))`, false, step)
}
}
|
javascript
|
{
"resource": ""
}
|
q61635
|
DrawtextCommand
|
validation
|
function DrawtextCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 3) throw new SyntaxError('DRAWTEXT command requires 3 arguments');
else if (parsed.args.length > 3 && parsed.args.length < 5) throw new SyntaxError('DRAWTEXT command requires 5 arguments');
this.text = parsed.args[0];
this.x1 = parsed.args[1];
this.y1 = parsed.args[2];
if (parsed.args.length > 3) {
this.x2 = parsed.args[3];
this.y2 = parsed.args[4];
} else {
this.x2 = false;
this.y2 = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q61636
|
writeLockFile
|
validation
|
function writeLockFile(path, data, cb) { // Like fs.writeFile within a lock.
lock(path, function (unlock) {
fse.writeFile(path, data, function (e, d) { unlock(); cb(e, d); });
});
}
|
javascript
|
{
"resource": ""
}
|
q61637
|
callHandlers
|
validation
|
function callHandlers(cults, e) {
var broken = false;
for (var i = 0; i < cults.length; i++) {
var cult = cults[i];
var handlers = cult && cult.events && cult.events[e.type];
if (!handlers) continue;
var selectors = Object.keys(handlers);
if (callHandler(cult, e, handlers, selectors) === false) {
broken = true;
break;
}
}
return broken;
}
|
javascript
|
{
"resource": ""
}
|
q61638
|
validation
|
function(def) {
var start = Array.isArray(def.start) ? def.start : [def.start];
var end = Array.isArray(def.end) ? def.end : [def.end];
var then = def.then ? (Array.isArray(def.then) ? def.then : [def.then]) : [];
var child = new Block(line, {
start: start,
end: end,
then: then
}, self);
self.children.push(child);
return child;
}
|
javascript
|
{
"resource": ""
}
|
|
q61639
|
entry
|
validation
|
function entry(object) {
var buffer;
switch(object.type) {
case 'header':
buffer = this.header(object.version);
break;
case 'database':
buffer = this.database(object.number);
break;
case 'key':
buffer = this.key(object);
//console.dir(object.type);
//console.dir(buffer);
break;
case 'eof':
buffer = this.eof();
break;
}
return buffer;
}
|
javascript
|
{
"resource": ""
}
|
q61640
|
database
|
validation
|
function database(n) {
var dbid = new Buffer([0xFE])
, len = this.getLengthEncoding(n, false);
return Buffer.concat([dbid, len], dbid.length + len.length);
}
|
javascript
|
{
"resource": ""
}
|
q61641
|
key
|
validation
|
function key(obj, vonly) {
var buffer = new Buffer(0)
, item;
if(obj.expiry !== undefined && !vonly) {
buffer = this.expiry(obj.expiry);
}
item = this[obj.rtype](obj, vonly);
return Buffer.concat(
[
buffer,
item
],
buffer.length + item.length
)
}
|
javascript
|
{
"resource": ""
}
|
q61642
|
expiry
|
validation
|
function expiry(expires) {
var buffer
, int64;
if(expires % 1000 === 0) {
buffer = new Buffer(5);
buffer.writeUInt8(0xFD, 0);
buffer.writeInt32LE(expires / 1000, 1);
}else{
buffer = new Buffer(9);
int64 = new Int64(expires);
buffer.writeUInt8(0xFC, 0);
buffer.writeUInt32LE(int64.low32(), 1);
buffer.writeUInt32LE(int64.high32(), 5);
}
return buffer;
}
|
javascript
|
{
"resource": ""
}
|
q61643
|
string
|
validation
|
function string(obj, vonly) {
var vtype = this.type(0)
, key = !vonly ? this.getStringBuffer(obj.key) : new Buffer(0)
, value = this.getStringBuffer(obj.value);
return Buffer.concat(
[
vtype,
key,
value
],
vtype.length + key.length + value.length
)
}
|
javascript
|
{
"resource": ""
}
|
q61644
|
list
|
validation
|
function list(obj, vonly) {
var vtype = this.type(1)
, key = !vonly ? this.getStringBuffer(obj.key) : new Buffer(0)
, len = this.getLengthEncoding(obj.value.length, false)
, value = this.array(obj.value);
return Buffer.concat(
[
vtype,
key,
len,
value
],
vtype.length + key.length + len.length + value.length
)
}
|
javascript
|
{
"resource": ""
}
|
q61645
|
zset
|
validation
|
function zset(obj, vonly) {
var vtype = this.type(3)
, key = !vonly ? this.getStringBuffer(obj.key) : new Buffer(0)
, length = obj.length !== undefined
? obj.length : Object.keys(obj.value).length
, len = this.getLengthEncoding(length, false)
, value = this.object(obj.value);
return Buffer.concat(
[
vtype,
key,
len,
value
],
vtype.length + key.length + len.length + value.length
)
}
|
javascript
|
{
"resource": ""
}
|
q61646
|
array
|
validation
|
function array(arr) {
var buffers = []
, buf
, i
, len = 0;
for(i = 0; i < arr.length; i++) {
buf = this.getStringBuffer(arr[i]);
len += buf.length;
buffers.push(buf);
}
return Buffer.concat(buffers, len);
}
|
javascript
|
{
"resource": ""
}
|
q61647
|
object
|
validation
|
function object(obj) {
var buffers = []
, buf
, k
, v
, len = 0;
for(k in obj) {
buf = this.getStringBuffer(k);
len += buf.length;
buffers.push(buf);
buf = this.getStringBuffer(obj[k]);
len += buf.length;
buffers.push(buf);
}
return Buffer.concat(buffers, len);
}
|
javascript
|
{
"resource": ""
}
|
q61648
|
getStringBuffer
|
validation
|
function getStringBuffer(s) {
var buffer
, n = typeof s === 'number' ? s : null
// compressed header buffer
, cheader
, compressed;
// Does it look like a number?
if(n !== null
|| typeof s === 'string' && s.match(/^-?\d+$/)) {
if(n === null) {
n = parseInt(s);
}
if (n >= -128 && n <= 127) {
buffer = new Buffer(1);
buffer.writeInt8(n, 0);
buffer = this.length(buffer, 0, true);
return buffer;
} else if (n >= -32768 && n <= 32767) {
buffer = new Buffer(2);
buffer.writeInt16LE(n, 0);
buffer = this.length(buffer, 1, true);
return buffer;
} else if (n >= -2147483648 && n <= 2147483647) {
buffer = new Buffer(4);
buffer.writeInt32LE(n, 0);
buffer = this.length(buffer, 2, true);
return buffer;
}
}
// It doesn't look like a number, or it's too big
if(typeof s === 'string') {
buffer = new Buffer(s, this.encoding);
}else if(s instanceof Buffer){
buffer = s;
}
if(buffer.length > this.compressionThreshold) {
compressed = lzf.compress(buffer);
if (compressed.length < buffer.length) {
// It saved some space
cheader = Buffer.concat(
[
this.getLengthEncoding(3, true),
this.getLengthEncoding(compressed.length, false),
this.getLengthEncoding(buffer.length, false)
]);
return Buffer.concat(
[cheader, compressed], cheader.length + compressed.length);
}
}
buffer = this.length(buffer, buffer.length, false);
return buffer;
}
|
javascript
|
{
"resource": ""
}
|
q61649
|
length
|
validation
|
function length(buffer, n, special) {
var len = this.getLengthEncoding(n, special);
return Buffer.concat([len, buffer], len.length + buffer.length);
}
|
javascript
|
{
"resource": ""
}
|
q61650
|
getLengthEncoding
|
validation
|
function getLengthEncoding(n, special) {
if(n < 0) throw new Error('Cannot write negative length encoding: ' + n);
if(!special) {
if(n <= 0x3F) {
return new Buffer([n]);
}else if (n <= 0x3FFF) {
return new Buffer([0x40 | (n >> 8), n & 0xFF]);
}else if (n <= 0xFFFFFFFF) {
var buffer = new Buffer(5);
buffer.writeUInt8(0x80, 0);
buffer.writeUInt32BE(n, 1);
return buffer;
}
throw new Error('Failed to write length encoding: ' + n);
}else{
if (n > 0x3F) {
throw new Error('Cannot encode ' + n + ' using special length encoding');
}
return new Buffer([0xC0 | n]);
}
}
|
javascript
|
{
"resource": ""
}
|
q61651
|
TextfontCommand
|
validation
|
function TextfontCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length > 2) {
this.family = parsed.args[0];
this.style = parsed.args[1];
this.size = parsed.args[2];
} else if (parsed.args.length > 1) {
this.familyOrStyle = parsed.args[0];
this.size = parsed.args[1];
} else if (parsed.args.length > 0) {
var arg = parsed.args[0];
if (arg.child.type === 'string' || arg.child instanceof statements.StringStatement) this.familyOrStyle = arg;
else this.size = arg;
} else {
this.reset = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q61652
|
MerchantCalculations
|
validation
|
function MerchantCalculations (objGoogleCheckout) {
var self = this;
//todo: check the constructor name
assert.ok(objGoogleCheckout, "A GoogleCheckout object is the only required argument");
self.gc = objGoogleCheckout;
self.settings = self.gc.settings;
}
|
javascript
|
{
"resource": ""
}
|
q61653
|
replace
|
validation
|
function replace(value, configData) {
if (typeof value != "string") {
return value;
} else {
return value.replace(propStringTmplRe, function(match, path) {
var value = get(configData, path);
if (!(value instanceof Error)) {
return value;
} else {
return match;
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q61654
|
get
|
validation
|
function get(object, path) {
if (memoGet[path]) {
return new Error("circular reference for " + path);
}
var parts = path.split(".");
var obj = object;
while (typeof obj === "object" && obj && parts.length) {
var part = parts.shift();
if (!(part in obj)) {
return new Error("invalid path");
}
obj = obj[part];
}
memoGet[path] = true;
// The replace can cause a circular reference
var value = replace(obj, object);
delete memoGet[path];
return value;
}
|
javascript
|
{
"resource": ""
}
|
q61655
|
checkBug
|
validation
|
function checkBug() {
// Check if it works on newly created node (fails in IE 9)
var a = document.createElement('div');
if (method.call(a, 'div')) {
return false;
}
// Check if it works when node is appended to another node (works in IE 9)
var b = document.createElement('div');
a.appendChild(b);
return method.call(b, 'div');
}
|
javascript
|
{
"resource": ""
}
|
q61656
|
workaround
|
validation
|
function workaround() {
var node = document.createElement('div');
function matches(element, selector) {
if (method.call(element, selector)) {
return true;
} else if (!element.parentNode) {
// If node is not attached, temporarily attach to node
node.appendChild(element);
var result = method.call(element, selector);
node.removeChild(element);
return result;
} else {
return false;
}
}
return matches;
}
|
javascript
|
{
"resource": ""
}
|
q61657
|
allow
|
validation
|
function allow(action, req, res, cb) {
// call the allow method in our options if it exists
// or we will just assume it is always allowed
if (options.allow) {
return options.allow.apply(this, arguments);
}
return cb && cb(null, true);
}
|
javascript
|
{
"resource": ""
}
|
q61658
|
clean
|
validation
|
function clean(action, result, req, res, cb) {
// call the clean method in our options if it exists
// or we will just assume it is always clean
if (options.clean) {
return options.clean.apply(this, arguments);
}
return cb && cb();
}
|
javascript
|
{
"resource": ""
}
|
q61659
|
find
|
validation
|
function find(action, req, res, cb) {
var result = {};
// TODO: run our query
// clean our result
clean(action, result, req, res, function(err) {
if (err) {
return cb(err);
}
// see if there is a method in our options that we need
// to run once we have found our results
if (options.found) {
options.found(result, req, res, cb);
} else {
cb && cb(null, result);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q61660
|
dispatch
|
validation
|
function dispatch(ctx) {
if (_curCtx) {
var ret = _curCtx.route.exit({
path: _curCtx.path,
params: _curCtx.params
}, true);
if (!ret) {
return;
}
}
_prevCtx = _curCtx;
_curCtx = ctx;
if (!_curCtx.route) {
var m = map(_curCtx.path);
_curCtx.route = m.route;
_curCtx.params = m.params;
}
var r = _curCtx.route.enter({
force: _curCtx.force,
path: _curCtx.path,
params: _curCtx.params
},true);
langx.Deferred.when(r).then(function() {
_hub.trigger(createEvent("routing", {
current: _curCtx,
previous: _prevCtx
}));
_curCtx.route.enter({
path: _curCtx.path,
params: _curCtx.params
},false);
if (_prevCtx) {
_prevCtx.route.exit({
path: _prevCtx.path,
params: _prevCtx.params
}, false);
}
_hub.trigger(createEvent("routed", {
current: _curCtx,
previous: _prevCtx
}));
});
}
|
javascript
|
{
"resource": ""
}
|
q61661
|
start
|
validation
|
function start() {
if (router.useHashbang == null && router.useHistoryApi == null) {
if (window.location.host && window.history.pushState) {
//web access
router.useHistoryApi = true;
} else {
// local access
router.useHashbang = true;
}
}
var initPath = "";
if (router.useHistoryApi) {
initPath = window.location.pathname;
if (_baseUrl === undefined) {
_baseUrl = initPath.replace(/\/$/, "");
}
initPath = initPath.replace(_baseUrl, "") || _homePath || "/";
} else if (router.useHashbang) {
initPath = window.location.hash.replace("#!", "") || _homePath || "/";
} else {
initPath = "/";
}
if (!initPath.startsWith("/")) {
initPath = "/" + initPath;
}
/*
eventer.on(document.body, "click", "a[href]", function(e) {
var elm = e.currentTarget,
url = elm.getAttribute("href");
if (url == "#") {
return;
}
if (url && langx.isSameOrigin(elm.href)) {
if (url.indexOf(_baseUrl) === 0) {
url = url.substr(_baseUrl.length);
eventer.stop(e);
url = url.replace('#!', '');
go(url);
}
}
});
*/
if (router.useHistoryApi) {
window.addEventListener("popstate", function(e) {
if(e.state) dispatch(e.state);
e.preventDefault();
});
} else if (router.useHashbang) {
window.addEventListener("hashchange", function(e) {
dispatch({
path: window.location.hash.replace(/^#!/, "")
});
e.preventDefault();
});
}
go(initPath);
}
|
javascript
|
{
"resource": ""
}
|
q61662
|
validation
|
function() {
var curCtx = router.current(),
prevCtx = router.previous();
var content = curCtx.route.render(curCtx);
if (content===undefined || content===null) {
return;
}
if (langx.isString(content)) {
this._rvc.innerHTML = content;
} else {
this._rvc.innerHTML = "";
this._rvc.appendChild(content);
}
curCtx.route.trigger(createEvent("rendered", {
route: curCtx.route,
content: content
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q61663
|
validation
|
function(key) {
var value;
if (key.indexOf('.') == -1) {
value = this.configObj[key];
} else {
var keyArray = key.split('.');
var keyStr = keyArray[0];
value = this.configObj[keyStr];
for(var i= 1,len=keyArray.length;i<len;i++) {
if (!value && i < len-1) {
exitProcess('the var ['+keyStr + '] is empty.', this.alarm);
return undefined;
}
var keyNow = keyArray[i];
keyStr += '.'+keyNow;
value = value[keyNow];
}
}
slogger.debug('load var ['+key+'],value:',value);
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q61664
|
validation
|
function(key) {
var value = this.loadVar(key);
if (typeof(value) =='undefined') {
exitProcess('the value of ' + key + ' is necessary , but now is undefined', this.alarm);
return false;
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
|
q61665
|
validation
|
function(key) {
var str = this.loadVar(key);
if (typeof (str) != 'string') {
exitProcess('the value of ' + key + ' is a necessary string, but get ' + str, this.alarm);
return false;
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
|
q61666
|
validation
|
function(key) {
var num = parseInt(this.loadVar(key));
if (isNaN(num)) {
exitProcess('the value of ' +key+' is a necessary int ,but get ' + num, this.alarm);
return false;
}
return num;
}
|
javascript
|
{
"resource": ""
}
|
|
q61667
|
validation
|
function(key) {
var obj = this.loadVar(key);
if (!obj || typeof (obj) != 'object') {
exitProcess('the value of ' +key+' is a necessary object ,but get '+ obj, this.alarm);
return false;
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
|
q61668
|
validation
|
function(key,onlyCheckDirectory) {
var filePath = this.loadVar(key);
if (!filePath) {
exitProcess('empty file path for ' + key, this.alarm);
return false;
}
if (!onlyCheckDirectory) {
if (!fs.existsSync(filePath)) {
exitProcess('the value of ' +key+' is a necessary file ,but not exists in '+ filePath, this.alarm);
return false;
}
} else {
var dirname = path.dirname(filePath);
if (!fs.lstatSync(dirname).isDirectory()) {
exitProcess('the path '+dirname + ' must exist and be a directory', this.alarm);
return false;
}
}
return filePath;
}
|
javascript
|
{
"resource": ""
}
|
|
q61669
|
validation
|
function(key,endWithSeparator) {
var filepath = this.loadNecessaryFile(key);
if (!filepath) {
exitProcess('empty directory for ' + key, this.alarm);
return false;
}
if (!fs.lstatSync(filepath).isDirectory()) {
exitProcess('the path '+filepath + ' must be a directory', this.alarm);
return false;
}
if (endWithSeparator && !filepath.endWith(path.sep)) {
exitProcess('the path '+filepath + ' must be end with a separator', this.alarm);
return false;
}
return filepath;
}
|
javascript
|
{
"resource": ""
}
|
|
q61670
|
validation
|
function(key,endWithSeparator) {
var url = this.loadNecessaryString(key);
if (!url) {
exitProcess('empty url for ' + key, this.alarm);
return false;
}
if (!url.startWith('http://') && !url.startWith('https://')) {
exitProcess('invalid url:' + url, this.alarm);
return false;
}
if (endWithSeparator && !url.endWith('/')) {
exitProcess('the url['+url+'] must be end with /', this.alarm);
return false;
}
if (!endWithSeparator && url.endWith('/')) {
exitProcess('the url['+url+'] must not be end with /', this.alarm);
return false;
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
|
q61671
|
VariableStatement
|
validation
|
function VariableStatement(name) {
var bracketIndex = name.indexOf('(');
if (bracketIndex !== -1) {
var endBracketIndex = name.indexOf(')');
if (endBracketIndex === -1) throw new SyntaxError('Expected end bracket');
var arrayName = name.substring(0, bracketIndex);
var arrayDimensionsText = name.substring(bracketIndex + 1, endBracketIndex).trim();
var arrayDimensions = new statements.ArgumentStatement(arrayDimensionsText);
name = arrayName;
this.isArray = true;
this.dimensions = arrayDimensions.args;
} else this.isArray = false;
if (name[name.length - 1] === '$') {
this.type = 'string';
this.name = name.substring(0, name.length - 1);
} else {
this.type = 'number';
this.name = name;
}
}
|
javascript
|
{
"resource": ""
}
|
q61672
|
validation
|
function() {
var versions = ["Msxml2.XMLHTTP",
"Msxml3.XMLHTTP",
"Microsoft.XMLHTTP",
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0"
]
if(XMLHttpRequest !== undefined) { // For non-IE browsers
createXMLHTTPObject = function() { // Use memoization to cache the factory
return new XMLHttpRequest()
}
return createXMLHTTPObject()
} else { // IE
for(var i=0, n=versions.length; i<n; i++) {
try {
var version = versions[i]
var fn = function() {
return new ActiveXObject(version)
}
createXMLHTTPObject = fn // Use memoization to cache the factory
return createXMLHTTPObject()
} catch(e) { }
}
}
throw new Error('Cant get XmlHttpRequest object')
}
|
javascript
|
{
"resource": ""
}
|
|
q61673
|
isLikeAFuture
|
validation
|
function isLikeAFuture(x) {
return x.isResolved !== undefined && x.queue !== undefined && x.then !== undefined
}
|
javascript
|
{
"resource": ""
}
|
q61674
|
validation
|
function(e) {
var stack = (e.stack + '\n').replace(/^\S[^\(]+?[\n$]/gm, '').
replace(/^\s+(at eval )?at\s+/gm, '').
replace(/^([^\(]+?)([\n$])/gm, '{anonymous}()@$1$2').
replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}()@$1').split('\n');
stack.pop();
return stack;
}
|
javascript
|
{
"resource": ""
}
|
|
q61675
|
validation
|
function(e) {
var lineRE = /^.*at (\w+) \(([^\)]+)\)$/gm;
return e.stack.replace(/at Anonymous function /gm, '{anonymous}()@')
.replace(/^(?=\w+Error\:).*$\n/m, '')
.replace(lineRE, '$1@$2')
.split('\n');
}
|
javascript
|
{
"resource": ""
}
|
|
q61676
|
validation
|
function(e) {
// " Line 43 of linked script file://localhost/G:/js/stacktrace.js\n"
// " Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n"
var ANON = '{anonymous}', lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
var lines = e.message.split('\n'), result = [];
for (var i = 2, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push(ANON + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\s+/, ''));
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q61677
|
validation
|
function(url) {
// TODO reuse source from script tags?
if (!(url in this.sourceCache)) {
this.sourceCache[url] = this.ajax(url).split('\n');
}
return this.sourceCache[url];
}
|
javascript
|
{
"resource": ""
}
|
|
q61678
|
recordAndTriggerHandlers
|
validation
|
function recordAndTriggerHandlers(type, eventData) {
this.history.push({type:type, data: eventData})
this.handlers[type].forEach(function(handlerInfo) {
try {
handlerInfo.handler.call(undefined, eventData)
} catch(e) {
// throw error asynchronously because these error should be separate from the test exceptions
var throwErrorFn = options.throwAsyncException
if(handlerInfo.domain) {
throwErrorFn = handlerInfo.domain.bind(throwErrorFn) // this domain bind is needed because emit is done inside deadunit's test domain, which isn't where we want to put errors caused by the event handlers
}
throwErrorFn(e)
}
})
}
|
javascript
|
{
"resource": ""
}
|
q61679
|
validation
|
function(name, mainTester, parentTester) {
if(!mainTester) mainTester = this
this.id = groupid()
this.mainTester = mainTester // the mainTester is used to easily figure out if the test results have been accessed (so early accesses can be detected)
this.parentTester = parentTester // used to reset timeouts
this.name = name
this.doneTests = 0
this.doneAsserts = 0
this.runningTests = 0 // the number of subtests created synchronously
this.doneCalled = false
this.doSourcemappery = true // whether to do source mapping, if possible, within this test
this.complete = new Future // resolved when done
}
|
javascript
|
{
"resource": ""
}
|
|
q61680
|
remove
|
validation
|
function remove(array, item) {
console.log("attempting to remove "+item)
var index = array.indexOf(item)
if(index !== -1)
array.splice(index, 1) // no longer throwing Error("Item doesn't exist to remove") if there's nothing to remove - in the case that mainTester.timeouts gets set back to [] (when done), it won't be there
}
|
javascript
|
{
"resource": ""
}
|
q61681
|
assert
|
validation
|
function assert(that, success, actualValue, expectedValue, type, functionName/*="ok"*/, lineInfo/*=dynamic*/, stackIncrease/*=0*/) {
if(!stackIncrease) stackIncrease = 1
if(!functionName) functionName = "ok"
if(!lineInfo)
var lineInfoFuture = getLineInformation(functionName, stackIncrease, that.doSourcemappery, that.warningHandler)
else
var lineInfoFuture = Future(lineInfo)
// reste timeouts up the chain
var cur = that
while(cur !== undefined) {
setTesterTimeout(cur)
cur = cur.parentTester
}
var emitData = lineInfoFuture.then(function(lineInfo) {
var result = lineInfo
result.type = 'assert'
if(type !=='count') result.success = success === true
if(actualValue !== undefined) result.actual = actualValue
if(expectedValue !== undefined) result.expected = expectedValue
result.parent = that.id
result.time = now()
return Future(result)
})
return that.manager.emit(type, emitData)
}
|
javascript
|
{
"resource": ""
}
|
q61682
|
getMappedSourceInfo
|
validation
|
function getMappedSourceInfo(sourceMapConsumer, originalFilePath, originalLine, originalColumn, originalFunctionName) {
var sourceMapInfo = sourceMapConsumer.originalPositionFor({line:originalLine, column:originalColumn||0}) // the 0 is for browsers (like firefox) that don't output column numbers
var line = sourceMapInfo.line
var column = sourceMapInfo.column
var fn = sourceMapInfo.name
if(sourceMapInfo.source !== null) {
var relative = isRelative(sourceMapInfo.source)
/* I don't think this is needed any longer, and probably isn't correct - this was working around an issue in webpack: See https://github.com/webpack/webpack/issues/559 and https://github.com/webpack/webpack/issues/238
if(sourceMapConsumer.sourceRoot !== null) {
sourceMapInfo.source = sourceMapInfo.source.replace(sourceMapConsumer.sourceRoot, '') // remove sourceRoot
}*/
if(relative) {
var file = Url.resolve(originalFilePath, path.basename(sourceMapInfo.source))
} else {
var file = sourceMapInfo.source
}
var originalFile = true
} else {
var file = originalFilePath
var originalFile = false
}
if(fn === null || !originalFile) {
fn = originalFunctionName
}
if(line === null || !originalFile) {
line = originalLine
column = originalColumn
}
if(column === null) {
column = undefined
}
if(file != undefined && sourceMapConsumer.sourcesContent != undefined) { // intentional single !=
var index = sourceMapConsumer.sources.indexOf(file)
var sourceLines = sourceMapConsumer.sourcesContent[index]
if(sourceLines !== undefined) sourceLines = sourceLines.split('\n')
}
return {
file: file,
function: fn,
line: line,
column: column,
usingOriginalFile: originalFile,
sourceLines: sourceLines
}
}
|
javascript
|
{
"resource": ""
}
|
q61683
|
getFunctionCallLines
|
validation
|
function getFunctionCallLines(sourcesContent, filePath, functionName, lineNumber, multiLineSearch, warningHandler) {
if(sourcesContent !== undefined) {
var source = Future(sourcesContent)
} else {
var source = options.getScriptSourceLines(filePath)
}
return source.catch(function(e) {
warningHandler(e)
return Future(undefined)
}).then(function(fileLines) {
if(fileLines !== undefined) {
var startLine = findStartLine(fileLines, functionName, lineNumber)
if(startLine === 'lineOfCodeNotFound') {
return Future("<line of code not found (possibly an error?)> ")
} else if(startLine !== 'sourceNotAvailable') {
if(multiLineSearch) {
return Future(findFullSourceLine(fileLines, startLine))
} else {
return Future(fileLines[startLine].trim())
}
}
}
// else
return Future("<source not available>")
})
}
|
javascript
|
{
"resource": ""
}
|
q61684
|
mapException
|
validation
|
function mapException(exception, warningHandler) {
try {
if(exception instanceof Error) {
var stacktrace;
return options.getExceptionInfo(exception).then(function(trace){
stacktrace = trace
var smcFutures = []
for(var n=0; n<trace.length; n++) {
if(trace[n].file !== undefined) {
smcFutures.push(getSourceMapConsumer(trace[n].file, warningHandler))
} else {
smcFutures.push(Future(undefined))
}
}
return Future.all(smcFutures)
}).then(function(sourceMapConsumers) {
var CustomMappedException = proto(MappedException, function() {
// set the name so it looks like the original exception when printed
// this subclasses MappedException so that name won't be an own-property
this.name = exception.name
})
try {
throw CustomMappedException(exception, stacktrace, sourceMapConsumers) // IE doesn't give exceptions stack traces unless they're actually thrown
} catch(mappedExcetion) {
return Future(mappedExcetion)
}
})
} else {
return Future(exception)
}
} catch(e) {
var errorFuture = new Future
errorFuture.throw(e)
return errorFuture
}
}
|
javascript
|
{
"resource": ""
}
|
q61685
|
YearMonthForm
|
validation
|
function YearMonthForm({ date, localeUtils, onChange, fromMonth, toMonth }) {
const months = localeUtils.getMonths();
const years = [];
for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) {
years.push(i);
}
const handleChange = function handleChange(e) {
const { year, month } = e.target.form;
onChange(new Date(year.value, month.value));
};
return (
<form className="DayPicker-Caption">
<select name="month" onChange={handleChange} value={date.getMonth()}>
{months.map((month, i) => <option key={i} value={i}>{month}</option>)}
</select>
<select name="year" onChange={handleChange} value={date.getFullYear()}>
{years.map((year, i) =>
<option key={i} value={year}>
{year}
</option>
)}
</select>
</form>
);
}
|
javascript
|
{
"resource": ""
}
|
q61686
|
Floodgate
|
validation
|
function Floodgate (opts) {
if (!(this instanceof Floodgate)) return new Floodgate(opts);
opts = opts || {};
Transform.call(this, opts);
this._interval = opts.interval || 0;
}
|
javascript
|
{
"resource": ""
}
|
q61687
|
remove
|
validation
|
function remove(obj, path, i) {
i = i || 0
var key = path[i],
last = i === path.length - 1
if (!obj || typeof obj !== 'object') {
throw new Error('Can\'t remove key ' + key + ' from non-object')
}
if (Array.isArray(obj)) {
if (typeof key !== 'number') {
obj.forEach(function (each) {
remove(each, path, i)
})
} else if (key >= 0 && key < obj.length) {
if (last) {
obj.splice(key, 1)
} else {
remove(obj[key], path, i + 1)
}
} else {
throw new Error('Can\'t remove index ' + key + ' from an array with ' + obj.length + ' elements')
}
} else {
if (typeof key !== 'string') {
throw new Error('Can\'t remove the numeric key ' + key + ' from an object')
} else if (key in obj) {
if (last) {
delete obj[key]
} else {
remove(obj[key], path, i + 1)
}
} else {
throw new Error('Can\'t remove key ' + key + ' from the object')
}
}
}
|
javascript
|
{
"resource": ""
}
|
q61688
|
validation
|
function(uuid_or_name, cb) {
if (_.isObject(uuid_or_name)) { return cb(new Error('parameter must be a uuid or name')); }
var self = this;
client.getEntity({ type: self._usergrid.type, uuid: uuid_or_name }, translateSDKCallback(function (err, entity) {
if (err) { return cb(err); }
cb(null, wrap(self, entity));
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q61689
|
validation
|
function(criteria, limit, cb) {
if (_.isFunction(limit)) { cb = limit; limit = undefined; }
var self = this;
var query = buildQuery(criteria, limit);
client.createCollection(options(self, query), translateSDKCallback(function (err, collection) {
if (err) { return cb(err); }
cb(null, wrapCollection(self, collection));
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q61690
|
validation
|
function(criteria, cb) {
var self = this;
this.first(criteria, function(err, entity) {
if (err) { return cb(err); }
if (entity) {
cb(null, entity);
} else {
self.create(criteria, cb);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q61691
|
options
|
validation
|
function options(Class, hash) {
var opts;
var type = { type: Class._usergrid.type };
if (hash) {
opts = _.assign({}, hash, type);
} else {
opts = type;
}
return opts;
}
|
javascript
|
{
"resource": ""
}
|
q61692
|
define
|
validation
|
function define(Class, constructor, type) {
if (!client) { throw new Error('Usergrid not configured'); }
if (typeof Class === 'function') {
type = constructor;
constructor = Class;
Class = {};
}
Class._usergrid = {
constructor: constructor,
type: (type) ? type : constructor.name.toLowerCase()
};
_.mixin(Class, usergridStatics(client));
return Class;
}
|
javascript
|
{
"resource": ""
}
|
q61693
|
SavespriteCommand
|
validation
|
function SavespriteCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 2) throw new SyntaxError('SAVESPRITE command requires 2 arguments');
this.id = parsed.args[0];
this.fileName = parsed.args[1];
}
|
javascript
|
{
"resource": ""
}
|
q61694
|
defer
|
validation
|
function defer(func) {
return new (class {
constructor(generator) {
this.generator = generator;
}
[Symbol.iterator]() {
return this.generator()[Symbol.iterator]();
}
})(func);
}
|
javascript
|
{
"resource": ""
}
|
q61695
|
forward
|
validation
|
function forward(event, source, target) {
source.on(event, target.emit.bind(target, event));
}
|
javascript
|
{
"resource": ""
}
|
q61696
|
validation
|
function (state, scope, secondaryScope) {
if(!validators.isBlockStart(state)) return state.error(constants.unexpectedToken);
state.next(); //Skip block start.
utils.statementsInBlock(state, scope, secondaryScope);
if(!validators.isBlockEnd(state)) return state.error(constants.unexpectedToken);
state.next(); //Skip block end.
}
|
javascript
|
{
"resource": ""
}
|
|
q61697
|
validation
|
function(state, scope, secondaryScope) {
state.createLexicalEnvironment();
state.levelDown(scope);
if(secondaryScope) state.levelDown(secondaryScope);
while(state.token && !validators.isBlockEnd(state)) {
state.processor.token(state);
}
if(secondaryScope) state.levelUp();
state.levelUp();
state.finalizeLexicalEnvironment();
}
|
javascript
|
{
"resource": ""
}
|
|
q61698
|
validation
|
function(state, noError) {
if(validators.isSemicolon(state)) {
state.next();
}
else if(state.token && !validators.isBlockEnd(state)) {
var lb = state.lookback();
if(!lb || state.token.line === lb.line) {
if(!noError) state.error(constants.unexpectedToken);
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q61699
|
ReadpixelCommand
|
validation
|
function ReadpixelCommand(args) {
var parsed = new statements.ArgumentStatement(args);
if (parsed.args.length < 2) throw new SyntaxError('READPIXEL command requires 2 arguments');
this.x = parsed.args[0];
this.y = parsed.args[1];
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.