_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q51300
|
train
|
function( version ) {
version = version || '4.0'
var keys = Object.keys( this.data )
var data = [ [ 'version', {}, 'text', version ] ]
var prop = null
for( var i = 0; i < keys.length; i++ ) {
if( keys[i] === 'version' ) continue;
prop = this.data[ keys[i] ]
if( Array.isArray( prop ) ) {
for( var k = 0; k < prop.length; k++ ) {
data.push( prop[k].toJSON() )
}
} else {
data.push( prop.toJSON() )
}
}
return [ 'vcard', data ]
}
|
javascript
|
{
"resource": ""
}
|
|
q51301
|
train
|
function( type ) {
type = ( type + '' ).toLowerCase()
return Array.isArray( this.type ) ?
this.type.indexOf( type ) >= 0 :
this.type === type
}
|
javascript
|
{
"resource": ""
}
|
|
q51302
|
train
|
function( version ) {
var propName = (this.group ? this.group + '.' : '') + capitalDashCase( this._field )
var keys = Object.keys( this )
var params = []
for( var i = 0; i < keys.length; i++ ) {
if (keys[i] === 'group') continue
params.push( capitalDashCase( keys[i] ) + '=' + this[ keys[i] ] )
}
return propName +
( params.length ? ';' + params.join( ';' ) : params ) + ':' +
( Array.isArray( this._data ) ? this._data.join( ';' ) : this._data )
}
|
javascript
|
{
"resource": ""
}
|
|
q51303
|
train
|
function() {
var params = Object.assign({},this)
if( params.value === 'text' ) {
params.value = void 0
delete params.value
}
var data = [ this._field, params, this.value || 'text' ]
switch( this._field ) {
default: data.push( this._data ); break
case 'adr':
case 'n':
data.push( this._data.split( ';' ) )
}
return data
}
|
javascript
|
{
"resource": ""
}
|
|
q51304
|
train
|
function(req, res, user) {
var jsonWebTokens = waterlock.config.jsonWebTokens || {};
var expiryUnit = (jsonWebTokens.expiry && jsonWebTokens.expiry.unit) || 'days';
var expiryLength = (jsonWebTokens.expiry && jsonWebTokens.expiry.length) || 7;
var expires = moment().add(expiryLength, expiryUnit).valueOf();
var issued = Date.now();
user = user || req.session.user;
var token = jwt.encode({
iss: user.id + '|' + req.remoteAddress,
sub: jsonWebTokens.subject,
aud: jsonWebTokens.audience,
exp: expires,
nbf: issued,
iat: issued,
jti: uuid.v1()
}, jsonWebTokens.secret);
return {
token: token,
expires: expires
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51305
|
train
|
function(req){
var token = null;
if (req.headers && req.headers.authorization) {
var parts = req.headers.authorization.split(' ');
if (parts.length === 2){
var scheme = parts[0];
var credentials = parts[1];
if (/^Bearer$/i.test(scheme)){
token = credentials;
}
}
}else{
token = this.allParams(req).access_token;
}
return token;
}
|
javascript
|
{
"resource": ""
}
|
|
q51306
|
train
|
function(token, cb){
try{
// decode the token
var _token = waterlock.jwt.decode(token, waterlock.config.jsonWebTokens.secret);
// set the time of the request
var _reqTime = Date.now();
// If token is expired
if(_token.exp <= _reqTime){
waterlock.logger.debug('access token rejected, reason: EXPIRED');
return cb('Your token is expired.');
}
// If token is early
if(_reqTime <= _token.nbf){
waterlock.logger.debug('access token rejected, reason: TOKEN EARLY');
return cb('This token is early.');
}
// If audience doesn't match
if(waterlock.config.jsonWebTokens.audience !== _token.aud){
waterlock.logger.debug('access token rejected, reason: AUDIENCE');
return cb('This token cannot be accepted for this domain.');
}
this.findUserFromToken(_token, cb);
} catch(err){
cb(err);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51307
|
train
|
function(token, cb){
// deserialize the token iss
var _iss = token.iss.split('|');
waterlock.User.findOne(_iss[0]).exec(function(err, user){
if(err){
waterlock.logger.debug(err);
}
cb(err, user);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51308
|
train
|
function(req, user){
req.session.authenticated = true;
req.session.user = user;
}
|
javascript
|
{
"resource": ""
}
|
|
q51309
|
train
|
function(token, address, cb){
waterlock.Jwt.findOne({token: token}, function(err, j){
if(err){
return cb(err);
}
if(!j){
waterlock.logger.debug('access token not found');
return cb('Token not found');
}
if(j.revoked){
waterlock.logger.debug('access token rejected, reason: REVOKED');
return cb('This token has been revoked');
}
var use = {jsonWebToken: j.id, remoteAddress: address.ip};
waterlock.Use.create(use).exec(function(){});
cb(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51310
|
train
|
function(address, token, user, cb){
this.findAndTrackJWT(token, address, function(err){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
cb(null, user);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51311
|
Waterlock
|
train
|
function Waterlock(){
events.EventEmitter.call(this);
this.sails = global.sails;
this.engine = _.bind(this.engine, this)();
this.config = _.bind(this.config, this)();
this.methods = _.bind(this.methods, this)().collect();
this.models = _.bind(this.models, this)();
this.actions = _.bind(this.actions, this)();
this.cycle = _.bind(this.cycle, this)();
// expose jwt so the implementing
// app doesn't need to require it.
this.jwt = require('jwt-simple');
this.validator = _.bind(this.validator, this)();
}
|
javascript
|
{
"resource": ""
}
|
q51312
|
train
|
function(auth, cb){
var self = this;
// create the user
if(!auth.user){
waterlock.User.create({auth:auth.id}).exec(function(err, user){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
// update the auth object
waterlock.Auth.update(auth.id, {user:user.id}).exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
user.auth = auth.shift();
cb(err, user);
});
});
}else{
// just fire off update to user object so we can get the
// backwards association going.
if(!auth.user.auth){
waterlock.User.update(auth.user.id, {auth:auth.id}).exec(function(){});
}
cb(null, self._invertAuth(auth));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51313
|
train
|
function(criteria, attributes, cb){
var self = this;
waterlock.Auth.findOrCreate(criteria, attributes)
.exec(function(err, newAuth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
waterlock.Auth.findOne(newAuth.id).populate('user')
.exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
self._attachAuthToUser(auth, cb);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51314
|
train
|
function(attributes, user, cb){
var self = this;
attributes.user = user.id;
waterlock.User.findOne(user.id).exec(function(err, user){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
if(user.auth){
delete(attributes.auth);
//update existing auth
waterlock.Auth.findOne(user.auth).exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
// Check if any attribtues have changed if so update them
if(self._updateAuth(auth, attributes)){
auth.save(function(err){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
user.auth = auth;
cb(err, user);
});
}else{
user.auth = auth;
cb(err, user);
}
});
}else{
// force create by pass of user id
self.findOrCreateAuth(user.id, attributes, cb);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51315
|
train
|
function(auth){
// nothing to invert
if(!auth || !auth.user){
return auth;
}
var u = auth.user;
delete(auth.user);
u.auth = auth;
return u;
}
|
javascript
|
{
"resource": ""
}
|
|
q51316
|
train
|
function(auth, attributes){
if(!_.isEqual(auth, attributes)){
_.merge(auth, attributes);
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q51317
|
train
|
function(actions){
waterlock.logger.verbose('bootstraping user actions');
var template = {
jwt: require('./actions/jwt')
};
return _.merge(template, actions);
}
|
javascript
|
{
"resource": ""
}
|
|
q51318
|
train
|
function(req, res, user) {
waterlock.logger.debug('user registration success');
if (!user) {
waterlock.logger.debug('registerSuccess requires a valid user object');
return res.serverError();
}
var address = this._addressFromRequest(req);
var attempt = {
user: user.id,
successful: true
};
_.merge(attempt, address);
waterlock.Attempt.create(attempt).exec(function(err) {
if (err) {
waterlock.logger.debug(err);
}
});
// store user in && authenticate the session
req.session.user = user;
req.session.authenticated = true;
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.register.success, user);
if (postResponse === 'jwt') {
//Returns the token immediately
var jwtData = waterlock._utils.createJwt(req, res, user);
Jwt.create({token: jwtData.token, uses: 0, owner: user.id}).exec(function(err){
if(err){
return res.serverError('JSON web token could not be created');
}
var result = {};
result[waterlock.config.jsonWebTokens.tokenProperty] = jwtData.token;
result[waterlock.config.jsonWebTokens.expiresProperty] = jwtData.expires;
if (waterlock.config.jsonWebTokens.includeUserInJwtResponse) {
result['user'] = user;
}
res.json(result);
});
}else if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51319
|
train
|
function(req, res, user, error) {
waterlock.logger.debug('user register failure');
if (user) {
var address = this._addressFromRequest(req);
var attempt = {
user: user.id,
successful: false
};
_.merge(attempt, address);
waterlock.Attempt.create(attempt).exec(function(err) {
if (err) {
waterlock.logger.debug(err);
}
});
}
if (req.session.authenticated) {
req.session.authenticated = false;
}
delete(req.session.user);
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.register.failure,
error);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.forbidden(postResponse);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51320
|
train
|
function(req, res) {
waterlock.logger.debug('user logout');
delete(req.session.user);
if (req.session.authenticated) {
this.logoutSuccess(req, res);
} else {
this.logoutFailure(req, res);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51321
|
train
|
function(req, res) {
req.session.authenticated = false;
var defaultString = 'You have successfully logged out.';
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.logout.success,
defaultString);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51322
|
train
|
function(req, res) {
var defaultString = 'You have successfully logged out.';
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.logout.failure,
defaultString);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51323
|
train
|
function(req) {
if (req.connection && req.connection.remoteAddress) {
return {
ip: req.connection.remoteAddress,
port: req.connection.remotePort
};
}
if (req.socket && req.socket.remoteAddress) {
return {
ip: req.socket.remoteAddress,
port: req.socket.remotePort
};
}
return {
ip: '0.0.0.0',
port: 'n/a'
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51324
|
train
|
function(obj) {
if (typeof obj.controller === 'undefined' || typeof obj.action === 'undefined') {
var error = new Error('You must define a controller and action to redirect to.').stack;
throw error;
}
return '/' + obj.controller + '/' + obj.action;
}
|
javascript
|
{
"resource": ""
}
|
|
q51325
|
train
|
function(target){
for(var i = 0; i < self.waterlockPlugins.length; i++){
var arr = this.readdirSyncComplete(self.waterlockPlugins[i] + '/' + target);
this.installArray = this.installArray.concat(arr);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51326
|
train
|
function(path){
var fullPath = [];
try{
var files = fs.readdirSync(path);
for(var i = 0; i < files.length; i++){
fullPath.push(path + '/' + files[i]);
}
return fullPath;
}catch(e){
return [];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51327
|
train
|
function(){
console.log('');
this.log('Usage: generate [resource]');
this.log('Resources:');
this.log(' all generates all components', false);
this.log(' models generates all models', false);
this.log(' controllers generates all controllers', false);
this.log(' configs generates default configs', false);
this.log(' views generates default view templates', false);
this.log(' policies generates all policies');
}
|
javascript
|
{
"resource": ""
}
|
|
q51328
|
train
|
function(src, dest){
if(fs.existsSync(dest)){
this.waitForResponse(src, dest);
}else{
this.copy(src, dest);
this.triggerNext();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51329
|
train
|
function(src, dest){
self.logger.info('generating '+dest);
fs.createReadStream(src).pipe(fs.createWriteStream(dest));
}
|
javascript
|
{
"resource": ""
}
|
|
q51330
|
train
|
function(src, dest){
self.logger.warn('File at '+dest+' exists, overwrite?');
rl.question('(yN) ', function(answer){
switch(answer.toLowerCase()){
case 'y':
this.copy(src, dest);
this.triggerNext();
break;
case 'n':
this.triggerNext();
break;
default:
this.waitForResponse(src, dest);
break;
}
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q51331
|
train
|
function(){
var func;
if(typeof waterlock.config.authMethod[0] === 'object'){
func = this._handleObjects;
}else if(typeof waterlock.config.authMethod === 'object'){
func = this._handleObject;
}else{
func = this._handleName;
}
return func.apply(this, [waterlock.config.authMethod]);
}
|
javascript
|
{
"resource": ""
}
|
|
q51332
|
train
|
function(authMethods){
var _method = {};
var _methodName;
try{
_.each(authMethods, function(method){
_methodName = method.name;
method = _.merge(require('../../'+_methodName), method);
_method[method.authType] = method;
});
}catch(e){
this._errorHandler(_methodName);
}
return _method;
}
|
javascript
|
{
"resource": ""
}
|
|
q51333
|
train
|
function(authMethod){
var method = {};
var _methodName = authMethod.name;
try{
var _method = _.merge(require('../../'+_methodName), authMethod);
method[_method.authType] = _method;
}catch(e){
this._errorHandler(_methodName);
}
return method;
}
|
javascript
|
{
"resource": ""
}
|
|
q51334
|
train
|
function(thing) {
if (L.existy(thing) && L.existy(thing.snapshot))
return thing.snapshot();
else
fail("snapshot not currently implemented")
//return L.snapshot(thing);
}
|
javascript
|
{
"resource": ""
}
|
|
q51335
|
train
|
function(index) {
return function(array) {
if ((index < 0) || (index > array.length - 1)) L.fail("L.nth failure: attempting to index outside the bounds of the given array.");
return array[index];
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51336
|
notify
|
train
|
function notify(oldVal, newVal) {
var count = 0;
for (var key in watchers) {
var watcher = watchers[key];
watcher.call(this, key, oldVal, newVal);
count++;
}
return count;
}
|
javascript
|
{
"resource": ""
}
|
q51337
|
getGoogleCerts
|
train
|
function getGoogleCerts(kid, callback) {
request({uri: 'https://www.googleapis.com/oauth2/v1/certs'}, function(err, res, body) {
if (err || !res || res.statusCode != 200) {
err = err || new Error('error while retrieving Google certs');
callback(err);
} else {
try {
var keys = JSON.parse(body);
} catch (e) {
return callback(new Error('could not parse certs'));
}
callback(null, keys[kid]);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51338
|
getArtists
|
train
|
function getArtists(library) {
var ret = [];
for (var i = 0; i < library.length; i++) {
ret.push(cell('artist', i, library));
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q51339
|
get
|
train
|
function get(datastore, kind, namespace) {
return function(id, cb) {
var keyParam = [kind, id];
if (namespace) {
keyParam = {
namespace: namespace,
path: keyParam
};
}
var key = datastore.key(keyParam);
datastore.get(key, function(err, entity) {
if (err)
return cb(err);
return cb(null, entity ? entity : null);
});
};
}
|
javascript
|
{
"resource": ""
}
|
q51340
|
save
|
train
|
function save(datastore, kind, namespace) {
return function(data, cb) {
var keyParam = [kind, data.id];
if (namespace) {
keyParam = {
namespace: namespace,
path: keyParam
};
}
var key = datastore.key(keyParam);
datastore.save({key: key, data: data}, cb);
};
}
|
javascript
|
{
"resource": ""
}
|
q51341
|
all
|
train
|
function all(datastore, kind, namespace) {
return function(cb) {
var query = null;
if (namespace) {
query = datastore.createQuery(namespace, kind);
} else {
query = datastore.createQuery(kind);
}
datastore.runQuery(query, function(err, entities) {
if (err)
return cb(err);
var list = (entities || []).map(function(entity) {
return entity;
});
cb(null, list);
});
};
}
|
javascript
|
{
"resource": ""
}
|
q51342
|
hasToSkipWord
|
train
|
function hasToSkipWord(word) {
if(word.length < options.minLength) return false;
if(lodash.find(options.skipWordIfMatch, function (aPattern) {
return word.match(aPattern);
})){
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q51343
|
mergeOptions
|
train
|
function mergeOptions(pluginOptions) {
const defaultOptions = {
config: null,
debug: false,
css: {
file_types: ['.css', '.less', '.sass', '.scss'],
},
html: {
file_types: ['.html'],
},
js: {
file_types: ['.js', '.json'],
},
};
// Load 'file options'
const explorer = cosmiconfig('jsbeautify');
let explorerResult;
if (pluginOptions && pluginOptions.config) {
explorerResult = explorer.loadSync(path.resolve(pluginOptions.config));
} else {
explorerResult = explorer.searchSync();
}
let fileOptions;
if (explorerResult) {
fileOptions = explorerResult.config;
}
// Merge options
const finalOptions = mergeWith({}, defaultOptions, fileOptions, pluginOptions, (objValue, srcValue) => {
if (Array.isArray(objValue)) {
return objValue.concat(srcValue);
}
return undefined;
});
// Show debug messages
if (finalOptions.debug) {
if (fileOptions) {
log(`File options:\n${JSON.stringify(fileOptions, null, 2)}`);
}
log(`Final options:\n${JSON.stringify(finalOptions, null, 2)}`);
}
// Delete properties not used
delete finalOptions.config;
delete finalOptions.debug;
return finalOptions;
}
|
javascript
|
{
"resource": ""
}
|
q51344
|
helper
|
train
|
function helper(pluginOptions, doValidation) {
const options = mergeOptions(pluginOptions);
return through.obj((file, encoding, callback) => {
let oldContent;
let newContent;
let type = null;
if (file.isNull()) {
callback(null, file);
return;
}
if (file.isStream()) {
callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
// Check if current file should be treated as JavaScript, HTML, CSS or if it should be ignored
['js', 'css', 'html'].some((value) => {
// Check if at least one element in 'file_types' is suffix of file basename
if (options[value].file_types.some(suffix => path.basename(file.path).endsWith(suffix))) {
type = value;
return true;
}
return false;
});
// Initialize properties for reporter
file.jsbeautify = {};
file.jsbeautify.type = type;
file.jsbeautify.beautified = false;
file.jsbeautify.canBeautify = false;
if (type) {
oldContent = file.contents.toString('utf8');
newContent = beautify[type](oldContent, options);
if (oldContent.toString() !== newContent.toString()) {
if (doValidation) {
file.jsbeautify.canBeautify = true;
} else {
file.contents = Buffer.from(newContent);
file.jsbeautify.beautified = true;
}
}
}
callback(null, file);
});
}
|
javascript
|
{
"resource": ""
}
|
q51345
|
flow
|
train
|
function flow(...args) {
const fns = flatten(args)
.filter(fn => isFunction(fn))
.map(fn => fn.applier === undefined ? (
([obj, appliedPaths]) => [fn(obj), appliedPaths]
) : (
([obj, appliedPaths]) => [
fn.applier(obj, appliedPaths),
[...appliedPaths, fn.applier.path],
]
))
return obj => {
const [result] = fns.reduce(
(acc, fn) => fn(acc),
[obj, []],
)
return result
}
}
|
javascript
|
{
"resource": ""
}
|
q51346
|
checkDecorator
|
train
|
function checkDecorator(decorator, value, node) {
const decoratorLine = decorator.loc.start.line;
const decoratorColumn = decorator.loc.end.column;
const valueLine = value.loc.start.line;
if (config === 'always') {
if (decoratorLine === valueLine) {
context.report({
node,
loc: { line: decoratorLine, column: decoratorColumn },
message: ALWAYS_MESSAGE,
});
}
} else {
if (decoratorLine !== valueLine) { // eslint-disable-line
context.report({
node,
loc: { line: decoratorLine, column: decoratorColumn },
message: NEVER_MESSAGE,
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51347
|
getFirstBlockToken
|
train
|
function getFirstBlockToken(token) {
let prev;
let first = token;
do {
prev = first;
first = sourceCode.getTokenAfter(first, { includeComments: true });
} while (isComment(first) && first.loc.start.line === prev.loc.end.line);
return first;
}
|
javascript
|
{
"resource": ""
}
|
q51348
|
getLastBlockToken
|
train
|
function getLastBlockToken(token) {
let last = token;
let next;
do {
next = last;
last = sourceCode.getTokenBefore(last, { includeComments: true });
} while (isComment(last) && last.loc.end.line === next.loc.start.line);
return last;
}
|
javascript
|
{
"resource": ""
}
|
q51349
|
requirePaddingFor
|
train
|
function requirePaddingFor(node) {
switch (node.type) {
case 'BlockStatement':
return options.blocks;
case 'SwitchStatement':
return options.switches;
case 'ClassBody':
return options.classes;
/* istanbul ignore next */
default:
throw new Error('unreachable');
}
}
|
javascript
|
{
"resource": ""
}
|
q51350
|
checkPadding
|
train
|
function checkPadding(node, type) {
const openBrace = getOpenBrace(node);
const firstBlockToken = getFirstBlockToken(openBrace);
const tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true });
const closeBrace = sourceCode.getLastToken(node);
const lastBlockToken = getLastBlockToken(closeBrace);
const tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true });
const blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken);
const blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast);
const onlyTopPadding = context.options[0][type] === 'top';
const onlyBottomPadding = context.options[0][type] === 'bottom';
if (requirePaddingFor(node)) {
if (!blockHasTopPadding && !onlyBottomPadding) {
context.report({
node,
loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
fix(fixer) {
return fixer.insertTextAfter(tokenBeforeFirst, '\n');
},
message: ALWAYS_MESSAGE,
});
}
if (!blockHasBottomPadding && !onlyTopPadding) {
context.report({
node,
loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
fix(fixer) {
return fixer.insertTextBefore(tokenAfterLast, '\n');
},
message: ALWAYS_MESSAGE,
});
}
} else {
if (blockHasTopPadding && !onlyBottomPadding) {
context.report({
node,
loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
fix(fixer) {
return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], '\n');
},
message: NEVER_MESSAGE,
});
}
if (blockHasBottomPadding && !onlyTopPadding) {
context.report({
node,
loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
fix(fixer) {
return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], '\n');
},
message: NEVER_MESSAGE,
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51351
|
train
|
function(element) {
if (element === elt) {
var wrapper = svgCanvas.getElement();
wrapper.parentNode.removeChild(wrapper);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51352
|
CliGraph
|
train
|
function CliGraph(options) {
// Initialize variables
var self = this
, settings = self.options = Ul.deepMerge(options, CliGraph.defaults)
, i = 0
, character = null
, str = ""
;
self.graph = [];
settings.width *= settings.aRatio;
// Set the center of the graph
settings.center = Ul.merge(settings.center, {
x: settings.width / 2
, y: settings.height / 2
});
settings.center.x = Math.round(settings.center.x);
settings.center.y = Math.round(settings.center.y);
// Background
for (i = 0; i < settings.height; ++i) {
self.graph[i] = new Array(settings.width).join(settings.marks.background).split("");
}
// Center
self.graph[settings.center.y][settings.center.x] = settings.marks.center;
// Ox axis
for (i = 0; i < settings.width; ++i) {
character = settings.marks.hAxis;
if (i === settings.center.x) {
character = settings.marks.center;
} else if (i === settings.width - 1) {
character = settings.marks.rightArrow;
}
self.graph[settings.center.y][i] = character;
}
// Oy asis
for (i = 0; i < settings.height; ++i) {
character = settings.marks.vAxis;
if (i === settings.center.y) {
character = settings.marks.center;
} else if (i === 0) {
character = settings.marks.topArrow;
}
self.graph[i][settings.center.x] = character;
}
}
|
javascript
|
{
"resource": ""
}
|
q51353
|
Subscription
|
train
|
function Subscription(name, topic) {
this._pattern = "%s://%s.mns.%s.aliyuncs.com/topics/%s/subscriptions/%s";
this._name = name;
this._topic = topic;
// make url
this._urlAttr = this.makeAttrURL();
// create the OpenStack object
this._openStack = new AliMNS.OpenStack(topic.getAccount());
}
|
javascript
|
{
"resource": ""
}
|
q51354
|
filter
|
train
|
function filter(data, action, format) {
return walk(data, action, format, data.meta || data[0].unMeta);
}
|
javascript
|
{
"resource": ""
}
|
q51355
|
walk
|
train
|
function walk(x, action, format, meta) {
if (Array.isArray(x)) {
var array = [];
x.forEach(function (item) {
if (item === Object(item) && item.t) {
var res = action(item.t, item.c || [], format, meta)
if (!res) {
array.push(walk(item, action, format, meta));
}
else if (Array.isArray(res)) {
res.forEach(function (z) {
array.push(walk(z, action, format, meta));
});
}
else {
array.push(walk(res, action, format, meta));
}
}
else {
array.push(walk(item, action, format, meta));
}
});
return array;
}
else if (x === Object(x)) {
var obj = {};
Object.keys(x).forEach(function (k) {
obj[k] = walk(x[k], action, format, meta);
});
return obj;
}
return x;
}
|
javascript
|
{
"resource": ""
}
|
q51356
|
stringify
|
train
|
function stringify(x) {
if (x === Object(x) && x.t === 'MetaString') return x.c;
var result = [];
var go = function (key, val) {
if (key === 'Str') result.push(val);
else if (key === 'Code') result.push(val[1]);
else if (key === 'Math') result.push(val[1]);
else if (key === 'LineBreak') result.push(' ');
else if (key === 'Space') result.push(' ');
};
walk(x, go, '', {});
return result.join('');
}
|
javascript
|
{
"resource": ""
}
|
q51357
|
attributes
|
train
|
function attributes(attrs) {
attrs = attrs || {};
var ident = attrs.id || '';
var classes = attrs.classes || [];
var keyvals = [];
Object.keys(attrs).forEach(function (k) {
if (k !== 'classes' && k !== 'id') keyvals.push([k,attrs[k]]);
});
return [ident, classes, keyvals];
}
|
javascript
|
{
"resource": ""
}
|
q51358
|
elt
|
train
|
function elt(eltType, numargs) {
return function () {
var args = Array.prototype.slice.call(arguments);
var len = args.length;
if (len !== numargs)
throw eltType + ' expects ' + numargs + ' arguments, but given ' + len;
return {'t':eltType,'c':(len === 1 ? args[0] : args)};
};
}
|
javascript
|
{
"resource": ""
}
|
q51359
|
postForm
|
train
|
function postForm(url, formData, cb, multipart) {
cb = cb || noop;
botkit.debug('** API CALL: ' + url);
if (Array.isArray(api.logByKey[url])) {
api.logByKey[url].push(formData);
} else {
api.logByKey[url] = [formData];
}
storage.process(url, formData, cb);
}
|
javascript
|
{
"resource": ""
}
|
q51360
|
generateTaskList
|
train
|
function generateTaskList (user) {
var text = '';
for (var t = 0; t < user.tasks.length; t++) {
text = text + '> `' + (t + 1) + '`) ' + user.tasks[t] + '\n';
}
return text;
}
|
javascript
|
{
"resource": ""
}
|
q51361
|
skipNewline
|
train
|
function skipNewline(text, index, opts) {
const backwards = opts && opts.backwards;
if (index === false) {
return false;
}
const atIndex = text.charAt(index);
if (backwards) {
if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
return index - 2;
}
if (
atIndex === "\n" ||
atIndex === "\r" ||
atIndex === "\u2028" ||
atIndex === "\u2029"
) {
return index - 1;
}
} else {
if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
return index + 2;
}
if (
atIndex === "\n" ||
atIndex === "\r" ||
atIndex === "\u2028" ||
atIndex === "\u2029"
) {
return index + 1;
}
}
return index;
}
|
javascript
|
{
"resource": ""
}
|
q51362
|
normalize
|
train
|
function normalize(options, opts) {
opts = opts || {};
const rawOptions = Object.assign({}, options);
const supportOptions = getSupportInfo(null, {
plugins: options.plugins,
showUnreleased: true,
showDeprecated: true
}).options;
const defaults = supportOptions.reduce(
(reduced, optionInfo) =>
optionInfo.default !== undefined
? Object.assign(reduced, { [optionInfo.name]: optionInfo.default })
: reduced,
Object.assign({}, hiddenDefaults)
);
if (!rawOptions.parser) {
if (!rawOptions.filepath) {
const logger = opts.logger || console;
logger.warn(
"No parser and no filepath given, using 'babel' the parser now " +
"but this will throw an error in the future. " +
"Please specify a parser or a filepath so one can be inferred."
);
rawOptions.parser = "babel";
} else {
rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
if (!rawOptions.parser) {
throw new UndefinedParserError(
`No parser could be inferred for file: ${rawOptions.filepath}`
);
}
}
}
const parser = resolveParser(
normalizer.normalizeApiOptions(
rawOptions,
[supportOptions.find(x => x.name === "parser")],
{ passThrough: true, logger: false }
)
);
rawOptions.astFormat = parser.astFormat;
rawOptions.locEnd = parser.locEnd;
rawOptions.locStart = parser.locStart;
const plugin = getPlugin(rawOptions);
rawOptions.printer = plugin.printers[rawOptions.astFormat];
const pluginDefaults = supportOptions
.filter(
optionInfo =>
optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name]
)
.reduce(
(reduced, optionInfo) =>
Object.assign(reduced, {
[optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
}),
{}
);
const mixedDefaults = Object.assign({}, defaults, pluginDefaults);
Object.keys(mixedDefaults).forEach(k => {
if (rawOptions[k] == null) {
rawOptions[k] = mixedDefaults[k];
}
});
if (rawOptions.parser === "json") {
rawOptions.trailingComma = "none";
}
return normalizer.normalizeApiOptions(
rawOptions,
supportOptions,
Object.assign({ passThrough: Object.keys(hiddenDefaults) }, opts)
);
}
|
javascript
|
{
"resource": ""
}
|
q51363
|
hasNgSideEffect
|
train
|
function hasNgSideEffect(path) {
return hasNode(path.getValue(), node => {
switch (node.type) {
case undefined:
return false;
case "CallExpression":
case "OptionalCallExpression":
case "AssignmentExpression":
return true;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51364
|
isMeaningfulJSXText
|
train
|
function isMeaningfulJSXText(node) {
return (
isLiteral(node) &&
(containsNonJsxWhitespaceRegex.test(rawText(node)) ||
!/\n/.test(rawText(node)))
);
}
|
javascript
|
{
"resource": ""
}
|
q51365
|
splitText
|
train
|
function splitText(text, options) {
const KIND_NON_CJK = "non-cjk";
const KIND_CJ_LETTER = "cj-letter";
const KIND_K_LETTER = "k-letter";
const KIND_CJK_PUNCTUATION = "cjk-punctuation";
const nodes = [];
(options.proseWrap === "preserve"
? text
: text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")
)
.split(/([ \t\n]+)/)
.forEach((token, index, tokens) => {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
return;
}
// word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
return;
}
token
.split(new RegExp(`(${cjkPattern})`))
.forEach((innerToken, innerIndex, innerTokens) => {
if (
(innerIndex === 0 || innerIndex === innerTokens.length - 1) &&
innerToken === ""
) {
return;
}
// non-CJK word
if (innerIndex % 2 === 0) {
if (innerToken !== "") {
appendNode({
type: "word",
value: innerToken,
kind: KIND_NON_CJK,
hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
hasTrailingPunctuation: punctuationRegex.test(
getLast(innerToken)
)
});
}
return;
}
// CJK character
appendNode(
punctuationRegex.test(innerToken)
? {
type: "word",
value: innerToken,
kind: KIND_CJK_PUNCTUATION,
hasLeadingPunctuation: true,
hasTrailingPunctuation: true
}
: {
type: "word",
value: innerToken,
kind: kRegex.test(innerToken)
? KIND_K_LETTER
: KIND_CJ_LETTER,
hasLeadingPunctuation: false,
hasTrailingPunctuation: false
}
);
});
});
return nodes;
function appendNode(node) {
const lastNode = getLast(nodes);
if (lastNode && lastNode.type === "word") {
if (
(lastNode.kind === KIND_NON_CJK &&
node.kind === KIND_CJ_LETTER &&
!lastNode.hasTrailingPunctuation) ||
(lastNode.kind === KIND_CJ_LETTER &&
node.kind === KIND_NON_CJK &&
!node.hasLeadingPunctuation)
) {
nodes.push({ type: "whitespace", value: " " });
} else if (
!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) &&
// disallow leading/trailing full-width whitespace
![lastNode.value, node.value].some(value => /\u3000/.test(value))
) {
nodes.push({ type: "whitespace", value: "" });
}
}
nodes.push(node);
function isBetween(kind1, kind2) {
return (
(lastNode.kind === kind1 && node.kind === kind2) ||
(lastNode.kind === kind2 && node.kind === kind1)
);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51366
|
extractWhitespaces
|
train
|
function extractWhitespaces(ast /*, options*/) {
const TYPE_WHITESPACE = "whitespace";
return ast.map(node => {
if (!node.children) {
return node;
}
if (
node.children.length === 0 ||
(node.children.length === 1 &&
node.children[0].type === "text" &&
node.children[0].value.trim().length === 0)
) {
return node.clone({
children: [],
hasDanglingSpaces: node.children.length !== 0
});
}
const isWhitespaceSensitive = isWhitespaceSensitiveNode(node);
const isIndentationSensitive = isIndentationSensitiveNode(node);
return node.clone({
isWhitespaceSensitive,
isIndentationSensitive,
children: node.children
// extract whitespace nodes
.reduce((newChildren, child) => {
if (child.type !== "text" || isWhitespaceSensitive) {
return newChildren.concat(child);
}
const localChildren = [];
const [, leadingSpaces, text, trailingSpaces] = child.value.match(
/^(\s*)([\s\S]*?)(\s*)$/
);
if (leadingSpaces) {
localChildren.push({ type: TYPE_WHITESPACE });
}
const ParseSourceSpan = child.sourceSpan.constructor;
if (text) {
localChildren.push({
type: "text",
value: text,
sourceSpan: new ParseSourceSpan(
child.sourceSpan.start.moveBy(leadingSpaces.length),
child.sourceSpan.end.moveBy(-trailingSpaces.length)
)
});
}
if (trailingSpaces) {
localChildren.push({ type: TYPE_WHITESPACE });
}
return newChildren.concat(localChildren);
}, [])
// set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
.reduce((newChildren, child, i, children) => {
if (child.type === TYPE_WHITESPACE) {
return newChildren;
}
const hasLeadingSpaces =
i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
const hasTrailingSpaces =
i !== children.length - 1 &&
children[i + 1].type === TYPE_WHITESPACE;
return newChildren.concat(
Object.assign({}, child, {
hasLeadingSpaces,
hasTrailingSpaces
})
);
}, [])
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51367
|
addIsSpaceSensitive
|
train
|
function addIsSpaceSensitive(ast /*, options */) {
return ast.map(node => {
if (!node.children) {
return node;
}
if (node.children.length === 0) {
return node.clone({
isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode(node)
});
}
return node.clone({
children: node.children
.map(child => {
return Object.assign({}, child, {
isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(child),
isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(child)
});
})
.map((child, index, children) =>
Object.assign({}, child, {
isLeadingSpaceSensitive:
index === 0
? child.isLeadingSpaceSensitive
: children[index - 1].isTrailingSpaceSensitive &&
child.isLeadingSpaceSensitive,
isTrailingSpaceSensitive:
index === children.length - 1
? child.isTrailingSpaceSensitive
: children[index + 1].isLeadingSpaceSensitive &&
child.isTrailingSpaceSensitive
})
)
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51368
|
forceBreakContent
|
train
|
function forceBreakContent(node) {
return (
forceBreakChildren(node) ||
(node.type === "element" &&
node.children.length !== 0 &&
(["body", "template", "script", "style"].indexOf(node.name) !== -1 ||
node.children.some(child => hasNonTextChild(child)))) ||
(node.firstChild &&
node.firstChild === node.lastChild &&
(hasLeadingLineBreak(node.firstChild) &&
(!node.lastChild.isTrailingSpaceSensitive ||
hasTrailingLineBreak(node.lastChild))))
);
}
|
javascript
|
{
"resource": ""
}
|
q51369
|
forceBreakChildren
|
train
|
function forceBreakChildren(node) {
return (
node.type === "element" &&
node.children.length !== 0 &&
(["html", "head", "ul", "ol", "select"].indexOf(node.name) !== -1 ||
(node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell"))
);
}
|
javascript
|
{
"resource": ""
}
|
q51370
|
replacePlaceholders
|
train
|
function replacePlaceholders(quasisDoc, expressionDocs) {
if (!expressionDocs || !expressionDocs.length) {
return quasisDoc;
}
const expressions = expressionDocs.slice();
let replaceCounter = 0;
const newDoc = mapDoc(quasisDoc, doc => {
if (!doc || !doc.parts || !doc.parts.length) {
return doc;
}
let parts = doc.parts;
const atIndex = parts.indexOf("@");
const placeholderIndex = atIndex + 1;
if (
atIndex > -1 &&
typeof parts[placeholderIndex] === "string" &&
parts[placeholderIndex].startsWith("prettier-placeholder")
) {
// If placeholder is split, join it
const at = parts[atIndex];
const placeholder = parts[placeholderIndex];
const rest = parts.slice(placeholderIndex + 1);
parts = parts
.slice(0, atIndex)
.concat([at + placeholder])
.concat(rest);
}
const atPlaceholderIndex = parts.findIndex(
part =>
typeof part === "string" && part.startsWith("@prettier-placeholder")
);
if (atPlaceholderIndex > -1) {
const placeholder = parts[atPlaceholderIndex];
const rest = parts.slice(atPlaceholderIndex + 1);
const placeholderMatch = placeholder.match(
/@prettier-placeholder-(.+)-id([\s\S]*)/
);
const placeholderID = placeholderMatch[1];
// When the expression has a suffix appended, like:
// animation: linear ${time}s ease-out;
const suffix = placeholderMatch[2];
const expression = expressions[placeholderID];
replaceCounter++;
parts = parts
.slice(0, atPlaceholderIndex)
.concat(["${", expression, "}" + suffix])
.concat(rest);
}
return Object.assign({}, doc, {
parts: parts
});
});
return expressions.length === replaceCounter ? newDoc : null;
}
|
javascript
|
{
"resource": ""
}
|
q51371
|
isStyledComponents
|
train
|
function isStyledComponents(path) {
const parent = path.getParentNode();
if (!parent || parent.type !== "TaggedTemplateExpression") {
return false;
}
const tag = parent.tag;
switch (tag.type) {
case "MemberExpression":
return (
// styled.foo``
isStyledIdentifier(tag.object) ||
// Component.extend``
isStyledExtend(tag)
);
case "CallExpression":
return (
// styled(Component)``
isStyledIdentifier(tag.callee) ||
(tag.callee.type === "MemberExpression" &&
((tag.callee.object.type === "MemberExpression" &&
// styled.foo.attr({})``
(isStyledIdentifier(tag.callee.object.object) ||
// Component.extend.attr({)``
isStyledExtend(tag.callee.object))) ||
// styled(Component).attr({})``
(tag.callee.object.type === "CallExpression" &&
isStyledIdentifier(tag.callee.object.callee))))
);
case "Identifier":
// css``
return tag.name === "css";
default:
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q51372
|
isCssProp
|
train
|
function isCssProp(path) {
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
return (
parentParent &&
parent.type === "JSXExpressionContainer" &&
parentParent.type === "JSXAttribute" &&
parentParent.name.type === "JSXIdentifier" &&
parentParent.name.name === "css"
);
}
|
javascript
|
{
"resource": ""
}
|
q51373
|
isHtml
|
train
|
function isHtml(path) {
const node = path.getValue();
return (
hasLanguageComment(node, "HTML") ||
isPathMatch(path, [
node => node.type === "TemplateLiteral",
(node, name) =>
node.type === "TaggedTemplateExpression" &&
node.tag.type === "Identifier" &&
node.tag.name === "html" &&
name === "quasi"
])
);
}
|
javascript
|
{
"resource": ""
}
|
q51374
|
checkSchema
|
train
|
async function checkSchema() {
const schema = await execa.stdout("node", ["scripts/generate-schema.js"]);
const remoteSchema = await logPromise(
"Checking current schema in SchemaStore",
fetch(RAW_URL)
.then(r => r.text())
.then(t => t.trim())
);
if (schema === remoteSchema) {
return;
}
return dedent(chalk`
{bold.underline The schema in {yellow SchemaStore} needs an update.}
- Open {cyan.underline ${EDIT_URL}}
- Run {yellow node scripts/generate-schema.js} and copy the new schema
- Paste it on GitHub interface
- Open a PR
`);
}
|
javascript
|
{
"resource": ""
}
|
q51375
|
installAll
|
train
|
function installAll(deps) {
npm.commands.install(dir, deps, function (err) {
if (err) {
return callback(err);
}
haibu.emit('npm:install:success', 'info', meta);
callback(null, deps);
});
}
|
javascript
|
{
"resource": ""
}
|
q51376
|
loadAndInstall
|
train
|
function loadAndInstall() {
meta = { packages: target };
exports.load(function (err) {
if (err) {
return callback(err);
}
installAll(target);
});
}
|
javascript
|
{
"resource": ""
}
|
q51377
|
onError
|
train
|
function onError(err) {
err.usage = 'tar -cvz . | curl -sSNT- HOST/deploy/USER/APP';
err.blame = {
type: 'system',
message: 'Unable to unpack tarball'
};
return callback(err);
}
|
javascript
|
{
"resource": ""
}
|
q51378
|
onStdout
|
train
|
function onStdout (data) {
data = data.toString();
haibu.emit('drone:stdout', 'info', data, meta);
if (!responded) {
stdout = stdout.concat(data.split('\n').filter(function (line) { return line.length > 0 }));
}
}
|
javascript
|
{
"resource": ""
}
|
q51379
|
onStderr
|
train
|
function onStderr (data) {
data = data.toString();
haibu.emit('drone:stderr', 'error', data, meta);
if (!responded) {
stderr = stderr.concat(data.split('\n').filter(function (line) { return line.length > 0 }));
}
}
|
javascript
|
{
"resource": ""
}
|
q51380
|
onCarapacePort
|
train
|
function onCarapacePort (info) {
if (!responded && info && info.event === 'port') {
responded = true;
result.socket = {
host: self.host,
port: info.data.port
};
drone.minUptime = 0;
haibu.emit('drone:port', 'info', {
pkg: app,
info: info
});
callback(null, result);
//
// Remove listeners to related events
//
drone.removeListener('exit', onExit);
drone.removeListener('error', onError);
clearTimeout(timeout);
}
}
|
javascript
|
{
"resource": ""
}
|
q51381
|
onChildStart
|
train
|
function onChildStart (monitor, data) {
result = {
monitor: monitor,
process: monitor.child,
data: data,
pid: monitor.childData.pid,
pkg: app
};
haibu.emit(['drone', 'start'], 'info', {
process: data,
pkg: result.pkg
});
}
|
javascript
|
{
"resource": ""
}
|
q51382
|
onChildRestart
|
train
|
function onChildRestart (monitor, data) {
haibu.emit(['drone', 'stop'], 'info', {
process: result.data,
pkg: result.pkg
});
haibu.emit(['drone', 'start'], 'info', {
process: data,
pkg: result.pkg
});
}
|
javascript
|
{
"resource": ""
}
|
q51383
|
onExit
|
train
|
function onExit () {
if (!responded) {
errState = true;
responded = true;
error = new Error('Error spawning drone');
error.blame = {
type: 'user',
message: 'Script prematurely exited'
}
error.stdout = stdout.join('\n');
error.stderr = stderr.join('\n');
callback(error);
//
// Remove listeners to related events.
//
drone.removeListener('error', onError);
drone.removeListener('message', onCarapacePort);
clearTimeout(timeout);
}
}
|
javascript
|
{
"resource": ""
}
|
q51384
|
startDrones
|
train
|
function startDrones (pkg, done) {
if (pkg.drones == 0) {
return done();
}
var started = 0;
async.whilst(function () {
return started < pkg.drones;
}, function (next) {
started++;
server.drone.start(pkg, next);
}, done);
}
|
javascript
|
{
"resource": ""
}
|
q51385
|
asyncstorage
|
train
|
async function asyncstorage(namespace) {
var debug, diagnostics;
try {
debug = await storage.getItem('debug');
diagnostics = await storage.getItem('diagnostics');
} catch (e) {
/* Nope, nothing. */
}
return enabled(namespace, debug || diagnostics || '');
}
|
javascript
|
{
"resource": ""
}
|
q51386
|
use
|
train
|
function use(adapter) {
if (~adapters.indexOf(adapter)) return false;
adapters.push(adapter);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q51387
|
enabled
|
train
|
function enabled(namespace) {
var async = [];
for (var i = 0; i < adapters.length; i++) {
if (adapters[i].async) {
async.push(adapters[i]);
continue;
}
if (adapters[i](namespace)) return true;
}
if (!async.length) return false;
//
// Now that we know that we Async functions, we know we run in an ES6
// environment and can use all the API's that they offer, in this case
// we want to return a Promise so that we can `await` in React-Native
// for an async adapter.
//
return new Promise(function pinky(resolve) {
Promise.all(
async.map(function prebind(fn) {
return fn(namespace);
})
).then(function resolved(values) {
resolve(values.some(Boolean));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51388
|
modify
|
train
|
function modify(fn) {
if (~modifiers.indexOf(fn)) return false;
modifiers.push(fn);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q51389
|
process
|
train
|
function process(message) {
for (var i = 0; i < modifiers.length; i++) {
message = modifiers[i].apply(modifiers[i], arguments);
}
return message;
}
|
javascript
|
{
"resource": ""
}
|
q51390
|
introduce
|
train
|
function introduce(fn, options) {
var has = Object.prototype.hasOwnProperty;
for (var key in options) {
if (has.call(options, key)) {
fn[key] = options[key];
}
}
return fn;
}
|
javascript
|
{
"resource": ""
}
|
q51391
|
nope
|
train
|
function nope(options) {
options.enabled = false;
options.modify = modify;
options.set = set;
options.use = use;
return introduce(function diagnopes() {
return false;
}, options);
}
|
javascript
|
{
"resource": ""
}
|
q51392
|
yep
|
train
|
function yep(options) {
/**
* The function that receives the actual debug information.
*
* @returns {Boolean} indication that we're logging.
* @public
*/
function diagnostics() {
var args = Array.prototype.slice.call(arguments, 0);
write.call(write, options, process(args, options));
return true;
}
options.enabled = true;
options.modify = modify;
options.set = set;
options.use = use;
return introduce(diagnostics, options);
}
|
javascript
|
{
"resource": ""
}
|
q51393
|
diagnostics
|
train
|
function diagnostics() {
var args = Array.prototype.slice.call(arguments, 0);
write.call(write, options, process(args, options));
return true;
}
|
javascript
|
{
"resource": ""
}
|
q51394
|
train
|
function(fn) {
return function() {
var realArgs = [];
var fnArgs = arguments;
each(fnArgs, function(val, i) {
if (i <= fnArgs.length) {
while (val && val.isComputed) {
val = val();
}
realArgs.push(val);
}
});
return fn.apply(this, realArgs);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51395
|
train
|
function () {
var old = view.lists,
data;
view.lists = function (list, renderer) {
data = {
list: list,
renderer: renderer
};
return Math.random();
};
// sets back to the old data
return function () {
view.lists = old;
return data;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51396
|
train
|
function(dirname, keydir, dataFile, cb1) {
var fileId = Number(path.basename(dataFile, '.medea.data'));
var file = new DataFileParser({ filename: dataFile });
file.on('error', cb1);
file.on('entry', function(entry) {
var key = entry.key.toString();
if (key.length === 0) {
return;
}
if (!keydir.has(key) || (keydir.has(key) && keydir.get(key).fileId === fileId)) {
var kEntry = new KeyDirEntry();
kEntry.key = key;
kEntry.fileId = fileId;
kEntry.timestamp = entry.timestamp;
kEntry.valueSize = entry.valueSize;
kEntry.valuePosition = entry.valuePosition;
keydir.set(key, kEntry);
}
});
file.on('end', cb1);
file.parse();
}
|
javascript
|
{
"resource": ""
}
|
|
q51397
|
PartiallyAppliedMessage
|
train
|
function PartiallyAppliedMessage(underlyingMessage, payload) {
function message(...otherPayloads) {
return underlyingMessage.apply(null, [payload, ...otherPayloads])
}
message.type = 'partiallyAppliedMessage'
message._id = underlyingMessage._id
message._name = underlyingMessage._name
message._isMessage = true
message.with = withPayload
// Used for VDOM Diffing (See util/shallowEqual)
message.payload = payload
return message
}
|
javascript
|
{
"resource": ""
}
|
q51398
|
postpatch
|
train
|
function postpatch(oldVnode, vnode) {
const oldData = oldVnode.data
const newData = vnode.data
// Server side rendering: Reconcilating with a server-rendered node will have skipped calling insert()
if (!oldData.component) {
insert(vnode)
}
// oldData wouldn't have a component reference set if it came from the server (it's first set in insert())
const component = oldData.component || newData.component
const oldProps = component.props
const newProps = newData.component.props
// Update the original component with any property that may have changed during this render pass
component.props = newProps
newData.component = component
// If the props changed, render immediately as we are already
// in the render context of our parent
if (!shallowEqual(oldProps, newProps)) {
component.lifecycle.propsChanging = true
component.lifecycle.propsChanged(newProps)
component.lifecycle.propsChanging = false
renderComponentNow(component)
}
}
|
javascript
|
{
"resource": ""
}
|
q51399
|
createHeaders
|
train
|
function createHeaders(options) {
const opts = Object.assign({}, options);
const headers = Object.assign({}, defaultHeaders, lowercaseKeys(opts.headers || {}));
if (!opts.bearer && !opts.token && !opts.username && !opts.password) {
return headers;
}
if (opts.token) {
headers['authorization'] = 'token ' + opts.token;
return headers;
}
if (opts.bearer) {
headers['authorization'] = 'Bearer ' + opts.bearer;
return headers;
}
const creds = opts.username + ':' + opts.password;
headers['authorization'] = 'Basic ' + toBase64(creds);
return headers;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.