_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q41500 | logger | train | function logger(options) {
DEBUG && debug('configure http logger middleware', options);
var format;
if (typeof options === 'string') {
format = options;
options = {};
} else {
format = options.format || 'combined';
delete options.format;
}
if (options.debug) {
... | javascript | {
"resource": ""
} |
q41501 | handlePeopleRetrieved | train | function handlePeopleRetrieved(state, action) {
if (action.error) {
return {
...state,
people: null,
error: getErrorDescription(action.payload)
};
}
return {
...state,
people: action.payload,
error: null
};
} | javascript | {
"resource": ""
} |
q41502 | train | function(element, options) {
var event;
options = options || {};
options.canBubble = ('false' === options.canBubble ? false : true);
options.cancelable = ('false' === options.cancelable ? false : true);
options.view = options.view || window;
try {
event = new Event(options.type, {
... | javascript | {
"resource": ""
} | |
q41503 | bind | train | function bind(method, path, controller, action) {
let handler = controllerRegistry[controller] && controllerRegistry[controller][action]
if (!handler) {
console.warn(`can't bind route ${ path } to unknown action ${ controller }.${ action }`)
return
}
const policyName = LocalUtil.getPolicyNa... | javascript | {
"resource": ""
} |
q41504 | verify | train | function verify(pattern, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
if (typeof callback !== 'function') {
errs.type('expect `callback` to be function');
}
if (typeof pattern !== 'string') {
errs.type('expect `pattern` to be string');
}
if (!regex.test... | javascript | {
"resource": ""
} |
q41505 | updateCurrentInput | train | function updateCurrentInput(input) {
if (input !== currentInput) {
body.classList.remove(`current-input-${currentInput}`);
body.classList.add(`current-input-${input}`);
currentInput = input;
}
} | javascript | {
"resource": ""
} |
q41506 | ArrayindexOf | train | function ArrayindexOf(thing) {
var index = 0;
var count = this.length;
while (index < count) {
if (this[index] === thing) return index
index = index + 1
}
return -1
} | javascript | {
"resource": ""
} |
q41507 | int64 | train | function int64(name) {
return joi.alternatives().meta({ cql: true, type: name }).try(
// a string that represents a number that is larger than JavaScript can handle
joi.string().regex(/^\-?\d{1,19}$/m),
// any integer that can be represented in JavaScript
joi.number().integer()
);
} | javascript | {
"resource": ""
} |
q41508 | decimal | train | function decimal(name) {
return joi.alternatives().meta({ cql: true, type: name }).try(
// a string that represents a number that is larger than JavaScript can handle
joi.string().regex(/^\-?\d+(\.\d+)?$/m),
// any number that can be represented in JavaScript
joi.number()
);
} | javascript | {
"resource": ""
} |
q41509 | train | function (keyType, valueType) {
var meta = findMeta(valueType);
return joi.object().meta({
cql: true,
type: 'map',
mapType: ['text', meta.type],
serialize: convertMap(meta.serialize),
deserialize: convertMap(meta.deserialize)
}).pattern(/[\-\w]+/, valueType);
} | javascript | {
"resource": ""
} | |
q41510 | train | function (type) {
var meta = findMeta(type);
var set = joi.array().sparse(false).unique().items(type);
return joi.alternatives().meta({
cql: true,
type: 'set',
setType: meta.type,
serialize: convertArray(meta.serialize),
deserialize: convertArray(meta.deserialize)
}).try(se... | javascript | {
"resource": ""
} | |
q41511 | train | function (type) {
var meta = findMeta(type);
var list = joi.array().sparse(false).items(type);
return joi.alternatives().meta({
cql: true,
type: 'list',
listType: meta.type,
serialize: convertArray(meta.serialize),
deserialize: convertArray(meta.deserialize)
}).try(list, jo... | javascript | {
"resource": ""
} | |
q41512 | train | function (validator, options) {
var when = options.default;
var fn = function (context, config) {
if ((when === config.context.operation) ||
(when === 'update' && ['create', 'update'].indexOf(config.context.operation) > -1)
) {
return new Date().toISOString();
}
return ... | javascript | {
"resource": ""
} | |
q41513 | train | function (validator, options) {
var fn = function (context, config) {
if (config.context.operation === 'create')
return options.default === 'empty' ? '00000000-0000-0000-0000-000000000000' : uuid[options.default]();
return undef;
};
fn.isJoi = true;
return validator.default(fn);
} | javascript | {
"resource": ""
} | |
q41514 | defaultify | train | function defaultify(type, validator, options) {
return options && options.default ? defaults[type](validator, options) : validator;
} | javascript | {
"resource": ""
} |
q41515 | findMeta | train | function findMeta(any, key) {
key = key || 'cql';
var meta = (any.describe().meta || []).filter(function (m) {
return key in m;
});
return meta[meta.length - 1];
} | javascript | {
"resource": ""
} |
q41516 | convertToJsonOnValidate | train | function convertToJsonOnValidate(any) {
var validate = any._validate;
any._validate = function () {
var result = validate.apply(this, arguments);
if (!result.error && result.value) {
result.value = JSON.stringify(result.value);
}
return result;
};
return any;
} | javascript | {
"resource": ""
} |
q41517 | defaultUuid | train | function defaultUuid(options, version) {
if (options && options.default) {
if ([version, 'empty'].indexOf(options.default) > -1) {
return options.default;
}
return version;
}
return undef;
} | javascript | {
"resource": ""
} |
q41518 | handleAdminEvents | train | function handleAdminEvents() {
//listen for clicks that bubble in up in the admin bar
document.body.addEventListener('click', function (ev) {
if(ev.target.hasAttribute('data-edit-include')) {
launchPluginEditor(ev.target);
} else if(ev.target.hasAttribute('data-... | javascript | {
"resource": ""
} |
q41519 | getIncludeDragData | train | function getIncludeDragData(ev) {
var data = ev.dataTransfer.getData('include-info');
return data ? JSON.parse(data) : null;
} | javascript | {
"resource": ""
} |
q41520 | train | function(callback) {
helpers.walk(buildInfo.srcApps, function(err, results) {
if (err) return callback("Error walking files.");
callback(null, results);
});
} | javascript | {
"resource": ""
} | |
q41521 | train | function(callback) {
helpers.walk(buildInfo.srcVendors, function(err, results) {
if (err) return callback("Error walking files.");
callback(null, results);
});
} | javascript | {
"resource": ""
} | |
q41522 | getUniqueRandomNumberAsync | train | function getUniqueRandomNumberAsync(callback) {
if (cb.check(callback)) { return; }
setTimeout(() => {
debugger
cb.done(Math.random());
}, 1000);
} | javascript | {
"resource": ""
} |
q41523 | initServiceModel | train | function initServiceModel(connectionUrl) {
log.logger.debug("initServiceModel ", {connectionUrl: connectionUrl});
if (!connectionUrl) {
log.logger.error("No Connection Url Specified");
return null;
}
//If the connection has not already been created, create it and initialise the Service Schema For That ... | javascript | {
"resource": ""
} |
q41524 | create | train | function create( arr ) {
var f = '';
f += 'return function fill( len ) {';
f += 'var arr = new Array( len );';
f += 'for ( var i = 0; i < len; i++ ) {';
f += 'arr[ i ] = ' + serialize( arr ) + ';';
f += '}';
f += 'return arr;';
f += '}';
return ( new Function( f ) )();
} | javascript | {
"resource": ""
} |
q41525 | hash | train | function hash() {
var ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [Math.floor(Math.random() * 100)];
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36;
if (!ids.splice) {... | javascript | {
"resource": ""
} |
q41526 | bunch | train | function bunch() {
var num = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 36;
if (typeof num !== 'number') {
throw new Type... | javascript | {
"resource": ""
} |
q41527 | request | train | function request(path, json) {
return new Promise(function (resolve, reject) {
oauth._performSecureRequest(config.telldusToken,
config.telldusTokenSecret,
'GET',
'https://api.telldus.com/json' + path,
null,
json,
!!json ? 'application/json' : null, function (err... | javascript | {
"resource": ""
} |
q41528 | clearAjax | train | function clearAjax() {
each(function(request) {
try {
request.onload = noop;
request.onerror = noop;
request.onabort = noop;
request.onreadystatechange = noop;
each(function(added) {
request[added[0]].apply(request, added[1]);
}, request._queue || []);
request.abo... | javascript | {
"resource": ""
} |
q41529 | getMoment | train | function getMoment(modelValue) {
return moment(modelValue, angular.isString(modelValue) ? configuration.parseFormat : undefined)
} | javascript | {
"resource": ""
} |
q41530 | debounce | train | function debounce(callback) {
let timeout = null;
return () => {
if (timeout !== null) {
return;
}
timeout = setTimeout(() => {
timeout = null;
callback();
}, 0);
}
} | javascript | {
"resource": ""
} |
q41531 | add | train | function add(keyId, sshKey, callback) {
try {
sshKeyparser(sshKey);
}catch (e) {
return callback(e);
}
commons.post(format('/%s/keys/', deis.version), {
id: keyId || deis.username,
'public': sshKey
},callback);
} | javascript | {
"resource": ""
} |
q41532 | remove | train | function remove(keyId, callback) {
commons.del(format('/%s/keys/%s', deis.version, keyId), callback);
} | javascript | {
"resource": ""
} |
q41533 | exposeAPI | train | function exposeAPI(log){
return {
emerg: log(_loglevel.EMERGENCY),
emergency: log(_loglevel.EMERGENCY),
alert: log(_loglevel.ALERT),
crit: log(_loglevel.CRITICAL),
critical: log(_loglevel.CRITICAL),
error: log(_loglevel.ERROR),
err: log(_loglevel.ERROR),
... | javascript | {
"resource": ""
} |
q41534 | createLogger | train | function createLogger(instance){
// generator
function log(level){
return function(...args){
// logging backend available ?
if (_loggingBackends.length > 0){
// trigger backends
_loggingBackends.forEach(function(backend){
bac... | javascript | {
"resource": ""
} |
q41535 | getLogger | train | function getLogger(instance){
// create new instance if not available
if (!_loggerInstances[instance]){
_loggerInstances[instance] = createLogger(instance);
}
return _loggerInstances[instance];
} | javascript | {
"resource": ""
} |
q41536 | addLoggingBackend | train | function addLoggingBackend(backend, minLoglevel=99){
// function or string input supported
if (typeof backend === 'function'){
_loggingBackends.push(backend);
// lookup
}else{
if (backend === 'fancy-cli'){
_loggingBackends.push(_fancyCliLogger(minLoglevel));
}else if... | javascript | {
"resource": ""
} |
q41537 | StanzaFetcher | train | function StanzaFetcher(db, getInterchangeSession) {
var self = this;
self.db = db;
self._closed = false;
self.getInterchangeSession = getInterchangeSession;
self._highWaterMarks = new Chain(self._fetchMostRecentStanzaSeq.bind(self));
events.EventEmitter.call(this);
} | javascript | {
"resource": ""
} |
q41538 | render | train | function render (vnode, parent, context) {
// render
var i = 0
var rendered = rawRender(vnode)
// mount
if (typeof parent === 'function') {
var nodes = rendered.nodes.length < 2 ? rendered.nodes[0] : rendered.nodes
parent(nodes)
} else if (parent) {
for (i = 0; i < rendered.nodes.length; i++) {... | javascript | {
"resource": ""
} |
q41539 | HttpError | train | function HttpError(message, status, cause) {
this.status = status || StatusCode.UNKNOWN;
HttpError.super_.call(this, errors.ErrorCode.HTTP + this.status, message || StatusLine[this.status] || StatusLine[StatusCode.UNKNOWN], cause);
} | javascript | {
"resource": ""
} |
q41540 | train | function(path, callbackSuccess, callbackError) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
callbackSuccess(xhr.responseText);
} else {
callbackError();
}
}
};
xhr.open('... | javascript | {
"resource": ""
} | |
q41541 | initPool | train | function initPool(name, config){
// new pool
const pool = _mysql.createPool(config);
// create pool wrapper
_pools[name || '_default'] = {
_instance: pool,
getConnection: function(scope){
return _poolConnection.getConnection(pool, scope);
}
}
} | javascript | {
"resource": ""
} |
q41542 | merge | train | function merge(target) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
for (var arg, len = args.length, index = 0; arg = args[index], index < len; index += 1) {
for (var all in arg) {
if (typeof HTMLElement !== 'u... | javascript | {
"resource": ""
} |
q41543 | getInnerHTML | train | function getInnerHTML(node) {
if (!node.children) return '';
if (!isArray(node.children) && typeof HTMLCollection !== 'undefined' && !(node.children instanceof HTMLCollection)) node.children = [node.children];
return (isArray(node) && node || (typeof HTMLCollection !== 'undefined' && node.children instanceof HTMLCo... | javascript | {
"resource": ""
} |
q41544 | createElement | train | function createElement(node, document) {
var tag = void 0;
if ((typeof node === 'undefined' ? 'undefined' : _typeof(node)) !== 'object') {
// we have a text node, so create one
tag = document.createTextNode('' + node);
} else {
tag = document.createElement(node.tagName);
// add all required attributes
Obje... | javascript | {
"resource": ""
} |
q41545 | train | function(opts) {
EventEmitter.call(this);
opts = opts || {};
this.maxLength = opts.maxLength || DEFAULT_MAX_LENGTH;
this.offset = 0;
this.left = 0;
this.length = 0;
this.buf = null;
this.state = ST_LENGTH;
} | javascript | {
"resource": ""
} | |
q41546 | send | train | function send(socket, host, port, loggingObject)
{
var buffer = new Buffer(JSON.stringify(loggingObject));
socket.send(buffer, 0, buffer.length, port, host, function(err, bytes)
{
if (err)
{
console.error('log4js-logstash-appender (%s:%p) - %s', host, port, util.inspect(err));
}
});
} | javascript | {
"resource": ""
} |
q41547 | appender | train | function appender(configuration)
{
var socket = dgram.createSocket('udp4');
return function(loggingEvent)
{
var loggingObject =
{
name: loggingEvent.categoryName,
message: layout(loggingEvent),
severity: loggingEvent.level.level,
severityText: loggingEvent.level.levelStr,
};
if (configuration.a... | javascript | {
"resource": ""
} |
q41548 | inarray | train | function inarray (list, item) {
list = Object.prototype.toString.call(list) === '[object Array]' ? list : []
var idx = -1
var end = list.length
while (++idx < end) {
if (list[idx] === item) return true
}
return false
} | javascript | {
"resource": ""
} |
q41549 | getIncludes | train | function getIncludes(file) {
var content = String(file.contents);
var matches = [];
while (regexMatch = DIRECTIVE_REGEX.exec(content)) {
matches.push(regexMatch);
}
// For every require fetch it's matching files
var fileLists = _.map(matches, function(match) {
return globMatch(matc... | javascript | {
"resource": ""
} |
q41550 | globMatch | train | function globMatch(match, file) {
var directiveType = match[1];
var globPattern = match[2]; // relative file
// require all files under a directory
if (directiveType.indexOf('_tree') !== -1) {
globPattern = globPattern.concat('/**/*');
directiveType = directiveType.replace('_tree', '');
... | javascript | {
"resource": ""
} |
q41551 | _inputInterfaces | train | function _inputInterfaces (interfaces, msg, type, options, i = 0) {
return i >= interfaces.length ? Promise.resolve() : Promise.resolve().then(() => {
let result = null;
switch (type) {
case "log":
result = interfaces[i].log(msg, options);
break;
case "success":
result = ... | javascript | {
"resource": ""
} |
q41552 | auth | train | function auth(endo, options) {
options || (options = {});
//
// add token utility methods, binding first options arg
//
endo.createToken = auth.createToken.bind(null, options.sign);
endo.verifyToken = auth.verifyToken.bind(null, options.verify);
//
// verify provided credentials are valid and set user... | javascript | {
"resource": ""
} |
q41553 | hslToRgb | train | function hslToRgb(h, s, l) {
h /= 360;
s /= 100;
l /= 100;
var r, g, b;
if (s === 0) {
r = g = b = l; // achromatic
} else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1 / 3);
}
... | javascript | {
"resource": ""
} |
q41554 | isCombinableSplit | train | function isCombinableSplit(tokenized) {
if (tokenized.tokens.length <= 1) {
return false;
}
for (var i = 1; i < tokenized.tokens.length; ++i) {
if (!tokenized.fusable[i]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q41555 | toCssModule | train | function toCssModule(styles) {
var done = false;
var res;
new modules().load(styles, prefix + uni()).then(function(next) {
done = true;
res = next;
});
deasync.loopWhile(function() {
return !done;
});
return res;
} | javascript | {
"resource": ""
} |
q41556 | SDFSplitter | train | function SDFSplitter(handler) {
parser.SDFTransform.call(this);
this.on('data', function (chunk) {
handler(String(chunk));
});
} | javascript | {
"resource": ""
} |
q41557 | PygmentizeOptions | train | function PygmentizeOptions (options) {
if(!(this instanceof PygmentizeOptions))
return new PygmentizeOptions(options);
if(options.lexer && validate.lexer.test(options.lexer))
this.lexer = options.lexer;
if(options.guess && !this.lexer)
this.guess = true;
if(options.formatter && validate.formatter... | javascript | {
"resource": ""
} |
q41558 | train | function(app, opts) {
this.app = app;
this.handlerMap = {};
if(!!opts.reloadHandlers) {
watchHandlers(app, this.handlerMap);
}
this.enableForwardLog = opts.enableForwardLog || false;
} | javascript | {
"resource": ""
} | |
q41559 | train | function(app, serverType, handlerMap) {
let p = pathUtil.getHandlerPath(app.getBase(), serverType);
if(p) {
handlerMap[serverType] = Loader.load(p, app);
}
} | javascript | {
"resource": ""
} | |
q41560 | train | function() {
if (!this.hasOwnProperty("_postalSubscriptions")) {
this._postalSubscriptions = {};
}
for (var topic in this.subscriptions) {
if (this.subscriptions.hasOwnProperty(topic)) {
var callback = this.subscriptions[topic];
this.subscribe(topic, callback);
}
}
... | javascript | {
"resource": ""
} | |
q41561 | fromShape | train | function fromShape(obj, propType, options=null) {
const declaration = propType[SHAPE];
if (!(declaration instanceof Declaration)) {
throw new Error('fromShape called with a non-shape property type');
}
const shape = declaration.shape;
const instance = {};
const checker = {};
Object.keys(shape).forEach... | javascript | {
"resource": ""
} |
q41562 | isRequiredWrapper | train | function isRequiredWrapper(propType) {
const isRequired = (props, propName, componentName, ...rest) => {
if (!props[propName]) {
return new Error(
`the property "${propName}" is marked as required for the component ` +
`"${componentName}" but "${props[propName]}" has been provided`
);
... | javascript | {
"resource": ""
} |
q41563 | frozenWrapper | train | function frozenWrapper(propType) {
const checkFrozen = (obj, propName, componentName) => {
if (!Object.isFrozen(obj)) {
throw new Error(
`the property "${propName}" provided to component ` +
`"${componentName}" is not frozen`
);
}
forEachKeyValue(obj, (name, prop) => {
co... | javascript | {
"resource": ""
} |
q41564 | deepFreeze | train | function deepFreeze(obj) {
Object.freeze(obj);
forEachKeyValue(obj, (name, prop) => {
const type = typeof obj;
if (
prop !== null &&
(type === 'object' || type === 'function') &&
!Object.isFrozen(prop)
) {
deepFreeze(prop);
}
});
return obj;
} | javascript | {
"resource": ""
} |
q41565 | train | function (level) {
var lowerCaseLevel = level.toLowerCase();
if (_.contains(LEVELS, lowerCaseLevel)) {
return lowerCaseLevel;
} else {
return LEVEL_OFF;
}
} | javascript | {
"resource": ""
} | |
q41566 | HouseCode | train | function HouseCode(houseCode) {
this.raw = null;
switch (typeof houseCode) {
case "string":
if (houseCode !== "" && houseCode.length === 1) {
var index = houseCode.charCodeAt(0) - 65;
if ((index >= 0) && (index <= (deviceCodes.length - 1))) {
this.raw = deviceCodes[index];
} else {
throw new Erro... | javascript | {
"resource": ""
} |
q41567 | UnitCode | train | function UnitCode(unitCode) {
switch (typeof unitCode) {
case "string":
unitCode = parseInt(unitCode, 10);
if (unitCode || unitCode === 0) {
var index = unitCode - 1;
if ((index >= 0) && (index <= (deviceCodes.length - 1))) {
this.raw = deviceCodes[index];
} else {
throw new Error("Unit code stri... | javascript | {
"resource": ""
} |
q41568 | Address | train | function Address(address) {
this.houseCode = null;
this.unitCode = null;
try {
switch (typeof address) {
case "object":
if (_.isArray(address) && address.length === 2) {
this.houseCode = new HouseCode(address[0]);
this.unitCode = new UnitCode(address[1]);
} else {
if (address.houseCode !== und... | javascript | {
"resource": ""
} |
q41569 | normalize | train | function normalize(recordTypes, recordTypeName, record, lang, validationSets) {
// check that we have the record
if ((record === null) || ((typeof record) !== 'object'))
throw new common.X2UsageError('Record object was not provided.');
// get the record type descriptor (or throw error if invalid record type)
co... | javascript | {
"resource": ""
} |
q41570 | getValidators | train | function getValidators(subjDesc, element, validationSets) {
const validators = subjDesc.validators;
if (!validators)
return null;
const allValidators = new Array();
for (let set in validators) {
if (element && !set.startsWith('element:'))
continue;
if (validationSets.has(element ? set.substring('element... | javascript | {
"resource": ""
} |
q41571 | list | train | function list(appName, callback) {
commons.get(format('/%s/apps/%s/perms/', deis.version, appName), callback);
} | javascript | {
"resource": ""
} |
q41572 | UI | train | function UI (input, output) {
this.rl = readline.createInterface({
input: input || ttys.stdin,
output: output || ttys.stdout
})
// Delegated events bind.
this.onLine = (function onLine () {
_events.line.apply(this, arguments)
}).bind(this)
this.onKeypress = (function onKeypress () {
if... | javascript | {
"resource": ""
} |
q41573 | lazyLoad | train | function lazyLoad(imgs, options) {
var setting = {
effect: 'fadeIn',
effect_speed: 10,
placeholder: 'data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP///93d3f///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw=='
},
$imgs;
if (typeof imgs === 'undefine... | javascript | {
"resource": ""
} |
q41574 | list | train | function list(appName, callback) {
var url = format('/%s/apps/%s/config/', deis.version, appName);
commons.get(url, function onListResponse(err, result) {
callback(err, result ? result.tags : null);
});
} | javascript | {
"resource": ""
} |
q41575 | set | train | function set(appName, tagValues, callback) {
if (!isObject(tagValues)) {
return callback(new Error('To set a variable pass an object'));
}
commons.post(format('/%s/apps/%s/config/', deis.version, appName), {
tags: tagValues
},function onSetResponse(err, result) {
callback(err, result ... | javascript | {
"resource": ""
} |
q41576 | unset | train | function unset(appName, tagNames, callback) {
if (!util.isArray(tagNames)) {
return callback(new Error('To unset a tag pass an array of names'));
}
var keyValues = {};
tagNames.forEach(function eachTag(tagName) {
keyValues[tagName] = null;
});
set(appName, keyValues, callback);
} | javascript | {
"resource": ""
} |
q41577 | getLevel | train | function getLevel(base, index) {
var level = (0, _bigInteger2.default)('0');
var current = index;
var parent = void 0;
while (current.gt(zero)) {
parent = current.prev().divide(base);
level = level.next();
current = parent;
}
return level;
} | javascript | {
"resource": ""
} |
q41578 | SpotSpec | train | function SpotSpec (options) {
if (this.constructor.name === 'Object') {
throw new Error('Object must be instantiated using new')
}
let self = this
let specOptions = Object.assign({}, options)
// Have the superclass constuct as an EC2 service
Service.call(this, SvcAws.EC2, specOptions)
this.logger.in... | javascript | {
"resource": ""
} |
q41579 | train | function ( options ) {
_.bindAll( this, "selectNext", "selectPrev", "onSelect", "render" );
this.collection = options.collection;
this.listenTo( this.collection, "select:one", this.onSelect );
this.listenTo( this.collection, "remove", this.render );
... | javascript | {
"resource": ""
} | |
q41580 | BufferStreamReader | train | function BufferStreamReader (data, options) {
if (!(this instanceof BufferStreamReader)) {
return new BufferStreamReader(data);
}
if (!options) {
options = {};
}
stream.Readable.call(this, options);
this._data = null;
this._chunkSize = options.chunkSize || -1;
if (typeof data === 'string') {... | javascript | {
"resource": ""
} |
q41581 | RootContext | train | function RootContext(argv, profileFilenames, view) {
var self = {
commands: COMMANDS, // Overwritten when interactive
profileFilenames: profileFilenames,
interactive: false,
argv: argv,
view: view,
config: null,
nick: null,
privkey: null,
hubClient: null,
vo... | javascript | {
"resource": ""
} |
q41582 | progress | train | function progress( _line ){
messages[ _line ].progress++;
if( (messages[ _line ].progress + messages[ _line ].diff) > 0 ){
messages[ _line ].progress = 0;
}
} | javascript | {
"resource": ""
} |
q41583 | anim | train | function anim( _line ){
var msg = messages[ _line ];
lcd.cursor( _line, 0 );
if( msg.progress === 0 ){
lcd.print( msg.msg );
progress( _line );
(function( _line ){
timeout = setTimeout(function(){
anim( _line )
}, anim_settings.firstCharP... | javascript | {
"resource": ""
} |
q41584 | Commit | train | function Commit(events, sequenceID, sequenceSlot, aggregateType, metadata){
if(!Array.isArray(events)){ throw new Error('events must be an array while constructing Commit'); }
if(typeof(sequenceID) !== 'string'){ throw new Error('sequenceID is not a string while constructing Commit'); }
if(!sequenceSlot){ throw new ... | javascript | {
"resource": ""
} |
q41585 | init | train | function init(ctx) {
if (glEnums == null) {
glEnums = { };
for (var propertyName in ctx) {
if (typeof ctx[propertyName] == 'number') {
glEnums[ctx[propertyName]] = propertyName;
}
}
}
} | javascript | {
"resource": ""
} |
q41586 | glEnumToString | train | function glEnumToString(value) {
checkInit();
var name = glEnums[value];
return (name !== undefined) ? name :
("*UNKNOWN WebGL ENUM (0x" + value.toString(16) + ")");
} | javascript | {
"resource": ""
} |
q41587 | glFunctionArgsToString | train | function glFunctionArgsToString(functionName, args) {
// apparently we can't do args.join(",");
var argStr = "";
for (var ii = 0; ii < args.length; ++ii) {
argStr += ((ii == 0) ? '' : ', ') +
glFunctionArgToString(functionName, ii, args[ii]);
}
return argStr;
} | javascript | {
"resource": ""
} |
q41588 | makeDebugContext | train | function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc) {
init(ctx);
opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) {
// apparently we can't do args.join(",");
var argStr = "";
for (var ii = 0; ii < args.length; ++ii) {
argStr += ((ii == 0) ? '' : ', ') ... | javascript | {
"resource": ""
} |
q41589 | createServer | train | function createServer(serverName) {
console.log("creating server", serverName)
var server = servers[serverName] = net.createServer(handleConnection)
ports.service(serverName, listen)
function handleConnection(connection) {
console.log("got incoming connection", connection)
... | javascript | {
"resource": ""
} |
q41590 | modifyOutRules | train | function modifyOutRules(rules) {
for (let i = 0; i < rules.length; ++i) {
if (rules[i].test) {
switch ('' + rules[i].test) {
// Images
case '/\\.(png|jpe?g|gif)$/':
modifyOutRule(rules[i], 'images');
break;
// Fonts
case '/\\.(woff2?|ttf|eot|svg|otf)$/':
modifyOutRule(rules[i], 'fon... | javascript | {
"resource": ""
} |
q41591 | modifyOutRule | train | function modifyOutRule(rule, type) {
rule.test = new RegExp(
'\\.(' + Config.out[type].extensions.join('|') + ')$'
);
} | javascript | {
"resource": ""
} |
q41592 | loadModelNames | train | function loadModelNames(modelPath) {
modelPath = modelPath || envModelPath;
debuglog(() => `modelpath is ${modelPath} `);
var mdls = FUtils.readFileAsJSON('./' + modelPath + '/models.json');
mdls.forEach(name => {
if (name !== makeMongoCollectionName(name)) {
throw new Error('bad mod... | javascript | {
"resource": ""
} |
q41593 | makeMongooseModelName | train | function makeMongooseModelName(collectionName) {
if (collectionName !== collectionName.toLowerCase()) {
throw new Error('expect lowercase, was ' + collectionName);
}
if (collectionName.charAt(collectionName.length - 1) === 's') {
return collectionName.substring(0, collectionName.length - 1);... | javascript | {
"resource": ""
} |
q41594 | makeMongoCollectionName | train | function makeMongoCollectionName(modelName) {
if (modelName !== modelName.toLowerCase()) {
throw new Error('expect lowercase, was ' + modelName);
}
if (modelName.charAt(modelName.length - 1) !== 's') {
return modelName + 's';
}
return modelName;
} | javascript | {
"resource": ""
} |
q41595 | token | train | function token(value) {
if ( !arguments.length ) return cred.token;
cred.token = (value && value.length > 0 ? value : undefined);
return that;
} | javascript | {
"resource": ""
} |
q41596 | generateAuthorizationHeaderValue | train | function generateAuthorizationHeaderValue(signedHeaders, signKey, signingMsg) {
var signature = CryptoJS.HmacSHA256(signingMsg, signKey);
var authHeader = 'SNWS2 Credential=' +cred.token
+',SignedHeaders=' +signedHeaders.join(';')
+',Signature=' +CryptoJS.enc.Hex.stringify(signature);
return authHeader;
} | javascript | {
"resource": ""
} |
q41597 | computeAuthorization | train | function computeAuthorization(url, method, data, contentType, date) {
date = (date || new Date());
var uri = URI.parse(url);
var canonQueryParams = canonicalQueryParameters(uri, data, contentType);
var canonHeaders = canonicalHeaders(uri, contentType, date, bodyContentDigest);
var bodyContentDigest = body... | javascript | {
"resource": ""
} |
q41598 | json | train | function json(url, method, data, contentType, callback) {
var requestUrl = url;
// We might be passed to queue, and then our callback will be the last argument (but possibly not #5
// if the original call to queue didn't pass all arguments) so we check for that at the start and
// adjust what we consider the me... | javascript | {
"resource": ""
} |
q41599 | check | train | function check(log, validity, req, res, type, full, finalValidator, callback) {
var validator, v;
log.info.call(log, 'deserializing and validating request body', {
serializerType: type,
full: full,
finalValidator: finalValidator ? true : false
});
if (!req.body) {
callback(new Error('Empty Req... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.