_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5000 | RecordKey | train | function RecordKey(path, recordType, name) {
this.path = LedgerPath.parse(path);
this.recordType = recordType;
this.name = name;
} | javascript | {
"resource": ""
} |
q5001 | pending | train | function pending(options) {
options = options || {};
var store = options.store;
var autoRemove = (typeof options.autoRemove === 'undefined') ? true : options.autoRemove;
if (!store) throw new Error('pending middleware requires a store');
return function pending(stanza, next) {
if (!stanza.id || !(st... | javascript | {
"resource": ""
} |
q5002 | train | function() {
var dest = gulp.dest('tmp/');
dest.on('end', function() {
grunt.log.ok('Created tmp/fn.js');
});
return gulp.src('test/fixtures/*.coffee')
.pipe(coffee())
.pipe(concat('fn.js'))
.pipe(dest);
} | javascript | {
"resource": ""
} | |
q5003 | CoapServerNode | train | function CoapServerNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
var node = this;
// Store local copies of the node configuration (as defined in the .html)
node.options = {};
node.options.name = n.name;
node.options.port = n.port;
node._in... | javascript | {
"resource": ""
} |
q5004 | train | function (showSignal) {
return function (msg) {
var b = new Buffer(1);
b.writeUInt8(showSignal ? 1 : 0, 0);
msg.addOption(new Option(Message.Option.URI_PATH, new Buffer("s")));
msg.addOption(new Option(Message.Option.URI_QUERY, b));
return msg;
... | javascript | {
"resource": ""
} | |
q5005 | pause | train | function pause (stream) {
var events = []
var onData = createEventListener('data', events)
var onEnd = createEventListener('end', events)
// buffer data
stream.on('data', onData)
// buffer end
stream.on('end', onEnd)
return {
end: function end () {
stream.removeListener('data', onData)
... | javascript | {
"resource": ""
} |
q5006 | train | function (data) {
var that = this;
if (!data) {
if (this._socketTimeout) {
clearTimeout(this._socketTimeout); //just in case
}
//waiting on data.
//logger.log("server: waiting on hello");
this._socketTimeout = setTimeout(funct... | javascript | {
"resource": ""
} | |
q5007 | train | function () {
//client will set the counter property on the message
//logger.log("server: send hello");
this.client.secureOut = this.secureOut;
this.client.sendCounter = CryptoLib.getRandomUINT16();
this.client.sendMessage("Hello", {}, null, null);
this.stage++;
... | javascript | {
"resource": ""
} | |
q5008 | train | function () {
var that = this;
this.socket.setNoDelay(true);
this.socket.setKeepAlive(true, 15 * 1000); //every 15 second(s)
this.socket.on('error', function (err) {
that.disconnect("socket error " + err);
});
this.socket.on('close', function (err) { that.dis... | javascript | {
"resource": ""
} | |
q5009 | train | function (data) {
var msg = messages.unwrap(data);
if (!msg) {
logger.error("routeMessage got a NULL coap message ", { coreID: this.getHexCoreID() });
return;
}
this._lastMessageTime = new Date();
//should be adequate
var msgCode = msg.getCode();... | javascript | {
"resource": ""
} | |
q5010 | train | function (name, uri, token, callback, once) {
var tokenHex = (token) ? utilities.toHexString(token) : null;
var beVerbose = settings.showVerboseCoreLogs;
//TODO: failWatch? What kind of timeout do we want here?
//adds a one time event
var that = this,
evtName = ('m... | javascript | {
"resource": ""
} | |
q5011 | train | function (name, type, callback) {
var that = this;
var performRequest = function () {
if (!that.HasSparkVariable(name)) {
callback(null, null, "Variable not found");
return;
}
var token = this.sendMessage("VariableRequest", { name: nam... | javascript | {
"resource": ""
} | |
q5012 | train | function (showSignal, callback) {
var timer = setTimeout(function () { callback(false); }, 30 * 1000);
//TODO: that.stopListeningFor("RaiseYourHandReturn", listenHandler);
//TODO: var listenHandler = this.listenFor("RaiseYourHandReturn", ... );
//logger.log("RaiseYourHand: asking cor... | javascript | {
"resource": ""
} | |
q5013 | train | function (name, args) {
var ready = when.defer();
var that = this;
when(this.ensureWeHaveIntrospectionData()).then(
function () {
var buf = that._transformArguments(name, args);
if (buf) {
ready.resolve(buf);
}
... | javascript | {
"resource": ""
} | |
q5014 | train | function (name, msg, callback) {
var varType = "int32"; //if the core doesn't specify, assume it's a "uint32"
//var fnState = (this.coreFnState) ? this.coreFnState.f : null;
//if (fnState && fnState[name] && fnState[name].returns) {
// varType = fnState[name].returns;
//}
... | javascript | {
"resource": ""
} | |
q5015 | train | function (name, args) {
//logger.log('transform args', { coreID: this.getHexCoreID() });
if (!args) {
return null;
}
if (!this.hasFnState()) {
logger.error("_transformArguments called without any function state!", { coreID: this.getHexCoreID() });
ret... | javascript | {
"resource": ""
} | |
q5016 | train | function () {
if (this.hasFnState()) {
return when.resolve();
}
//if we don't have a message pending, send one.
if (!this._describeDfd) {
this.sendMessage("Describe");
this._describeDfd = when.defer();
}
//let everybody else queue up ... | javascript | {
"resource": ""
} | |
q5017 | train | function(msg) {
//got a description, is it any good?
var loaded = (this.loadFnState(msg.getPayload()));
if (this._describeDfd) {
if (loaded) {
this._describeDfd.resolve();
}
else {
this._describeDfd.reject("something went wrong... | javascript | {
"resource": ""
} | |
q5018 | train | function(msg) {
//moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch).
var stamp = moment().utc().unix();
var binVal = messages.ToBinary(stamp, "uint32");
this.sendReply("GetTimeReturn", msg.getId(), binVal, msg.getToken());
} | javascript | {
"resource": ""
} | |
q5019 | train | function (isPublic, name, data, ttl, published_at, coreid) {
var rawFn = function (msg) {
try {
msg.setMaxAge(parseInt((ttl && (ttl >= 0)) ? ttl : 60));
if (published_at) {
msg.setTimestamp(moment(published_at).toDate());
}
... | javascript | {
"resource": ""
} | |
q5020 | train | function() {
if (this._chunkReceivedHandler) {
this.client.removeListener("ChunkReceived", this._chunkReceivedHandler);
}
this._chunkReceivedHandler = null;
// logger.log("HERE - _waitForMissedChunks done waiting! ", this.getLogInfo());
this.clearWatch("CompleteTransfer");
this.stage = Flasher.stages... | javascript | {
"resource": ""
} | |
q5021 | train | function (name, seconds, callback) {
if (!this._timers) {
this._timers = {};
}
if (!seconds) {
clearTimeout(this._timers[name]);
delete this._timers[name];
}
else {
this._timers[name] = setTimeout(function () {
//log... | javascript | {
"resource": ""
} | |
q5022 | train | function (fn, scope) {
return function () {
try {
return fn.apply(scope, arguments);
}
catch (ex) {
logger.error(ex);
logger.error(ex.stack);
logger.log('error bubbled up ' + ex);
}
};
} | javascript | {
"resource": ""
} | |
q5023 | train | function (left, right) {
if (!left && !right) {
return true;
}
var matches = true;
for (var prop in right) {
if (!right.hasOwnProperty(prop)) {
continue;
}
matches &= (left[prop] == right[prop]);
}
return ma... | javascript | {
"resource": ""
} | |
q5024 | train | function (dir, search, excludedDirs) {
excludedDirs = excludedDirs || [];
var result = [];
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
var fullpath = path.join(dir, files[i]);
var stat = fs.statSync(fullpath);
if (stat.is... | javascript | {
"resource": ""
} | |
q5025 | train | function (arr, handler) {
var tmp = when.defer();
var index = -1;
var results = [];
var doNext = function () {
try {
index++;
if (index > arr.length) {
tmp.resolve(results);
}
var file = ar... | javascript | {
"resource": ""
} | |
q5026 | train | function(a, b) {
var keys = Object.keys(b)
, i = 0
, l = keys.length
, val;
for (; i < l; i++) {
val = b[keys[i]];
if (has(a, val)) return true;
}
return false;
} | javascript | {
"resource": ""
} | |
q5027 | train | function(a, b) {
var found = 0
, keys = Object.keys(b)
, i = 0
, l = keys.length
, val;
for (; i < l; i++) {
val = b[keys[i]];
if (has(a, val)) found++;
}
return found === l;
} | javascript | {
"resource": ""
} | |
q5028 | getAttributes | train | function getAttributes(tag) {
let running = true;
const attributes = [];
const regexp = /(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/g;
while (running) {
const match = regexp.exec(tag);
if (match) {
attributes.push({
k... | javascript | {
"resource": ""
} |
q5029 | getPartial | train | function getPartial(attributes) {
const splitAttr = partition(attributes, (attribute) => attribute.key === 'src');
const sourcePath = splitAttr[0][0] && splitAttr[0][0].value;
let file;
if (sourcePath && fs.existsSync(options.basePath + sourcePath)) {
file = injectHTML(fs.re... | javascript | {
"resource": ""
} |
q5030 | replaceAttributes | train | function replaceAttributes(file, attributes) {
return (attributes || []).reduce((html, attrObj) =>
html.replace(options.variablePrefix + attrObj.key, attrObj.value), file && file.toString() || '');
} | javascript | {
"resource": ""
} |
q5031 | getPagesConfig | train | function getPagesConfig(entry) {
const pages = {}
// 规范中定义每个单页文件结构
// index.html,main.js,App.vue
glob.sync(PAGE_PATH + '/*/main.js')
.forEach(filePath => {
const pageName = path.basename(path.dirname(filePath))
if (entry && entry !== pageName) return
pages[pageName] = {
e... | javascript | {
"resource": ""
} |
q5032 | getHandler | train | function getHandler (method, getArgs, trans, domain = 'feathers') {
return function (req, res, next) {
res.setHeader('Allow', Object.values(allowedMethods).join(','));
let params = Object.assign({}, req.params || {});
delete params.service;
delete params.id;
delete params.subresources;
delete... | javascript | {
"resource": ""
} |
q5033 | info | train | function info (cb) {
var data = {
name: pjson.name,
message: 'pong',
version: pjson.version,
node_env: process.env.NODE_ENV,
node_ver: process.versions.node,
timestamp: Date.now(),
hostname: os.hostname(),
uptime: process.uptime(),
loadavg: os.loadavg()[0]
};
cb(null, data);
} | javascript | {
"resource": ""
} |
q5034 | parseCaseStatements | train | function parseCaseStatements (spec) {
return _(spec)
.remove(statement => !_.isUndefined(statement.case))
.map(parseCaseStatement)
.value()
} | javascript | {
"resource": ""
} |
q5035 | create | train | function create (spec) {
const accumulator = new Accumulator()
accumulator.value = spec.value
accumulator.context = spec.context
accumulator.reducer = {
spec: spec.context
}
accumulator.entityOverrides = merge({}, spec.entityOverrides)
accumulator.locals = merge({}, spec.locals)
accumulator.values ... | javascript | {
"resource": ""
} |
q5036 | calculateCountOfReplacementChar | train | function calculateCountOfReplacementChar(string, replaceByChar = ' ') {
var characters = 0
string
.split('')
.forEach(char => {
var size = charSizes.get(char) || 1
characters += size
})
// All sizes were measured against space char. Recalculate if needed.
if (replaceByChar !== ' ')
characters = charac... | javascript | {
"resource": ""
} |
q5037 | sanitizeLines | train | function sanitizeLines(frame) {
// Sanitize newlines & replace tabs.
lines = stripAnsi(frame)
.replace(/\r/g, '')
.split('\n')
.map(l => l.replace(/\t/g, ' '))
// Remove left caret.
var leftCaretLine = lines.find(l => l.startsWith('>'))
if (leftCaretLine) {
lines[lines.indexOf(leftCaretLine)] = leftCaretL... | javascript | {
"resource": ""
} |
q5038 | extractMessage | train | function extractMessage(error) {
var {message} = error
if (error.plugin === 'babel') {
// Hey Babel, you're not helping!
var filepath = error.id
var message = error.message
function stripFilePath() {
var index = message.indexOf(filepath)
console.log(index, filepath.length)
message = message.slice(0, ... | javascript | {
"resource": ""
} |
q5039 | readSync | train | function readSync(description, options) {
var file = vfile(description)
file.contents = fs.readFileSync(path.resolve(file.cwd, file.path), options)
return file
} | javascript | {
"resource": ""
} |
q5040 | writeSync | train | function writeSync(description, options) {
var file = vfile(description)
fs.writeFileSync(
path.resolve(file.cwd, file.path),
file.contents || '',
options
)
} | javascript | {
"resource": ""
} |
q5041 | set | train | function set (target, key, value) {
const obj = {}
obj[key] = value
return Object.assign({}, target, obj)
} | javascript | {
"resource": ""
} |
q5042 | train | function (certparams) {
var keys = forge.pki.rsa.generateKeyPair(2048);
this.publicKey = keys.publicKey;
this.privateKey = keys.privateKey;
this.cert = this.createCertificate(certparams);
this.keycred = null;
this.digest = null;
} | javascript | {
"resource": ""
} | |
q5043 | clear | train | function clear (store) {
const forDeletion = []
const now = Date.now()
for (const [key, entry] of store) {
// mark for deletion entries that have timed out
if (now - entry.created > entry.ttl) {
forDeletion.push(key)
}
}
const forDeletionLength = forDeletion.length
// if nothing to clean... | javascript | {
"resource": ""
} |
q5044 | exists | train | function exists (store, key) {
const entry = store.get(key)
// checks entry exists and it has not timed-out
return !!entry && Date.now() - entry.created < entry.ttl
} | javascript | {
"resource": ""
} |
q5045 | assignParamsHelper | train | function assignParamsHelper (accumulator, entity) {
if (accumulator.entityOverrides[entity.entityType]) {
return merge(
{},
entity.params,
accumulator.entityOverrides[entity.entityType].params
)
}
return entity.params
} | javascript | {
"resource": ""
} |
q5046 | get | train | function get (manager, errorInfoCb, id) {
const value = manager.store.get(id)
if (_.isUndefined(value)) {
const errorInfo = errorInfoCb(id)
const e = new Error(errorInfo.message)
e.name = errorInfo.name
throw e
}
return value
} | javascript | {
"resource": ""
} |
q5047 | isRevalidatingCacheKey | train | function isRevalidatingCacheKey (ctx, currentEntryKey) {
const revalidatingCache = ctx.locals.revalidatingCache
return (revalidatingCache && revalidatingCache.entryKey) === currentEntryKey
} | javascript | {
"resource": ""
} |
q5048 | resolveStaleWhileRevalidateEntry | train | function resolveStaleWhileRevalidateEntry (service, entryKey, cache, ctx) {
// NOTE: pulling through module.exports allows us to test if they were called
const {
resolveStaleWhileRevalidate,
isRevalidatingCacheKey,
shouldTriggerRevalidate,
revalidateEntry
} = module.exports
// IMPORTANT: we onl... | javascript | {
"resource": ""
} |
q5049 | train | function(a){
// Copy prototype properties.
for(var b in a.prototype){var c=b.match(/^(.*?[A-Z]{2,})(.*)$/),d=j(b);null!==c&&(d=c[1]+j(c[2])),d!==b&&(
// Add static methods as aliases.
d in a||(a[d]=function(b){return function(){var c=new a;return c[b].apply(c,arguments)}}(b),l(a,d,b)),
// Create `camelCase` aliases.
d ... | javascript | {
"resource": ""
} | |
q5050 | setSWRStaleEntry | train | function setSWRStaleEntry (service, key, value, ttl) {
return setEntry(service, createSWRStaleKey(key), value, ttl)
} | javascript | {
"resource": ""
} |
q5051 | _getLocalPositionFromWorldPosition | train | function _getLocalPositionFromWorldPosition(transform) {
if (transform.parent === undefined)
return transform.position;
else
return transform.parent.rotation.inverse().mulVector3(transform.position.sub(transform.parent.position));
} | javascript | {
"resource": ""
} |
q5052 | _getWorldPositionFromLocalPosition | train | function _getWorldPositionFromLocalPosition(transform) {
if (transform.parent === undefined)
return transform.localPosition;
else
return transform.parent.position.add(transform.parent.rotation.mulVector3(transform.localPosition));
} | javascript | {
"resource": ""
} |
q5053 | _getLocalRotationFromWorldRotation | train | function _getLocalRotationFromWorldRotation(transform) {
if(transform.parent === undefined)
return transform.rotation;
else
return transform.parent.rotation.inverse().mul(transform.rotation);
} | javascript | {
"resource": ""
} |
q5054 | _getWorldRotationFromLocalRotation | train | function _getWorldRotationFromLocalRotation(transform) {
if(transform.parent === undefined)
return transform.localRotation;
else
return transform.parent.rotation.mul(transform.localRotation);
} | javascript | {
"resource": ""
} |
q5055 | _adjustChildren | train | function _adjustChildren(children) {
children.forEach(function (child) {
child.rotation = _getWorldRotationFromLocalRotation(child);
child.position = _getWorldPositionFromLocalPosition(child);
});
} | javascript | {
"resource": ""
} |
q5056 | _getLocalToWorldMatrix | train | function _getLocalToWorldMatrix(transform) {
return function() {
return Matrix4x4.LocalToWorldMatrix(transform.position, transform.rotation, Vector3.one);
}
} | javascript | {
"resource": ""
} |
q5057 | _getWorldtoLocalMatrix | train | function _getWorldtoLocalMatrix(transform) {
return function() {
return Matrix4x4.WorldToLocalMatrix(transform.position, transform.rotation, Vector3.one);
}
} | javascript | {
"resource": ""
} |
q5058 | _getRoot | train | function _getRoot(transform) {
return function() {
var parent = transform.parent;
return parent === undefined ? transform : parent.root;
}
} | javascript | {
"resource": ""
} |
q5059 | disposeInactiveEntries | train | function disposeInactiveEntries(
devMiddleware,
entries,
lastAccessPages,
maxInactiveAge
) {
const disposingPages = [];
Object.keys(entries).forEach(page => {
const { lastActiveTime, status } = entries[page];
// This means this entry is currently building or just added
// We don't need to disp... | javascript | {
"resource": ""
} |
q5060 | resolveOptions | train | function resolveOptions (accumulator, resolveReducer) {
const url = resolveUrl(accumulator)
const specOptions = accumulator.reducer.spec.options
return resolveReducer(accumulator, specOptions).then(acc => {
const options = getRequestOptions(url, acc.value)
return utils.assign(accumulator, { options })
}... | javascript | {
"resource": ""
} |
q5061 | train | function (p1x, p1y, p2x, p2y) {
return Math.sqrt((p2x - p1x) * (p2x - p1x) + (p2y - p1y) * (p2y - p1y));
} | javascript | {
"resource": ""
} | |
q5062 | bootstrapAPI | train | function bootstrapAPI (cache) {
cache.set = set.bind(null, cache)
cache.get = get.bind(null, cache)
cache.del = del.bind(null, cache)
return cache
} | javascript | {
"resource": ""
} |
q5063 | _getRows | train | function _getRows(matrix) {
var rows = [];
for (var i=0; i<matrix.size.rows; i++) {
rows.push([]);
for (var j=0; j<matrix.size.columns; j++)
rows[i].push(matrix.values[matrix.size.columns * i + j]);
}
return rows;
} | javascript | {
"resource": ""
} |
q5064 | _getColumns | train | function _getColumns(matrix) {
var cols = [];
for (var i=0; i<matrix.size.columns; i++) {
cols.push([]);
for (var j=0; j<matrix.size.rows; j++)
cols[i].push(matrix.values[i + j * matrix.size.columns]);
}
return cols;
} | javascript | {
"resource": ""
} |
q5065 | _sizesMatch | train | function _sizesMatch(matrix1, matrix2) {
return matrix1.size.rows == matrix2.size.rows &&
matrix1.size.columns == matrix2.size.columns;
} | javascript | {
"resource": ""
} |
q5066 | _fromVector | train | function _fromVector(vector) {
return new _Vector4(vector.values[0], vector.values[1], vector.values[2], vector.values[3]);
} | javascript | {
"resource": ""
} |
q5067 | _normalizedCoordinates | train | function _normalizedCoordinates(x, y, z, w) {
var magnitude = Math.sqrt(x * x + y * y + z * z + w * w);
if (magnitude === 0)
return this;
return {
"x": x / magnitude,
"y": y / magnitude,
"z": z / magnitude,
"w": w / magnitude};
} | javascript | {
"resource": ""
} |
q5068 | _fromAngleAxis | train | function _fromAngleAxis(axis, angle) {
var s = Math.sin(angle/2);
var c = Math.cos(angle/2);
return new _Quaternion(axis.x * s, axis.y * s, axis.z * s, c);
} | javascript | {
"resource": ""
} |
q5069 | _getAngleAxis | train | function _getAngleAxis(quaternion) {
return function() {
var sqrt = Math.sqrt(1 - quaternion.w * quaternion.w);
return {
axis: new Vector3(quaternion.x / sqrt, quaternion.y / sqrt, quaternion.z / sqrt),
angle: 2 * Math.acos(quaternion.w) * radToDeg
};
}
} | javascript | {
"resource": ""
} |
q5070 | normalizeInput | train | function normalizeInput (source) {
let result = ReducerList.parse(source)
if (result.length === 1) {
// do not create a ReducerList that only contains a single reducer
result = result[0]
}
return result
} | javascript | {
"resource": ""
} |
q5071 | resolveReducer | train | function resolveReducer (manager, accumulator, reducer) {
// this conditional is here because BaseEntity#resolve
// does not check that lifecycle methods are defined
// before trying to resolve them
if (!reducer) {
return Promise.resolve(accumulator)
}
const isTracing = accumulator.trace
const acc =... | javascript | {
"resource": ""
} |
q5072 | _magnitudeOf | train | function _magnitudeOf(values) {
var result = 0;
for (var i = 0; i < values.length; i++)
result += values[i] * values[i];
return Math.sqrt(result);
} | javascript | {
"resource": ""
} |
q5073 | augmentAccumulatorTrace | train | function augmentAccumulatorTrace (accumulator, reducer) {
const acc = module.exports.createTracedAccumulator(accumulator, reducer)
acc.traceGraph.push(acc.traceNode)
return acc
} | javascript | {
"resource": ""
} |
q5074 | read | train | function read(description, options, callback) {
var file = vfile(description)
if (!callback && typeof options === 'function') {
callback = options
options = null
}
if (!callback) {
return new Promise(executor)
}
executor(resolve, callback)
function resolve(result) {
callback(null, resu... | javascript | {
"resource": ""
} |
q5075 | write | train | function write(description, options, callback) {
var file = vfile(description)
// Weird, right? Otherwise `fs` doesn’t accept it.
if (!callback && typeof options === 'function') {
callback = options
options = undefined
}
if (!callback) {
return new Promise(executor)
}
executor(resolve, call... | javascript | {
"resource": ""
} |
q5076 | warnLooseParamsCacheDeprecation | train | function warnLooseParamsCacheDeprecation (params) {
if (params.ttl || params.cacheKey || params.staleWhileRevalidate) {
module.exports.looseCacheParamsDeprecationWarning()
}
} | javascript | {
"resource": ""
} |
q5077 | _shutdownNextServices | train | async function _shutdownNextServices(reversedServiceSequence) {
if (0 === reversedServiceSequence.length) {
return;
}
await Promise.all(
reversedServiceSequence.pop().map(async serviceName => {
const singletonServiceDescriptor = await _this._pickupSin... | javascript | {
"resource": ""
} |
q5078 | List | train | function List(options) {
if (!(this instanceof List)) {
return new List(options);
}
Base.call(this);
this.is('list');
this.define('isCollection', true);
this.use(utils.option());
this.use(utils.plugin());
this.init(options || {});
} | javascript | {
"resource": ""
} |
q5079 | decorate | train | function decorate(list, method, prop) {
utils.define(list.items, method, function() {
var res = list[method].apply(list, arguments);
return prop ? res[prop] : res;
});
} | javascript | {
"resource": ""
} |
q5080 | handleLayout | train | function handleLayout(obj, stats, depth) {
var layoutName = obj.layout.basename;
debug('applied layout (#%d) "%s", to file "%s"', depth, layoutName, file.path);
file.currentLayout = obj.layout;
file.define('layoutStack', stats.history);
app.handleOnce('onLayout', file);
... | javascript | {
"resource": ""
} |
q5081 | buildStack | train | function buildStack(app, name, view) {
var layoutExists = false;
var registered = 0;
var layouts = {};
// get all collections with `viewType` layout
var collections = app.viewTypes.layout;
var len = collections.length;
var idx = -1;
while (++idx < len) {
var collection = app[coll... | javascript | {
"resource": ""
} |
q5082 | Collection | train | function Collection(options) {
if (!(this instanceof Collection)) {
return new Collection(options);
}
Base.call(this, {}, options);
this.is('Collection');
this.items = {};
this.use(utils.option());
this.use(utils.plugin());
this.init(options || {});
} | javascript | {
"resource": ""
} |
q5083 | Templates | train | function Templates(options) {
if (!(this instanceof Templates)) {
return new Templates(options);
}
Base.call(this, null, options);
this.is('templates');
this.define('isApp', true);
this.use(utils.option());
this.use(utils.plugin());
this.initTemplates();
} | javascript | {
"resource": ""
} |
q5084 | setHelperOptions | train | function setHelperOptions(context, key) {
var optsHelper = context.options.helper || {};
if (optsHelper.hasOwnProperty(key)) {
context.helper.options = optsHelper[key];
}
} | javascript | {
"resource": ""
} |
q5085 | Context | train | function Context(app, view, context, helpers) {
this.helper = {};
this.helper.options = createHelperOptions(app, view, helpers);
this.context = context;
utils.define(this.context, 'view', view);
this.options = utils.merge({}, app.options, view.options, this.helper.options);
// make `this.optio... | javascript | {
"resource": ""
} |
q5086 | decorate | train | function decorate(obj) {
utils.define(obj, 'merge', function() {
var args = [].concat.apply([], [].slice.call(arguments));
var len = args.length;
var idx = -1;
while (++idx < len) {
var val = args[idx];
if (!utils.isObject(val)) continue;
if (val.hasOwnProperty('hash... | javascript | {
"resource": ""
} |
q5087 | mergePartials | train | function mergePartials(options) {
var opts = utils.merge({}, this.options, options);
var names = opts.mergeTypes || this.viewTypes.partial;
var partials = {};
var self = this;
names.forEach(function(name) {
var collection = self.views[name];
for (var key in collection) {
var vie... | javascript | {
"resource": ""
} |
q5088 | FixEncryptLength | train | function FixEncryptLength(text) {
var len = text.length;
var stdLens = [256, 512, 1024, 2048, 4096];
var stdLen, i, j;
for (i = 0; i < stdLens.length; i++) {
stdLen = stdLens[i];
if (len === stdLen) {
return text;
} else if (len < stdLen) {
var times = stdLen - len;
var preText = '... | javascript | {
"resource": ""
} |
q5089 | Group | train | function Group(config) {
if (!(this instanceof Group)) {
return new Group(config);
}
Base.call(this, config);
this.is('Group');
this.use(utils.option());
this.use(utils.plugin());
this.init();
} | javascript | {
"resource": ""
} |
q5090 | handleErrors | train | function handleErrors(group, val) {
if (utils.isObject(val)) {
var List = group.List;
var keys = Object.keys(List.prototype);
keys.forEach(function(key) {
if (typeof val[key] !== 'undefined') return;
utils.define(val, key, function() {
throw new Error(key + ' can only be used with an... | javascript | {
"resource": ""
} |
q5091 | objectFactory | train | function objectFactory(data) {
// if we are given an object Object, no-op and return it now.
if (_.isPlainObject(data)) {
return data;
}
// If we are given a byte Buffer, parse it as utf-8
if (data instanceof Buffer) {
data = data.toString('utf-8');
}
// If we now have a st... | javascript | {
"resource": ""
} |
q5092 | createKafkaConsumerAsync | train | function createKafkaConsumerAsync(kafkaConfig) {
let topicConfig = {};
if ('default_topic_config' in kafkaConfig) {
topicConfig = kafkaConfig.default_topic_config;
delete kafkaConfig.default_topic_config;
}
const consumer = P.promisifyAll(
new kafka.KafkaConsumer(kafkaConfig, to... | javascript | {
"resource": ""
} |
q5093 | getAvailableTopics | train | function getAvailableTopics(topicsInfo, allowedTopics) {
const existentTopics = topicsInfo.map(
e => e.name
)
.filter(t => t !== '__consumer_offsets');
if (allowedTopics) {
return existentTopics.filter(t => _.includes(allowedTopics, t));
}
else {
return existentTopics;
... | javascript | {
"resource": ""
} |
q5094 | assignmentsForTimesAsync | train | function assignmentsForTimesAsync(kafkaConsumer, assignments) {
const assignmentsWithTimestamps = assignments.filter(a => 'timestamp' in a && !('offset' in a)).map((a) => {
return {topic: a.topic, partition: a.partition, offset: a.timestamp };
});
// If there were no timestamps to resolve, just ret... | javascript | {
"resource": ""
} |
q5095 | deserializeKafkaMessage | train | function deserializeKafkaMessage(kafkaMessage) {
kafkaMessage.message = objectFactory(kafkaMessage.value);
kafkaMessage.message._kafka = {
topic: kafkaMessage.topic,
partition: kafkaMessage.partition,
offset: kafkaMessage.offset,
timestamp: kafkaMessage.timestamp || null,... | javascript | {
"resource": ""
} |
q5096 | findView | train | function findView(app, name) {
var keys = app.viewTypes.renderable;
var len = keys.length;
var i = -1;
var res = null;
while (++i < len) {
res = app.find(name, keys[i]);
if (res) {
break;
}
}
return res;
} | javascript | {
"resource": ""
} |
q5097 | getView | train | function getView(app, view) {
if (typeof view !== 'string') {
return view;
}
if (app.isCollection) {
view = app.getView(view);
} else if (app.isList) {
view = app.getItem(view);
} else {
view = findView(app, view);
}
return view;
} | javascript | {
"resource": ""
} |
q5098 | Generator | train | function Generator (fn, opts) {
if (fn instanceof Function) {
if (typeof opts === 'number') {
opts = {duration: opts};
}
else {
opts = opts || {};
}
opts.generate = fn;
}
else {
opts = fn || {};
}
//sort out arguments
opts = extend({
//total duration of a stream
duration: Infinity,
//tim... | javascript | {
"resource": ""
} |
q5099 | deserializeQueryParam | train | function deserializeQueryParam(param) {
if (!!param && (typeof param === 'object')) {
if (param.__type === 'Date') {
return new Date(param.iso);
}
}
return param;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.