_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1800
|
train
|
function(properties)
{
if ( !isValue( properties ) )
{
return this.length;
}
var resolver = createPropertyResolver( properties );
var result = 0;
for (var i = 0; i < this.length; i++)
{
var resolved = resolver( this[ i ] );
if ( isValue( resolved ) )
{
result++;
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q1801
|
train
|
function(values, keys)
{
var valuesResolver = createPropertyResolver( values );
if ( keys )
{
var keysResolver = createPropertyResolver( keys );
var result = {};
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
var value = valuesResolver( model );
var key = keysResolver( model );
result[ key ] = value;
}
return result;
}
else
{
var result = [];
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
var value = valuesResolver( model );
result.push( value );
}
return result;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1802
|
train
|
function(callback, context)
{
var callbackContext = context || this;
for (var i = 0; i < this.length; i++)
{
var item = this[ i ];
callback.call( callbackContext, item, i );
if ( this[ i ] !== item )
{
i--;
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1803
|
train
|
function(callback, properties, values, equals)
{
var where = createWhere( properties, values, equals );
for (var i = 0; i < this.length; i++)
{
var item = this[ i ];
if ( where( item ) )
{
callback.call( this, item, i );
if ( this[ i ] !== item )
{
i--;
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1804
|
train
|
function(reducer, initialValue)
{
for (var i = 0; i < this.length; i++)
{
initialValue = reducer( initialValue, this[ i ] );
}
return initialValue;
}
|
javascript
|
{
"resource": ""
}
|
|
q1805
|
train
|
function(properties, value, equals)
{
var where = createWhere( properties, value, equals );
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
if ( where( model ) )
{
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q1806
|
train
|
function(grouping)
{
var by = createPropertyResolver( grouping.by );
var having = createWhere( grouping.having, grouping.havingValue, grouping.havingEquals );
var select = grouping.select || {};
var map = {};
if ( isString( grouping.by ) )
{
if ( !(grouping.by in select) )
{
select[ grouping.by ] = 'first';
}
}
else if ( isArray( grouping.by ) )
{
for (var prop in grouping.by)
{
if ( !(prop in select) )
{
select[ prop ] = 'first';
}
}
}
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
var key = by( model );
var group = map[ key ];
if ( !group )
{
group = map[ key ] = this.cloneEmpty();
}
group.add( model, true );
}
var groupings = this.cloneEmpty();
groupings.setComparator( grouping.comparator, grouping.comparatorNullsFirst );
for (var key in map)
{
var grouped = {};
var groupArray = map[ key ];
for (var propName in select)
{
var aggregator = select[ propName ];
if ( isString( aggregator ) )
{
grouped[ propName ] = groupArray[ aggregator ]( propName );
}
else if ( isFunction( aggregator ) )
{
grouped[ propName ] = aggregator( groupArray, propName );
}
}
if ( grouping.track !== false )
{
grouped.$group = groupArray;
}
if ( grouping.count !== false )
{
grouped.$count = groupArray.length;
}
if ( having( grouped, groupArray ) )
{
groupings.push( grouped );
}
}
groupings.sort();
return groupings;
}
|
javascript
|
{
"resource": ""
}
|
|
q1807
|
train
|
function(database, models, remoteData)
{
Class.props(this, {
database: database,
map: new Map()
});
this.map.values = this;
this.reset( models, remoteData );
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1808
|
train
|
function(models, remoteData)
{
var map = this.map;
map.reset();
if ( isArray( models ) )
{
for (var i = 0; i < models.length; i++)
{
var model = models[ i ];
var parsed = this.parseModel( model, remoteData );
if ( parsed )
{
map.put( parsed.$key(), parsed );
}
}
}
else if ( isObject( models ) )
{
var parsed = this.parseModel( models, remoteData );
if ( parsed )
{
map.put( parsed.$key(), parsed );
}
}
this.trigger( Collection.Events.Reset, [this] );
this.sort();
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1809
|
train
|
function(key, model, delaySort)
{
this.map.put( key, model );
this.trigger( Collection.Events.Add, [this, model, this.map.indices[ key ]] );
if ( !delaySort )
{
this.sort();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1810
|
train
|
function(input, delaySort, remoteData)
{
var model = this.parseModel( input, remoteData );
var key = model.$key();
this.map.put( key, model );
this.trigger( Collection.Events.Add, [this, model, this.map.indices[ key ]] );
if ( !delaySort )
{
this.sort();
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1811
|
train
|
function()
{
var values = AP.slice.apply( arguments );
var indices = [];
for (var i = 0; i < values.length; i++)
{
var model = this.parseModel( values[ i ] );
var key = model.$key();
this.map.put( key, model );
indices.push( this.map.indices[ key ] );
}
this.trigger( Collection.Events.Adds, [this, values, indices] );
this.sort();
return this.length;
}
|
javascript
|
{
"resource": ""
}
|
|
q1812
|
train
|
function(models, delaySort, remoteData)
{
if ( isArray( models ) )
{
var indices = [];
for (var i = 0; i < models.length; i++)
{
var model = this.parseModel( models[ i ], remoteData );
var key = model.$key();
this.map.put( key, model );
indices.push( this.map.indices[ key ] );
}
this.trigger( Collection.Events.Adds, [this, models, indices] );
if ( !delaySort )
{
this.sort();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1813
|
train
|
function(delaySort)
{
var removed = this[ 0 ];
this.map.removeAt( 0 );
this.trigger( Collection.Events.Remove, [this, removed, 0] );
if ( !delaySort )
{
this.sort();
}
return removed;
}
|
javascript
|
{
"resource": ""
}
|
|
q1814
|
train
|
function(i, delaySort)
{
var removing;
if (i >= 0 && i < this.length)
{
removing = this[ i ];
this.map.removeAt( i );
this.trigger( Collection.Events.Remove, [this, removing, i] );
if ( !delaySort )
{
this.sort();
}
}
return removing;
}
|
javascript
|
{
"resource": ""
}
|
|
q1815
|
train
|
function(input, delaySort)
{
var key = this.buildKeyFromInput( input );
var removing = this.map.get( key );
if ( removing )
{
var i = this.map.indices[ key ];
this.map.remove( key );
this.trigger( Collection.Events.Remove, [this, removing, i] );
if ( !delaySort )
{
this.sort();
}
}
return removing;
}
|
javascript
|
{
"resource": ""
}
|
|
q1816
|
train
|
function(inputs, delaySort)
{
var map = this.map;
var removed = [];
var removedIndices = [];
for (var i = 0; i < inputs.length; i++)
{
var key = this.buildKeyFromInput( inputs[ i ] );
var removing = map.get( key );
if ( removing )
{
removedIndices.push( map.indices[ key ] );
removed.push( removing );
}
}
removedIndices.sort();
for (var i = removedIndices.length - 1; i >= 0; i--)
{
map.removeAt( removedIndices[ i ] );
}
this.trigger( Collection.Events.Removes, [this, removed, removedIndices] );
if ( !delaySort )
{
this.sort();
}
return removed;
}
|
javascript
|
{
"resource": ""
}
|
|
q1817
|
train
|
function(input)
{
var key = this.buildKeyFromInput( input );
var index = this.map.indices[ key ];
return index === undefined ? -1 : index;
}
|
javascript
|
{
"resource": ""
}
|
|
q1818
|
train
|
function(properties, value, equals)
{
var where = createWhere( properties, value, equals );
var hasChanges = function( model )
{
return where( model ) && model.$hasChanges();
};
return this.contains( hasChanges );
}
|
javascript
|
{
"resource": ""
}
|
|
q1819
|
train
|
function(properties, value, equals, out)
{
var where = createWhere( properties, value, equals );
var changes = out && out instanceof ModelCollection ? out : this.cloneEmpty();
this.each(function(model)
{
if ( where( model ) && model.$hasChanges() )
{
changes.put( model.$key(), model.$getChanges() );
}
});
return changes;
}
|
javascript
|
{
"resource": ""
}
|
|
q1820
|
train
|
function(cloneModels, cloneProperties)
{
var source = this;
if ( cloneModels )
{
source = [];
for (var i = 0; i < this.length; i++)
{
source[ i ] = this[ i ].$clone( cloneProperties );
}
}
return ModelCollection.create( this.database, source, true );
}
|
javascript
|
{
"resource": ""
}
|
|
q1821
|
train
|
function(base, filter)
{
if ( this.base )
{
this.base.database.off( Database.Events.ModelUpdated, this.onModelUpdated );
}
ModelCollection.prototype.init.call( this, base.database );
Filtering.init.call( this, base, filter );
base.database.on( Database.Events.ModelUpdated, this.onModelUpdated );
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1822
|
train
|
function(model)
{
var exists = this.has( model.$key() );
var matches = this.filter( model );
if ( exists && !matches )
{
this.remove( model );
}
if ( !exists && matches )
{
this.add( model );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1823
|
DiscriminateCollection
|
train
|
function DiscriminateCollection(collection, discriminator, discriminatorsToModel)
{
Class.props( collection,
{
discriminator: discriminator,
discriminatorsToModel: discriminatorsToModel
});
// Original Functions
var buildKeyFromInput = collection.buildKeyFromInput;
var parseModel = collection.parseModel;
var clone = collection.clone;
var cloneEmpty = collection.cloneEmpty;
Class.props( collection,
{
/**
* Builds a key from input. Discriminated collections only accept objects as
* input - otherwise there's no way to determine the discriminator. If the
* discriminator on the input doesn't map to a Rekord instance OR the input
* is not an object the input will be returned instead of a model instance.
*
* @param {modelInput} input -
* The input to create a key for.
* @return {Any} -
* The built key or the given input if a key could not be built.
*/
buildKeyFromInput: function(input)
{
if ( isObject( input ) )
{
var discriminatedValue = input[ this.discriminator ];
var model = this.discriminatorsToModel[ discriminatedValue ];
if ( model )
{
return model.Database.keyHandler.buildKeyFromInput( input );
}
}
return input;
},
/**
* Takes input and returns a model instance. The input is expected to be an
* object, any other type will return null.
*
* @param {modelInput} input -
* The input to parse to a model instance.
* @param {Boolean} [remoteData=false] -
* Whether or not the input is coming from a remote source.
* @return {Rekord.Model} -
* The model instance parsed or null if none was found.
*/
parseModel: function(input, remoteData)
{
if ( input instanceof Model )
{
return input;
}
var discriminatedValue = isValue( input ) ? input[ this.discriminator ] : null;
var model = this.discriminatorsToModel[ discriminatedValue ];
return model ? model.Database.parseModel( input, remoteData ) : null;
},
/**
* Returns a clone of this collection.
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to a clone collection.
*/
clone: function()
{
return DiscriminateCollection( clone.apply( this ), discriminator, discriminatorsToModel );
},
/**
* Returns an empty clone of this collection.
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to a clone collection.
*/
cloneEmpty: function()
{
return DiscriminateCollection( cloneEmpty.apply( this ), discriminator, discriminatorsToModel );
}
});
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q1824
|
train
|
function(input)
{
if ( isObject( input ) )
{
var discriminatedValue = input[ this.discriminator ];
var model = this.discriminatorsToModel[ discriminatedValue ];
if ( model )
{
return model.Database.keyHandler.buildKeyFromInput( input );
}
}
return input;
}
|
javascript
|
{
"resource": ""
}
|
|
q1825
|
train
|
function(input, remoteData)
{
if ( input instanceof Model )
{
return input;
}
var discriminatedValue = isValue( input ) ? input[ this.discriminator ] : null;
var model = this.discriminatorsToModel[ discriminatedValue ];
return model ? model.Database.parseModel( input, remoteData ) : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q1826
|
train
|
function(database, field, options)
{
applyOptions( this, options, this.getDefaults( database, field, options ) );
this.database = database;
this.name = field;
this.options = options;
this.initialized = false;
this.property = this.property || (indexOf( database.fields, this.name ) !== false);
this.discriminated = !isEmpty( this.discriminators );
if ( this.discriminated )
{
if ( !Polymorphic )
{
throw 'Polymorphic feature is required to use the discriminated option.';
}
Class.props( this, Polymorphic );
}
this.setReferences( database, field, options );
}
|
javascript
|
{
"resource": ""
}
|
|
q1827
|
train
|
function (cb) {
o1._client.auth(function (err) {
if (err && !(err instanceof Error)) {
err = new Error(err.message || err);
}
if (!err) {
o1.config = {
storage : o1._client._serviceUrl
};
}
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q1828
|
train
|
function (cb) {
if (o1.options.tempURLKey) {
o1._log('Setting temporary URL key for account...');
o1._client.setTemporaryUrlKey(o1.options.tempURLKey, cb);
} else {
cb();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1829
|
train
|
function (cb) {
o1._client.createContainer(sName, function (err, _container) {
if (err)
return cb(err);
// check that a parallel operation didn't just add the same container
container = _.find(o1.aContainers, { name : sName });
if (!container) {
o1.aContainers.push(_container);
container = _container;
}
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q1830
|
train
|
function (cb) {
if (!o1.options.useCDN)
return cb();
o1._log('CDN enabling the container');
container.enableCdn(function (err, _container) {
if (err)
return cb(err);
// check that a parallel operation didn't just CDN enable the same container
var index = _.findIndex(o1.aContainers, { name : sName });
container = o1.aContainers[index] = _container;
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q1831
|
train
|
function (err, results) {
if (err) {
return cb(err);
}
// Generate file id
var id = options.filename || utils.uid(24);
//
// Generate the headers to be send to Rackspace
//
var headers = {};
// set the content-length of transfer-encoding as appropriate
if (fromFile) {
headers['content-length'] = results.stats.size;
} else {
if (source.headers && source.headers['content-length'])
headers['content-length'] = source.headers['content-length'];
else
headers['transfer-encoding'] = 'chunked';
}
// Add any additonal headers
var sKey;
for (sKey in options.headers) {
if (options.headers.hasOwnProperty(sKey)) {
headers[sKey] = options.headers[sKey];
}
}
//
// Generate the cloud request options
//
var _options = {
container : results.container.name,
remote : id,
headers : headers,
metadata : options.meta,
contentType : type
};
var readStream;
if (fromFile)
readStream = fs.createReadStream(source);
else {
readStream = source;
source.resume();
if (source.headers) {
// We want to remove any headers from the source stream so they don't clobber our own headers.
delete source.headers;
}
}
var writeStream = o1._client.upload(_options);
writeStream.on('error', cb);
writeStream.on('success', function (file) {
results.container.count++;
cb(null, results.container.name + '/' + id);
});
readStream.pipe(writeStream);
}
|
javascript
|
{
"resource": ""
}
|
|
q1832
|
train
|
function (err) {
var i;
// If the extended option is off, just return cloudpaths
if (!options.extended) {
i = aObjects.length;
while (i--) {
aObjects[i] = aObjects[i].cloudpath;
}
}
cb(err, err ? undefined : aObjects);
}
|
javascript
|
{
"resource": ""
}
|
|
q1833
|
collapse
|
train
|
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q1834
|
click
|
train
|
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
|
javascript
|
{
"resource": ""
}
|
q1835
|
encryptJson
|
train
|
function encryptJson(password, json) {
return Q.all([
randomBytes(pbkdf2SaltLen),
randomBytes(cipherIvLen)
]).spread(function (salt, iv) {
return pbkdf2(password, salt, pbkdf2Iterations, pbkdf2KeyLen, pbkdf2Digest).then(function (key) {
var cipher = crypto.createCipheriv(cipherAlgorithm, key, iv);
var value = cipher.update(JSON.stringify(json), 'utf8', 'base64');
value += cipher.final('base64');
var data = {
salt: salt.toString('base64'),
iv: iv.toString('base64'),
value: value
};
var tag = cipher.getAuthTag();
if (tag) {
data.tag = tag.toString('base64');
}
return data;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q1836
|
decryptJson
|
train
|
function decryptJson(password, data) {
var salt = new Buffer(data.salt, 'base64');
return pbkdf2(password, salt, pbkdf2Iterations, pbkdf2KeyLen, pbkdf2Digest).then(function (key) {
var iv = new Buffer(data.iv, 'base64');
var decipher = crypto.createDecipheriv(cipherAlgorithm, key, iv);
var tag = data.tag;
if (tag) {
decipher.setAuthTag(new Buffer(tag, 'base64'));
}
var value = decipher.update(data.value, 'base64', 'utf8');
value += decipher.final('utf8');
return value;
}).then(JSON.parse);
}
|
javascript
|
{
"resource": ""
}
|
q1837
|
OnlineCheckout
|
train
|
function OnlineCheckout(body) {
if (!body) throw new Error('No data provided')
const config = this.config
const hubtelurl =
'https://api.hubtel.com/v1/merchantaccount/onlinecheckout/invoice/create'
const auth =
'Basic ' +
Buffer.from(config.clientid + ':' + config.secretid).toString('base64')
return request.post(hubtelurl, {
body: body,
headers: {
Authorization: auth,
'content-type': 'application/json',
},
json: true,
})
}
|
javascript
|
{
"resource": ""
}
|
q1838
|
train
|
function(raw){
var clone = canReflect.serialize(raw);
if(clone.page) {
clone[offset] = clone.page.start;
clone[limit] = (clone.page.end - clone.page.start) + 1;
delete clone.page;
}
return clone;
}
|
javascript
|
{
"resource": ""
}
|
|
q1839
|
ToxError
|
train
|
function ToxError(type, code, message) {
this.name = "ToxError";
this.type = ( type || "ToxError" );
this.code = ( code || 0 ); // 0 = unsuccessful
this.message = ( message || (this.type + ": " + this.code) );
Error.captureStackTrace(this, ToxError);
}
|
javascript
|
{
"resource": ""
}
|
q1840
|
CheckStatus
|
train
|
function CheckStatus(token) {
if (!token) throw 'Invoice Token must be provided'
const config = this.config
const hubtelurl = `https://api.hubtel.com/v1/merchantaccount/onlinecheckout/invoice/status/${token}`
const auth =
'Basic ' +
Buffer.from(config.clientid + ':' + config.secretid).toString('base64')
return request.get(hubtelurl, {
headers: {
Authorization: auth,
'content-type': 'application/json',
},
json: true,
})
}
|
javascript
|
{
"resource": ""
}
|
q1841
|
hydrateAndValue
|
train
|
function hydrateAndValue(value, prop, SchemaType, hydrateChild) {
// The `SchemaType` is the type of value on `instances` of
// the schema. `Instances` values are different from `Set` values.
if (SchemaType) {
// If there's a `SetType`, we will use that
var SetType = SchemaType[setTypeSymbol];
if (SetType) {
/// If it exposes a hydrate, this means it can use the current hydrator to
// hydrate its children.
// I'm not sure why it's not taking the `unknown` hydrator instead.
if (SetType.hydrate) {
return SetType.hydrate(value, comparisonsConverter.hydrate);
}
// If the SetType implemented `union`, `intersection`, `difference`
// We can create instances of it directly.
else if (set.hasComparisons(SetType)) {
// Todo ... canReflect.new
return new SetType(value);
}
// If the SetType did not implement the comparison methods,
// it's probably just a "Value" comparison type. We will hydrate
// as a comparison converter, but create an instance of this `"Value"`
// comparison type within the comparison converter.
else {
// inner types
return comparisonsConverter.hydrate(value, function(value) {
return new SetType(value);
});
}
} else {
// There is a `SchemaType`, but it doesn't have a `SetType`.
// Can we create the SetType from the `SchemaType`?
if (makeEnum.canMakeEnumSetType(SchemaType)) {
if (!setTypeMap.has(SchemaType)) {
setTypeMap.set(SchemaType, makeEnum.makeEnumSetType(SchemaType));
}
SetType = setTypeMap.get(SchemaType);
return new SetType(value);
}
// It could also have a `ComparisonSetType` which are the values
// within the Maybe type.
else if (makeMaybe.canMakeMaybeSetType(SchemaType)) {
if (!setTypeMap.has(SchemaType)) {
setTypeMap.set(SchemaType, makeMaybe.makeMaybeSetTypes(SchemaType));
}
SetType = setTypeMap.get(SchemaType).Maybe;
return SetType.hydrate(value, comparisonsConverter.hydrate);
}
// We can't create the `SetType`, so lets hydrate with the default behavior.
else {
return comparisonsConverter.hydrate(value, hydrateChild);
}
}
} else {
// HERE {$gt: 1} -> new is.GreaterThan(1)
return comparisonsConverter.hydrate(value, hydrateChild);
}
}
|
javascript
|
{
"resource": ""
}
|
q1842
|
loadCollection
|
train
|
function loadCollection(collection, data) {
return Q(collection.fetch()).then(function () {
// delete all before running tests
return Q.all(collection.models.slice().map(function (model) {
return model.destroy();
})).then(function () {
chai_1.assert.equal(collection.models.length, 0, 'collection must be empty initially after destroy');
return collection;
});
}).then(function (collection2) {
// load sample data into fresh database
chai_1.assert.equal(collection2, collection, 'same collection object');
return Q.all(data.map(function (attrs) {
return new TestModel(attrs, {
collection: collection2
}).save();
})).then(function () {
chai_1.assert.equal(collection2.models.length, data.length, 'collection was updated by async events');
return collection2;
});
});
}
|
javascript
|
{
"resource": ""
}
|
q1843
|
endsWith
|
train
|
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
|
javascript
|
{
"resource": ""
}
|
q1844
|
defaultRenderer
|
train
|
function defaultRenderer(template, data) {
return template.replace(/%\w+/g, function (match) {
return data[match.slice(1)];
});
}
|
javascript
|
{
"resource": ""
}
|
q1845
|
makeObjectID
|
train
|
function makeObjectID() {
return hexString(8, Date.now() / 1000) +
hexString(6, machineId) +
hexString(4, processId) +
hexString(6, counter++); // a 3-byte counter, starting with a random value.
}
|
javascript
|
{
"resource": ""
}
|
q1846
|
train
|
function (key) {
if (key === undefined) {
that.push({
key: 'DOCUMENT' + sep + docId + sep,
lastPass: true
})
return end()
}
that.options.indexes.get(key, function (err, val) {
if (!err) {
that.push({
key: key,
value: val
})
}
pushValue(docFields[i++])
})
}
|
javascript
|
{
"resource": ""
}
|
|
q1847
|
train
|
function(req, res, fromMessage) {
var name = req.params.name;
var doc = req.body;
var id = this.toId(req.params.id || doc._id);
if (typeof id === 'undefined' || id === '') {
return res.send(400, "invalid id.");
}
doc._id = id;
doc._time = new Date().getTime();
var collection = new mongodb.Collection(this.db, name);
collection.update(
{ "_id" : id },
doc,
{ safe:true, upsert:true },
function(err, n) {
if(err) {
res.send("Oops!: " + err);
} else {
if (n==0) {
res.send(404, 'Document not found!');
} else {
var msg = {
method: 'update',
id: doc._id,
time: doc._time,
data: doc
};
rest.onSuccess(name, msg, fromMessage);
res.send(doc);
}
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q1848
|
train
|
function(req, res, fromMessage) {
var name = req.params.name;
var id = this.toId(req.params.id);
if (typeof id === 'undefined' || id === '') {
return res.send(400, "invalid id.");
}
var doc = {};
doc._id = id;
doc._time = new Date().getTime();
var collection = new mongodb.Collection(this.db, name);
if (id === 'all' || id === 'clean') {
collection.drop(function (err) {
if(err) {
res.send(400, err);
} else {
var msg = {
method: 'delete',
id: doc._id,
time: doc._time
};
rest.onSuccess(name, msg, fromMessage);
res.send(doc);
}
});
} else {
collection.remove({ "_id" : id }, { }, function(err, n){
if(err) {
res.send(400, err);
} else {
if (n==0) {
res.send(404, 'Document not found!');
}
if (n > 0) {
var msg = {
method: 'delete',
id: doc._id,
time: doc._time,
data: doc
};
rest.onSuccess(name, msg, fromMessage);
res.send(doc);
}
}
}
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1849
|
train
|
function(entity, msg) {
if (!msg._id) {
msg._id = new ObjectID();
}
var collection = new mongodb.Collection(this.db, "__msg__" + entity);
if (msg.method === 'delete' && (msg.id === 'all' || msg.id === 'clean')) {
collection.remove(function () {
if (msg.id === 'all') {
collection.insert(msg, { safe: false } );
}
});
} else {
collection.insert(msg, { safe: false } );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1850
|
train
|
function(entity, time, callback) {
var collection = new mongodb.Collection(this.db, "__msg__" + entity);
time = parseInt(time);
if (time || time === 0) {
collection.ensureIndex(
{ time: 1, id: 1 },
{ unique:true, background:true, w:1 },
function(err, indexName) {
var cursor = collection.find({ time: { $gt: time } });
var id, lastMsg;
cursor.sort([['id', 1], ['time', 1]]).each(function(err, msg) {
if (msg && msg.id) {
// the same id, merge document
if (id && id === msg.id) {
if (lastMsg) {
msg = rest.mergeMessage(lastMsg, msg);
}
} else if (lastMsg) {
// send the document to the client
callback(lastMsg);
}
lastMsg = msg;
id = msg.id;
} else {
if (lastMsg) {
callback(lastMsg);
}
callback(null);
}
});
}
);
} else {
callback(null);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1851
|
hashCode
|
train
|
function hashCode() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
var hash = 0;
for (var i = 0; i < args.length; ++i) {
var str = args[i] || '';
for (var j = 0, l = str.length; j < l; ++j) {
var char = str.charCodeAt(j);
hash = ((hash << 5) - hash) + char;
hash |= 0; // Convert to 32bit integer
}
}
return hash;
}
|
javascript
|
{
"resource": ""
}
|
q1852
|
readInteger
|
train
|
function readInteger(width, reader) {
return function (start, cb) {
var i = Math.floor(start/block_size)
var _i = start%block_size
//if the UInt32BE aligns with in a block
//read directly and it's 3x faster.
if(_i < block_size - width)
get(i, function (err, block) {
if(err) return cb(err)
var value = reader(block, start%block_size)
cb(null, value)
})
//but handle overlapping reads this easier way
//instead of messing around with bitwise ops
else
read(start, start+width, function (err, buf, bytes_read) {
if(err) return cb(err)
var value = reader(buf, 0);
cb(isNaN(value) ? new Error('Number is too large') : null, value)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q1853
|
init
|
train
|
function init(app) {
app.post('/api/v1/push/registration',
/**
* register the device on the push Service
*
* @param req containing body JSON to pass as input.
* @param res result of call is provided as JSON body data.
* @param next function to invoke error handling.
*/
function serviceCall(req, res, next) {
Q(pushService.registerPushDevice(req.body)).then(res.json.bind(res), next).done();
});
app.post('/api/v1/push',
/**
* posts push notification(s).
*
* @param req containing body JSON to pass as input.
* @param res result of call is provided as JSON body data.
* @param next function to invoke error handling.
*/
function serviceCall(req, res, next) {
Q(pushService.postPushNotification(req.body)).then(res.json.bind(res), next).done();
});
app.get('/api/v1/push/:uuid',
/**
* gets push notification status.
*
* @param req containing body JSON to pass as input.
* @param res result of call is provided as JSON body data.
* @param next function to invoke error handling.
*/
function serviceCall(req, res, next) {
Q(pushService.fetchPushNotification(req.params.uuid)).then(res.json.bind(res), next).done();
});
}
|
javascript
|
{
"resource": ""
}
|
q1854
|
serviceCall
|
train
|
function serviceCall(req, res, next) {
Q(pushService.registerPushDevice(req.body)).then(res.json.bind(res), next).done();
}
|
javascript
|
{
"resource": ""
}
|
q1855
|
patch
|
train
|
function patch(node, p5, parentSchema) {
var schema = parentSchema
var position = node.position
var children = node.children
var childNodes = []
var length = children ? children.length : 0
var index = -1
var child
if (node.type === 'element') {
if (schema.space === 'html' && node.tagName === 'svg') {
schema = svg
}
p5.namespaceURI = ns[schema.space]
}
while (++index < length) {
child = one(children[index], schema)
child.parentNode = p5
childNodes[index] = child
}
if (node.type === 'element' || node.type === 'root') {
p5.childNodes = childNodes
}
if (position && position.start && position.end) {
p5.sourceCodeLocation = {
startLine: position.start.line,
startCol: position.start.column,
startOffset: position.start.offset,
endLine: position.end.line,
endCol: position.end.column,
endOffset: position.end.offset
}
}
return p5
}
|
javascript
|
{
"resource": ""
}
|
q1856
|
resolveServer
|
train
|
function resolveServer(path, options) {
if (options === void 0) { options = {}; }
var serverUrl = options.serverUrl || init.initOptions.serverUrl;
if (path) {
if (serverUrl) {
path = url.resolve(serverUrl, path);
}
}
else {
path = serverUrl;
}
return url.resolve(path, '/');
}
|
javascript
|
{
"resource": ""
}
|
q1857
|
resolveUrl
|
train
|
function resolveUrl(path, options) {
if (options === void 0) { options = {}; }
var serverUrl = resolveServer(path, options);
if (!serverUrl) {
return path;
}
if (path.charAt(0) !== '/') {
// construct full application url
var tenantOrga = options.tenantOrga;
if (!tenantOrga) {
// following extracts the tenantOrga set on the specific server
var serverObj = server.Server.getInstance(serverUrl);
tenantOrga = serverObj.applyOptions({
serverUrl: serverUrl
}).tenantOrga;
if (!tenantOrga) {
tenantOrga = init.initOptions.tenantOrga;
if (!tenantOrga) {
var organization = serverObj.organization;
if (organization) {
tenantOrga = organization.uniqueName;
}
}
}
}
var application = options.application || init.initOptions.application;
serverUrl = url.resolve(serverUrl, '/' + tenantOrga + '/' + application + '/');
}
return url.resolve(serverUrl, path);
}
|
javascript
|
{
"resource": ""
}
|
q1858
|
resolveApp
|
train
|
function resolveApp(baseAliasOrNameOrApp, options) {
if (options === void 0) { options = {}; }
// defaults on arguments given
var url;
if (!baseAliasOrNameOrApp) {
url = options.application || init.initOptions.application;
}
else if (_.isString(baseAliasOrNameOrApp)) {
url = baseAliasOrNameOrApp;
}
else {
url = baseAliasOrNameOrApp.baseAlias || baseAliasOrNameOrApp.name;
}
// application must not include the leading slash for resolveUrl to do the job
url = url.replace(/\/?(.*)/, '$1');
// resolve local path against application
return resolveUrl('.', _.defaults({
application: url
}, options));
}
|
javascript
|
{
"resource": ""
}
|
q1859
|
isStore
|
train
|
function isStore(object) {
if (!object || typeof object !== 'object') {
return false;
}
else if ('isStore' in object) {
diag.debug.assert(function () { return object.isStore === Store.prototype.isPrototypeOf(object); });
return object.isStore;
}
else {
return Store.prototype.isPrototypeOf(object);
}
}
|
javascript
|
{
"resource": ""
}
|
q1860
|
loadConfig
|
train
|
function loadConfig(justJson) {
if (!justJson) {
const configScript = path.resolve(currentDir, configScriptFileName);
if (fs.existsSync(configScript)) {
return require(configScript);
}
}
const configJson = path.resolve(currentDir, configJsonFileName);
if (fs.existsSync(configJson)) {
return require(configJson);
}
const errorMessage = [
`Specify a ${configScriptFileName} or ${configJsonFileName} file to configure the swagen tool.`,
``,
`To create a configuration file in the current directory, use the following command:`,
``,
` swagen init`,
``,
`This will ask you a series of questions and generate a configuration file based on your answers.`
].join(os.EOL);
throw errorMessage;
}
|
javascript
|
{
"resource": ""
}
|
q1861
|
init
|
train
|
function init(app) {
app.post('/api/v1/connectors/:connection',
/**
* installs session data such as credentials.
*
* @param req containing body JSON to pass as input.
* @param res result of call is provided as JSON body data.
* @param next function to invoke error handling.
*/
function serviceCall(req, res, next) {
connector.configureSession(req.params.connection, req.body);
res.send(204); // success --> 204 no content
});
app.post('/api/v1/connectors/:connection/:call',
/**
* calls directly into a service connection.
*
* @param req containing body JSON to pass as input.
* @param res result of call is provided as JSON body data.
* @param next function to invoke error handling.
*/
function serviceCall(req, res, next) {
connector.runCall(req.params.connection, req.params.call, req.body).then(res.json.bind(res), next).done();
});
}
|
javascript
|
{
"resource": ""
}
|
q1862
|
serviceCall
|
train
|
function serviceCall(req, res, next) {
connector.configureSession(req.params.connection, req.body);
res.send(204); // success --> 204 no content
}
|
javascript
|
{
"resource": ""
}
|
q1863
|
serviceCall
|
train
|
function serviceCall(req, res, next) {
connector.runCall(req.params.connection, req.params.call, req.body).then(res.json.bind(res), next).done();
}
|
javascript
|
{
"resource": ""
}
|
q1864
|
train
|
function(callback) {
// Asynchronously set our name and status message using promises
Promise.join(
tox.setNameAsync('Bluebird'),
tox.setStatusMessageAsync('Some status message')
).then(function() {
console.log('Successfully set name and status message!');
callback();
}).catch(function(err) {
console.error('Error (initSelf):', err);
callback(err);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q1865
|
train
|
function(callback) {
tox.on('friendRequest', function(evt) {
console.log('Accepting friend request from ' + evt.publicKeyHex());
// Automatically accept the request
tox.addFriendNoRequestAsync(evt.publicKey()).then(function() {
console.log('Successfully accepted the friend request!');
}).catch(function(err) {
console.error('Couldn\'t accept the friend request:', err);
});
});
tox.on('friendMessage', function(evt) {
console.log('Message from friend ' + evt.friend() + ': ' + evt.message());
// Echo message back to friend
tox.sendMessageAsync(evt.friend(), evt.message()).then(function(receipt) {
console.log('Echoed message back to friend, received receipt ' + receipt);
}).catch(function(err) {
console.error('Couldn\'t echo message back to friend:', err);
});
});
// Setup friendMessage callback to listen for groupchat invite requests
tox.on('friendMessage', function(evt) {
if(evt.message() === 'invite text') {
tox.inviteAsync(evt.friend(), groupchats['text']).then(function() {
console.log('Invited ' + evt.friend() + ' to the text groupchat');
});
} else if(evt.message() === 'invite av') {
tox.inviteAsync(evt.friend(), groupchats['av']).then(function() {
console.log('Invited ' + evt.friend() + ' to the audio/video groupchat');
});
}
});
callback();
}
|
javascript
|
{
"resource": ""
}
|
|
q1866
|
train
|
function(callback) {
async.parallelAsync([
tox.addGroupchat.bind(tox),
tox.getAV().addGroupchat.bind(tox.getAV())
]).then(function(results) {
groupchats['text'] = results[0];
groupchats['av'] = results[1];
}).finally(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q1867
|
handleCommandError
|
train
|
function handleCommandError(ex) {
// If the command throws an exception, display the error message and command help.
if (ex instanceof Error) {
console.log(chalk.red(ex.message));
} else {
console.log(chalk.red(ex));
}
console.log();
const helpArgs = {
_: [command]
};
helpCommand(helpArgs);
}
|
javascript
|
{
"resource": ""
}
|
q1868
|
train
|
function(tox, opts) {
// If one argument and not tox, assume opts
if(arguments.length === 1 && !(tox instanceof Tox)) {
opts = tox;
tox = undefined;
}
if(!(tox instanceof Tox)) {
tox = undefined;
//var err = new Error('Tox instance required for ToxEncryptSave');
//throw err;
}
if(!opts) {
opts = {};
}
this._tox = tox;
this._libpath = opts['path'];
if(opts['sync'] === undefined || opts['sync'] === null) {
this._sync = true;
} else {
this._sync = !!opts['sync'];
}
this._toxencryptsave = this.createLibrary(this._libpath);
}
|
javascript
|
{
"resource": ""
}
|
|
q1869
|
HubtelMobilePayment
|
train
|
function HubtelMobilePayment({
secretid = required('secretid'),
clientid = required('clientid'),
merchantaccnumber = required('merchantaccnumber'),
}) {
this.config = {}
this.config['clientid'] = clientid
this.config['secretid'] = secretid
this.config['merchantaccnumber'] = merchantaccnumber
this.hubtelurl = 'https://api.hubtel.com/v1/merchantaccount/'
}
|
javascript
|
{
"resource": ""
}
|
q1870
|
validateCurlyPair
|
train
|
function validateCurlyPair(openingCurly, closingCurly) {
const tokenBeforeOpeningCurly = sourceCode.getTokenBefore(openingCurly),
tokenAfterOpeningCurly = sourceCode.getTokenAfter(openingCurly),
tokenBeforeClosingCurly = sourceCode.getTokenBefore(closingCurly),
singleLineException = params.allowSingleLine && astUtils.isTokenOnSameLine(openingCurly, closingCurly),
isOpeningCurlyOnSameLine = astUtils.isTokenOnSameLine(openingCurly, tokenAfterOpeningCurly),
isClosingCurlyOnSameLine = astUtils.isTokenOnSameLine(tokenBeforeClosingCurly, closingCurly);
if (style !== 'allman' && !astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly)) {
context.report({
node: openingCurly,
messageId: 'nextLineOpen',
fix: removeNewlineBetween(tokenBeforeOpeningCurly, openingCurly),
});
}
if (style === 'allman' && astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly) && !singleLineException) {
context.report({
node: openingCurly,
messageId: 'sameLineOpen',
fix: (fixer) => fixer.insertTextBefore(openingCurly, '\n'),
});
}
if (isOpeningCurlyOnSameLine && tokenAfterOpeningCurly !== closingCurly && !singleLineException) {
context.report({
node: openingCurly,
messageId: 'blockSameLine',
fix: (fixer) => fixer.insertTextAfter(openingCurly, '\n'),
});
}
if (tokenBeforeClosingCurly !== openingCurly && !singleLineException && isClosingCurlyOnSameLine) {
context.report({
node: closingCurly,
messageId: 'singleLineClose',
fix: (fixer) => fixer.insertTextBefore(closingCurly, '\n'),
});
}
}
|
javascript
|
{
"resource": ""
}
|
q1871
|
isModel
|
train
|
function isModel(object) {
if (!object || typeof object !== 'object') {
return false;
}
else if ('isModel' in object) {
diag.debug.assert(function () { return object.isModel === Model.prototype.isPrototypeOf(object); });
return object.isModel;
}
else {
return Model.prototype.isPrototypeOf(object);
}
}
|
javascript
|
{
"resource": ""
}
|
q1872
|
train
|
function(dnsaddr) {
var domain = getAddressDomain(dnsaddr);
if(domain !== undefined && clients[domain] !== undefined)
return clients[domain];
}
|
javascript
|
{
"resource": ""
}
|
|
q1873
|
train
|
function(opts) {
if(!opts) opts = {};
var libpath = opts['path'];
var key = opts['key'];
this._library = this._createLibrary(libpath);
this._initKey(key);
this._initHandle(this._key);
}
|
javascript
|
{
"resource": ""
}
|
|
q1874
|
train
|
function(not, primitive){
// NOT(5) U 5
if( set.isEqual( not.value, primitive) ) {
return set.UNIVERSAL;
}
// NOT(4) U 6
else {
throw new Error("Not,Identity Union is not filled out");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q1875
|
train
|
function (url, options) {
return Object.keys(options).reduce(this._replacePlaceholderInUrl.bind(this, options), url);
}
|
javascript
|
{
"resource": ""
}
|
|
q1876
|
train
|
function (options, cb, wd, params) {
// if no cb is given, generate a body with the `desiredCapabilities` object
if (!cb) {
// check if we have parameters set up
if (Object.keys(params).length > 0) {
return JSON.stringify(params);
}
return '';
}
// invoke the given callback & stringify
var data = cb.call(wd, params);
return data === null ? '{}' : JSON.stringify(data);
}
|
javascript
|
{
"resource": ""
}
|
|
q1877
|
train
|
function (hostname, port, prefix, url, method, body, auth) {
var options = {
hostname: hostname,
port: port,
path: prefix + url,
method: method,
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Content-Length': Buffer.byteLength(body, 'utf8')
}
};
// check if auth information is available
if (auth) {
options.auth = auth;
}
return options;
}
|
javascript
|
{
"resource": ""
}
|
|
q1878
|
train
|
function (remote, driver) {
return function webdriverCommand() {
var deferred = Q.defer();
// the request meta data
var params = Driver.generateParamset(remote.params, arguments);
var body = Driver.generateBody({}, remote.onRequest, this, params);
var options = Driver.generateRequestOptions(this.opts.host, this.opts.port, this.opts.path, Driver.parseUrl(remote.url, this.options), remote.method, body, this.opts.auth);
// generate the request, wait for response & fire the request
var req = new http.ClientRequest(options);
req.on('response', driver._onResponse.bind(this, driver, remote, options, deferred));
req.end(body);
return deferred.promise;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q1879
|
train
|
function (driver, remote, options, deferred, response) {
this.data = '';
response.on('data', driver._concatDataChunks.bind(this));
response.on('end', driver._onResponseEnd.bind(this, driver, response, remote, options, deferred));
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1880
|
train
|
function (driver, response, remote, options, deferred) {
return driver[(response.statusCode === 500 ? '_onError' : '_onSuccess')].bind(this)(driver, response, remote, options, deferred);
}
|
javascript
|
{
"resource": ""
}
|
|
q1881
|
train
|
function (driver, response, remote, options, deferred) {
// Provide a default error handler to prevent hangs.
if (!remote.onError) {
remote.onError = function (request, remote, options, deferred, data) {
data = JSON.parse(data);
var value = -1;
if (typeof data.value.message === 'string') {
var msg = JSON.parse(data.value.message);
value = msg.errorMessage;
}
deferred.resolve(JSON.stringify({'sessionId': data.sessionId, value: value}));
};
}
remote.onError.call(this, response, remote, options, deferred, this.data);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1882
|
train
|
function (driver, response, remote, options, deferred) {
// log response data
this.events.emit('driver:webdriver:response', {
statusCode: response.statusCode,
method: response.req.method,
path: response.req.path,
data: this.data
});
if (remote.onResponse) {
remote.onResponse.call(this, response, remote, options, deferred, this.data);
} else {
deferred.resolve(this.data);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q1883
|
handleFileSwagger
|
train
|
function handleFileSwagger(profile, profileKey) {
const inputFilePath = path.resolve(currentDir, profile.file);
console.log(chalk`{green [${profileKey}]} Input swagger file : {cyan ${inputFilePath}}`);
fs.readFile(inputFilePath, 'utf8', (error, swagger) => {
if (error) {
console.log(chalk`{red Cannot read swagger file '{bold ${profile.file}}'.}`);
console.log(chalk.red(error));
} else {
handleSwagger(swagger, profile, profileKey);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q1884
|
handleUrlSwagger
|
train
|
function handleUrlSwagger(profile, profileKey) {
console.log(chalk`{green [${profileKey}]} Input swagger URL : {cyan ${profile.url}}`);
const options = {
rejectUnauthorized: false
};
needle.get(profile.url, options, (err, resp, body) => {
if (err) {
console.log(chalk`{red Cannot read swagger URL '{bold ${profile.url}}'.}`);
console.log(chalk.red(err));
} else {
handleSwagger(body, profile, profileKey);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q1885
|
verifyProfile
|
train
|
function verifyProfile(profile, profileKey) {
if (!profile.file && !profile.url) {
throw new Error(`[${profileKey}] Must specify a file or url in the configuration.`);
}
if (!profile.output) {
throw new Error(`[${profileKey}] Must specify an output file path in the configuration.`);
}
if (!profile.generator) {
throw new Error(`[${profileKey}] Must specify a generator in the configuration.`);
}
if (profile.generator.toLowerCase() === 'core') {
throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. This name is reserved.`);
}
if (profile.generator.match(/^[\w-]+-language$/i)) {
throw new Error(`[${profileKey}] Invalid generator ${profile.generator}. The -language suffix is reserved for language helper packages.`);
}
profile.debug = profile.debug || {};
profile.filters = profile.filters || {};
profile.transforms = profile.transforms || {};
profile.options = profile.options || {};
}
|
javascript
|
{
"resource": ""
}
|
q1886
|
processInputs
|
train
|
function processInputs(config) {
for (const profileKey in config) {
const profile = config[profileKey];
if (profile.skip) {
continue;
}
verifyProfile(profile, profileKey);
if (profile.file) {
handleFileSwagger(profile, profileKey);
} else {
handleUrlSwagger(profile, profileKey);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q1887
|
toMinorRange
|
train
|
function toMinorRange(version) {
var regex = /^\d+\.\d+/;
var range = version.match(regex);
if (range) {
return '^' + range[0];
}
else {
var regex = /^\d+\.x/;
var range = version.match(regex);
if (range) {
return range[0];
}
}
return version;
}
|
javascript
|
{
"resource": ""
}
|
q1888
|
toDrupalMajorVersion
|
train
|
function toDrupalMajorVersion(version) {
var regex = /^(\d+)\.\d+\.[x\d+]/;
var match = version.match(regex)
if (match) {
return match[1] + '.x';
}
return version;
}
|
javascript
|
{
"resource": ""
}
|
q1889
|
isCached
|
train
|
function isCached(project, majorVersion) {
var cid = project+majorVersion;
return cache[cid] && cache[cid].short_name[0] == project && cache[cid].api_version[0] == majorVersion;
}
|
javascript
|
{
"resource": ""
}
|
q1890
|
train
|
function(userName, firstName, lastName, password) {
var _this = this;
_this['userName'] = userName;
_this['firstName'] = firstName;
_this['lastName'] = lastName;
_this['password'] = password;
}
|
javascript
|
{
"resource": ""
}
|
|
q1891
|
BasicQuery
|
train
|
function BasicQuery(query) {
assign(this, query);
if (!this.filter) {
this.filter = set.UNIVERSAL;
}
if (!this.page) {
this.page = new RecordRange();
}
if (!this.sort) {
this.sort = "id";
}
if (typeof this.sort === "string") {
this.sort = new DefaultSort(this.sort);
}
}
|
javascript
|
{
"resource": ""
}
|
q1892
|
ParsedArgs
|
train
|
function ParsedArgs (args) {
/**
* The command to run ("browserify" or "watchify")
* @type {string}
*/
this.cmd = "browserify";
/**
* The base directory for the entry-file glob pattern.
* See {@link helpers#getBaseDir} for details.
* @type {string}
*/
this.baseDir = "";
/**
* Options for how the entry-file glob pattern should be parsed.
* For example if an --exclude argument is specified, then `globOptions.ignore` will be set accordingly.
* @type {object}
*/
this.globOptions = { ignore: []};
/**
* The index of the entry-file glob argument.
* If there is no entry-file argument, or it's not a glob pattern, then this will be -1.
* @type {number}
*/
this.globIndex = -1;
/**
* The index of the outfile argument.
* If there is no outfile argument, or it's not a glob pattern, then this will be -1;
* @type {number}
*/
this.outfileIndex = -1;
/**
* The arguments to pass to browserify.
* If {@link globIndex} or {@link outfileIndex} are set, then the corresponding elements in
* this array will be the corresponding functions.
* @type {Array}
*/
this.args = [];
args = args || [];
while (args.length > 0) {
parseOutfile(args, this) ||
parseExclude(args, this) ||
parseWatch(args, this) ||
parseSubArgs(args, this) ||
parseDashArgs(args, this) ||
parseGlobs(args, this) ||
passThrough(args, this);
}
}
|
javascript
|
{
"resource": ""
}
|
q1893
|
openDatabase
|
train
|
function openDatabase(options) {
var db;
var sqlitePlugin = 'sqlitePlugin';
if (global[sqlitePlugin]) {
// device implementation
options = _.clone(options);
if (!options.key) {
if (options.security) {
options.key = options.security;
delete options.security;
}
else if (options.credentials) {
options.key = cipher.hashJsonSync(options.credentials, 'sha256').toString('hex');
delete options.credentials;
}
}
if (!options.location) {
options.location = 2;
}
db = global[sqlitePlugin].openDatabase(options);
}
else if (global['openDatabase']) {
// native implementation
db = global['openDatabase'](options.name, options.version || '', options.description || '', options.size || 1024 * 1024);
}
else if (process && !process['browser']) {
// node.js implementation
var websql = void 0;
try {
websql = require('websql');
}
catch (error) {
diag.debug.warn(error);
}
if (websql) {
db = websql(options.name, options.version || '', options.description || '', options.size || 1024 * 1024);
}
}
if (!db) {
// when this is reached no supported implementation is present
throw new Error('WebSQL implementation is not available');
}
return db;
}
|
javascript
|
{
"resource": ""
}
|
q1894
|
erroz
|
train
|
function erroz(error) {
var errorFn = function (data) {
//apply all attributes on the instance
for (var errKey in errorFn.prototype) {
if (errorFn.prototype.hasOwnProperty(errKey)) {
this[errKey] = errorFn.prototype[errKey];
}
}
//overwrite message if invoked with string
if (typeof data === "string") {
this.message = data;
data = {};
}
this.data = data || {};
this.message = this.message || erroz.options.renderMessage(error.template || "", this.data);
errorFn.super_.call(this, this.constructor);
};
util.inherits(errorFn, AbstractError);
//add static error properties (name, status, etc)
for (var errKey in error) {
if (error.hasOwnProperty(errKey)) {
errorFn.prototype[errKey] = error[errKey];
}
}
/**
* return an object containing only JSend attributes
* @returns {{status: *, code: *, message: *, data: (*|string|Object[]|Object|String)}}
*/
errorFn.prototype.toJSend = function () {
var data = this.data;
if (erroz.options.includeStack && this.stack) {
data.stack = this.stack;
}
if (!this.status) {
this.status = deriveStatusFromStatusCode(this.statusCode);
}
return {
status: this.status,
code: this.code,
message: this.message,
data: data
};
};
return errorFn;
}
|
javascript
|
{
"resource": ""
}
|
q1895
|
metadata
|
train
|
function metadata(log, value) {
var lines = value.split('\n');
log.commit = lines[0].split(' ')[1];
log.author = lines[1].split(':')[1].trim();
log.date = lines[2].slice(8);
return log
}
|
javascript
|
{
"resource": ""
}
|
q1896
|
stopDefaultBrowserBehavior
|
train
|
function stopDefaultBrowserBehavior(element, css_props) {
if(!css_props || !element || !element.style) {
return;
}
// with css properties for modern browsers
Hammer.utils.each(['webkit', 'khtml', 'moz', 'Moz', 'ms', 'o', ''], function(vendor) {
Hammer.utils.each(css_props, function(value, prop) {
// vender prefix at the property
if(vendor) {
prop = vendor + prop.substring(0, 1).toUpperCase() + prop.substring(1);
}
// set the style
if(prop in element.style) {
element.style[prop] = value;
}
});
});
// also the disable onselectstart
if(css_props.userSelect == 'none') {
element.onselectstart = function() {
return false;
};
}
// and disable ondragstart
if(css_props.userDrag == 'none') {
element.ondragstart = function() {
return false;
};
}
}
|
javascript
|
{
"resource": ""
}
|
q1897
|
detect
|
train
|
function detect(eventData) {
if(!this.current || this.stopped) {
return;
}
// extend event data with calculations about scale, distance etc
eventData = this.extendEventData(eventData);
// instance options
var inst_options = this.current.inst.options;
// call Hammer.gesture handlers
Hammer.utils.each(this.gestures, function(gesture) {
// only when the instance options have enabled this gesture
if(!this.stopped && inst_options[gesture.name] !== false) {
// if a handler returns false, we stop with the detection
if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
this.stopDetect();
return false;
}
}
}, this);
// store as previous event event
if(this.current) {
this.current.lastEvent = eventData;
}
// endevent, but not the last touch, so dont stop
if(eventData.eventType == Hammer.EVENT_END && !eventData.touches.length - 1) {
this.stopDetect();
}
return eventData;
}
|
javascript
|
{
"resource": ""
}
|
q1898
|
stopDetect
|
train
|
function stopDetect() {
// clone current data to the store as the previous gesture
// used for the double tap gesture, since this is an other gesture detect session
this.previous = Hammer.utils.extend({}, this.current);
// reset the current
this.current = null;
// stopped!
this.stopped = true;
}
|
javascript
|
{
"resource": ""
}
|
q1899
|
register
|
train
|
function register(gesture) {
// add an enable gesture options if there is no given
var options = gesture.defaults || {};
if(options[gesture.name] === undefined) {
options[gesture.name] = true;
}
// extend Hammer default options with the Hammer.gesture options
Hammer.utils.extend(Hammer.defaults, options, true);
// set its index
gesture.index = gesture.index || 1000;
// add Hammer.gesture to the list
this.gestures.push(gesture);
// sort the list by index
this.gestures.sort(function(a, b) {
if(a.index < b.index) { return -1; }
if(a.index > b.index) { return 1; }
return 0;
});
return this.gestures;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.