_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q35600 | add | train | function add (obj, name, value) {
const previous = obj[name]
if (previous) {
const arr = [].concat(previous)
arr.push(value)
return arr
} else return value
} | javascript | {
"resource": ""
} |
q35601 | retrieveContextAtReceiver | train | function retrieveContextAtReceiver(req, res) {
if(redirect(req.params.id, '', '', res)) {
return;
}
switch(req.accepts(['json', 'html'])) {
case 'html':
res.sendFile(path.resolve(__dirname + '/../../web/response.html'));
break;
default:
var options = {
query: 'receivedStrongestBy',
id: req.params.id,
omit: [ 'timestamp' ] };
var rootUrl = req.protocol + '://' + req.get('host');
var queryPath = req.originalUrl;
req.chickadee.getDevicesContext(req, options, rootUrl, queryPath,
function(response, status) {
res.status(status).json(response);
});
break;
}
} | javascript | {
"resource": ""
} |
q35602 | popContext | train | function popContext(state) {
if (state.context) {
var oldContext = state.context;
state.context = oldContext.prev;
return oldContext;
}
// we shouldn't be here - it means we didn't have a context to pop
return null;
} | javascript | {
"resource": ""
} |
q35603 | isTokenSeparated | train | function isTokenSeparated(stream) {
return stream.sol() ||
stream.string.charAt(stream.start - 1) == " " ||
stream.string.charAt(stream.start - 1) == "\t";
} | javascript | {
"resource": ""
} |
q35604 | loadPackage | train | function loadPackage(target, location, section, options, done) {
if(section == 'config') {
options.dirname = path.resolve(location + '/' + section);
} else {
options.dirname = path.resolve(location + '/api/' + section);
}
buildDictionary.optional(options, function(err, modules) {
if(err) return done(err);
if(section == 'config') {
for(var i in modules) {
target.config = _.extend(target.config || {}, modules[i]);
}
} else {
target[section] = _.extend(target[section] || {}, modules);
}
return done();
});
} | javascript | {
"resource": ""
} |
q35605 | train | function(sails, done) {
sails.log.silly('Initializing Bulkhead packages...');
// Detach models from the Sails instance
var bulkheads = Object.keys(Bulkhead),
i = 0,
detachedLoadModels = sails.modules.loadModels;
/**
* Reload event that loads each Bulkhead package's models
*/
var reloadedEvent = function() {
_.each(Bulkhead, function(bulkhead, bulkheadName) {
// A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead
_.each(bulkhead.models, function(model, index) {
bulkhead.models[model.originalIdentity] = sails.models[model.identity];
bulkhead[model.originalGlobalId] = bulkhead.models[model.originalIdentity];
delete model.originalIdentity;
delete model.originalGlobalId;
});
_.each(bulkhead.services, function(service, index) {
service.plugin = bulkhead;
bulkhead[service.originalIdentity] = bulkhead.services[index];
delete service.originalIdentity;
});
sails.log.silly(Object.keys(bulkhead.models).length + ' loaded from the ' + path.basename(bulkheadName) + ' package...');
});
sails.removeListener('hook:orm:reloaded', reloadedEvent);
sails.modules.loadModels = detachedLoadModels;
loaded = true;
sails.log.silly('Bulkhead packages are active.');
done();
};
// Attach a custom reload event
sails.on('hook:orm:reloaded', reloadedEvent);
// Attaches and reloads the ORM
if(!loaded && Bulkhead[bulkheads[i]]) {
// We detach the model path to make sure that the loadModels module never refreshes and overrides
sails.modules.loadModels = function(cb) {
// Load all models into the global scope with namespacing
sails.log.silly('Loading Bulkhead models...');
async.series([
detachedLoadModels,
function(next) {
var models = {};
_.each(Bulkhead, function(bulkhead) {
_.each(bulkhead.models, function(model) {
models[model.identity] = model;
});
});
next(null, models);
}
], function(err, results) {
cb(null, _.extend(results[0], results[1]));
});
};
sails.hooks.orm.reload();
} else {
// No Bulkheads were detected
if(loaded) {
sails.log.silly('Bulkhead already loaded.');
} else {
sails.log.silly('No Bulkhead packages found!');
}
done();
}
} | javascript | {
"resource": ""
} | |
q35606 | train | function() {
_.each(Bulkhead, function(bulkhead, bulkheadName) {
// A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead
_.each(bulkhead.models, function(model, index) {
bulkhead.models[model.originalIdentity] = sails.models[model.identity];
bulkhead[model.originalGlobalId] = bulkhead.models[model.originalIdentity];
delete model.originalIdentity;
delete model.originalGlobalId;
});
_.each(bulkhead.services, function(service, index) {
service.plugin = bulkhead;
bulkhead[service.originalIdentity] = bulkhead.services[index];
delete service.originalIdentity;
});
sails.log.silly(Object.keys(bulkhead.models).length + ' loaded from the ' + path.basename(bulkheadName) + ' package...');
});
sails.removeListener('hook:orm:reloaded', reloadedEvent);
sails.modules.loadModels = detachedLoadModels;
loaded = true;
sails.log.silly('Bulkhead packages are active.');
done();
} | javascript | {
"resource": ""
} | |
q35607 | make | train | function make(x, options = {}) {
var {debug = DEBUG_ALL} = options;
var u;
debug = DEBUG && debug;
if (x === undefined) u = makeUndefined();
else if (x === null) u = makeNull();
else {
u = Object(x);
if (!is(u)) {
add(u, debug);
defineProperty(u, 'change', { value: change });
}
}
if (debug) console.debug(...channel.debug("Created upwardable", u._upwardableId, "from", x));
return u;
} | javascript | {
"resource": ""
} |
q35608 | change | train | function change(x) {
var u = this;
var debug = u._upwardableDebug;
if (x !== this.valueOf()) {
u = make(x, { debug });
getNotifier(this).notify({object: this, newValue: u, type: 'upward'});
if (debug) {
console.debug(...channel.debug("Replaced upwardable", this._upwardableId, "with", u._upwardableId));
}
}
return u;
} | javascript | {
"resource": ""
} |
q35609 | setQRstyle | train | function setQRstyle (dst, src, caller) {
dst['qrpopup'] = src.qrpopup ? src.qrpopup : false
dst['qrsize'] = src.qrsize > 0 ? src.qrsize : 128
dst['qrvoffset'] = src.qrvoffset >= 0 ? src.qrvoffset : 20
dst['qrpadding'] = src.qrpadding ? src.qrpadding : '1em'
dst['qrposition'] = POSITIONS.includes(src.qrposition) ? src.qrposition : 'bottom right'
dst['qrtext'] = src.qrtext ? src.qrtext : caller
} | javascript | {
"resource": ""
} |
q35610 | convertData2Hexd | train | function convertData2Hexd (data) {
if (!isHexString(data)) {
var hex = ''
for (var i = 0; i < data.length; i++) {
hex += data.charCodeAt(i).toString(16)
}
return '0x' + hex
}
return data
} | javascript | {
"resource": ""
} |
q35611 | augmenter | train | function augmenter(object, subject, hookCb)
{
var unaugment, originalCb = object[subject];
unaugment = function()
{
// return everything back to normal
object[subject] = originalCb;
};
object[subject] = function()
{
var args = Array.prototype.slice.call(arguments)
, result = originalCb.apply(this, args)
;
// revert callback augmentation
unaugment();
// with everything out of the way
// invoke custom hook
return hookCb.call(this, [result].concat(args));
};
return unaugment;
} | javascript | {
"resource": ""
} |
q35612 | step | train | function step() {
var f = script.shift();
if(f) {
f(stack, step);
}
else {
return cb(null, stack.pop());
}
} | javascript | {
"resource": ""
} |
q35613 | train | function(ciphertext, key, iv, encoding) {
var binary, bytes, hex;
if (encoding == null) {
encoding = "buffer";
}
iv = this.toBuffer(iv);
key = this.toBuffer(key);
ciphertext = this.toBuffer(ciphertext);
binary = Gibberish.rawDecrypt(ciphertext, key, iv, true);
hex = this.bin2hex(binary);
if (encoding === 'hex') {
return hex;
}
bytes = Gibberish.h2a(hex);
if (encoding === 'base64') {
return Gibberish.Base64.encode(bytes);
}
if (encoding === "buffer") {
return bytes;
} else {
throw new Error("Encoding now supported");
}
} | javascript | {
"resource": ""
} | |
q35614 | train | function(password, salt, iterations, keysize) {
var bits, hmac, self;
if (iterations == null) {
iterations = 10000;
}
if (keysize == null) {
keysize = 512;
}
self = this;
hmac = (function() {
function hmac(key) {
this.key = sjcl.codec.bytes.fromBits(key);
}
hmac.prototype.encrypt = function(sjclArray) {
var bits, byteArray, hex;
byteArray = sjcl.codec.bytes.fromBits(sjclArray);
hex = self.hmac(byteArray, this.key, keysize);
bits = sjcl.codec.hex.toBits(hex);
return bits;
};
return hmac;
})();
salt = sjcl.codec.hex.toBits(this.toHex(salt));
bits = sjcl.misc.pbkdf2(password, salt, iterations, keysize, hmac);
return sjcl.codec.hex.fromBits(bits);
} | javascript | {
"resource": ""
} | |
q35615 | train | function(data, key, keysize) {
var input, mode;
if (keysize == null) {
keysize = 512;
}
data = this.toHex(data);
key = this.toHex(key);
mode = "SHA-" + keysize;
input = new jsSHA(data, "HEX");
return input.getHMAC(key, "HEX", mode, "HEX");
} | javascript | {
"resource": ""
} | |
q35616 | train | function(data, keysize) {
var input, mode;
if (keysize == null) {
keysize = 512;
}
data = this.toHex(data);
mode = "SHA-" + keysize;
input = new jsSHA(data, "HEX");
return input.getHash(mode, "HEX");
} | javascript | {
"resource": ""
} | |
q35617 | train | function(data) {
var bytesToPad, padding;
bytesToPad = BLOCKSIZE - (data.length % BLOCKSIZE);
padding = this.randomBytes(bytesToPad);
return this.concat([padding, data]);
} | javascript | {
"resource": ""
} | |
q35618 | train | function(length) {
var array, byte, _i, _len, _results;
array = new Uint8Array(length);
window.crypto.getRandomValues(array);
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
byte = array[_i];
_results.push(byte);
}
return _results;
} | javascript | {
"resource": ""
} | |
q35619 | train | function(data, encoding) {
if (encoding == null) {
encoding = 'hex';
}
if (Array.isArray(data)) {
return data;
}
switch (encoding) {
case 'base64':
return Gibberish.base64.decode(data);
case 'hex':
return Gibberish.h2a(data);
case 'utf8':
return Gibberish.s2a(data);
default:
throw new Error("Encoding not supported");
}
} | javascript | {
"resource": ""
} | |
q35620 | train | function(hex) {
var pow, result;
result = 0;
pow = 0;
while (hex.length > 0) {
result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
hex = hex.substring(2, hex.length);
pow += 8;
}
return result;
} | javascript | {
"resource": ""
} | |
q35621 | train | function(number, pad) {
var endian, i, multiplier, padding, power, remainder, value, _i;
if (pad == null) {
pad = true;
}
power = Math.floor((Math.log(number) / Math.LN2) / 8) * 8;
multiplier = Math.pow(2, power);
value = Math.floor(number / multiplier);
remainder = number % multiplier;
endian = "";
if (remainder > 255) {
endian += this.stringifyLittleEndian(remainder, false);
} else if (power !== 0) {
endian += this.dec2hex(remainder);
}
endian += this.dec2hex(value);
if (pad) {
padding = 16 - endian.length;
for (i = _i = 0; _i < padding; i = _i += 1) {
endian += "0";
}
}
return endian;
} | javascript | {
"resource": ""
} | |
q35622 | train | function(dec) {
var hex;
hex = dec.toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
} | javascript | {
"resource": ""
} | |
q35623 | train | function(binary) {
var char, hex, _i, _len;
hex = "";
for (_i = 0, _len = binary.length; _i < _len; _i++) {
char = binary[_i];
hex += char.charCodeAt(0).toString(16).replace(/^([\dA-F])$/i, "0$1");
}
return hex;
} | javascript | {
"resource": ""
} | |
q35624 | train | function(length) {
var bytes, hex;
if (length == null) {
length = 32;
}
length /= 2;
bytes = this.randomBytes(length);
return hex = this.toHex(bytes).toUpperCase();
} | javascript | {
"resource": ""
} | |
q35625 | decorate | train | function decorate (Comp) {
var component
// instantiate classes
if (typeof Comp === 'function') {
component = new Comp()
} else {
// make sure we don't change the id on a cached component
component = Object.create(Comp)
}
// components get a new id on render,
// so we can clear the previous component cache.
component._durrutiId = String(componentIndex++)
// cache component
componentCache.push({
id: component._durrutiId,
component: component
})
return component
} | javascript | {
"resource": ""
} |
q35626 | cleanAttrNodes | train | function cleanAttrNodes ($container, includeParent) {
var nodes = [].slice.call($container.querySelectorAll(durrutiElemSelector))
if (includeParent) {
nodes.push($container)
}
nodes.forEach(($node) => {
// cache component in node
$node._durruti = getCachedComponent($node)
// clean-up data attributes
$node.removeAttribute(durrutiAttr)
})
return nodes
} | javascript | {
"resource": ""
} |
q35627 | getComponentNodes | train | function getComponentNodes ($container, traverse = true, arr = []) {
if ($container._durruti) {
arr.push($container)
}
if (traverse && $container.children) {
for (let i = 0; i < $container.children.length; i++) {
getComponentNodes($container.children[i], traverse, arr)
}
}
return arr
} | javascript | {
"resource": ""
} |
q35628 | extend | train | function extend(classDefinition, superclass, extraProperties) {
var subclassName = className(classDefinition, 'Subclass');
// Find the right classDefinition - either the one provided, a new one or the one from extraProperties.
var extraPropertiesHasConstructor = typeof extraProperties !== 'undefined' &&
extraProperties.hasOwnProperty('constructor') &&
typeof extraProperties.constructor === 'function';
if (classDefinition != null) {
if (extraPropertiesHasConstructor && classDefinition !== extraProperties.constructor) {
throw new Error(msg(ERROR_MESSAGES.TWO_CONSTRUCTORS, subclassName));
}
} else if (extraPropertiesHasConstructor) {
classDefinition = extraProperties.constructor;
} else {
classDefinition = function() {
superclass.apply(this, arguments);
};
}
// check arguments
assertArgumentOfType('function', classDefinition, ERROR_MESSAGES.SUBCLASS_NOT_CONSTRUCTOR);
assertArgumentOfType('function', superclass, ERROR_MESSAGES.SUPERCLASS_NOT_CONSTRUCTOR, subclassName);
assertNothingInObject(classDefinition.prototype, ERROR_MESSAGES.PROTOTYPE_NOT_CLEAN, subclassName);
// copy class properties
for (var staticPropertyName in superclass) {
if (superclass.hasOwnProperty(staticPropertyName)) {
// this is because we shouldn't copy nonenumerables, but removing enumerability isn't shimmable in ie8.
// We need to make sure we don't inadvertently copy across any of the 'internal' fields we are using to
// keep track of things.
if (internalUseNames.indexOf(staticPropertyName) >= 0) {
continue;
}
classDefinition[staticPropertyName] = superclass[staticPropertyName];
}
}
// create the superclass property on the subclass constructor
Object.defineProperty(classDefinition, 'superclass', { enumerable: false, value: superclass });
// create the prototype with a constructor function.
classDefinition.prototype = Object.create(superclass.prototype, {
'constructor': { enumerable: false, value: classDefinition }
});
// copy everything from extra properties.
if (extraProperties != null) {
for (var property in extraProperties) {
if (extraProperties.hasOwnProperty(property) && property !== 'constructor') {
classDefinition.prototype[property] = extraProperties[property];
}
}
}
// this is purely to work around a bad ie8 shim, when ie8 is no longer needed it can be deleted.
if (classDefinition.prototype.hasOwnProperty('__proto__')) {
delete classDefinition.prototype['__proto__'];
}
clearAssignableCache(classDefinition, superclass);
return classDefinition;
} | javascript | {
"resource": ""
} |
q35629 | mixin | train | function mixin(target, Mix) {
assertArgumentOfType('function', target, ERROR_MESSAGES.NOT_CONSTRUCTOR, 'Target', 'mixin');
Mix = toFunction(
Mix,
new TypeError(
msg(
ERROR_MESSAGES.WRONG_TYPE,
'Mix',
'mixin',
'non-null object or function',
Mix === null ? 'null' : typeof Mix
)
)
);
var targetPrototype = target.prototype, mixinProperties = Mix.prototype, resultingProperties = {};
var mixins = nonenum(target, '__multiparents__', []);
var myMixId = mixins.length;
for (var property in mixinProperties) {
// property might spuriously be 'constructor' if you are in ie8 and using a shim.
if (typeof mixinProperties[property] === 'function' && property !== 'constructor') {
if (property in targetPrototype === false) {
resultingProperties[property] = getSandboxedFunction(myMixId, Mix, mixinProperties[property]);
} else if (targetPrototype[property]['__original__'] !== mixinProperties[property]) {
throw new Error(
msg(
ERROR_MESSAGES.PROPERTY_ALREADY_PRESENT,
property,
className(Mix, 'mixin'),
className(target, 'target')
)
);
}
} // we only mixin functions
}
copy(resultingProperties, targetPrototype);
mixins.push(Mix);
clearAssignableCache(target, Mix);
return target;
} | javascript | {
"resource": ""
} |
q35630 | inherit | train | function inherit(target, parent) {
assertArgumentOfType('function', target, ERROR_MESSAGES.NOT_CONSTRUCTOR, 'Target', 'inherit');
parent = toFunction(
parent,
new TypeError(
msg(
ERROR_MESSAGES.WRONG_TYPE,
'Parent',
'inherit',
'non-null object or function',
parent === null ? 'null' : typeof parent
)
)
);
if (classIsA(target, parent)) {
return target;
}
var resultingProperties = {};
var targetPrototype = target.prototype;
for (var propertyName in parent.prototype) {
// These properties should be nonenumerable in modern browsers, but shims might create them in ie8.
if (propertyName === 'constructor' || propertyName === '__proto__' || propertyName === 'toString' || propertyName.match(/^Symbol\(__proto__\)/)) {
continue;
}
var notInTarget = targetPrototype[propertyName] === undefined;
var parentHasNewerImplementation = notInTarget || isOverriderOf(propertyName, parent, target);
if (parentHasNewerImplementation) {
resultingProperties[propertyName] = parent.prototype[propertyName];
} else {
var areTheSame = targetPrototype[propertyName] === parent.prototype[propertyName];
var targetIsUpToDate = areTheSame || isOverriderOf(propertyName, target, parent);
if (targetIsUpToDate === false) {
// target is not up to date, but we can't bring it up to date.
throw new Error(
msg(
ERROR_MESSAGES.ALREADY_PRESENT,
propertyName,
className(parent, 'parent'),
className(target, 'target')
)
);
}
// otherwise we don't need to do anything.
}
}
copy(resultingProperties, targetPrototype);
var multiparents = nonenum(target, '__multiparents__', []);
multiparents.push(parent);
clearAssignableCache(target, parent);
return target;
} | javascript | {
"resource": ""
} |
q35631 | implement | train | function implement(classDefinition, protocol) {
doImplement(classDefinition, protocol);
setTimeout(function() {
assertHasImplemented(classDefinition, protocol);
}, 0);
return classDefinition;
} | javascript | {
"resource": ""
} |
q35632 | hasImplemented | train | function hasImplemented(classDefinition, protocol) {
doImplement(classDefinition, protocol);
assertHasImplemented(classDefinition, protocol);
return classDefinition;
} | javascript | {
"resource": ""
} |
q35633 | isA | train | function isA(instance, parent) {
if(instance == null) {
assertArgumentNotNullOrUndefined(instance, ERROR_MESSAGES.NULL, 'Object', 'isA');
}
// sneaky edge case where we're checking against an object literal we've mixed in or against a prototype of
// something.
if (typeof parent === 'object' && parent.hasOwnProperty('constructor')) {
parent = parent.constructor;
}
if((instance.constructor === parent) || (instance instanceof parent)) {
return true;
}
return classIsA(instance.constructor, parent);
} | javascript | {
"resource": ""
} |
q35634 | classFulfills | train | function classFulfills(classDefinition, protocol) {
assertArgumentNotNullOrUndefined(classDefinition, ERROR_MESSAGES.NULL, 'Class', 'classFulfills');
assertArgumentNotNullOrUndefined(protocol, ERROR_MESSAGES.NULL, 'Protocol', 'classFulfills');
return fulfills(classDefinition.prototype, protocol);
} | javascript | {
"resource": ""
} |
q35635 | nonenum | train | function nonenum(object, propertyName, defaultValue) {
var value = object[propertyName];
if (typeof value === 'undefined') {
value = defaultValue;
Object.defineProperty(object, propertyName, {
enumerable: false,
value: value
});
}
return value;
} | javascript | {
"resource": ""
} |
q35636 | toFunction | train | function toFunction(obj, couldNotCastError) {
if (obj == null) {
throw couldNotCastError;
}
var result;
if (typeof obj === 'object') {
if (obj.hasOwnProperty('constructor')) {
if (obj.constructor.prototype !== obj) {
throw couldNotCastError;
}
result = obj.constructor;
} else {
var EmptyInitialiser = function() {};
EmptyInitialiser.prototype = obj;
Object.defineProperty(obj, 'constructor', {
enumerable: false, value: EmptyInitialiser
});
result = EmptyInitialiser;
}
} else if (typeof obj === 'function') {
result = obj;
} else {
throw couldNotCastError;
}
return result;
} | javascript | {
"resource": ""
} |
q35637 | missingAttributes | train | function missingAttributes(classdef, protocol) {
var result = [], obj = classdef.prototype, requirement = protocol.prototype;
var item;
for (item in requirement) {
if (typeof obj[item] !== typeof requirement[item]) {
result.push(item);
}
}
for (item in protocol) {
var protocolItemType = typeof protocol[item];
if (protocol.hasOwnProperty(item) && protocolItemType === 'function' && typeof classdef[item] !== protocolItemType) {
// If we're in ie8, our internal variables won't be nonenumerable, so we include a check for that here.
if (internalUseNames.indexOf(item) < 0) {
result.push(item + ' (class method)');
}
}
}
return result;
} | javascript | {
"resource": ""
} |
q35638 | makeMethod | train | function makeMethod(func) {
return function() {
var args = [this].concat(slice.call(arguments));
return func.apply(null, args);
};
} | javascript | {
"resource": ""
} |
q35639 | getSandboxedFunction | train | function getSandboxedFunction(myMixId, Mix, func) {
var result = function() {
var mixInstances = nonenum(this, '__multiparentInstances__', []);
var mixInstance = mixInstances[myMixId];
if (mixInstance == null) {
if (typeof Mix === 'function') {
mixInstance = new Mix();
} else {
mixInstance = Object.create(Mix);
}
// could add a nonenum pointer to __this__ or something if we wanted to allow escape from the sandbox.
mixInstances[myMixId] = mixInstance;
}
return func.apply(mixInstance, arguments);
};
nonenum(result, '__original__', func);
nonenum(result, '__source__', Mix);
return result;
} | javascript | {
"resource": ""
} |
q35640 | bnToBuffer | train | function bnToBuffer( bn ) {
var hex = bn.toString( 16 )
hex = hex.length % 2 === 1 ? '0' + hex : hex
return Buffer.from( hex, 'hex' )
} | javascript | {
"resource": ""
} |
q35641 | extract | train | function extract( line, from, to ) {
return line.substring( from, to )
.replace( /^\s+|\s+$/g, '' )
} | javascript | {
"resource": ""
} |
q35642 | getCustomRepository | train | function getCustomRepository(RepositoryClass, knex, entityModel) {
validate.inheritsFrom(
RepositoryClass,
EntityRepository,
'Custom repository class must inherit from EntityRepository'
);
return memoizedGetCustomRepository(...arguments);
} | javascript | {
"resource": ""
} |
q35643 | FixedAgent | train | function FixedAgent(app, options) {
if (!(this instanceof FixedAgent)) {
return new FixedAgent(app, options);
}
Agent.call(this, app, options);
} | javascript | {
"resource": ""
} |
q35644 | fixedSaveCookies | train | function fixedSaveCookies(res) {
const cookies = res.headers['set-cookie'];
if (cookies) {
const fixedCookies = cookies.reduce(
(cookies, cookie) => cookies.concat(cookie.split(/,(?!\s)/)),
[]
);
this.jar.setCookies(fixedCookies);
}
} | javascript | {
"resource": ""
} |
q35645 | writeFile | train | function writeFile(fs, p, content, method, cb) {
fs.metadata(p)
.then(function(metadata) {
if (metadata.is_dir) {
throw fs.error('EISDIR');
}
}, function(e) {
if (e.code === 'ENOENT') {
var parent = path.dirname(p);
return this.mkdir(parent);
} else {
throw e;
}
})
.then(function() {
return this._promise(method, p, content);
})
.done(cb, cb);
} | javascript | {
"resource": ""
} |
q35646 | copy | train | function copy(el, text) {
var result, lastText;
if (text) {
lastText = el.value;
el.value = text;
} else {
text = el.value;
}
el.value = multiLineTrim(text);
try {
el.select();
result = document.execCommand('copy');
} catch (err) {
result = false;
} finally {
if (lastText !== undefined) {
el.value = lastText;
}
el.blur();
}
return result;
} | javascript | {
"resource": ""
} |
q35647 | update | train | function update(v, i, params, {oldValue}) {
switch (i) {
case 'children': _unobserveChildren(oldValue); _observeChildren(v); break;
case 'attrs': _unobserveAttrs (oldValue); _observeAttrs (v); break;
}
} | javascript | {
"resource": ""
} |
q35648 | report | train | function report(type, state, params)
{
var reporter = defaultReporter;
// get rest of arguments
params = Array.prototype.slice.call(arguments, 1);
// `init` and `done` types don't have command associated with them
if (['init', 'done'].indexOf(type) == -1)
{
// second (1) position is for command
// if command present get string representation of it
params[1] = stringifyCommand(state, params[1]);
}
if (state && state.options && state.options.reporter)
{
reporter = state.options.reporter;
}
reporter[type].apply(null, params);
} | javascript | {
"resource": ""
} |
q35649 | stringifyCommand | train | function stringifyCommand(state, command)
{
var name;
if (typeof command == 'function')
{
name = typeof command.commandDescription == 'function'
? command.commandDescription(state)
: Function.prototype.toString.call(command)
;
// truncate long functions
name = name.split('\n');
// remove inline comments
name = name.filter((line) => !line.match(/^\s*\/\//));
name = name
.map((line) => line.replace(/^([^'"]*)\s*\/\/.*$/, '$1')) // remove end of line comments
.map((line) => line.trim()) // remove extra space
;
if (name.length > 6)
{
// get side lines
name.splice(3, name.length - 5);
// join first and last lines
name = [name.slice(0, name.length - 2).join(' '), name.slice(-2).join(' ')].join(' ... ');
}
else
{
name = name.join(' ');
}
}
else if (Array.isArray(command))
{
name = '[' + command.join(', ') + ']';
}
else if (typeOf(command) == 'object')
{
name = JSON.stringify(command);
}
else
{
name = '' + command;
}
return name;
} | javascript | {
"resource": ""
} |
q35650 | train | function() {
if (this.parent) {
var newListItem = document.createElement(CHILD_TAG);
if (this.notesEl) {
newListItem.appendChild(this.notesEl);
}
if (!this.keep) {
var el = this.templates.get('removeButton');
el.addEventListener('click', this.remove.bind(this));
newListItem.appendChild(el);
}
newListItem.appendChild(this.el);
this.parent.el.querySelector(CHILDREN_TAG).appendChild(newListItem);
}
} | javascript | {
"resource": ""
} | |
q35651 | parseHmtxTable | train | function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) {
var p, i, glyph, advanceWidth, leftSideBearing;
p = new parse.Parser(data, start);
for (i = 0; i < numGlyphs; i += 1) {
// If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
if (i < numMetrics) {
advanceWidth = p.parseUShort();
leftSideBearing = p.parseShort();
}
glyph = glyphs[i];
glyph.advanceWidth = advanceWidth;
glyph.leftSideBearing = leftSideBearing;
}
} | javascript | {
"resource": ""
} |
q35652 | iterator | train | function iterator(state, tasks, callback)
{
var keys
, tasksLeft = tasks.length
, task = tasks.shift()
;
if (tasksLeft === 0)
{
return callback(null, state);
}
// init current task reference
state._currentTask = {waiters: {}};
if (typeOf(task) == 'object')
{
// update state with new options
// to make it available for all the subcommands
if (typeOf(task.options) == 'object')
{
state.options = extend(state.options || {}, task.options);
// no need to process it further
delete task.options;
}
// generate list of properties to update
keys = Object.keys(task);
}
// convert non-array and non-object elements
// into single element arrays
if (typeof task != 'object')
{
task = [task];
}
execute(state, task, keys, function(err, modifiedState)
{
// reset current task
// if it's error and modified state
// isn't provided, use context
(modifiedState || state)._currentTask = undefined; // eslint-disable-line no-undefined
if (err) return callback(err);
// proceed to the next element
iterator(modifiedState, tasks, callback);
});
} | javascript | {
"resource": ""
} |
q35653 | execute | train | function execute(state, task, keys, callback)
{
var key
, control
, assignment = 'ASSIGNMENT'
// get list of commands left for this iteration
, commandsLeft = (keys || task).length
, command = (keys || task).shift()
// job id within given task
, jobId = commandsLeft
;
// we're done here
// wait for all the commands
if (commandsLeft === 0)
{
// if it's last one proceed to callback
if (Object.keys(state._currentTask.waiters).length === 0)
{
callback(null, state); // eslint-disable-line callback-return
}
return;
}
if (keys)
{
key = command;
command = task[command];
// consider anything but strings, functions and arrays as direct state modifiers
// there is no one right way to merge arrays, so leave it for custom functions
if (['array', 'function', 'string'].indexOf(typeOf(command)) == -1)
{
report('start', state, assignment);
// do shallow merge, until we needed otherwise
state[key] = typeOf(command) == 'object' ? extend(state[key], command) : command;
report('store', state, assignment, key);
report('output', state, assignment, command);
execute(state, task, keys, callback);
return;
}
}
report('start', state, command);
// run the command and get terminator reference
// if it'd need to be stopped
control = run(clone(command), state, function(err, data)
{
// clean up waiters
delete state._currentTask.waiters[jobId];
if (err)
{
report('error', state, command, err);
cleanWaiters(state);
return callback(err);
}
// modify state if requested
if (key)
{
state[key] = data;
report('store', state, command, key);
}
report('output', state, command, data);
// if it's last one proceed to callback
if (Object.keys(state._currentTask.waiters).length === 0)
{
callback(null, state); // eslint-disable-line callback-return
return;
}
});
// if no control object returned
// means run task was prematurely terminated
// do not proceed
if (!control)
{
return;
}
// keep reference to command related elements
state._currentTask.waiters[jobId] =
{
command : command,
callback : control.callback,
terminator : control.terminator
};
// proceed to the next command within task
execute(state, task, keys, callback);
} | javascript | {
"resource": ""
} |
q35654 | cleanWaiters | train | function cleanWaiters(state)
{
var list = state._currentTask.waiters;
Object.keys(list).forEach(function(job)
{
// prevent callback from execution
// by modifying up `once`'s `called` property
list[job].callback.called = true;
// if called it will return false
list[job].callback.value = false;
// send termination signal to the job
list[job].terminator();
// report termination
report('killed', state, list[job].command);
delete list[job];
});
} | javascript | {
"resource": ""
} |
q35655 | recallInMap | train | function recallInMap(resMap, absPath) {
if (resMap.has(absPath) && resMap.get(absPath).size > 0) {
for (let keyPath of resMap.get(absPath)) {
//update first
forceUpdate(keyPath)
recallInMap(resMap, keyPath)
}
}
} | javascript | {
"resource": ""
} |
q35656 | handle | train | function handle(event) {
if(event.data.type == 1 || event.data.type == 3 || event.data.type == 7){
facade.models.login().findCreateFind({
where:{
uid: event.user.id,
type: event.data.type,
},
defaults: {
uid: event.user.id,
type: event.data.type,
time: event.data.time
},
});
}
} | javascript | {
"resource": ""
} |
q35657 | get | train | function get ( keypath ) {
if ( !keypath ) return this._element.parentFragment.findContext().get( true );
var model = resolveReference( this._element.parentFragment, keypath );
return model ? model.get( true ) : undefined;
} | javascript | {
"resource": ""
} |
q35658 | add$1 | train | function add$1 ( keypath, value ) {
if ( value === undefined ) value = 1;
if ( !isNumeric( value ) ) throw new Error( 'Bad arguments' );
return set( this.ractive, build$1( this, keypath, value ).map( function ( pair ) {
var model = pair[0], val = pair[1], value = model.get();
if ( !isNumeric( val ) || !isNumeric( value ) ) throw new Error( 'Cannot add non-numeric value' );
return [ model, value + val ];
}) );
} | javascript | {
"resource": ""
} |
q35659 | train | function ( Parent, proto, options ) {
if ( !options.css ) return;
var id = uuid();
var styles = options.noCssTransform ? options.css : transformCss( options.css, id );
proto.cssId = id;
addCSS( { id: id, styles: styles } );
} | javascript | {
"resource": ""
} | |
q35660 | makeQuotedStringMatcher | train | function makeQuotedStringMatcher ( okQuote ) {
return function ( parser ) {
var literal = '"';
var done = false;
var next;
while ( !done ) {
next = ( parser.matchPattern( stringMiddlePattern ) || parser.matchPattern( escapeSequencePattern ) ||
parser.matchString( okQuote ) );
if ( next ) {
if ( next === ("\"") ) {
literal += "\\\"";
} else if ( next === ("\\'") ) {
literal += "'";
} else {
literal += next;
}
} else {
next = parser.matchPattern( lineContinuationPattern );
if ( next ) {
// convert \(newline-like) into a \u escape, which is allowed in JSON
literal += '\\u' + ( '000' + next.charCodeAt(1).toString(16) ).slice( -4 );
} else {
done = true;
}
}
}
literal += '"';
// use JSON.parse to interpret escapes
return JSON.parse( literal );
};
} | javascript | {
"resource": ""
} |
q35661 | getConditional | train | function getConditional ( parser ) {
var start, expression, ifTrue, ifFalse;
expression = readLogicalOr$1( parser );
if ( !expression ) {
return null;
}
start = parser.pos;
parser.allowWhitespace();
if ( !parser.matchString( '?' ) ) {
parser.pos = start;
return expression;
}
parser.allowWhitespace();
ifTrue = readExpression( parser );
if ( !ifTrue ) {
parser.error( expectedExpression );
}
parser.allowWhitespace();
if ( !parser.matchString( ':' ) ) {
parser.error( 'Expected ":"' );
}
parser.allowWhitespace();
ifFalse = readExpression( parser );
if ( !ifFalse ) {
parser.error( expectedExpression );
}
return {
t: CONDITIONAL,
o: [ expression, ifTrue, ifFalse ]
};
} | javascript | {
"resource": ""
} |
q35662 | truncateStack | train | function truncateStack ( stack ) {
if ( !stack ) return '';
var lines = stack.split( '\n' );
var name = Computation.name + '.getValue';
var truncated = [];
var len = lines.length;
for ( var i = 1; i < len; i += 1 ) {
var line = lines[i];
if ( ~line.indexOf( name ) ) {
return truncated.join( '\n' );
} else {
truncated.push( line );
}
}
} | javascript | {
"resource": ""
} |
q35663 | Ractive$teardown | train | function Ractive$teardown () {
if ( this.torndown ) {
warnIfDebug( 'ractive.teardown() was called on a Ractive instance that was already torn down' );
return Promise$1.resolve();
}
this.torndown = true;
this.fragment.unbind();
this.viewmodel.teardown();
this._observers.forEach( cancel );
if ( this.fragment.rendered && this.el.__ractive_instances__ ) {
removeFromArray( this.el.__ractive_instances__, this );
}
this.shouldDestroy = true;
var promise = ( this.fragment.rendered ? this.unrender() : Promise$1.resolve() );
teardownHook$1.fire( this );
return promise;
} | javascript | {
"resource": ""
} |
q35664 | train | function(test, fromEnd) {
var i;
if (typeof test !== 'function') return undefined;
if (fromEnd) {
i = this.length;
while (i--) {
if (test(this[i], i, this)) {
return this[i];
}
}
} else {
i = 0;
while (i < this.length) {
if (test(this[i], i, this)) {
return this[i];
}
i++;
}
}
return null;
} | javascript | {
"resource": ""
} | |
q35665 | train | function(count, direction) {
return direction ? this.concat(this.splice(0, count)) : this.splice(this.length - count).concat(this);
} | javascript | {
"resource": ""
} | |
q35666 | promiseWrapper | train | function promiseWrapper (resolve, reject) {
// Wait for the process to exit
process.on ("exit", (code) => {
// Did the process crash?
if (code !== 0) reject (process.stderr.textContent);
// Resolve
resolve (process.stdout.textContent);
});
// Pipe the script into stdin and end
process.stdin.write (script);
process.stdin.end ();
} | javascript | {
"resource": ""
} |
q35667 | run | train | function run(params, command, callback)
{
var job;
// decouple commands
command = clone(command);
// start command execution and get job reference
job = executioner(command, stringify(extend(this, params)), this.options || {}, callback);
// make ready to call task termination function
return partial(executioner.terminate, job);
} | javascript | {
"resource": ""
} |
q35668 | stringify | train | function stringify(origin)
{
var i, keys, prepared = {};
keys = Object.keys(origin);
i = keys.length;
while (i--)
{
// skip un-stringable things
if (typeOf(origin[keys[i]]) == 'function'
|| typeOf(origin[keys[i]]) == 'object')
{
continue;
}
// export it
prepared[keys[i]] = origin[keys[i]];
// make it shell ready
if (typeOf(prepared[keys[i]]) == 'boolean')
{
prepared[keys[i]] = prepared[keys[i]] ? '1' : '';
}
if (typeOf(prepared[keys[i]]) == 'undefined' || typeOf(prepared[keys[i]]) == 'null')
{
prepared[keys[i]] = '';
}
// convert everything else to string
prepared[keys[i]] = prepared[keys[i]].toString();
}
return prepared;
} | javascript | {
"resource": ""
} |
q35669 | allocateAndFillSyncFunctionArgs | train | function allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, userArgs) {
functionInfo.requiredArgTypes.forEach(function(type, i) {
var buf = ljTypeOps[type].allocate(userArgs[i]);
buf = ljTypeOps[type].fill(buf, userArgs[i]);
funcArgs.push(buf);
});
} | javascript | {
"resource": ""
} |
q35670 | parseAndStoreSyncFunctionArgs | train | function parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, saveObj) {
functionInfo.requiredArgTypes.forEach(function(type, i) {
var buf = funcArgs[i];
var parsedVal = ljTypeOps[type].parse(buf);
var argName = functionInfo.requiredArgNames[i];
saveObj[argName] = parsedVal;
});
} | javascript | {
"resource": ""
} |
q35671 | createSyncFunction | train | function createSyncFunction(functionName, functionInfo) {
return function syncLJMFunction() {
if(arguments.length != functionInfo.args.length) {
var errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += 'Given: ' + arguments.length + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += '.';
console.error('Error in ljm-ffi syncLJMFunction', errStr);
throw new LJMFFIError(errStr);
} else {
// Create an array that will be filled with values to call the
// LJM function with.
var funcArgs = [];
// Parse and fill the function arguments array with data.
allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, arguments);
// Execute the synchronous LJM function.
var ljmFunction = liblabjack[functionName];
var ljmError = ljmFunction.apply(this, funcArgs);
// Create an object to be returned.
var retObj = {
'ljmError': ljmError,
};
if(ljmError !== 0) {
retObj.errorInfo = modbus_map.getErrorInfo(ljmError);
}
// Fill the object being returned with data.
parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, retObj);
return retObj;
}
};
} | javascript | {
"resource": ""
} |
q35672 | createAsyncFunction | train | function createAsyncFunction(functionName, functionInfo) {
return function asyncLJMFunction() {
var userCB;
function cb(err, res) {
if(err) {
console.error('Error Reported by Async Function', functionName);
}
// Create an object to be returned.
var ljmError = res;
var retObj = {
'ljmError': ljmError,
};
if(ljmError !== 0) {
retObj.errorInfo = modbus_map.getErrorInfo(ljmError);
}
// Fill the object being returned with data.
parseAndStoreSyncFunctionArgs(functionInfo, funcArgs, retObj);
// Execute the user's callback function.
userCB(retObj);
return;
}
// Check arg-length + 1 for the callback.
if(arguments.length != (functionInfo.args.length + 1)) {
var errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += ', ' + 'callback.';
throw new LJMFFIError(errStr);
// } else if(typeof(arguments[arguments.length]) !== 'function') {
// var errStr
} else {
if(typeof(arguments[functionInfo.args.length]) !== 'function') {
userCB = function() {};
} else {
userCB = arguments[functionInfo.args.length];
}
// Create an array that will be filled with values to call the
// LJM function with.
var funcArgs = [];
// Parse and fill the function arguments array with data.
allocateAndFillSyncFunctionArgs(functionInfo, funcArgs, arguments);
// Over-write the function callback in the arguments list.
funcArgs[funcArgs.length] = cb;
// Execute the asynchronous LJM function.
var ljmFunction = liblabjack[functionName].async;
ljmFunction.apply(this, funcArgs);
return;
}
};
} | javascript | {
"resource": ""
} |
q35673 | createSafeAsyncFunction | train | function createSafeAsyncFunction(functionName, functionInfo) {
return function safeAsyncFunction() {
// Define a variable to store the error string in.
var errStr;
// Check to make sure the arguments seem to be valid.
if(arguments.length != (functionInfo.args.length + 1)) {
// Throw an error if an invalid number of arguments were found.
errStr = 'Invalid number of arguments. Should be: ';
errStr += functionInfo.args.length.toString() + '. ';
errStr += getFunctionArgNames(functionInfo).join(', ');
errStr += '.';
throw new LJMFFIError(errStr);
} else {
if(typeof(arguments[functionInfo.args.length]) !== 'function') {
// Throw an error if the last argument is not a function. This
// is mandatory for all async function calls.
errStr = 'Invalid argument; last argument must be a function ';
errStr += 'but was not. Function name: \'';
errStr += functionName;
errStr += '\'.';
throw new LJMFFIError(errStr);
}
// Get a reference to the LJM function being called.
var ljmFunction = ffi_liblabjack[functionName].async;
// Check to make sure that the function being called has been
// defined.
if(typeof(ljmFunction) === 'function') {
// Define a variable to store the ljmError value in.
var ljmError;
try {
// Execute the synchronous LJM function.
ljmError = ljmFunction.apply(this, arguments);
} catch(err) {
// Throw an error if the function being called doesn't exist.
errStr = 'The function: ';
errStr += functionName;
errStr += ' is not implemented by the installed version of LJM.';
throw new LJMFFIError(errStr);
}
// Return the ljmError
return ljmError;
} else {
// Throw an error if the function being called doesn't exist.
errStr = 'The function: ';
errStr += functionName;
errStr += ' is not implemented by the installed version of LJM.';
throw new LJMFFIError(errStr);
}
}
};
} | javascript | {
"resource": ""
} |
q35674 | makeUnique | train | function makeUnique (boxes = []) {
// boxes converted to string, for easier comparison
const ref = [];
const result = [];
boxes.forEach((item) => {
const item_string = item.toString();
if (ref.indexOf(item_string) === -1) {
ref.push(item_string);
result.push(item);
}
});
return result;
} | javascript | {
"resource": ""
} |
q35675 | train | function(src) {
var _deferred = $q.defer();
// Instance
var _loadable = {
src: src,
// Loading completion flag
isComplete: false,
promise: _deferred.promise,
// TODO switch to $document
$element: document.createElement('script')
};
// Build DOM element
_loadable.$element.src = src;
_loadable.$element.type = 'text/javascript';
_loadable.$element.async = false;
_head.insertBefore(_loadable.$element, _head.firstChild);
// Mark loading in progress
_loadingList.push(_loadable);
// Completion
_loadable.$element.onload = _loadable.$element.onreadystatechange = function() {
if(!_loadable.isComplete && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
_loadable.isComplete = true;
_loadable.$element.onload = _loadable.$element.onreadystatechange = null;
if(_head && _loadable.$element.parentNode) {
_head.removeChild(_loadable.$element);
}
// Mark complete
var i = _loadingList.indexOf(_loadable);
if(i !== -1) {
_loadingList.splice(i, 1);
}
_completedList.push(_loadable);
_deferred.resolve(_loadable);
}
};
return _loadable;
} | javascript | {
"resource": ""
} | |
q35676 | train | function(src) {
var loadable;
// Valid state name required
if(!src || src === '') {
var error;
error = new Error('Loadable requires a valid source.');
error.code = 'invalidname';
throw error;
}
// Already exists
if(_loadableHash[src]) {
loadable = _loadableHash[src];
// Create new
} else {
// Create new instance
loadable = new _Loadable(src);
_loadableHash[src] = loadable;
// Broadcast creation, progress
$rootScope.$broadcast('$loadableCreated', loadable);
$rootScope.$broadcast('$loadableProgress', _getProgress());
// Completion
loadable.promise.then(function() {
// Broadcast complete
$rootScope.$broadcast('$loadableProgress', _getProgress());
if(_loadingList.length === 0) {
$rootScope.$broadcast('$loadableComplete', loadable);
}
});
}
return loadable;
} | javascript | {
"resource": ""
} | |
q35677 | train | function() {
var deferred = $q.defer();
var current = $state.current();
// Evaluate
if(current) {
var sources = (typeof current.load === 'string' ? [current.load] : current.load) || [];
// Get promises
$q.all(sources
.map(function(src) {
return _createLoadable(src);
})
.filter(function(loadable) {
return !loadable.isComplete;
})
.map(function(loadable) {
return loadable.promise;
})
)
.then(function() {
deferred.resolve();
}, function(err) {
$rootScope.$broadcast('$loadableError', err);
deferred.reject(err);
});
// No state
} else {
deferred.resolve();
}
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q35678 | postToFirstAvailableServer | train | function postToFirstAvailableServer (destinationNode, signallingServers, path, message) {
return new Promise(function (resolve, reject) {
if (signallingServers.length === 0) {
reject(new Utils.UnreachableError(createUnreachableErrorMessage(destinationNode)));
}
else {
//noinspection JSCheckFunctionSignatures
httpRequestService.post(url.resolve(signallingServers[0].signallingApiBase, path), message)
.then(resolve)
.catch(function (error) {
logger.warn("An error occurred sending signalling message using " + signallingServers[0].signallingApiBase + " trying next signalling server", error);
postToFirstAvailableServer(destinationNode, signallingServers.slice(1), path, message).then(resolve, reject);
});
}
});
} | javascript | {
"resource": ""
} |
q35679 | pad | train | function pad( str, chr, n ) {
return (chr.repeat( Math.max( n - str.length, 0 ) ) + str).substr(-n)
} | javascript | {
"resource": ""
} |
q35680 | train | function() {
var block = this.rng.random() * this.discreteValues << 0
return pad( block.toString( this.base ), this.fill, this.blockSize )
} | javascript | {
"resource": ""
} | |
q35681 | train | function() {
return this.timestamp().substr( -2 ) +
this.count().toString( this.base ).substr( -4 ) +
this._fingerprint[0] +
this._fingerprint[ this._fingerprint.length - 1 ] +
this.randomBlock().substr( -2 )
} | javascript | {
"resource": ""
} | |
q35682 | findPackage | train | function findPackage(config, match) {
var map = getPackageMap(config.relativeTo, config.packages);
return _.reduce(map, function (prev, pkg) {
// Resolve using last priority. Priority:
// 1. package is a file
// 2. package granularity (done by file depth)
if (pkg.regexp.test(match) && (!prev || (pkg.dir && prev.dir && pkg.depth >= pkg.depth) || pkg.file)) {
return pkg;
} else {
return prev;
}
}, null);
} | javascript | {
"resource": ""
} |
q35683 | matchDirective | train | function matchDirective($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
scope.$watch(function () {
return [scope.$eval(attrs.match), ctrl.$viewValue];
}, function (values) {
ctrl.$setValidity('match', values[0] === values[1]);
}, true);
}
};
} | javascript | {
"resource": ""
} |
q35684 | Base | train | function Base(client, endpoint) {
var base = this;
/**
* Get a list of all records for the current API
*
* @method list
* @param {Object} query - OPTIONAL querystring params
* @param {Function} callback
*/
base.list = function() {
return function(query, callback) {
var q = '';
if (query && 'function' === typeof callback)
q = '?' + querystring.stringify(query);
client.exec({
path: '/' + endpoint + q
}, arguments[arguments.length - 1]);
};
};
/**
* Get a single record by its key
*
* @method fetch
* @param {Integer|String} key
* @param {Function} callback
*/
base.fetch = function() {
return function(key, callback) {
client.exec({
path: '/' + endpoint + '/' + key
}, callback);
};
};
/**
* Create a new record
*
* @method create
* @param {Object|String} data
* @param {Function} callback
*/
base.create = function() {
return function(data, callback) {
client.exec({
method: 'POST',
path: '/' + endpoint,
body: data
}, callback);
};
};
/**
* Update a record
*
* @method update
* @param {Integer|String} key
* @param {Object|String} data
* @param {Function} callback
*/
base.update = function() {
return function(key, data, callback) {
client.exec({
method: 'PUT',
path: '/' + endpoint + '/' + key,
body: data
}, callback);
};
};
/**
* Remove a record
*
* @method remove
* @param {Integer|String} key
* @param {Function} callback
*/
base.remove = function() {
return function(key, callback) {
client.exec({
method: 'DELETE',
path: '/' + endpoint + '/' + key
}, callback);
};
};
/**
* Do requested action
*
* @method doAction
* @param {Integer|String} key
* @param {String} action
* @param {Object} body
* @param {Function} callback
*/
base.doAction = function() {
return function(key, action, body, callback) {
body = body || {};
body.type = action;
client.exec({
method: 'POST',
path: '/' + endpoint + '/' + key + '/actions',
body: body
}, callback);
};
};
} | javascript | {
"resource": ""
} |
q35685 | train | function(config) {
this.events = new EventEmitter();
this.config = config || {};
// Allow someone to change the complete event label.
if (!this.config.complete) {
this.config.complete = '__complete';
}
debug('Chain created with the following configuration: ' + JSON.stringify(this.config));
} | javascript | {
"resource": ""
} | |
q35686 | _validateIsModel | train | function _validateIsModel(model) {
let parentClass = Object.getPrototypeOf(model);
while (parentClass.name !== 'Model' && parentClass.name !== '') {
parentClass = Object.getPrototypeOf(parentClass);
}
validationUtils.booleanTrue(
parentClass.name === 'Model',
'Parameter is not an Objection.js model'
);
} | javascript | {
"resource": ""
} |
q35687 | doNativeWasm | train | function doNativeWasm(global, env, providedBuffer) {
if (typeof WebAssembly !== 'object') {
err('no native wasm support detected');
return false;
}
// prepare memory import
if (!(Module['wasmMemory'] instanceof WebAssembly.Memory)) {
err('no native wasm Memory in use');
return false;
}
env['memory'] = Module['wasmMemory'];
// Load the wasm module and create an instance of using native support in the JS engine.
info['global'] = {
'NaN': NaN,
'Infinity': Infinity
};
info['global.Math'] = Math;
info['env'] = env;
// handle a generated wasm instance, receiving its exports and
// performing other necessary setup
function receiveInstance(instance, module) {
exports = instance.exports;
if (exports.memory) mergeMemory(exports.memory);
Module['asm'] = exports;
Module["usingWasm"] = true;
removeRunDependency('wasm-instantiate');
}
addRunDependency('wasm-instantiate');
// User shell pages can write their own Module.instantiateWasm = function(imports, successCallback) callback
// to manually instantiate the Wasm module themselves. This allows pages to run the instantiation parallel
// to any other async startup actions they are performing.
if (Module['instantiateWasm']) {
try {
return Module['instantiateWasm'](info, receiveInstance);
} catch(e) {
err('Module.instantiateWasm callback failed with error: ' + e);
return false;
}
}
function receiveInstantiatedSource(output) {
// 'output' is a WebAssemblyInstantiatedSource object which has both the module and instance.
// receiveInstance() will swap in the exports (to Module.asm) so they can be called
receiveInstance(output['instance'], output['module']);
}
function instantiateArrayBuffer(receiver) {
getBinaryPromise().then(function(binary) {
return WebAssembly.instantiate(binary, info);
}).then(receiver).catch(function(reason) {
err('failed to asynchronously prepare wasm: ' + reason);
abort(reason);
});
}
// Prefer streaming instantiation if available.
if (!Module['wasmBinary'] &&
typeof WebAssembly.instantiateStreaming === 'function' &&
!isDataURI(wasmBinaryFile) &&
typeof fetch === 'function') {
WebAssembly.instantiateStreaming(fetch(wasmBinaryFile, { credentials: 'same-origin' }), info)
.then(receiveInstantiatedSource)
.catch(function(reason) {
// We expect the most common failure cause to be a bad MIME type for the binary,
// in which case falling back to ArrayBuffer instantiation should work.
err('wasm streaming compile failed: ' + reason);
err('falling back to ArrayBuffer instantiation');
instantiateArrayBuffer(receiveInstantiatedSource);
});
} else {
instantiateArrayBuffer(receiveInstantiatedSource);
}
return {}; // no exports yet; we'll fill them in later
} | javascript | {
"resource": ""
} |
q35688 | train | function(event) {
var e = event || window.event;
JSEvents.fillMouseEventData(JSEvents.wheelEvent, e, target);
HEAPF64[(((JSEvents.wheelEvent)+(72))>>3)]=e["deltaX"];
HEAPF64[(((JSEvents.wheelEvent)+(80))>>3)]=e["deltaY"];
HEAPF64[(((JSEvents.wheelEvent)+(88))>>3)]=e["deltaZ"];
HEAP32[(((JSEvents.wheelEvent)+(96))>>2)]=e["deltaMode"];
var shouldCancel = Module['dynCall_iiii'](callbackfunc, eventTypeId, JSEvents.wheelEvent, userData);
if (shouldCancel) {
e.preventDefault();
}
} | javascript | {
"resource": ""
} | |
q35689 | get | train | function get(city, _options) {
extend(options, _options, {city: city});
getWeather = $q.when(getWeather || angular.copy(getCache()) || getWeatherFromServer(city));
// Clear the promise cached, after resolve or reject the promise. Permit access to the cache data, when
// the promise excecution is done (finally).
getWeather.finally(function getWeatherFinally() {
getWeather = undefined;
});
return getWeather;
} | javascript | {
"resource": ""
} |
q35690 | getWeatherFromServer | train | function getWeatherFromServer(city) {
var deferred = $q.defer();
var url = openweatherEndpoint;
var params = {
q: city,
units: 'metric',
APPID: Config.openweather.apikey || ''
};
$http({
method: 'GET',
url: url,
params: params,
withoutToken: true,
cache: true
}).success(function(data) {
// Prepare the Weather object.
var weatherData = prepareWeather(data);
setCache(weatherData);
// Start refresh automatic the weather, according the interval of time.
options.refresh && startRefreshWeather();
deferred.resolve(weatherData);
});
return deferred.promise;
} | javascript | {
"resource": ""
} |
q35691 | startRefreshWeather | train | function startRefreshWeather() {
interval = $interval(getWeatherFromServer(options.city), options.delay);
localforage.setItem('aw.refreshing', true);
} | javascript | {
"resource": ""
} |
q35692 | prepareWeather | train | function prepareWeather(weatherData) {
return {
temperature: weatherData.main.temp,
icon: (angular.isDefined(weatherIcons[weatherData.weather[0].icon])) ? weatherData.weather[0].icon : weatherData.weather[0].id,
description: weatherData.weather[0].description
}
} | javascript | {
"resource": ""
} |
q35693 | func$withContext | train | function func$withContext(fn, item, i, ctx) { // eslint-disable-line max-params
return fn.call(ctx, item, i)
} | javascript | {
"resource": ""
} |
q35694 | getNeighbor | train | function getNeighbor(owner, item, dataPropertyName) {
const data = validateAttached(owner)
return obtainTrueValue(item[data[dataPropertyName]])
} | javascript | {
"resource": ""
} |
q35695 | CalendarList | train | function CalendarList(_super) {
_super(this, {
flexGrow: 1,
alignSelf: FlexLayout.AlignSelf.STRETCH,
backgroundColor: Color.GREEN,
});
this.init();
} | javascript | {
"resource": ""
} |
q35696 | validateMeta | train | function validateMeta( meta, errBuf ) {
var supportedLocales =
'ar,am,bg,bn,ca,cs,da,de,el,en,en_GB,en_US,es,es_419,et,' +
'fa,fi,fil,fr,gu,he,hi,hr,hu,id,it,ja,kn,ko,lt,lv,ml,mr,' +
'ms,nl,no,pl,pt_BR,pt_PT,ro,ru,sk,sl,sr,sv,sw,ta,te,th,' +
'tr,uk,vi,zh_CN,zh_TW'.split(','),
isFormatValid = true,
isImportsValid = true,
isDestValid = true,
isLocalesValid = true,
isDefintionsValid = true;
// `format` MUST BE a string of value: monolith|category|language
if ( typeof meta.format !== 'string' ) {
errBuf.push(
'Error (META): `format` field is not defined or in wrong format'
);
isFormatValid = false;
} else {
if ( !/^(monolith|category|language)$/.test( meta.format ) ) {
errBuf.push(
'Error (META): "' + meta.format + '" value in `format` field not supported'
);
isFormatValid = false;
} // if
} // if..else
// `imports` MUST BE defined if `format` is != monolith
if ( isFormatValid ) {
if ( meta.format === 'category' ) {
if ( typeof meta.imports !== 'string' && !Array.isArray( meta.imports ) ) {
errBuf.push(
'Error (META): when in "category" mode, `imports` field can' +
' be either a string or an array'
);
isImportsValid = false;
} // if
} else {
if ( meta.format === 'language' ) {
if ( typeof meta.imports !== 'string' ) {
errBuf.push(
'Error (META): when in "language" mode, `imports` field' +
' can be only a string pointing to a directory'
);
isImportsValid = false;
} else {
if ( meta.imports.lastIndexOf( path.sep ) !== meta.imports.length-1 ) {
errBuf.push( 'Error: (META): `imports` field is not a directory' );
isImportsValid = false;
} // if
} // if
} // if
} // if..else
} // if
// `dest` MUST BE ALWAYS defined as string pointing to a directory
if ( typeof meta.dest !== 'string' ) {
errBuf.push( 'Error (META): `dest` field MUST be a string' );
isDestValid = false;
} else {
if ( meta.dest.lastIndexOf( path.sep ) !== meta.dest.length-1 ) {
errBuf.push( 'Error (META): `dest` is not a directory' );
isDestValid = false;
} // if
} // if..else
// `locales` MUST BE ALWAYS defined as array with a minimum of one
// country code
if ( !Array.isArray( meta.locales ) ) {
errBuf.push( 'Error (META): `locales` field MUST be an array' );
isLocalesValid = false;
} else {
meta.locales.forEach( function( locale ){
if ( !~supportedLocales.indexOf( locale ) ) {
errBuf.push(
'Error (META): `locales` field\'s country-code "' +
locale + '" is not supported'
);
} // if
});
} // if..else
// `definitions` MUST BE ALWAYS defined as literal object when in
// `language` mode.
if ( meta.format === 'language' ) {
if ( typeof meta.definitions !== 'object' ) {
errBuf.push( 'Error (definitions): in `language` mode, ' +
'`definitions` field MUST be an object' );
isDefintionsValid = false;
} // if
} // if
return isFormatValid && isImportsValid && isDestValid &&
isLocalesValid && isDefintionsValid;
} | javascript | {
"resource": ""
} |
q35697 | listen | train | function listen(next) {
listenSocket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
listenSocket.on('message', function(payload, rinfo) {
var message = parseMessage(payload, rinfo);
if (message) {
if (message.id != id) {
if (message.status == "ONE") {
updateNodeList(message);
} else if (message.name != listenNameIdentifier && message.status == "NAMETAKEN") {
stop(function() {
//throw new Error('name already taken "' + name + '"');
self.emit("error", {cause: "Name already taken"});
});
}
} else {
//self.emit('error', id + " already exists in network");
throw new Error(id + ' already exits in network');
stop();
}
}
});
listenSocket.bind(function(err) {
var info = listenSocket.address();
self.port = info.port;
next(err);
});
} | javascript | {
"resource": ""
} |
q35698 | createMessage | train | function createMessage(status) {
var message = [];
message.push(broadcastIdentifier);
message.push(compabilityVersion);
message.push(netId);
message.push(id);
message.push(name);
message.push(self.port);
message.push(status);
//message.push(mode);
payloadLength = payload.length;
message.push(payloadLength + ':' + payload);
var messageString = message.join(" ");
return new Buffer(messageString);
} | javascript | {
"resource": ""
} |
q35699 | Request | train | function Request(Safe, uri, method) {
if (!this)
return new Request(Safe, uri, method);
this.Safe = Safe;
this.uri = uri;
this.method = method;
this._needAuth = false;
this._returnMeta = false;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.