_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3200
|
getMessagingConfig
|
train
|
function getMessagingConfig() {
return {
host: process.env.FH_MESSAGING_HOST || '',
cluster: process.env.FH_MESSAGING_CLUSTER || '',
realTimeLoggingEnabled: isRealtimeLoggingEnabled(),
mbaasType: mbaasType(),
decoupled: process.env.FH_MBAAS_DECOUPLED || false,
msgServer: {
logMessageURL: getLogMessageURL()
},
backupFiles: {
fileName: process.env.FH_MESSAGING_BACKUP_FILE || ''
},
recoveryFiles:{
fileName: process.env.FH_MESSAGING_RECOVERY_FILE || ''
}
};
}
|
javascript
|
{
"resource": ""
}
|
q3201
|
getLogMessageURL
|
train
|
function getLogMessageURL() {
var url = '';
if (process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP) {
url = 'http://' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP + ':' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_PORT;
url += '/sys/admin/reports/TOPIC';
} else {
url = process.env.FH_MESSAGING_SERVER || ''; // Default setting
}
return url;
}
|
javascript
|
{
"resource": ""
}
|
q3202
|
isRealtimeLoggingEnabled
|
train
|
function isRealtimeLoggingEnabled() {
var flag = process.env.FH_MESSAGING_REALTIME_ENABLED;
if (flag && (flag === 'true' || flag === true) ) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q3203
|
getMetadata
|
train
|
function getMetadata (dir) {
var json = path.join(dir, 'meta.json')
var js = path.join(dir, 'meta.js')
var opts = {}
if (exists(json)) {
opts = metadata.sync(json)
} else if (exists(js)) {
var req = require(path.resolve(js))
if (req !== Object(req)) {
throw new Error('meta.js needs to expose an object')
}
opts = req
}
return opts
}
|
javascript
|
{
"resource": ""
}
|
q3204
|
PopulateDecorator
|
train
|
function PopulateDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
populate: joi.func().required(),
timeoutPopulateIn: joi.number().integer().default(1000 * 30),
leaseExpiresIn: joi.number().integer()
}));
this._store = this._getStore();
this._lease = this._store.createLease(
this._config.leaseExpiresIn || this._config.timeoutPopulateIn + 1000);
this.on('get:stale', this._onStaleEvent.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q3205
|
logRequest
|
train
|
function logRequest(err, res) {
if (res) {
let ms = new Date() - res.requestStartTime;
var time = ms < 1000 ? `${ms}ms` : `${(ms/1000).toFixed(2)}s`;
logRoute(`${res.req.method} ${res.statusCode} (${time}): ${res.req.originalUrl}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q3206
|
train
|
function() {
self.isWin32 = ( os.platform() == 'win32' ) ? true : false;
self.path = _( __dirname.substring(0, (__dirname.length - "script".length)-1 ) );
self.root = process.cwd().toString();
createVersionFile();
//console.log('[ debug ] createVersionFile()');
createGinaFileForPlatform();
//console.log('[ debug ] createGinaFileForPlatform()');
}
|
javascript
|
{
"resource": ""
}
|
|
q3207
|
train
|
function(win32Name, callback) {
var name = require( _(self.path + '/package.json') ).name;
var appPath = _( self.path.substring(0, (self.path.length - ("node_modules/" + name + '/').length)) );
var source = _(self.path + '/core/template/command/gina.tpl');
var target = _(appPath +'/'+ name);
if ( typeof(win32Name) != 'undefined') {
target = _(appPath +'/'+ win32Name)
}
//Will override.
if ( typeof(callback) != 'undefined') {
try {
utils.generator.createFileFromTemplateSync(source, target);
setTimeout(function () {
callback(false)
}, 1000)
} catch (err) {
callback(err)
}
} else {
utils.generator.createFileFromTemplateSync(source, target)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3208
|
train
|
function(callback) {
try {
var controller = require(path);
callback(null, controller);
} catch (e) {
return callback(e);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3209
|
train
|
function(controller, callback) {
// Allow configure-method less controllers
if ('function' !== typeof controller.configure) {
return callback(null, controller);
}
controller.configure(
self.worker.app,
self.worker.server,
function(err) {
callback(err, controller);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3210
|
train
|
function(controller, callback) {
// Add the given name to the controller
controller.name = name;
controller.module = module;
// Set default value on the controller instance
controller.basePath = self.getBasePath(
controller, path, module
);
// Add the canonical path
controller.canonicalPath = self.getCanonicalPath(
path, name, module
);
callback(null, controller);
}
|
javascript
|
{
"resource": ""
}
|
|
q3211
|
train
|
function(controller, callback) {
self.prepareControllerActions(controller, function(err, actions) {
callback(err, controller, actions);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3212
|
train
|
function(controller, actions, callback) {
self.worker.context.routes = self.worker.context.routes.concat(
actions
);
callback(null, controller);
}
|
javascript
|
{
"resource": ""
}
|
|
q3213
|
train
|
function(callback) {
async.map(modules, function(module, callback) {
callback && callback(
null,
{
name: module,
path: process.cwd() + '/modules/' +
module + '/controllers/'
}
);
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q3214
|
train
|
function(map, callback) {
async.filter(map, function(module, callback) {
fs.exists(module.path, callback);
}, function(map) {
callback(null, map);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3215
|
train
|
function(map, callback) {
// Walk through all modules in parallel
async.map(map, function(module, callback) {
// Filter all non-js files in parallel
async.filter(
pathHelper.list(module.path),
function(path, callback) {
callback(path.match(/\.js$/i));
}, function(paths) {
module.paths = paths;
callback(null, module);
});
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q3216
|
train
|
function(map, callback) {
// Walk through all modules in parallel
async.map(map, function(module, callback) {
logger.info('Loading ' + (module.name).blue + ' module');
// Walk through all possible controllers of the module
async.map(module.paths, function(path, callback) {
self.loadController(
path,
basename(path.replace(/\.js$/g, '')),
module.name,
callback
);
}, function(err, controllers) {
module.controllers = controllers;
callback(err, module);
});
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q3217
|
getText
|
train
|
function getText(locale, ...args) {
const key = args[0];
if (!key) return null;
// try locale
let resource = ebLocales[locale] || {};
let text = resource[key];
if (text === undefined && locale !== 'en-us') {
// try en-us
resource = ebLocales['en-us'] || {};
text = resource[key];
}
// equal key
if (text === undefined) {
text = key;
}
// format
args[0] = text;
return localeutil.getText.apply(localeutil, args);
}
|
javascript
|
{
"resource": ""
}
|
q3218
|
create
|
train
|
function create (key, scopes, callback) {
const data = {
key: key,
scopes: scopes
}
db.put(key, data, function (err) {
if (err) return callback(err)
else callback(null, data)
})
}
|
javascript
|
{
"resource": ""
}
|
q3219
|
update
|
train
|
function update (key, scopes, callback) {
const unlock = lock(key)
get(key, function (err, account) {
if (err) {
unlock()
return callback(err)
}
account.scopes = scopes
db.put(key, account, function (err) {
unlock()
if (err) return callback(err)
else callback(null, account)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q3220
|
verify
|
train
|
function verify (key, scopes, callback) {
db.get(key, function (err, account) {
if (err) return callback(err)
var scopeAccess = verifyScopes(account, scopes)
if (scopeAccess) return callback(null, account)
else callback(new Error('Access denied'))
})
}
|
javascript
|
{
"resource": ""
}
|
q3221
|
verifyScopes
|
train
|
function verifyScopes (data, scopes) {
let i = 0
const l = scopes.length
for (i; i < l; i++) {
if (!verifyScope(data, scopes[i])) return false
}
return true
}
|
javascript
|
{
"resource": ""
}
|
q3222
|
verifyScope
|
train
|
function verifyScope (account, scope) {
if (!account || !account.scopes || !account.scopes.length || !scope) return false
return account.scopes.includes(scope)
}
|
javascript
|
{
"resource": ""
}
|
q3223
|
_suite
|
train
|
function _suite(description, cb) {
var test = new this(description, {});
var it = test._addAction;
_(["suite", "test", "timeout", "getAction", "beforeAll", "beforeEach",
"afterAll", "afterEach", "context", "get", "set", "skip"]).forEach(function (key) {
it[key] = test[key];
});
cb(test);
return test;
}
|
javascript
|
{
"resource": ""
}
|
q3224
|
run
|
train
|
function run(filter) {
var filter;
if (typeof window !== "undefined") {
try {
it.reporter("html", "it");
} catch (e) {
it.reporter("tap");
}
var paramStr = window.location.search.substring(1);
var params = {};
if (paramStr.length > 0) {
_(paramStr.split('&')).forEach(function (part) {
var p = part.split('=');
params[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
});
}
if (params.hasOwnProperty("filter")) {
filter = params.filter;
}
} else {
it.reporter("tap");
}
return interfaces.run(filter);
}
|
javascript
|
{
"resource": ""
}
|
q3225
|
parseNumberString
|
train
|
function parseNumberString(numberString, type, decimalSeparator) {
let result;
if (numberString !== undefined) {
if (typeof numberString === 'string') {
// The given value is a string
if (decimalSeparator === ',') {
numberString = numberString.replace(/\./g, '');
numberString = numberString.replace(/,/g, '\.');
} else {
numberString = numberString.replace(/,/g, '');
}
if (numberString.match(/[^0-9\.]/g)) {
// check if the string contains NO number values
result = 'NUMBER_NOT_VALID';
} else if ((numberString.match(/\./g) || []).length > 1) {
// proof that only one decimal separator exists
result = 'NUMBER_NOT_VALID';
} else {
if (type === 'float') {
result = parseFloat(numberString);
if (result === undefined) {
result = 'NOT_FLOAT';
}
} else if (type === 'integer') {
if (numberString.match(/\./g)) {
result = 'NOT_INTEGER';
} else {
result = parseInt(numberString);
if (result === undefined) {
result = 'NOT_INTEGER';
}
}
} else if (type === 'number') {
result = parseFloat(numberString);
if (result === undefined) {
result = parseInt(numberString);
result = 'NUMBER_NOT_VALID';
}
}
}
} else if (typeof numberString === 'number') {
result = numberString;
} else {
result = 'NUMBER_NOT_VALID';
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q3226
|
validateModel
|
train
|
function validateModel(json, model) {
var schemaKeys = [];
for (var keyInSchema in model) {
schemaKeys.push(keyInSchema);
}
// Check if foreing keys are allowed.
if (!model[SCHEMAALLOWUNKNOWN]) {
// TODO ensure that null and false enter here.
checkUnknown(json, schemaKeys);
}
for (var schemaKeyI = 0; schemaKeyI < schemaKeys.length; schemaKeyI++) {
var node = null;
var schemaKey = schemaKeys[schemaKeyI];
if (json[schemaKey]) {
node = json[schemaKey];
}
if (!isReservedWord(schemaKey)) {
validateNode(node, model[schemaKey], schemaKey);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3227
|
isRequired
|
train
|
function isRequired(schema) {
var required = false;
if (schema[SCHEMAREQUIRED]) {
try {
required = schema[SCHEMAREQUIRED];
if (typeof required != "boolean") {
throw new ValidationException(
schema[SCHEMAREQUIRED] + " cast exception."
);
}
} catch (e) {
throw new ValidationException(
schema[SCHEMAREQUIRED] + " cast exception."
);
}
}
return required;
}
|
javascript
|
{
"resource": ""
}
|
q3228
|
checkUnknown
|
train
|
function checkUnknown(json, schemaKeys) {
var jsonKeys = [];
for (var k in json) {
if (schemaKeys.indexOf(k) === -1) {
throw new ValidationException(
"The key: " +
k +
" is not declared in the schema. Declare it or allow unknown keys."
);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q3229
|
validateObject
|
train
|
function validateObject(node, schema, key) {
if (typeof node == "object") {
try {
validateModel(node, schema[SCHEMADATA]);
} catch (e) {
throw new ValidationException(e.message + " at " + key + ".");
}
} else {
throw new ValidationException("Expected object for " + key);
}
}
|
javascript
|
{
"resource": ""
}
|
q3230
|
validateArray
|
train
|
function validateArray(node, schema, key) {
if (Array.isArray(node)) {
if (schema[SCHEMALENGTH]) {
checkLength(node.length, schema, key);
}
for (var arrayI = 0; arrayI < node.length; arrayI++) {
try {
validateNode(node[arrayI], schema[SCHEMADATA], "");
} catch (e) {
throw new ValidationException(
e.message + key + " position " + arrayI
);
}
}
} else {
throw new ValidationException("Expected array for " + key);
}
}
|
javascript
|
{
"resource": ""
}
|
q3231
|
validateNumber
|
train
|
function validateNumber(node, schema, key) {
if (isNaN(parseFloat(node)) || !isFinite(node)) {
throw new ValidationException("Expected number for " + key);
}
if (schema[SCHEMAREGEX]) {
checkRegex(node, schema, key);
}
}
|
javascript
|
{
"resource": ""
}
|
q3232
|
checkLength
|
train
|
function checkLength(size, schema, key) {
//Check if it is an int
if (Number.isInteger(schema[SCHEMALENGTH])) {
if (size != schema[SCHEMALENGTH]) {
throw new ValidationException("Size of " + key + " is not correct.");
}
} else if (typeof schema[SCHEMALENGTH] == "string") {
if (
size < getMin(schema[SCHEMALENGTH], key) ||
size > getMax(schema[SCHEMALENGTH], key)
) {
throw new ValidationException("Size of " + key + " is not correct.");
}
} else {
throw new ValidationException(SCHEMALENGTH + " cast exception: " + key);
}
}
|
javascript
|
{
"resource": ""
}
|
q3233
|
checkRegex
|
train
|
function checkRegex(node, schema, key) {
try {
schema[SCHEMAREGEX].test(node);
} catch (e) {
throw new ValidationException(key + " doesn't match its regex.");
}
}
|
javascript
|
{
"resource": ""
}
|
q3234
|
defineGlobals
|
train
|
function defineGlobals() {
Object.keys(NODEIFY_FUNCTIONS).forEach((nodeifyName) => {
global[nodeifyName] = NODEIFY_FUNCTIONS[nodeifyName].nodeify;
});
Object.keys(PROMISE_TYPES).forEach((promiseName) => {
global[promiseName] = PROMISE_TYPES[promiseName].Promise;
});
}
|
javascript
|
{
"resource": ""
}
|
q3235
|
Collection
|
train
|
function Collection(name) {
// retrieve collections state
collections = JSON.parse(storage.getItem(this['bucket']));
//console.log('collections ', (collections || null) );
if ( typeof(collections[name]) == 'undefined' ) {
collections[name] = [];
storage.setItem(this['bucket'], JSON.stringify(collections));
collections = JSON.parse(storage.getItem(this['bucket']));
}
entities[name] = { '_collection': name, '_bucket': this['bucket'] };
entities[name] = merge(entities[name], entityProto);
return entities[name]
}
|
javascript
|
{
"resource": ""
}
|
q3236
|
collectionInsert
|
train
|
function collectionInsert(content) {
// TODO - add uuid
content['_id'] = uuid.v1();
content['_createdAt'] = new Date().format("isoDateTime");
content['_updatedAt'] = new Date().format("isoDateTime");
collections[ this['_collection'] ][ collections[ this['_collection'] ].length ] = content;
storage.setItem(this['_bucket'], JSON.stringify(collections));
}
|
javascript
|
{
"resource": ""
}
|
q3237
|
collectionFind
|
train
|
function collectionFind(filter, options) {
if (!filter) {
// TODO - limit of ten by
return collections[ this['_collection'] ]
}
if ( typeof(filter) !== 'object' ) { // == findAll
throw new Error('filter must be an object');
} else {
//console.log('search into ', this['_collection'], collections[ this['_collection'] ], collections);
var content = collections[ this['_collection'] ]
, condition = filter.count()
, i = 0
, found = []
, localeLowerCase = '';
for (var o in content) {
for (var f in filter) {
localeLowerCase = ( typeof(filter[f]) != 'boolean' ) ? filter[f].toLocaleLowerCase() : filter[f];
if ( filter[f] && keywords.indexOf(localeLowerCase) > -1 && localeLowerCase == 'not null' && typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] != 'null' && content[o][f] != 'undefined' ) {
if (found.indexOf(content[o][f]) < 0 ) {
found[i] = content[o][f];
++i
}
} else if ( typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] === filter[f] ) {
found[i] = content[o];
++i
}
}
}
}
return found
}
|
javascript
|
{
"resource": ""
}
|
q3238
|
collectionDelete
|
train
|
function collectionDelete(filter) {
if ( typeof(filter) !== 'object' ) {
throw new Error('filter must be an object');
} else {
var content = JSON.parse(JSON.stringify( collections[ this['_collection'] ] ))
//, condition = filter.count()
, i = 0
, found = [];
for (var o in content) {
for (var f in filter) {
if ( filter[f] && keywords.indexOf(filter[f].toLocaleLowerCase()) > -1 && filter[f].toLowerCase() == 'not null' && typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] != 'null' && content[o][f] != 'undefined' ) {
if (found.indexOf(content[o][f]) < 0 ) {
found[i] = content[o][f];
delete collections[ this['_collection'] ][o][f];
++i
}
} else if ( typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] === filter[f] ) {
found[i] = content[o];
collections[ this['_collection'] ].splice(o, 1);
++i
}
}
}
}
if (found.length > 0 ) {
storage.setItem(this['_bucket'], JSON.stringify(collections));
return true
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q3239
|
WS
|
train
|
function WS(opts) {
var forceBase64 = opts && opts.forceBase64;
if (forceBase64) {
this.supportsBinary = false;
}
this.perMessageDeflate = opts.perMessageDeflate;
this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
this.protocols = opts.protocols;
if (!this.usingBrowserWebSocket) {
WebSocket = NodeWebSocket;
}
Transport.call(this, opts);
}
|
javascript
|
{
"resource": ""
}
|
q3240
|
isArray
|
train
|
function isArray(it) {
if (Array.isArray != null)
return Array.isArray(it);
return Object.prototype.toString.call(it) === "[object Array]";
}
|
javascript
|
{
"resource": ""
}
|
q3241
|
train
|
function(err) {
if (
process.argv[2] == '-s' && startWithGina
|| process.argv[2] == '--start' && startWithGina
//Avoid -h, -v ....
|| !startWithGina && isPath && process.argv.length > 3
) {
if (isPath && !startWithGina) {
console.log('You are trying to load gina by hand: just make sure that your env ['+env+'] matches the given path ['+ path +']');
} else if ( typeof(err.stack) != 'undefined' ) {
console.log('Gina could not determine which bundle to load: ' + err +' ['+env+']' + '\n' + err.stack);
} else {
console.log('Gina could not determine which bundle to load: ' + err +' ['+env+']');
}
process.exit(1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3242
|
render
|
train
|
async function render(template) {
const content = {
badges: await badges(argv.context),
usage: ''
}
if (argv.usage) {
content.usage = readFileSync(resolve(argv.usage))
}
const page = await remark().use(gap).use(squeeze).process(template(content))
process.stdout.write(page.toString())
}
|
javascript
|
{
"resource": ""
}
|
q3243
|
promiseSequence
|
train
|
function promiseSequence(promiseFactories) {
return __awaiter(this, void 0, void 0, function* () {
const ret = [];
for (const f of promiseFactories) {
ret.push(yield f());
}
return ret;
});
}
|
javascript
|
{
"resource": ""
}
|
q3244
|
train
|
function(source, destination, i, callback, excluded) {
var isExcluded = false;
if ( typeof(excluded) != 'undefined' && excluded != undefined) {
var f, p = source.split('/');
f = p[p.length-1];
for (var r= 0; r<excluded.length; ++r) {
if ( typeof(excluded[r]) == 'object' ) {
if (excluded[r].test(f)) {
isExcluded = true
}
} else if (f === excluded[r]) {
isExcluded = true
}
}
}
if (!isExcluded) {
fs.lstat(destination, function(err, stats) {
//Means that nothing exists. Needs create.
if (err) {
startCopy(source, destination, i, function(err, i) {
//TODO - log error.
callback(err, source, i)
})
} else {
if ( stats.isDirectory() ) {
var str;
var path = '/'+ (str = source.split(/\//g))[str.length-1];
destination += path
}
fs.exists(destination, function(replaceFlag) {
if (replaceFlag) {
fs.unlink(destination, function(err) {
//TODO - log error.
startCopy(source, destination, i, function(err, i) {
callback(err, source, i)
})
})
} else {
startCopy(source, destination, i, function(err, i) {
//TODO - log error.
callback(err, source, i)
})
}
})
}//EO if (err)
})
} else {
callback(false, source, i)
}
var startCopy = function(source, destination, i, callback) {
copyFile(source, destination, i, function(err, i) {
if (err) {
console.error(err.stack)
}
callback(err, i)
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3245
|
entries
|
train
|
function entries(obj) {
return Object.keys(obj)
.map(key => [key, obj[key]]);
}
|
javascript
|
{
"resource": ""
}
|
q3246
|
filter
|
train
|
function filter(obj, predicate) {
return composeObject(entries(obj).filter(([key, value]) => predicate(value, key)));
}
|
javascript
|
{
"resource": ""
}
|
q3247
|
composeObject
|
train
|
function composeObject(properties) {
return properties.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q3248
|
unmarshallWrapper
|
train
|
function unmarshallWrapper (cb) {
return function (err, value) {
if (err) return cb(err);
var m = unmarshall(value);
cb(m.error, m.value);
};
}
|
javascript
|
{
"resource": ""
}
|
q3249
|
train
|
function (streamIterator, onItem) {
StreamIterator.apply(this, arguments);
this._streamIterator = streamIterator;
this._onItem = onItem;
// Pipe data so that we can filter it in FilteredStreamIterator
streamIterator.pipe(this);
}
|
javascript
|
{
"resource": ""
}
|
|
q3250
|
train
|
function(callback)
{
// Connect to the given URI with the given options
self.mongo.MongoClient.connect(self.config.uri, defaultOpts, function(err, db) {
if (err) {
return callback && callback(err);
}
// Rewrite connection
self.connection = db;
callback && callback(null, db);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3251
|
restXhr
|
train
|
function restXhr(store, url, eventName, sortRequest) {
// Set up request
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// TODO - Set range header parameter
xhr.setRequestHeader("Content-Type", "application/json");
// Callback
xhr.onload = function(e) {
// If operation has been completed - ready state 4
if (xhr.readyState === 4) {
// Response status successfully completed - status 200
if (xhr.status === 200) {
// Set up store
store._setUpData(xhr.response);
// Process store data filters and lists
vcomet.StoreMemory.processData(store);
// Set data as sorted
store.data.__sorted = sortRequest;
// Update store data items length
store.size = xhr.getResponseHeader("Total");
// Trigger user callback once data has been retrieved
vcomet.triggerCallback(eventName, store, store, [store.rootData]);
vcomet.createCallback("onSourceChanged", store, store, [store.rootData]);
}
}
};
// Execute request
store.onLoaded(function(){xhr.send()});
}
|
javascript
|
{
"resource": ""
}
|
q3252
|
train
|
function(callback) {
var binary = binaries.bower;
binary.command = 'bower --allow-root install';
helper.runCommand(
binary, path,
'bower binary is not ready to use, fix this (npm install -g bower) and retry ' +
'installation of frontend dependencies manually'.grey,
callback
);
}
|
javascript
|
{
"resource": ""
}
|
|
q3253
|
train
|
function(binaries, callback) {
helper.createProjectStructure(appPath, function(err) {
callback && callback(err, binaries);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3254
|
train
|
function (fieldDefinition, fieldName) {
const fieldType = propertyHelper.getFieldType(fieldDefinition);
if (fieldType === 'date') {
// This field is a date field. Create the checks
return createDateChecks(fieldDefinition, fieldName);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3255
|
train
|
function(route) {
return (route != null && self.routes != null && typeof(self.routes[route]) != 'undefined' && self.routes[route] != null)
}
|
javascript
|
{
"resource": ""
}
|
|
q3256
|
train
|
function(route, args) {
var index;
// There is a requirement for this route.
if (typeof(self.routes[route].requirements) != 'undefined') {
// For each arguments.
for (index in args) {
// If there is a requirement.
if (self.routes[route].requirements[index] != null) {
// Check if it is fulfilled.
var regTest = (new RegExp(self.routes[route].requirements[index]));
// If not, replace data with :argument.
if (!regTest.test(args[index])) {
args[index] = ':' + index
}
}
}
}
return args
}
|
javascript
|
{
"resource": ""
}
|
|
q3257
|
getCheckInfo
|
train
|
function getCheckInfo(checkProperty, fieldName) {
let severity;
let value;
if (typeof checkProperty[fieldName] === 'object') {
severity = checkProperty[fieldName].severity;
value = checkProperty[fieldName].val;
} else {
severity = checkProperty.severity;
value = checkProperty[fieldName];
}
return {
val: value,
severity: severity
};
}
|
javascript
|
{
"resource": ""
}
|
q3258
|
PromiseDecorator
|
train
|
function PromiseDecorator(cache) {
BaseDecorator.call(this, cache);
this.get = promisify(this.get.bind(this));
this.set = promisify(this.set.bind(this));
this.del = promisify(this.del.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q3259
|
train
|
function(app, file, content, callback) {
var paths = {
root : content.paths.root,
utils : content.paths.utils
};
var gnaFolder = content.paths.root + '/.gna';
self.project = content.project;
self.paths = paths;
//Create path.
var createFolder = function(){
if ( fs.existsSync(gnaFolder) ) {
if ( !fs.existsSync(gnaFolder +'/'+ file) ) {
createContent(gnaFolder +'/'+ file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
} else { // already existing ... won't overwrite
callback(false)
}
} else {
fs.mkdir(gnaFolder, 0777, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Creating content.
createContent(gnaFolder+ '/' +file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
}
})
}
};
fs.exists(gnaFolder, function(exists){
if (!exists) {
createFolder()
} else {
// test if decalred path matches real path and overwrite if not the same
// in case you move your project
var filename = _(gnaFolder +'/'+ file, true);
var checksumFileOld = _(gnaFolder +'/'+ math.checkSumSync( JSON.stringify( require(filename) ), 'sha1'), true) + '.txt';
var checksumFile = _(gnaFolder +'/'+ math.checkSumSync( JSON.stringify(content), 'sha1'), true) + '.txt';
var verified = (checksumFileOld == checksumFile) ? true : false;
if ( !fs.existsSync(checksumFile) && fs.existsSync(filename) || !fs.existsSync(filename) || !verified) {
if ( fs.existsSync(filename) ) fs.unlinkSync(filename);
if ( fs.existsSync(checksumFile) ) fs.unlinkSync(checksumFile);
createContent(filename, gnaFolder, content, function(err){
fs.openSync(checksumFile, 'w');
setTimeout(function(){
callback(err)
}, 500)
})
} else if ( fs.existsSync(filename) ) {
var locals = require(gnaFolder +'/'+ file);
if (paths.utils != locals.paths.utils) {
new _(gnaFolder).rm( function(err){
if (err) {
console.warn('found error while trying to remove `.gna`\n' + err.stack)
}
//setTimeout(function(){
//console.debug('Done removing `gnaFolder` : '+ gnaFolder);
createFolder();
//}, 200);
})
} else {
callback(false)// nothing to do
}
} else {
callback(false)// nothing to do
}
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q3260
|
train
|
function(){
if ( fs.existsSync(gnaFolder) ) {
if ( !fs.existsSync(gnaFolder +'/'+ file) ) {
createContent(gnaFolder +'/'+ file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
} else { // already existing ... won't overwrite
callback(false)
}
} else {
fs.mkdir(gnaFolder, 0777, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Creating content.
createContent(gnaFolder+ '/' +file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3261
|
train
|
function(path, callback){
fs.exists(path, function(exists){
if (exists) {
fs.lstat(path, function(err, stats){
if (err) console.error(err.stack);
if ( stats.isSymbolicLink() ) fs.unlink(path, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Trigger.
onSymlinkRemoved(self.paths, function(err){
if (err) console.error(err.stack);
callback(false)
})
}
})
})
} else {
//log & ignore. This is not a real issue.
//logger.warn('gina', 'UTILS:CONFIG:WARN:1', 'Path not found: ' + path, __stack);
console.warn( 'Path not found: ' + path, __stack);
onSymlinkRemoved(self.paths, function(err){
//if (err) logger.error('gina', 'UTILS:CONFIG:ERR:9', err, __stack);
if (err) console.error(err.stack||err.message);
callback(false)
})
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q3262
|
train
|
function(namespace, config) {
if ( typeof(config) == "undefined" )
var config = self.getSync(app);
if (config != null) {
var split = namespace.split('.'), k=0;
while (k<split.length) {
config = config[split[k++]]
}
return config
} else {
return null
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3263
|
train
|
function(app, namespace, callback){
self.get(app, function(err, config){
if (err) {
//logger.error('gina', 'UTILS:CONFIG:ERR:4', err, __stack);
console.error(err.stack||err.message);
callback(err + 'Utils.Config.get(...)');
}
try {
callback( false, getVar('paths.' + namespace, config) );
} catch (err) {
var err = new Error('Config.getPath(app, cat, callback): cat not found');
callback(err)
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q3264
|
train
|
function(callback) {
var data = JSON.parse(JSON.stringify(self.projectData, null, 4));
data.bundles[self.bundle] = {
"comment" : "Your comment goes here.",
"tag" : "001",
"src" : "src/" + bundle,
"release" : {
"version" : "0.0.1",
"link" : "bundles/"+ bundle
}
};
try {
fs.writeFileSync(self.project, JSON.stringify(data, null, 4));
callback(false, data)
} catch (err) {
callback(err, undefined)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3265
|
validVersion
|
train
|
function validVersion(version, spec) {
// Normalize route versions
var test = spec.versions || [spec.version]
// Check for direct version match
if (~test.indexOf(version)) {
return true
}
// Use semver and attempt to match on supplied version
return !!test.filter(function(v) {
return semver.satisfies(v, version)
}).length
}
|
javascript
|
{
"resource": ""
}
|
q3266
|
errorWrap
|
train
|
function errorWrap(err, param, sent) {
if (err instanceof restify.RestError) {
err.body.parameter = param
err.body.received = sent
}
return err
}
|
javascript
|
{
"resource": ""
}
|
q3267
|
arrayDefaults
|
train
|
function arrayDefaults(arr, values) {
values.forEach(function(x) {
if (!~arr.indexOf(x)) arr.push(x)
})
}
|
javascript
|
{
"resource": ""
}
|
q3268
|
getParams
|
train
|
function getParams(obj) {
var defs = []
for (var name in obj) {
var data = obj[name]
, fromPath = ~required.indexOf(name)
// If string, assume a single data type
if (typeof data === 'string') {
data = data.split(',')
}
// If array, assume array of data types
if (Array.isArray(data)) {
data = obj[name] = {
dataTypes: data
}
}
// Check for singular spelling
if (data.dataType) {
data.dataTypes = data.dataType
}
// Ensure datatypes is an array
if (!Array.isArray(data.dataTypes)) {
data.dataTypes = [data.dataTypes]
}
// Normalize data types
var types = _.uniq((data.dataTypes || []).map(function(type) {
return type && type.toLowerCase()
}))
// Parameter type / source
var paramType = 'path'
if (!fromPath) {
// If not a URI param, check to see if a `post` source
// was specified, otherwise default to `querystring`
paramType = (data.paramType && data.paramType === 'post')
? 'post'
: 'querystring'
}
// Parameter spec information
var param = {
name: name
, required: fromPath ? true : !!data.required
, paramType: paramType
, dataTypes: types
}
// If we have a number, check if a min / max value was set
if (~types.indexOf('number')) {
if (_.has(data, 'min')) param.min = +data.min;
if (_.has(data, 'max')) param.max = +data.max;
}
// Add in any extra information defined from options
if (self.options.paramProperties) {
self.options.paramProperties.forEach(function(prop) {
if (_.has(data, prop)) {
param[prop] = data[prop]
}
})
}
// If we have an object type, check for sub-schemas
if (~types.indexOf('object') && data.params) {
param.params = getParams(data.params)
}
defs.push(param)
}
return defs
}
|
javascript
|
{
"resource": ""
}
|
q3269
|
spawnCommand
|
train
|
function spawnCommand(command, args, options) {
if (!command) throw new Error('Please specify a command to spawn.')
const proc = /** @type {!_spawncommand.ChildProcessWithPromise} */ (spawn(command, args, options))
const promise = getPromise(proc)
proc.promise = promise
/** @suppress {checkTypes} */
proc.spawnCommand = proc['spawnargs'].join(' ')
return proc
}
|
javascript
|
{
"resource": ""
}
|
q3270
|
fork
|
train
|
function fork(mod, args, options) {
if (!mod) throw new Error('Please specify a module to fork')
const proc = /** @type {!_spawncommand.ChildProcessWithPromise} */ (forkCp(mod, args, options))
const promise = getPromise(proc)
proc.promise = promise
/** @suppress {checkTypes} */
proc.spawnCommand = proc['spawnargs'].join(' ')
return proc
}
|
javascript
|
{
"resource": ""
}
|
q3271
|
isSameObjectId
|
train
|
function isSameObjectId(a, b) {
assert(isObjectId(a), '1st argument is not an ObjectId')
assert(isObjectId(b), '2nd argument is not an ObjectId')
return a.toString() === b.toString()
}
|
javascript
|
{
"resource": ""
}
|
q3272
|
assertInstance
|
train
|
function assertInstance(instance, model) {
const modelName = get('modelName')(model)
try {
mongoose.model(modelName)
} catch (err) {
throw Error(`no such model as ${modelName}`)
}
const errMsg = stripIndents`
Expected an instance of ${modelName} but got this:
${JSON.stringify(instance, undefined, 2)}`
assert(instance instanceof model, errMsg)
}
|
javascript
|
{
"resource": ""
}
|
q3273
|
ExpiresDecorator
|
train
|
function ExpiresDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
expiresIn: joi.number().integer().min(0).default(Infinity),
staleIn: joi.number().integer().min(0).default(Infinity)
}));
this.on('set:after', this.setCreatedAt.bind(this));
this._store = this._getStore();
}
|
javascript
|
{
"resource": ""
}
|
q3274
|
train
|
function(err) {
var message = 'Error occured while performing a JSON-WSP request. ' +
err.message + '\n' +
JSON.stringify({
options : curOpts
}, null, ' ').yellow;
logger.error(message);
}
|
javascript
|
{
"resource": ""
}
|
|
q3275
|
promesify
|
train
|
function promesify(err, res) {
if (!err) return Promise.resolve(res);
else return Promise.reject(err);
}
|
javascript
|
{
"resource": ""
}
|
q3276
|
ECSignature
|
train
|
function ECSignature (r, s) {
typeforce(types.tuple(types.BigInt, types.BigInt), arguments)
/** @type {BigInteger} */ this.r = r
/** @type {BigInteger} */ this.s = s
}
|
javascript
|
{
"resource": ""
}
|
q3277
|
ConfigLoader
|
train
|
function ConfigLoader(strategies, logger) {
this.strategies = [];
if (logger) {
if (typeof logger.debug !== 'function') {
throw new Error('Provided logger is required to have method debug().');
}
this.logger = logger;
}
if (strategies && !(strategies instanceof Array)) {
throw new Error('Argument \'strategies\' must be an array.');
}
for (var i = 0; i < strategies.length; i++) {
this.add(strategies[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
q3278
|
train
|
function() {
//Default.
var pathObj = new _( getPath('root') + '/tmp/pid/' );
var path = pathObj.toString();
//Create dir if needed.
//console.debug("MKDIR pathObj (pid:"+self.proc.pid+") - ", self.bundle);
process.list = (process.list == undefined) ? [] : process.list;
process.pids = (process.pids == undefined) ? {} : process.pids;
self.register(self.bundle, self.proc.pid);
if (usePidFile) {
pathObj.mkdir( function(err, path){
console.debug('path created ('+path+') now saving PID ' + bundle);
//logger.info('gina', 'PROC:INFO:1', 'path created ('+path+') now saving PID ' + bundle, __stack);
//Save file.
if (!err) {
self.PID = self.proc.pid;
self.path = path + pathObj.sep;
//Add PID file.
setPID(self.bundle, self.PID, self.proc);
save(self.bundle, self.PID, self.proc)
}
})
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3279
|
train
|
function(callback)
{
self.pool = (require('mysql')).createPool({
user : self.config.username,
password : self.config.password,
database : self.config.db,
host : self.config.host,
port : self.config.port
});
// Initiate a connection - just to proof configuration
self.pool.getConnection(function(err, connection) {
if (err || !connection) {
callback && callback(err);
return;
}
self.prepare(connection);
// The connection can be closed immediately
connection.release();
return callback && callback(null, self.pool);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q3280
|
Locales
|
train
|
function Locales() {
var _require = function(path) {
var cacheless = (process.env.IS_CACHELESS == 'false') ? false : true;
if (cacheless) {
try {
delete require.cache[require.resolve(path)];
return require(path)
} catch (err) {
throw err
}
} else {
return require(path)
}
}
/**
* init
*
* return {array} regions collection
* */
var init = function () {
var dir = __dirname + '/dist/region' // regions by language
, files = fs.readdirSync(dir)
, i = 0
, key = null
, regions = []
;
for (var f = 0, len = files.length; f < len; ++f) {
if ( ! /^\./.test(files[f]) || f == len-1 ) {
key = files[f].split(/\./)[0];
regions[i] = { lang: key, content: _require( dir + '/' + files[f] ) }
}
}
return regions
}
return init()
}
|
javascript
|
{
"resource": ""
}
|
q3281
|
train
|
function(bundle, env) {
if ( !self.isStandalone ) {
if ( !bundle && typeof(self.bundle) != 'undefined' ) {
var bundle = self.bundle
}
return ( typeof(self.envConf) != "undefined" ) ? self.envConf[bundle][env] : null;
} else {
if (!bundle) { // if getContext().bundle is lost .. eg.: worker context
var model = (arguments.length == 1) ? bundle : model
, file = ( !/node_modules/.test(__stack[1].getFileName()) ) ? __stack[1].getFileName() : __stack[2].getFileName()
, a = file.replace('.js', '').split('/')
, i = a.length-1
, bundles = getContext('gina').config.bundles
, index = 0;
for (; i >= 0; --i) {
index = bundles.indexOf(a[i]);
if ( index > -1 ) {
bundle = bundles[index];
break
}
}
}
if ( typeof(self.envConf) != "undefined" ) {
self.envConf[bundle][env].hostname = self.envConf[self.startingApp][env].hostname;
self.envConf[bundle][env].content.routing = self.envConf[self.startingApp][env].content.routing;
if ( bundle && env ) {
return self.envConf[bundle][env]
} else if ( bundle && !env ) {
return self.envConf[bundle]
} else {
return self.envConf
}
}
return null
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3282
|
random
|
train
|
function random(length, options) {
length || (length = 8);
options || (options = {});
var chars = '';
var result = '';
if (options === true) {
chars = numbers + letters + specials;
} else if (typeof options == 'string') {
chars = options;
} else {
if (options.numbers !== false) {
chars += (typeof options.numbers == 'string') ? options.numbers : numbers;
}
if (options.letters !== false) {
chars += (typeof options.letters == 'string') ? options.letters : letters;
}
if (options.specials) {
chars += (typeof options.specials == 'string') ? options.specials : specials;
}
}
while (length > 0) {
length--;
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q3283
|
post_process
|
train
|
function post_process(){
var error = false;
var invalid_reasons = []
if (read_result.riff_head != "RIFF") invalid_reasons.push("Expected \"RIFF\" string at 0" )
if (read_result.wave_identifier != "WAVE") invalid_reasons.push("Expected \"WAVE\" string at 4")
if (read_result.fmt_identifier != "fmt ") invalid_reasons.push("Expected \"fmt \" string at 8")
if (
(read_result.audio_format != 1) && // Wav
(read_result.audio_format != 65534) && // Extensible PCM
(read_result.audio_format != 2) && // Wav
(read_result.audio_format != 22127) && // Vorbis ?? (issue #11)
(read_result.audio_format != 3)) // Wav
invalid_reasons.push("Unknown format: "+read_result.audio_format)
if ((read_result.chunk_size + 8) !== stats.size) invalid_reasons.push("chunk_size does not match file size")
//if ((read_result.data_identifier) != "data") invalid_reasons.push("Expected data identifier at the end of the header")
if (invalid_reasons.length > 0) error = true;
if (error) return cb({
error : true,
invalid_reasons: invalid_reasons,
header: read_result,
stats: stats
});
cb(null, {
header: read_result,
stats: stats,
duration: ((read_result.chunk_size) / (read_result.sample_rate * read_result.num_channels * (read_result.bits_per_sample / 8)))
});
}
|
javascript
|
{
"resource": ""
}
|
q3284
|
train
|
function (name) {
/**
* Any of the allowed functions. Arguments are shifted if params is a function so there's no need to give an empty params array.
* @param {Array} params optional array of parameters for the function. Treated as success callback if a function instead.
* @param {function} success Callback function
* @param {function} error Error handler
*/
RPC_API[name] = function (params, success, error) {
if (name === 'getInfo') {
// hide params from external getInfo calls
error = success;
success = params;
params = [rpcClientVersion];
}
if (typeof params === 'function') {
error = success;
success = params;
params = [];
}
channel.call({
method: name,
params: params,
success: success,
error: error || defaultErrorHandler
});
};
}
|
javascript
|
{
"resource": ""
}
|
|
q3285
|
absolutize
|
train
|
function absolutize(path){
var startX = 0
var startY = 0
var x = 0
var y = 0
return path.map(function(seg){
seg = seg.slice()
var type = seg[0]
var command = type.toUpperCase()
// is relative
if (type != command) {
seg[0] = command
switch (type) {
case 'a':
seg[6] += x
seg[7] += y
break
case 'v':
seg[1] += y
break
case 'h':
seg[1] += x
break
default:
for (var i = 1; i < seg.length;) {
seg[i++] += x
seg[i++] += y
}
}
}
// update cursor state
switch (command) {
case 'Z':
x = startX
y = startY
break
case 'H':
x = seg[1]
break
case 'V':
y = seg[1]
break
case 'M':
x = startX = seg[1]
y = startY = seg[2]
break
default:
x = seg[seg.length - 2]
y = seg[seg.length - 1]
}
return seg
})
}
|
javascript
|
{
"resource": ""
}
|
q3286
|
train
|
function (config) {
var guide = config.categoryAxis.guides[0]
var filter = this.filteredCollection.getFilters(this.filteredCollection.getTriggerField())
if (filter) {
if (config.categoryAxis.parseDates) {
guide.date = filter.expression.value[0].value
guide.toDate = filter.expression.value[1].value
} else {
guide.category = guide.toCategory = filter.expression.value
}
} else {
if (guide.date) delete guide.date
if (guide.toDate) delete guide.toDate
if (guide.category) delete guide.category
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3287
|
train
|
function (e) {
// console.log('Filtered by', (new Date(e.start)).toISOString(), (new Date(e.end)).toISOString())
var field = this.collection.getTriggerField()
var start = new Date(e.start)
var startIso = trimLastCharacter(start.toISOString())
var startFriendly = start.toLocaleDateString()
var end = new Date(e.end)
var endIso = trimLastCharacter(end.toISOString())
var endFriendly = end.toLocaleDateString()
// Trigger the global event handler with this filter
this.vent.trigger(this.collection.getDataset() + '.filter', {
field: field,
expression: {
type: 'and',
value: [
{
type: '>=',
value: startIso,
label: startFriendly
},
{
type: '<=',
value: endIso,
label: endFriendly
}
]
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q3288
|
train
|
function (tableState, dataTablesCallback, dataTablesSettings) {
this.collection.setSearch(tableState.search.value ? tableState.search.value : null)
this.collection.unsetRecordCount()
this.renderFilters()
// Get record count first because it needs to be passed into the collection.fetch callback
this.collection.getRecordCount().then(_.bind(function (recordCount) {
if (!this.recordsTotal) {
this.recordsTotal = recordCount
}
var recordsTotal = this.recordsTotal // for use in callback below
this.collection.setOffset(tableState.start || 0)
this.collection.setLimit(tableState.length || 25)
if (tableState.order.length) {
this.collection.setOrder(tableState.columns[tableState.order[0].column].data + ' ' + tableState.order[0].dir)
}
this.collection.fetch({
success: function (collection, response, options) {
dataTablesCallback({
data: collection.toJSON(),
recordsTotal: recordsTotal,
recordsFiltered: recordCount
})
}
})
}, this))
}
|
javascript
|
{
"resource": ""
}
|
|
q3289
|
train
|
function (data) {
this.collection.setFilter(data)
this.collection.unsetRecordCount()
this.table.ajax.reload()
this.renderFilters()
}
|
javascript
|
{
"resource": ""
}
|
|
q3290
|
train
|
function (e) {
if (e.index == null) {
this.hovering = null
} else {
this.hovering = this.chart.categoryAxis.data[e.index]
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3291
|
train
|
function (data) {
// Add the filter to the filtered collection and fetch it with the filter
this.filteredCollection.setFilter(data)
// Only re-fetch if it's another chart (since this view doesn't filter itself)
if (data.field !== this.filteredCollection.getTriggerField()) {
this.filteredCollection.fetch()
// If it's this chart and the filter is being removed, re-render the chart
} else if (!data.expression) {
this.render()
}
this.renderFilters()
}
|
javascript
|
{
"resource": ""
}
|
|
q3292
|
train
|
function () {
// Create hash table for easy reference
var collectionValues = hashTable(this.collection.toJSON(), 'label', 'value')
var filteredCollectionValues = hashTable(this.filteredCollection.toJSON(), 'label', 'value')
// Add value from hash tables to geojson properties
var idAttribute = this.boundaries.idAttribute
var filtered = this.filteredCollection.getFilters().length
this.boundaries.forEach(function (item) {
var properties = item.get('properties')
properties.value = collectionValues[properties[idAttribute]]
if (filtered) {
properties.filteredValue = filteredCollectionValues[properties[idAttribute]] || 0
}
item.set('properties', properties)
}, this)
}
|
javascript
|
{
"resource": ""
}
|
|
q3293
|
scripts
|
train
|
function scripts (src, dest, watch) {
var bundleOpts = _.extend({}, watchify.args)
if (watch) bundleOpts.debug = true
var bundle = browserify(src, bundleOpts)
if (watch) {
bundle = watchify(bundle)
bundle.on('update', function () { compileBundle(bundle, dest) }) // when a dependency changes, recompile
bundle.on('log', gutil.log) // output build logs to terminal
} else {
bundle.transform({ global: true }, 'uglifyify')
}
return compileBundle(bundle, dest)
}
|
javascript
|
{
"resource": ""
}
|
q3294
|
OptimizeCssnanoPlugin
|
train
|
function OptimizeCssnanoPlugin(options) {
this.options = Object.assign({
sourceMap: false,
cssnanoOptions: {
preset: 'default',
},
}, options);
if (this.options.sourceMap) {
this.options.sourceMap = Object.assign(
{inline: false},
this.options.sourceMap || {});
}
}
|
javascript
|
{
"resource": ""
}
|
q3295
|
help
|
train
|
function help() {
console.log("Usage:");
console.log(" qrcode-svg [options] <content>");
console.log("");
console.log("Options:");
console.log(" --help Print this message");
console.log(" --padding [value] Offset in number of modules");
console.log(" --width [px] Image width in pixels");
console.log(" --height [px] Image height in pixels");
console.log(" --color [color] Foreground color, hex or name");
console.log(" --background [color] Background color, hex or name");
console.log(" --ecl [value] Error correction level: L, M, H, Q");
console.log(" -o [file] Output file name");
console.log(" -f Force overwrite");
console.log(" -v Print version number");
console.log("");
console.log("Examples:");
console.log(" qrcode-svg http://github.com");
console.log(" qrcode-svg -f -o hello.svg \"Hello World\"");
console.log(" qrcode-svg --padding 2 --width 120 --height 120 \"Little fox...\"");
console.log(" qrcode-svg --color blue --background #ececec \"...jumps over\"");
}
|
javascript
|
{
"resource": ""
}
|
q3296
|
_getGradientTexture
|
train
|
function _getGradientTexture() {
// Only update the texture when the gradient has changed.
if (this._prevGradientColors === this.props.gradientColors) {
return this._gradientTexture;
}
var canvas = document.createElement('canvas');
// 512, 10 because these are the same dimensions webgl-heatmap uses for its
// built in gradient textures.
var width = 512;
var height = 10;
canvas.width = String(width);
canvas.height = String(height);
var ctx = canvas.getContext('2d');
var gradient = ctx.createLinearGradient(0, height / 2, width, height / 2);
var colors = this.props.gradientColors;
colors.forEach(function each(color, index) {
var position = index / (colors.size - 1);
gradient.addColorStop(position, color);
});
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
var image = new window.Image();
image.src = canvas.toDataURL('image/png');
return image;
}
|
javascript
|
{
"resource": ""
}
|
q3297
|
decodeUTF8
|
train
|
function decodeUTF8(bytes) {
var s = '';
var i = 0;
while (i < bytes.length) {
var c = bytes[i++];
if (c > 127) {
if (c > 191 && c < 224) {
if (i >= bytes.length)
throw new Error('UTF-8 decode: incomplete 2-byte sequence');
c = ((c & 31) << 6) | (bytes[i] & 63);
} else if (c > 223 && c < 240) {
if (i + 1 >= bytes.length)
throw new Error('UTF-8 decode: incomplete 3-byte sequence');
c = ((c & 15) << 12) | ((bytes[i] & 63) << 6) | (bytes[++i] & 63);
} else if (c > 239 && c < 248) {
if (i + 2 >= bytes.length)
throw new Error('UTF-8 decode: incomplete 4-byte sequence');
c =
((c & 7) << 18) |
((bytes[i] & 63) << 12) |
((bytes[++i] & 63) << 6) |
(bytes[++i] & 63);
} else
throw new Error(
'UTF-8 decode: unknown multibyte start 0x' +
c.toString(16) +
' at index ' +
(i - 1)
);
++i;
}
if (c <= 0xffff) s += String.fromCharCode(c);
else if (c <= 0x10ffff) {
c -= 0x10000;
s += String.fromCharCode((c >> 10) | 0xd800);
s += String.fromCharCode((c & 0x3ff) | 0xdc00);
} else
throw new Error(
'UTF-8 decode: code point 0x' + c.toString(16) + ' exceeds UTF-16 reach'
);
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
q3298
|
train
|
function(obj, keys) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (keys.hasOwnProperty(key)) {
if (typeof obj[key] !== keys[key])
throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key]));
} else {
var errorStr = "Unknown property, " + key + ". Valid properties are:";
for (var validKey in keys)
if (keys.hasOwnProperty(validKey))
errorStr = errorStr+" "+validKey;
throw new Error(errorStr);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q3299
|
train
|
function(client, window, timeoutSeconds, action, args) {
this._window = window;
if (!timeoutSeconds)
timeoutSeconds = 30;
var doTimeout = function (action, client, args) {
return function () {
return action.apply(client, args);
};
};
this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000);
this.cancel = function() {
this._window.clearTimeout(this.timeout);
};
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.