_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q36600
train
function(symbol, ctx, partials, indent) { var partial = this.ep(symbol, partials); if (!partial) { return ''; } return partial.ri(ctx, partials, indent); }
javascript
{ "resource": "" }
q36601
train
function(func, ctx, partials) { var cx = ctx[ctx.length - 1]; return func.call(cx); }
javascript
{ "resource": "" }
q36602
findInScope
train
function findInScope(key, scope, doModelGet) { var val, checkVal; if (scope && typeof scope == 'object') { if (scope[key] != null) { val = scope[key]; // try lookup with get for backbone or similar model data } else if (doModelGet && scope.get && typeof scope.get == 'function') { val = scope.get(key); } } return val; }
javascript
{ "resource": "" }
q36603
_mergeOptions
train
function _mergeOptions () { var options = {} for (var i = 0; i < arguments.length; ++i) { let obj = arguments[i] for (var attr in obj) { options[attr] = obj[attr] } } return options }
javascript
{ "resource": "" }
q36604
Base
train
function Base(runner) { var self = this , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } , failures = this.failures = []; if (!runner) return; this.runner = runner; runner.stats = stats; runner.on('start', function(){ stats.start = new Date; }); runner.on('suite', function(suite){ stats.suites = stats.suites || 0; suite.root || stats.suites++; }); runner.on('test end', function(test){ stats.tests = stats.tests || 0; stats.tests++; }); runner.on('pass', function(test){ stats.passes = stats.passes || 0; var medium = test.slow() / 2; test.speed = test.duration > test.slow() ? 'slow' : test.duration > medium ? 'medium' : 'fast'; stats.passes++; }); runner.on('fail', function(test, err){ stats.failures = stats.failures || 0; stats.failures++; test.err = err; failures.push(test); }); runner.on('end', function(){ stats.end = new Date; stats.duration = new Date - stats.start; }); runner.on('pending', function(){ stats.pending++; }); }
javascript
{ "resource": "" }
q36605
inlineDiff
train
function inlineDiff(err, escape) { var msg = errorDiff(err, 'WordsWithSpace', escape); // linenos var lines = msg.split('\n'); if (lines.length > 4) { var width = String(lines.length).length; msg = lines.map(function(str, i){ return pad(++i, width) + ' |' + ' ' + str; }).join('\n'); } // legend msg = '\n' + color('diff removed', 'actual') + ' ' + color('diff added', 'expected') + '\n\n' + msg + '\n'; // indent msg = msg.replace(/^/gm, ' '); return msg; }
javascript
{ "resource": "" }
q36606
unifiedDiff
train
function unifiedDiff(err, escape) { var indent = ' '; function cleanUp(line) { if (escape) { line = escapeInvisibles(line); } if (line[0] === '+') return indent + colorLines('diff added', line); if (line[0] === '-') return indent + colorLines('diff removed', line); if (line.match(/\@\@/)) return null; if (line.match(/\\ No newline/)) return null; else return indent + line; } function notBlank(line) { return line != null; } msg = diff.createPatch('string', err.actual, err.expected); var lines = msg.split('\n').splice(4); return '\n ' + colorLines('diff added', '+ expected') + ' ' + colorLines('diff removed', '- actual') + '\n\n' + lines.map(cleanUp).filter(notBlank).join('\n'); }
javascript
{ "resource": "" }
q36607
stringify
train
function stringify(obj) { if (obj instanceof RegExp) return obj.toString(); return JSON.stringify(obj, null, 2); }
javascript
{ "resource": "" }
q36608
canonicalize
train
function canonicalize(obj, stack) { stack = stack || []; if (utils.indexOf(stack, obj) !== -1) return obj; var canonicalizedObj; if ('[object Array]' == {}.toString.call(obj)) { stack.push(obj); canonicalizedObj = utils.map(obj, function(item) { return canonicalize(item, stack); }); stack.pop(); } else if (typeof obj === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; utils.forEach(utils.keys(obj).sort(), function(key) { canonicalizedObj[key] = canonicalize(obj[key], stack); }); stack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; }
javascript
{ "resource": "" }
q36609
RejectedPromise
train
function RejectedPromise(reason, unused, onRejected, deferred) { if (!onRejected) { deferredAdopt(deferred, RejectedPromise, reason); return this; } if (!deferred) { deferred = new Deferred(this.constructor); } defer(tryCatchDeferred(deferred, onRejected, reason)); return deferred.promise; }
javascript
{ "resource": "" }
q36610
PendingPromise
train
function PendingPromise(queue, onFulfilled, onRejected, deferred) { if (!deferred) { if (!onFulfilled && !onRejected) { return this; } deferred = new Deferred(this.constructor); } queue.push({ deferred: deferred, onFulfilled: onFulfilled || deferred.resolve, onRejected: onRejected || deferred.reject }); return deferred.promise; }
javascript
{ "resource": "" }
q36611
adopt
train
function adopt(promise, state, value, adoptee) { var queue = promise._value; promise._state = state; promise._value = value; if (adoptee && state === PendingPromise) { adoptee._state(value, void 0, void 0, { promise: promise, resolve: void 0, reject: void 0 }); } for (var i = 0; i < queue.length; i++) { var next = queue[i]; promise._state( value, next.onFulfilled, next.onRejected, next.deferred ); } queue.length = 0; // Determine if this rejected promise will be "handled". if (state === RejectedPromise && promise._isChainEnd) { setTimeout(function() { if (promise._isChainEnd) { onPossiblyUnhandledRejection(value, promise); } }, 0); } }
javascript
{ "resource": "" }
q36612
deferredAdopt
train
function deferredAdopt(deferred, state, value) { if (deferred) { var promise = deferred.promise; promise._state = state; promise._value = value; } }
javascript
{ "resource": "" }
q36613
each
train
function each(collection, iterator) { for (var i = 0; i < collection.length; i++) { iterator(collection[i], i); } }
javascript
{ "resource": "" }
q36614
tryCatchDeferred
train
function tryCatchDeferred(deferred, fn, arg) { var promise = deferred.promise; var resolve = deferred.resolve; var reject = deferred.reject; return function() { try { var result = fn(arg); doResolve(promise, resolve, reject, result, result); } catch (e) { reject(e); } }; }
javascript
{ "resource": "" }
q36615
password
train
function password (n, special) { n = n || 3; special = special === true; var result = "", i = -1, used = {}, hasSub = false, hasExtra = false, flip, lth, pos, rnd, word; function sub (x, idx) { if (!hasSub && word.indexOf(x) > -1) { word = word.replace(x, subs[idx]); hasSub = true; flip = false; } } if (!special) { while (++i < n) { result += words[random(nth, used)]; } } else { rnd = Math.floor(Math.random() * n); while (++i < n) { word = words[random(nth, used)]; // Capitalizing a letter in a word if (i === rnd) { lth = word.length; pos = Math.floor(Math.random() * lth); if (pos === 0) { word = word.charAt(0).toUpperCase() + word.slice(1); } else if (pos < lth - 1) { word = word.slice(0, pos) + word.charAt(pos).toUpperCase() + word.slice(pos + 1, lth); } else { word = word.slice(0, pos) + word.charAt(pos).toUpperCase(); } } // or specializing if in the second half else if (i >= ( n / 2 )) { // Simulating a coin flip flip = Math.random() >= 0.5 ? 1 : 0; // Substituting a character if (flip && !hasSub) { replace.forEach(sub); } // Adding a character if (flip && !hasExtra) { word += extra[Math.floor(Math.random() * eth)]; hasExtra = true; } } result += word; } if (!hasSub) { result += subs[Math.floor(Math.random() * rth)]; } if (!hasExtra) { result += extra[Math.floor(Math.random() * eth)]; } } return result; }
javascript
{ "resource": "" }
q36616
CountStream
train
function CountStream (opts) { if (!(this instanceof CountStream)) return new CountStream(opts) stream.PassThrough.call(this, opts) this.destroyed = false this.size = 0 }
javascript
{ "resource": "" }
q36617
train
function(stack) { if (exports.async_trace_limit <= 0) { return; } var count = exports.async_trace_limit - 1; var previous = stack; while (previous && count > 1) { previous = previous.__previous__; --count; } if (previous) { delete previous.__previous__; } }
javascript
{ "resource": "" }
q36618
train
function(callback) { // capture current error location var trace_error = new Error(); trace_error.id = ERROR_ID++; trace_error.__previous__ = current_trace_error; trace_error.__trace_count__ = current_trace_error ? current_trace_error.__trace_count__ + 1 : 1; limit_frames(trace_error); var new_callback = function() { current_trace_error = trace_error; trace_error = null; var res = callback.apply(this, arguments); current_trace_error = null; return res; }; new_callback.__original_callback__ = callback; return new_callback; }
javascript
{ "resource": "" }
q36619
addTime
train
function addTime(options, client) { return function(next, project) { var dates = options.dates; delete options.dates; var join = futures.join(); join.add(dates.map(function(date) { var promise = futures.future(); // we must clone to prevent options.date override var opts = utils.clone(options); opts.date = date; var message = ('Save '+ opts.time + ' ' + (opts.billable ? 'billable' : 'non billable') + ' hours for '+ opts.date); intervals.addTime(project, opts, client, function (err, res) { var msg = 'OK'; if (err) { msg = 'ERROR'; console.error(err); } else if (res.status != 201) { msg = 'ERROR'; console.error('Unexpected status '+ res.status +' for addTime method'); }; console.log(message + ' ' + msg); promise.deliver(); }); return promise; })); join.when(function() { next(project); }); }; }
javascript
{ "resource": "" }
q36620
askForSave
train
function askForSave(conf) { return function(next, project) { process.stdout.write('Do you yant to save this project combinaison: (y/N)'); utils.readInput(function(input) { if (input == 'y') { process.stdout.write('Name of this combinaison: '); utils.readInput(function(input) { conf.projects ? '': conf.projects = []; project.name = input; conf.projects.push(project); config.write(conf, function(err) { if (err) throw err; console.log('ok. You can add time to this combinaison with intervals --project '+ input); next(); }) }); } else { next(); } }); } }
javascript
{ "resource": "" }
q36621
optionsFrom
train
function optionsFrom(argv) { var date = argv.date, dates = utils.parseDate(date), options = { time: argv.hours, dates: dates, billable: argv.billable || argv.b, description: argv.description }; return options; }
javascript
{ "resource": "" }
q36622
reqURL
train
function reqURL(req, newPath) { return url.format({ protocol: 'https', //req.protocol, // by default this returns http which gets redirected host: req.get('host'), pathname: newPath }) }
javascript
{ "resource": "" }
q36623
ToolTip
train
function ToolTip({ className, children, label, position, type }) { const classes = cx( tooltipClassName, `${tooltipClassName}--${position}`, `${tooltipClassName}--${type}`, className ) return ( <button role="tooltip" type="button" className={classes} aria-label={label}> {children} </button> ) }
javascript
{ "resource": "" }
q36624
format
train
function format(node, context, recur) { var blockComments = context.blockComments(node); for (var i = 0; i < node.body.length; i++) { var previous = node.body[i - 1]; var current = node.body[i]; var next = node.body[i + 1]; if (current.type === 'EmptyStatement') { continue;} if (newlines.extraNewLineBetween(previous, current)) { context.write('\n');} context.write(blockComments.printLeading(current, previous)); context.write(context.getIndent()); recur(current); context.write(utils.getLineTerminator(current)); context.write(blockComments.printTrailing(current, previous, next)); if (next) { context.write('\n');}}}
javascript
{ "resource": "" }
q36625
showFields
train
function showFields (data, version, fields) { var o = {} ;[data,version].forEach(function (s) { Object.keys(s).forEach(function (k) { o[k] = s[k] }) }) return search(o, fields.split("."), version._id, fields) }
javascript
{ "resource": "" }
q36626
findPartials
train
function findPartials(fragment) { var found = []; walkRecursive(fragment.t, function(item) { if (item.t === 8) { found.push(item.r); } }); return _.uniq(found); }
javascript
{ "resource": "" }
q36627
train
function (location, opts, callback) { resolve(location, function (err, fileUri) { if (err) { return callback(err) } bundle(fileUri, opts, callback) }) }
javascript
{ "resource": "" }
q36628
sendError
train
function sendError(req, res, err) { return res.end("(" + function (err) { throw new Error(err) } + "(" + JSON.stringify(err.message) + "))") }
javascript
{ "resource": "" }
q36629
ByteCharateristic
train
function ByteCharateristic(opts) { ByteCharateristic.super_.call(this, opts); this.on('beforeWrite', function(data, res) { res(data.length == opts.sizeof ? Results.Success : Results.InvalidAttributeLength); }); this.toBuffer = byte2buf(opts.sizeof); this.fromBuffer = buf2byte(opts.sizeof); }
javascript
{ "resource": "" }
q36630
LockStateCharateristic
train
function LockStateCharateristic(opts) { LockStateCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2081-8786-40ba-ab96-99b91ac981d8', properties: ['read'], sizeof: 1 }, opts)); }
javascript
{ "resource": "" }
q36631
TxPowerLevelCharateristic
train
function TxPowerLevelCharateristic(opts) { TxPowerLevelCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2084-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], }, opts)); this.on('beforeWrite', function(data, res) { res(data.length == 4 ? Results.Success : Results.InvalidAttributeLength); }); this.toBuffer = arr2buf; this.fromBuffer = buf2arr; }
javascript
{ "resource": "" }
q36632
TxPowerModeCharateristic
train
function TxPowerModeCharateristic(opts) { TxPowerModeCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2087-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], sizeof: 1 }, opts)); this.removeAllListeners('beforeWrite'); this.on('beforeWrite', function(data, res) { var err = Results.Success; var value = this.fromBuffer(data); if (data.length !== 1) { err = Results.InvalidAttributeLength; } else if (value < TxPowerMode.Lowest || value > TxPowerMode.High) { err = Results.WriteNotPermitted; } res(err); }); }
javascript
{ "resource": "" }
q36633
BeaconPeriodCharateristic
train
function BeaconPeriodCharateristic(opts) { BeaconPeriodCharateristic.super_.call(this, objectAssign({ uuid: 'ee0c2088-8786-40ba-ab96-99b91ac981d8', properties: ['read', 'write'], sizeof: 2 }, opts)); }
javascript
{ "resource": "" }
q36634
getBrowserLanguage
train
function getBrowserLanguage() { var first = window.navigator.languages ? window.navigator.languages[0] : null var lang = first || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage return lang }
javascript
{ "resource": "" }
q36635
isPositiveIntegerArray
train
function isPositiveIntegerArray(value) { var success = true; for(var i = 0; i < value.length; i++) { if(!config.checkIntegerValue.test(value[i]) || parseInt(value[i]) <= 0) { success = false; break; } } return success; }
javascript
{ "resource": "" }
q36636
isValidDate
train
function isValidDate(dateString, dateFormat, returnDateFormat) { if(moment(dateString, dateFormat).format(dateFormat) !== dateString) { return false; } if(!moment(dateString, dateFormat).isValid()) { return false; } if(returnDateFormat) { return moment(dateString, dateFormat).format(returnDateFormat); } return true; }
javascript
{ "resource": "" }
q36637
objValByStr
train
function objValByStr(name, separator, context) { var func, i, n, ns, _i, _len; if (!name || !separator || !context) { return null; } ns = name.split(separator); func = context; try { for (i = _i = 0, _len = ns.length; _i < _len; i = ++_i) { n = ns[i]; func = func[n]; } return func; } catch (e) { return e; } }
javascript
{ "resource": "" }
q36638
train
function (arrArg) { return arrArg.filter(function (elem, pos, arr) { return arr.indexOf(elem) === pos; }); }
javascript
{ "resource": "" }
q36639
CSP
train
function CSP(class1, class2) { var cov1 = stat.cov(class1); var cov2 = stat.cov(class2); this.V = numeric.eig(math.multiply(math.inv(math.add(cov1, cov2)), cov1)).E.x; }
javascript
{ "resource": "" }
q36640
FieldLabel
train
function FieldLabel(props) { var label = props.label, indicator = props.indicator, tooltipProps = props.tooltipProps, infoIconProps = props.infoIconProps; var indicatorEl = null; if (indicator === 'optional') { indicatorEl = React.createElement("span", { className: 'indicator' }, "(optional)"); } if (indicator === 'required') { indicatorEl = React.createElement("span", { className: 'indicator' }, "*"); } var indicatorClass = classNames({ 'optional': props.indicator === 'optional', 'required': props.indicator === 'required' }); var tooltipEl = null; if (infoIconProps && tooltipProps != null) { tooltipEl = React.createElement(tooltip_1.Tooltip, { tooltip: tooltipProps.tooltip, tooltipAlignment: tooltipProps.tooltipAlignment, tooltipPosition: tooltipProps.tooltipPosition }, React.createElement(info_icon_1.InfoIcon, { iconContent: infoIconProps.iconContent, iconCustomTypeName: infoIconProps.iconCustomTypeName })); } else if (tooltipProps != null) { tooltipEl = React.createElement(tooltip_1.Tooltip, { tooltip: tooltipProps.tooltip, tooltipAlignment: tooltipProps.tooltipAlignment, tooltipPosition: tooltipProps.tooltipPosition }); } else if (infoIconProps != null) { tooltipEl = React.createElement(info_icon_1.InfoIcon, { iconContent: infoIconProps.iconContent, iconCustomTypeName: infoIconProps.iconCustomTypeName }); } return React.createElement("div", { className: indicatorClass }, label, " ", indicatorEl, " ", tooltipEl); }
javascript
{ "resource": "" }
q36641
FieldError
train
function FieldError(props) { var touched = props.touched, error = props.error; if (touched && error) { return React.createElement("div", { className: 'c-form-field--error-message' }, error); } return null; }
javascript
{ "resource": "" }
q36642
buffered
train
function buffered(fn) { var ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; var id = void 0; var bn = function bn() { var _this = this; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new Promise(function (resolve) { clearTimeout(id); id = setTimeout(function () { return resolve(fn.apply(_this, args)); }, ms); }); }; bn.cancel = function () { clearTimeout(id); }; return bn; }
javascript
{ "resource": "" }
q36643
imgGlitch
train
function imgGlitch(img, options) { var imgElement = 'string' === typeof img ? document.querySelector(img) : img; if (!(imgElement instanceof HTMLImageElement && imgElement.constructor === HTMLImageElement)) { throw new TypeError('renderImgCorruption expects input img to be a valid image element'); } var corrupt64 = getCorrupt64(options); var data = imgElement.src; var corruption = undefined; return { start: start, stop: stop, clear: clear }; /** * Start rendering the * corruption * */ function start() { corruption = requestAnimationFrame(render); } /** * Render the corruption * */ function render() { imgElement.src = corrupt64(data); start(); } /** * Stop rendering the * corruption * */ function stop() { cancelAnimationFrame(corruption); } /** * Stop rendering the * corruption and * clear its effects * */ function clear() { stop(); imgElement.src = data; } }
javascript
{ "resource": "" }
q36644
add
train
function add(name, methods) { // Create a container class that extends Document for our methods. class ConcreteDocument extends Document { constructor(document, root) { super(name, document, root); } } // Assign the methods to the new classes prototype. assignIn(ConcreteDocument.prototype, methods); // Add a factory method for the new type. Document.factory[name] = (document, root) => new ConcreteDocument(document, root); }
javascript
{ "resource": "" }
q36645
train
function(subpath, regs){ for(var i = 0, len = regs.length; i < len; i++){ var reg = regs[i]; if(reg && fis.util.filter(subpath, reg)){ return i; } } return false; }
javascript
{ "resource": "" }
q36646
confBool
train
function confBool(obj, field) { if (field in obj) obj[field] = bool(obj[field]); }
javascript
{ "resource": "" }
q36647
train
function (consumer_key, consumer_secret) { this.oauth = new OAuth.OAuth( 'https://query.yahooapis.com/v1/yql/', 'https://query.yahooapis.com/v1/yql/', consumer_key, //consumer key consumer_secret, //consumer secret '1.0', null, 'HMAC-SHA1' ); this.oauth.setClientOptions({ requestTokenHttpMethod: 'POST' }); return this; }
javascript
{ "resource": "" }
q36648
clone
train
function clone (obj) { if(!isObject(obj, true)) return obj var _obj _obj = Array.isArray(obj) ? [] : {} for(var k in obj) _obj[k] = clone(obj[k]) return _obj }
javascript
{ "resource": "" }
q36649
iteratePipeFile
train
function iteratePipeFile () { if (!isIterating()) { return undefined; } let data = iterateData; let file = data.collection[data.i]; data.i++; if (data.i >= data.collection.length) { resetIterateData(); pipeLastFile(file); } else { pipeFile(file, iteratePipeFile); } }
javascript
{ "resource": "" }
q36650
iterateWriteArray
train
function iterateWriteArray () { if (!isIterating()) { return undefined; } let data = iterateData; let content = data.collection[data.i]; data.i++; if (data.i >= data.collection.length) { resetIterateData(); writable.write(content, 'utf8', onWriteFinish); } else { writable.write(content, 'utf8', iterateWriteArray); } }
javascript
{ "resource": "" }
q36651
iterateWriteLinkedList
train
function iterateWriteLinkedList () { if (!isIterating()) { return undefined; } let data = iterateData; let content = iterateData.item.content; data.item = data.item.next; if (data.item === null) { resetIterateData(); writable.write(content, 'utf8', onWriteFinish); } else { writable.write(content, 'utf8', iterateWriteLinkedList); } }
javascript
{ "resource": "" }
q36652
pipeFile
train
function pipeFile (file, endCallback) { testPipeFile(); testFunction(endCallback, 'endCallback'); let readable = fs.createReadStream(file); readableEndCallback = endCallback; readable.once('error', throwAsyncError); readable.once('close', onReadableClose); readable.pipe(writable, { end: false }); }
javascript
{ "resource": "" }
q36653
pipeFileArray
train
function pipeFileArray (arr) { testPipeFile(); // Just end WriteStream if no files need to be read to keep default pipe behavior. if (arr.length === 0) { writable.end(); } else { iterateData.collection = arr; iteratePipeFile(); } }
javascript
{ "resource": "" }
q36654
pipeLastFile
train
function pipeLastFile (file) { testPipeFile(); let readable = fs.createReadStream(file); readable.once('error', throwAsyncError); readable.pipe(writable); }
javascript
{ "resource": "" }
q36655
Leverage
train
function Leverage(client, sub, options) { if (!this) return new Leverage(client, sub, options); // // Flakey detection if we got a options argument or an actual Redis client. We // could do an instanceOf RedisClient check but I don't want to have Redis as // a dependency of this module. // if ('object' === typeof sub && !options && !sub.send_command) { options = sub; sub = null; } options = options || {}; // !IMPORTANT // // As the scripts are introduced to the `prototype` of our Leverage module we // want to make sure that we don't pollute this namespace to much. That's why // we've decided to move most of our internal logic in to a `._` private // object that contains most of our logic. This way we only have a small // number prototypes and properties that should not be overridden by scripts. // // !IMPORTANT this._ = Object.create(null, { // // The namespace is used to prefix all keys that are used by this module. // namespace: { value: options.namespace || 'leverage' }, // // Stores the SHA1 keys from the scripts that are added. // SHA1: { value: options.SHA1 || Object.create(null) }, // // Stores the scripts that we're currently using in Leverage // scripts: { value: Leverage.scripts.slice(), }, // // The amount of items we should log for our Pub/Sub. // backlog: { value: options.backlog || 100000 }, // // How many seconds should the item stay alive in our backlog. // expire: { value: options.expire || 1000 }, // // The pre-configured & authenticated Redis client that is used to send // commands and is loaded with the scripts. // client: { value: client }, // // Dedicated client that is used for subscribing to a given channel. // sub: { value: sub }, // // Introduce a bunch of private methods. // load: { value: Leverage.load.bind(this) }, prepare: { value: Leverage.prepare.bind(this) }, refresh: { value: Leverage.refresh.bind(this) }, seval: { value: Leverage.seval.bind(this) } }); // // Proxy all readyState changes to another event to make some of our internal // usage a bit easier. // this.on('readystatechange', function readystatechange(state) { debug('updated the readyState to %s', state); this.emit('readystate#'+ state); }); if (this._.client === this._.sub) { throw new Error('The pub and sub clients should separate connections'); } this._.load(); }
javascript
{ "resource": "" }
q36656
failed
train
function failed(err) { leverage.emit(channel +'::error', err); if (!bailout) return debug('received an error without bailout mode, gnoring it', err.message); leverage.emit(channel +'::bailout', err); leverage.unsubscribe(channel); }
javascript
{ "resource": "" }
q36657
parse
train
function parse(packet) { if ('object' === typeof packet) return packet; try { return JSON.parse(packet); } catch (e) { return failed(e); } }
javascript
{ "resource": "" }
q36658
flush
train
function flush() { if (queue.length) { // // We might want to indicate that these are already queued, so we don't // fetch data again. // queue.splice(0).sort(function sort(a, b) { return a.id - b.id; }).forEach(onmessage); } }
javascript
{ "resource": "" }
q36659
allowed
train
function allowed(packet) { if (!packet) return false; if (uv.position === 'inactive' || (!uv.received(packet.id) && ordered)) { queue.push(packet); return false; } return true; }
javascript
{ "resource": "" }
q36660
onmessage
train
function onmessage(packet) { if (arguments.length === 2) packet = arguments[1]; packet = parse(packet); if (allowed(packet)) emit(packet); }
javascript
{ "resource": "" }
q36661
initialize
train
function initialize(config, callback, config_helper) { config_helper = config_helper || require('../config/index'); if(!checkConfSanity(config)) { callback(new Error('conf.dbopt is not sane, can\'t initialize composite adapter')); return; } populateDatabasesArray(config, config_helper, function(err, databases) { if(err) return callback(err); var adapter = new Compositeadapter(config, databases); callback(null, adapter); }); }
javascript
{ "resource": "" }
q36662
deepSync
train
function deepSync(target, source, overwrite) { if (!(((target) && (typeof target === 'object')) && ((source) && (typeof source === 'object'))) || (source instanceof Array) || (target instanceof Array)) { throw new TypeError('Source and Target must be objects.'); } let sourceKeys = new Set(); let temp = {}; if (target && typeof target === 'object') { Object.keys(target).forEach(function (key) { temp[key] = target[key]; }) } Object.keys(source).forEach(function (key) { sourceKeys.add(key); if (typeof source[key] !== 'object' || !source[key]) { // keep old value if the key can be found if (target[key]) { if (overwrite === true) { temp[key] = source[key]; } else { temp[key] = target[key]; } } else { temp[key] = source[key]; } } else { if (!target[key]) { temp[key] = source[key]; } else { temp[key] = deepSync(target[key], source[key], overwrite); } } }); // remove keys that are not present in the sync source for (let targetKey in temp) { if (!sourceKeys.has(targetKey)) { delete temp[targetKey]; } } return temp; }
javascript
{ "resource": "" }
q36663
equalSimpleArrays
train
function equalSimpleArrays(arr1, arr2) { if (arr1 && (arr1.length > 0)) return ( arr2 && (arr2.length === arr1.length) && arr2.every((v, i) => (v === arr1[i])) ); return (!arr2 || (arr2.length === 0)); }
javascript
{ "resource": "" }
q36664
equalSimpleMaps
train
function equalSimpleMaps(map1, map2) { const keys1 = (map1 && Object.keys(map1)); if (map1 && (keys1.length > 0)) { const keys2 = (map2 && Object.keys(map2)); return ( keys2 && (keys2.length === keys1.length) && keys2.every(k => (map2[k] === map1[k])) ); } return (!map2 || (Object.keys(map2).length === 0)); }
javascript
{ "resource": "" }
q36665
needsAdd
train
function needsAdd(ptr, record, value) { const propDesc = ptr.propDesc; if (propDesc.isArray()) { if (ptr.collectionElement) return true; if (propDesc.scalarValueType === 'object') return !equalObjectArrays(/*ptr.getValue(record), value*/); return !equalSimpleArrays(ptr.getValue(record), value); } if (propDesc.isMap() && !ptr.collectionElement) { if (propDesc.scalarValueType === 'object') return !equalObjectMaps(/*ptr.getValue(record), value*/); return !equalSimpleMaps(ptr.getValue(record), value); } if (propDesc.scalarValueType === 'object') return !equalObjects(/*ptr.getValue(record), value*/); return (ptr.getValue(record) !== value); }
javascript
{ "resource": "" }
q36666
build
train
function build(recordTypes, recordTypeName, patch) { // get the record type descriptor if (!recordTypes.hasRecordType(recordTypeName)) throw new common.X2UsageError( `Unknown record type ${recordTypeName}.`); const recordTypeDesc = recordTypes.getRecordTypeDesc(recordTypeName); // make sure the patch spec is an array if (!Array.isArray(patch)) throw new common.X2SyntaxError('Patch specification is not an array.'); // process patch operations const involvedPropPaths = new Set(); const updatedPropPaths = new Set(); const patchOps = patch.map((patchOpDef, opInd) => parsePatchOperation( recordTypes, recordTypeDesc, patchOpDef, opInd, involvedPropPaths, updatedPropPaths)); // return the patch object return new RecordPatch(patchOps, involvedPropPaths, updatedPropPaths); }
javascript
{ "resource": "" }
q36667
buildMerge
train
function buildMerge(recordTypes, recordTypeName, mergePatch) { // only object merge patches are supported if (((typeof mergePatch) !== 'object') || (mergePatch === null)) throw new common.X2SyntaxError('Merge patch must be an object.'); // build JSON patch const jsonPatch = new Array(); buildMergeLevel('', mergePatch, jsonPatch); // build and return the record patch return build(recordTypes, recordTypeName, jsonPatch); }
javascript
{ "resource": "" }
q36668
buildMergeLevel
train
function buildMergeLevel(basePtr, levelMergePatch, jsonPatch) { for (let propName in levelMergePatch) { const mergeVal = levelMergePatch[propName]; const path = basePtr + '/' + propName; if (mergeVal === null) { jsonPatch.push({ op: 'remove', path: path }); } else if (Array.isArray(mergeVal)) { jsonPatch.push({ op: 'replace', path: path, value: mergeVal }); } else if ((typeof mergeVal) === 'object') { const nestedPatch = new Array(); buildMergeLevel(path, mergeVal, nestedPatch); jsonPatch.push({ op: 'merge', path: path, value: mergeVal, patch: nestedPatch }); } else { jsonPatch.push({ op: 'replace', path: path, value: mergeVal }); } } }
javascript
{ "resource": "" }
q36669
resolvePropPointer
train
function resolvePropPointer(recordTypeDesc, propPointer, noDash, ptrUse) { // parse the pointer const ptr = pointers.parse(recordTypeDesc, propPointer, noDash); // check if top pointer if (ptr.isRoot()) throw new common.X2SyntaxError( 'Patch operations involving top records as a whole are not' + ' allowed.'); // check the use if (ptrUse === PTRUSE.SET) { if (!ptr.propDesc.modifiable) throw new common.X2SyntaxError( `May not update non-modifiable property ${ptr.propPath}.`); } else if (ptrUse === PTRUSE.ERASE) { if ((ptr.propDesc.isScalar() || !ptr.collectionElement) && !ptr.propDesc.optional) throw new common.X2SyntaxError( `May not remove a required property ${ptr.propPath}.`); } // return the resolved pointer return ptr; }
javascript
{ "resource": "" }
q36670
validatePatchOperationValue
train
function validatePatchOperationValue( recordTypes, opType, opInd, pathPtr, val, forUpdate) { // error function const validate = errMsg => { if (errMsg) throw new common.X2SyntaxError( `Invalid value in patch operation #${opInd + 1} (${opType}):` + ` ${errMsg}`); }; // check if we have the value if (val === undefined) validate('no value is provided for the operation.'); // get target property descriptor const propDesc = pathPtr.propDesc; // "merge" operation is a special case if (opType === 'merge') { // value must be an object if (((typeof val) !== 'object') || (val === null)) validate('merge value must be a non-null object.'); // target must be a single object or a whole map if (!(propDesc.isMap() && !pathPtr.collectionElement) && !((propDesc.scalarValueType === 'object') && ( propDesc.isScalar() || pathPtr.collectionElement))) validate('invalid merge target record element type.'); // valid value, return it return val; } // validate if null is acceptable if (val === null) { if ((propDesc.isScalar() || !pathPtr.collectionElement) && !propDesc.optional) validate('null for required property.'); if (pathPtr.collectionElement && (propDesc.scalarValueType === 'object')) validate('null for nested object collection element.'); return val; // valid } // validate depending on the property type if (propDesc.isArray() && !pathPtr.collectionElement) { if (!Array.isArray(val)) validate('expected an array.'); if (!propDesc.optional && (val.length === 0)) validate('empty array for required property.'); val.forEach(v => { validate(isInvalidScalarValueType( recordTypes, v, propDesc, forUpdate)); }); } else if (propDesc.isMap() && !pathPtr.collectionElement) { if ((typeof val) !== 'object') validate('expected an object.'); const keys = Object.keys(val); if (!propDesc.optional && (keys.length === 0)) validate('empty object for required property.'); keys.forEach(k => { validate(isInvalidScalarValueType( recordTypes, val[k], propDesc, forUpdate)); }); } else { validate(isInvalidScalarValueType( recordTypes, val, propDesc, forUpdate)); } // the value is valid, return it return val; }
javascript
{ "resource": "" }
q36671
isValidRefValue
train
function isValidRefValue(recordTypes, val, propDesc) { if ((typeof val) !== 'string') return false; const hashInd = val.indexOf('#'); if ((hashInd <= 0) || (hashInd === val.length - 1)) return false; const refTarget = val.substring(0, hashInd); if (refTarget !== propDesc.refTarget) return false; const refTargetDesc = recordTypes.getRecordTypeDesc(refTarget); const refIdPropDesc = refTargetDesc.getPropertyDesc( refTargetDesc.idPropertyName); if ((refIdPropDesc.scalarValueType === 'number') && !Number.isFinite(Number(val.substring(hashInd + 1)))) return false; return true; }
javascript
{ "resource": "" }
q36672
isValidObjectValue
train
function isValidObjectValue(recordTypes, val, objectPropDesc, forUpdate) { const container = objectPropDesc.nestedProperties; for (let propName of container.allPropertyNames) { const propDesc = container.getPropertyDesc(propName); if (propDesc.isView() || propDesc.isCalculated()) continue; const propVal = val[propName]; if ((propVal === undefined) || (propVal === null)) { if (!propDesc.optional && (!forUpdate || !propDesc.isGenerated())) return false; } else if (propDesc.isArray()) { if (!Array.isArray(propVal)) return false; if (!propDesc.optional && (propVal.length === 0)) return false; if (propVal.some( v => isInvalidScalarValueType( recordTypes, v, propDesc, forUpdate))) return false; } else if (propDesc.isMap()) { if ((typeof propVal) !== 'object') return false; const keys = Object.keys(propVal); if (!propDesc.optional && (keys.length === 0)) return false; if (keys.some( k => isInvalidScalarValueType( recordTypes, propVal[k], propDesc, forUpdate))) return false; } else { if (isInvalidScalarValueType( recordTypes, propVal, propDesc, forUpdate)) return false; } } return true; }
javascript
{ "resource": "" }
q36673
validatePatchOperationFrom
train
function validatePatchOperationFrom(opType, opInd, pathPtr, fromPtr, forMove) { const invalidFrom = msg => new common.X2SyntaxError( `Invalid "from" pointer in patch operation #${opInd + 1} (${opType}):` + ` ${msg}`); if (forMove && pathPtr.isChildOf(fromPtr)) throw invalidFrom('may not move location into one of its children.'); const fromPropDesc = fromPtr.propDesc; const toPropDesc = pathPtr.propDesc; if (fromPropDesc.scalarValueType !== toPropDesc.scalarValueType) throw invalidFrom('incompatible property value types.'); if (toPropDesc.isRef() && (fromPropDesc.refTarget !== toPropDesc.refTarget)) throw invalidFrom('incompatible reference property targets.'); if ((toPropDesc.scalarValueType === 'object') && !isCompatibleObjects(fromPropDesc, toPropDesc)) throw invalidFrom('incompatible nested objects.'); if (toPropDesc.isArray() && !pathPtr.collectionElement) { if (!fromPropDesc.isArray() || fromPropDesc.collectionElement) throw invalidFrom('not an array.'); } else if (toPropDesc.isMap() && !pathPtr.collectionElement) { if (!fromPropDesc.isMap() || fromPropDesc.collectionElement) throw invalidFrom('not a map.'); } else { if (!fromPropDesc.isScalar() && !fromPtr.collectionElement) throw invalidFrom('not a scalar.'); } return fromPtr; }
javascript
{ "resource": "" }
q36674
isCompatibleObjects
train
function isCompatibleObjects(objectPropDesc1, objectPropDesc2) { const propNames2 = new Set(objectPropDesc2.allPropertyNames); const container1 = objectPropDesc1.nestedProperties; const container2 = objectPropDesc2.nestedProperties; for (let propName of objectPropDesc1.allPropertyNames) { const propDesc1 = container1.getPropertyDesc(propName); if (propDesc1.isView() || propDesc1.isCalculated()) continue; if (!propNames2.has(propName)) { if (!propDesc1.optional) return false; continue; } propNames2.delete(propName); const propDesc2 = container2.getPropertyDesc(propName); if (!propDesc1.optional && propDesc2.optional) return false; if ((propDesc1.isArray() && !propDesc2.isArray()) || (propDesc1.isMap() && !propDesc2.isMap()) || (propDesc1.isScalar() && !propDesc2.isScalar())) return false; if (propDesc1.scalarValueType !== propDesc2.scalarValueType) return false; if (propDesc1.isRef() && (propDesc1.refTarget !== propDesc2.refTarget)) return false; if ((propDesc1.scalarValueType === 'object') && !isCompatibleObjects(propDesc1, propDesc2)) return false; } for (let propName of propNames2) { const propDesc2 = container2.getPropertyDesc(propName); if (!propDesc2.isView() && !propDesc2.isCalculated()) return false; } return true; }
javascript
{ "resource": "" }
q36675
addInvolvedProperty
train
function addInvolvedProperty(pathPtr, involvedPropPaths, updatedPropPaths) { if (updatedPropPaths) { const propPathParts = pathPtr.propPath.split('.'); let propPath = ''; for (let i = 0, len = propPathParts.length - 1; i < len; i++) { if (propPath.length > 0) propPath += '.'; propPath += propPathParts[i]; updatedPropPaths.add(propPath); } } const propDesc = pathPtr.propDesc; if (propDesc.scalarValueType === 'object') { addInvolvedObjectProperty(propDesc, involvedPropPaths, updatedPropPaths); } else { involvedPropPaths.add(pathPtr.propPath); if (updatedPropPaths) updatedPropPaths.add(pathPtr.propPath); } return pathPtr; }
javascript
{ "resource": "" }
q36676
addInvolvedObjectProperty
train
function addInvolvedObjectProperty( objectPropDesc, involvedPropPaths, updatedPropPaths) { if (updatedPropPaths) updatedPropPaths.add( objectPropDesc.container.nestedPath + objectPropDesc.name); const container = objectPropDesc.nestedProperties; for (let propName of container.allPropertyNames) { const propDesc = container.getPropertyDesc(propName); if (propDesc.isCalculated() || propDesc.isView()) continue; if (propDesc.scalarValueType === 'object') { addInvolvedObjectProperty( objectPropDesc, involvedPropPaths, updatedPropPaths); } else { const propPath = container.nestedPath + propName; involvedPropPaths.add(propPath); if (updatedPropPaths) updatedPropPaths.add(propPath); } } }
javascript
{ "resource": "" }
q36677
convertArabicBack
train
function convertArabicBack(apfb) { var toReturn = "", selectedChar; theLoop: for( var i = 0 ; i < apfb.length ; ++i ) { selectedChar = apfb.charCodeAt(i); for( var j = 0 ; j < charsMap.length ; ++j ) { if( charsMap[j][4] == selectedChar || charsMap[j][2] == selectedChar || charsMap[j][1] == selectedChar || charsMap[j][3] == selectedChar ) { toReturn += String.fromCharCode(charsMap[j][0]); continue theLoop; } } for( var j = 0 ; j < combCharsMap.length ; ++j ) { if( combCharsMap[j][4] == selectedChar || combCharsMap[j][2] == selectedChar || combCharsMap[j][1] == selectedChar || combCharsMap[j][3] == selectedChar ) { toReturn += String.fromCharCode(combCharsMap[j][0][0]) + String.fromCharCode(combCharsMap[j][0][1]); continue theLoop; } } toReturn += String.fromCharCode( selectedChar ); } return toReturn; }
javascript
{ "resource": "" }
q36678
createFilesProvider
train
function createFilesProvider({ regex = null , single = HANDLE , multi = PROMPT_AND_HANDLE , choiceAll = true , handler = null , promptHeader = defaultPromptHeader , promptFooter = defaultPromptFooter } = {}) { return new FilesProvider({ regex , single , multi , choiceAll , handler , promptHeader , promptFooter }) }
javascript
{ "resource": "" }
q36679
prepareStackTrace
train
function prepareStackTrace( error, structuredStackTrace ) { // If error already have a cached trace inside, just return that // happens on true errors most if ( error.__cachedTrace ) { return error.__cachedTrace; } const stackTrace = utils.createStackTrace( error, structuredStackTrace ); error.__cachedTrace = utils.removeInternalFrames( filename, stackTrace ); if ( !error.__previous ) { let previousTraceError = currentTraceError; while ( previousTraceError ) { const previousTrace = utils.removeInternalFrames( filename, previousTraceError.stack ); // append old stack trace to the "cachedTrace" error.__cachedTrace += `${utils.separator}${utils.breakLn}${previousTraceError.__location}\n`; error.__cachedTrace += previousTrace.substring( previousTrace.indexOf( '\n' ) + 1 ); previousTraceError = previousTraceError.__previous; } } return error.__cachedTrace; }
javascript
{ "resource": "" }
q36680
wrapCallback
train
function wrapCallback( fn, frameLocation ) { const traceError = new Error(); traceError.__location = frameLocation; traceError.__previous = currentTraceError; return function $wrappedCallback( ...args ) { currentTraceError = traceError; try { return fn.call( this, ...args ); } catch ( e ) { throw e; // we just need the the 'finally' } finally { currentTraceError = null; } }; }
javascript
{ "resource": "" }
q36681
$wrapped
train
function $wrapped( ...args ) { const wrappedArgs = args.slice(); args.forEach( ( arg, i ) => { if ( typeof arg === 'function' ) { wrappedArgs[i] = wrapCallback( args[i], origin ); } } ); return method.call( this, ...wrappedArgs ); }
javascript
{ "resource": "" }
q36682
ls_
train
function ls_ (req, depth, cb) { if (typeof cb !== "function") cb = depth, depth = 1 mkdir(npm.cache, function (er) { if (er) return log.er(cb, "no cache dir")(er) function dirFilter (f, type) { return type !== "dir" || ( f && f !== npm.cache + "/" + req && f !== npm.cache + "/" + req + "/" ) } find(path.join(npm.cache, req), dirFilter, depth, function (er, files) { if (er) return cb(er) return cb(null, files.map(function (f) { f = f.substr(npm.cache.length + 1) f = f.substr((f === req ? path.dirname(req) : req).length) .replace(/^\//, '') return f })) }) }) }
javascript
{ "resource": "" }
q36683
parse
train
function parse(cmd, params) { return Object.keys(params).reduce(iterator.bind(this, params), cmd); }
javascript
{ "resource": "" }
q36684
iterator
train
function iterator(params, cmd, p) { var value = params[p]; // shortcut if (!cmd) return cmd; // fold booleans into strings accepted by shell if (typeof value == 'boolean') { value = value ? '1' : ''; } if (value !== null && ['undefined', 'string', 'number'].indexOf(typeof value) == -1) { // empty out cmd to signal the error return ''; } // use empty string for `undefined` return cmd.replace(new RegExp('\\$\\{' + p + '\\}', 'g'), (value !== undefined && value !== null) ? value : ''); }
javascript
{ "resource": "" }
q36685
buildPropsTreeBranches
train
function buildPropsTreeBranches( recordTypes, topPropDesc, clause, baseValueExprCtx, scopePropPath, propPatterns, options) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, topPropDesc, baseValueExprCtx, clause); // add direct patterns const valuePropsTrees = new Map(); const excludedPaths = new Set(); let wcPatterns = (!(options && options.noWildcards) && new Array()); for (let propPattern of propPatterns) { if (propPattern.startsWith('-')) excludedPaths.add(propPattern.substring(1)); else addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns); } // add wildcard patterns while (wcPatterns && (wcPatterns.length > 0)) { const wcPatterns2 = new Array(); wcPatterns.forEach(propPattern => { if (!excludedPaths.has(propPattern)) addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns2); }); wcPatterns = wcPatterns2; } // add scope if requested if (options && options.includeScopeProp && scopePropPath && !topNode.includesProp(scopePropPath)) { const scopeOptions = Object.create(options); scopeOptions.includeScopeProp = false; scopeOptions.noCalculated = true; scopeOptions.allowLeafObjects = true; addProperty(topNode, null, scopePropPath, clause, scopeOptions); } // de-branch the tree and merge in the value trees const assertSingleBranch = (branches, enable) => { if (enable && (branches.length > 1)) throw new Error('Internal X2 error: unexpected multiple branches.'); return branches; }; const valuePropsTreesArray = Array.from(valuePropsTrees.entries()); return assertSingleBranch(topNode.debranch().map( branch => valuePropsTreesArray.reduce((res, pair) => { const valuePropPath = pair[0]; const valuePropsTree = pair[1]; if (!res.includesProp(valuePropPath)) return res; return res.combine(valuePropsTree); }, branch) ), scopePropPath); }
javascript
{ "resource": "" }
q36686
buildSuperPropsTreeBranches
train
function buildSuperPropsTreeBranches( recordTypes, recordTypeDesc, superPropNames) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, { isScalar() { return true; }, isCalculated() { return false; }, refTarget: recordTypeDesc.superRecordTypeName }, new ValueExpressionContext('', [ recordTypes.getRecordTypeDesc(recordTypeDesc.superRecordTypeName) ]), 'select'); // add super-properties to the tree const valuePropsTrees = new Map(); for (let superPropName of superPropNames) addProperty( topNode, null, superPropName, 'select', null, valuePropsTrees); // de-branch the tree and merge in the value trees const valuePropsTreesArray = Array.from(valuePropsTrees.entries()); return topNode.debranch().map( branch => valuePropsTreesArray.reduce((res, pair) => { const valuePropPath = pair[0]; const valuePropsTree = pair[1]; if (!res.includesProp(valuePropPath)) return res; return res.combine(valuePropsTree); }, branch) ); }
javascript
{ "resource": "" }
q36687
buildSimplePropsTree
train
function buildSimplePropsTree( recordTypes, topPropDesc, clause, baseValueExprCtx, propPaths) { // create the branching tree top node const topNode = PropertyTreeNode.createTopNode( recordTypes, topPropDesc, baseValueExprCtx, clause); // add properties const valuePropsTrees = new Map(); const options = { ignoreScopedOrders: true, ignorePresenceTests: (clause !== 'select') }; for (let propPath of propPaths) addProperty(topNode, null, propPath, clause, options, valuePropsTrees); // make sure there was no value trees if (valuePropsTrees.size > 0) throw new Error( 'Internal X2 error: unexpected value trees for ' + Array.from(valuePropsTrees.keys()).join(', ') + '.'); // return the tree return topNode; }
javascript
{ "resource": "" }
q36688
addProperty
train
function addProperty( topNode, scopePropPath, propPattern, clause, options, valuePropsTrees, wcPatterns) { // process the pattern parts let expandChildren = false; const propPatternParts = propPattern.split('.'); const numParts = propPatternParts.length; let parentNode = topNode; let patternPrefix = topNode.path, patternSuffix = ''; for (let i = 0; i < numParts; i++) { const propName = propPatternParts[i]; // check if wildcard if (propName === '*') { // check if allowed if (!wcPatterns) throw new common.X2SyntaxError( `Invalid property path "${propPattern}":` + ` wild cards are not allowed here.`); // set up the expansion expandChildren = true; if (i < numParts - 1) patternSuffix = '.' + propPatternParts.slice(i + 1).join('.'); // done looping through pattern parts break; } // get the child node let node = parentNode.getChild(propName); // create new node if necessary if (!node) { // create new child node node = parentNode.addChild( propName, clause, scopePropPath, options, propPattern, valuePropsTrees); } else { // existing node // include the existing node in the clause node.addClause(clause); } // add part to the reconstructed pattern prefix patternPrefix += propName + '.'; // advance down the tree parentNode = node; } // expand selected object if (!expandChildren && (parentNode.desc.scalarValueType === 'object')) { // set up the expansion if (wcPatterns) expandChildren = true; else if (!(options && options.allowLeafObjects)) // check if allowed throw new common.X2SyntaxError( `Invalid property path "${propPattern}":` + ` object properties are not allowed here.`); } // generate expanded patterns if (expandChildren) { // make sure there is a children container if (!parentNode.childrenContainer) throw new common.X2SyntaxError( `Invalid property pattern "${propPattern}":` + ` property ${parentNode.desc.container.nestedPath}` + `${parentNode.desc.name} of ` + `${String(parentNode.desc.container.recordTypeName)}` + ` is not an object nor reference and cannot be used as an` + ` intermediate property in a path.`); // generate patterns for all nested properties included by default parentNode.childrenContainer.allPropertyNames.forEach(propName => { const propDesc = parentNode.childrenContainer.getPropertyDesc( propName); if (propDesc.fetchByDefault) wcPatterns.push(patternPrefix + propName + patternSuffix); }); } // return the leaf node return parentNode; }
javascript
{ "resource": "" }
q36689
train
function(model, options, finish) { var asyncCreator = async() // Task runner that actually creates all the Mongo records // Deal with timeout errors (usually unsolvable circular references) {{{ .timeout(settings.timeout || 2000, function() { var taskIDs = {}; var remaining = this._struct // Prepare a lookup table of tasks IDs that have already finished {{{ .map(function(task) { if (task.completed) taskIDs[_(task.payload).keys().first()] = true; return task; }) // }}} // Remove non defered objects + completed tasks {{{ .filter(function(task) { return (task.type == 'deferObject' && !task.completed); }) // }}} // Remove any task that has resolved prereqs {{{ .filter(function(task) { if (!task.prereq.length) return true; // Has no prereqs anyway return ! task.prereq .every(function(prereq) { return (!! taskIDs[prereq]); }); }) // }}} // Remove any task that nothing else depends on {{{ .filter(function(task) { return true; }); // }}} finish( 'Unresolvable circular reference\n' + 'Remaining refs:\n' + remaining // Format the output {{{ .map(function(task) { return ( ' * ' + (_(task.payload).keys().first() || '???') + (task.prereq.length > 0 ? ' (Requires: ' + task.prereq .filter(function(prereq) { return (! taskIDs[prereq]); // Pre-req resolved ok? }) .join(', ') + ')': '') ); }) .join('\n') // }}} , { unresolved: remaining.map(function(task) { return _(task.payload).keys().first(); }), processed: this._struct .filter(function(task) { return (task.type == 'deferObject' && task.completed); }) .length, }); }); // }}} async() .then(function(next) { // Coherce args into scenario(<model>, [options], [callback]) {{{ if (!model) throw new Error('No arguments passed to scenario()'); if (_.isFunction(options)) { // Form: (model, callback) finish = options; } else if (options) { // Form: model(model, options) _.merge(settings, options); } if (!finish) finish = function() {}; next(); }) // }}} .then(function(next) { // Sanity checks {{{ if (!settings.connection) throw new Error('Invalid connection to Mongoose'); if (!_.isObject(model)) throw new Error('Invalid scenario invoke style - scenario(' + typeof model + ')'); next(); }) // }}} .then(function(next) { // Reset all state variables {{{ settings.progress.created = {}; if (settings.reset) settings.refs = {}; next(); }) /// }}} .then(function(next) { // Optionally Nuke existing models {{{ if (!settings.nuke) return next(); async() .set('models', _.isArray(settings.nuke) ? settings.nuke : settings.getModels()) .forEach('models', function(next, model) { var collection = settings.getCollection(model); if (!collection) return next('Model "' + model + '" is present in the Scenario schema but no model can be found matching that name, did you forget to load it?'); collection.remove({}, function(err) { if (err) next(err); settings.progress.nuked.push(model); next(); }); }) .end(next); }) // }}} .forEach(model, function(next, rows, collection) { // Compute FKs for each model {{{ if (settings.knownFK[collection]) return next(); // Already computed the FKs for this collection settings.knownFK[collection] = {}; var collectionSchema = settings.getCollectionSchema(collection); if (!collectionSchema) throw new Error('Collection "' + collection + '" not found in Mongoose schema. Did you forget to load its model?'); // Merge extracted keys into knownFKs storage settings.knownFK[collection] = extractFKs(collectionSchema); next(); }) // }}} .forEach(model, function(next, rows, collection) { // Process the Scenario profile {{{ async() .forEach(rows, function(next, row) { // Split all incomming items into defered tasks {{{ var rowFlattened = flatten(row); var id = row[settings.keys.ref] ? row[settings.keys.ref] : 'anon-' + settings.idVal++; var dependents = determineFKs(rowFlattened, settings.knownFK[collection]); var rowUnflattened = unflatten(rowFlattened); asyncCreator.defer(dependents, id, function(next) { createRow(collection, id, rowUnflattened, next); }); next(); }) // }}} .end(next); }) // }}} .then(function(next) { // Run all tasks {{{ asyncCreator .await() .end(next); }) // }}} // End {{{ .end(function(err) { if (err) return finish(err); finish(null, settings.progress); }); // }}} return scenarioImport; }
javascript
{ "resource": "" }
q36690
extractFKs
train
function extractFKs(schema) { var FKs = {}; _.forEach(schema.paths, function(path, id) { if (id == 'id' || id == '_id') { // Pass } else if (path.instance && path.instance == 'ObjectID') { FKs[id] = {type: FK_OBJECTID}; } else if (path.caster && path.caster.instance == 'ObjectID') { // Array of ObjectIDs FKs[id] = {type: FK_OBJECTID_ARRAY}; } else if (path.schema) { FKs[id] = { type: FK_SUBDOC, fks: extractFKs(path.schema), }; } }); return FKs; }
javascript
{ "resource": "" }
q36691
injectFKs
train
function injectFKs(row, fks) { _.forEach(fks, function(fk, id) { if (!_.has(row, id)) return; // Skip omitted FK refs var lookupKey = _.get(row, id); switch (fk.type) { case FK_OBJECTID: // 1:1 relationship if (!settings.refs[lookupKey]) throw new Error('Attempting to inject non-existant reference "' + row[lookupKey] + '" (from lookup ref "' + lookupKey + '") into field path "' + id + '" before its been created!'); _.set(row, id, settings.refs[lookupKey]); break; case FK_OBJECTID_ARRAY: // 1:M array based relationship _.set(row, id, _.map(lookupKey, function(fieldValueArr) { // Resolve each item in the array if (!settings.refs[fieldValueArr]) throw new Error('Attempting to use reference "' + fieldValueArr + '" in 1:M field path "' + id + '" before its been created!'); return settings.refs[fieldValueArr]; })); break; case FK_SUBDOC: // Mongo subdocument _.forEach(_.get(row, id), function(subdocItem, subdocIndex) { injectFKs(subdocItem, fks[id].fks); }); break; } }); }
javascript
{ "resource": "" }
q36692
determineFKs
train
function determineFKs(row, fks) { var refs = []; _.forEach(fks, function(fk, id) { if (row[id] === undefined) return; // Skip omitted FK refs switch (fk.type) { case FK_OBJECTID: // 1:1 relationship refs.push(row[id]); break; case FK_OBJECTID_ARRAY: // 1:M array based relationship _.forEach(row[id], function(v) { refs.push(v); }); break; case FK_SUBDOC: // Mongo subdocument _.forEach(row[id], function(v) { determineFKs(v, fks[id].fks).forEach(function(dep) { refs.push(dep); }); }); break; } }); return refs; }
javascript
{ "resource": "" }
q36693
unflatten
train
function unflatten(obj) { var out = {}; _.forEach(obj, function(v, k) { _.set(out, k, v); }); return out; }
javascript
{ "resource": "" }
q36694
createRow
train
function createRow(collection, id, row, callback) { injectFKs(row, settings.knownFK[collection]); // build up list of all sub-document _ref's that we need to find in the newly saved document // this is to ensure we capture _id from inside nested array documents that do not exist at root level var refsMeta = []; traverse(row).forEach(function (value) { var path; if ('_ref' === this.key) { path = this.path.concat(); path[path.length - 1] = '_id'; refsMeta.push({ ref: value, path: path }); } }); row = _.omit(row, settings.omitFields); settings.getCollection(collection).create(row, function(err, newItem) { if (err) return callback(err); var newItemAsObject = newItem.toObject(); for(var i = 0; i < refsMeta.length; i++) { if (traverse(newItemAsObject).has(refsMeta[i].path)) { settings.refs[refsMeta[i].ref] = traverse(newItemAsObject).get(refsMeta[i].path).toString(); } } if (id) { // This unit has its own reference - add it to the stack settings.refs[id] = newItem._id.toString(); } if (!settings.progress.created[collection]) settings.progress.created[collection] = 0; settings.progress.created[collection]++; callback(null, newItem._id); }); }
javascript
{ "resource": "" }
q36695
train
function(arr, iterator) { if (typeof iterator !== 'function') return apiRejection('iterator must be a function'); var self = this; var i = 0; return Promise.resolve().then(function iterate() { if (i == arr.length) return; return Promise.resolve(iterator.call(self, arr[i])) .then(function(result) { if (result !== undefined) return result; i++; return iterate(); }); }); }
javascript
{ "resource": "" }
q36696
train
function(value, ifFn, elseFn) { if ((ifFn && typeof ifFn !== 'function') || (elseFn && typeof elseFn !== 'function')) return apiRejection('ifFn and elseFn must be functions'); var fn = value ? ifFn : elseFn; if (!fn) return Promise.resolve(value); return Promise.resolve(fn.call(this, value)); }
javascript
{ "resource": "" }
q36697
fill
train
function fill(buffer, value) { $.checkArgumentType(buffer, 'Buffer', 'buffer'); $.checkArgumentType(value, 'number', 'value'); var length = buffer.length; for (var i = 0; i < length; i++) { buffer[i] = value; } return buffer; }
javascript
{ "resource": "" }
q36698
emptyBuffer
train
function emptyBuffer(bytes) { $.checkArgumentType(bytes, 'number', 'bytes'); var result = new buffer.Buffer(bytes); for (var i = 0; i < bytes; i++) { result.write('\0', i); } return result; }
javascript
{ "resource": "" }
q36699
integerAsBuffer
train
function integerAsBuffer(integer) { $.checkArgumentType(integer, 'number', 'integer'); var bytes = []; bytes.push((integer >> 24) & 0xff); bytes.push((integer >> 16) & 0xff); bytes.push((integer >> 8) & 0xff); bytes.push(integer & 0xff); return new Buffer(bytes); }
javascript
{ "resource": "" }