_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q53800
|
EventUploadMessage
|
train
|
function EventUploadMessage(properties) {
this.events = [];
if (properties)
for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
if (properties[keys[i]] != null)
this[keys[i]] = properties[keys[i]];
}
|
javascript
|
{
"resource": ""
}
|
q53801
|
getRoutedMessageHandler
|
train
|
function getRoutedMessageHandler(params, onMessage, onError, isRetryPatchMode) {
var expectedBatchMessageCount = 0;
var numBatchesDetermined = false;
var messageBatchBuffer = [];
var lastSeenDataTime = 0;
var lastSeenDataBatchTime = 0;
function composeDataBatches(dataArray) {
if (dataArray.length === 0) {
if (messageBatchBuffer.length > 0) {
console.error('Composed an empty data batch despite having data in the buffer!');
}
return null;
}
var errorOccurred = false;
var basisData = dataArray[0];
var expectedTimeStamp = basisData.logicalTimestampMs;
lastSeenDataBatchTime = expectedTimeStamp;
dataArray.slice(1).forEach(function (batch) {
if (batch.logicalTimestampMs !== expectedTimeStamp) {
errorOccurred = true;
} else {
basisData.data = basisData.data.concat(batch.data);
}
});
if (errorOccurred) {
console.error('Bad timestamp pairs when flushing data batches! Inconsistent data!');
return null;
}
return basisData;
}
function flushBuffer() {
if (numBatchesDetermined && messageBatchBuffer.length === expectedBatchMessageCount && messageBatchBuffer.length > 0) {
onMessage(composeDataBatches(messageBatchBuffer));
messageBatchBuffer = [];
}
}
return {
getLatestBatchTimeStamp: function () {
return lastSeenDataBatchTime;
},
onMessage: function messageReceived(msg) {
if (!msg.type && msg.hasOwnProperty('error')) {
onMessage(msg);
return;
}
switch (msg.type) {
case 'data':
if (lastSeenDataTime && lastSeenDataTime !== msg.logicalTimestampMs) {
// if zero time series are encountered, then no metadata arrives, but data batches arrive with differing
// timestamp as the only evidence of a stream block
numBatchesDetermined = true;
}
lastSeenDataTime = msg.logicalTimestampMs;
messageBatchBuffer.push(msg);
if (!numBatchesDetermined) {
expectedBatchMessageCount++;
} else if (messageBatchBuffer.length === expectedBatchMessageCount) {
flushBuffer();
}
break;
case 'message':
if (msg.message && msg.message.messageCode === 'JOB_RUNNING_RESOLUTION') {
numBatchesDetermined = true;
flushBuffer();
}
onMessage(msg);
break;
case 'metadata':
case 'event':
onMessage(msg);
break;
case 'control-message':
if (isRetryPatchMode && !numBatchesDetermined) {
break;
}
onMessage(msg);
break;
case 'error':
if (onError) {
onError(msg);
}
break;
default:
console.log('Unrecognized message type.');
break;
}
flushBuffer();
}
};
}
|
javascript
|
{
"resource": ""
}
|
q53802
|
load_shims_sync
|
train
|
function load_shims_sync(paths, browser) {
// identify if our file should be replaced per the browser field
// original filename|id -> replacement
var shims = Object.create(null);
var cur_path;
while (cur_path = paths.shift()) {
var pkg_path = path.join(cur_path, 'package.json');
try {
var data = fs.readFileSync(pkg_path, 'utf8');
find_shims_in_package(data, cur_path, shims, browser);
return shims;
}
catch (err) {
// ignore paths we can't open
// avoids an exists check
if (err.code === 'ENOENT') {
continue;
}
throw err;
}
}
return shims;
}
|
javascript
|
{
"resource": ""
}
|
q53803
|
hexTypeFactory
|
train
|
function hexTypeFactory (serizalizer, size, name) {
return Object.defineProperties({}, {
size: {
get: () => () => size,
enumerable: true
},
name: {
get: () => name,
enumerable: true
},
serialize: {
get: () => serizalizer
}
})
}
|
javascript
|
{
"resource": ""
}
|
q53804
|
Uuid
|
train
|
function Uuid (validator, serializer, factory) {
const size = 16
const name = 'Uuid'
function cleaner (value) {
return String(value).replace(/-/g, '')
}
validator = validator.bind(null, name, size)
serializer = serializer((value) => validator(cleaner(value)))
return factory(serializer, size, name)
}
|
javascript
|
{
"resource": ""
}
|
q53805
|
Hash
|
train
|
function Hash (validator, serializer, factory) {
const size = HASH_LENGTH
const name = 'Hash'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
const hasher = function (value) {
return validator(value) && value
}
return Object.defineProperty(factory(serializer, size, name),
'hash',
{
value: hasher
})
}
|
javascript
|
{
"resource": ""
}
|
q53806
|
Digest
|
train
|
function Digest (validator, serializer, factory) {
const size = 64
const name = 'Digest'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
return factory(serializer, size, name)
}
|
javascript
|
{
"resource": ""
}
|
q53807
|
PublicKey
|
train
|
function PublicKey (validator, serializer, factory) {
const size = PUBLIC_KEY_LENGTH
const name = 'PublicKey'
validator = validator.bind(null, name, size)
serializer = serializer(validator)
return factory(serializer, size, name)
}
|
javascript
|
{
"resource": ""
}
|
q53808
|
insertIntegerToByteArray
|
train
|
function insertIntegerToByteArray (number, buffer, from, size) {
let value = bigInt(number) // convert a number-like object into a big integer
for (let pos = 0; pos < size; pos++) {
const divmod = value.divmod(256)
buffer[from + pos] = divmod.remainder.toJSNumber()
value = divmod.quotient
}
return buffer
}
|
javascript
|
{
"resource": ""
}
|
q53809
|
calcHeight
|
train
|
function calcHeight (count) {
let i = 0
while (bigInt(2).pow(i).lt(count)) {
i++
}
return i
}
|
javascript
|
{
"resource": ""
}
|
q53810
|
getHash
|
train
|
function getHash (data, depth, index) {
let element
let elementsHash
if (depth !== 0 && (depth + 1) !== height) {
throw new Error('Value node is on wrong height in tree.')
}
if (start.gt(index) || end.lt(index)) {
throw new Error('Wrong index of value node.')
}
if (start.plus(elements.length).neq(index)) {
throw new Error('Value node is on wrong position in tree.')
}
if (typeof data === 'string') {
if (!validateHexadecimal(data)) {
throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.')
}
element = data
elementsHash = element
} else {
if (Array.isArray(data)) {
if (!validateBytesArray(data)) {
throw new TypeError('Tree element of wrong type is passed. Bytes array expected.')
}
element = data.slice(0) // clone array of 8-bit integers
elementsHash = hash(element)
} else {
if (!isObject(data)) {
throw new TypeError('Invalid value of data parameter.')
}
if (!isType(type)) {
throw new TypeError('Invalid type of type parameter.')
}
element = data
elementsHash = hash(element, type)
}
}
elements.push(element)
return elementsHash
}
|
javascript
|
{
"resource": ""
}
|
q53811
|
recursive
|
train
|
function recursive (node, depth, index) {
let hashLeft
let hashRight
let summingBuffer
// case with single node in tree
if (depth === 0 && node.val !== undefined) {
return getHash(node.val, depth, index * 2)
}
if (node.left === undefined) {
throw new Error('Left node is missed.')
}
if (typeof node.left === 'string') {
if (!validateHexadecimal(node.left)) {
throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.')
}
hashLeft = node.left
} else {
if (!isObject(node.left)) {
throw new TypeError('Invalid type of left node.')
}
if (node.left.val !== undefined) {
hashLeft = getHash(node.left.val, depth, index * 2)
} else {
hashLeft = recursive(node.left, depth + 1, index * 2)
}
}
if (depth === 0) {
rootBranch = 'right'
}
if (node.right !== undefined) {
if (typeof node.right === 'string') {
if (!validateHexadecimal(node.right)) {
throw new TypeError('Tree element of wrong type is passed. Hexadecimal expected.')
}
hashRight = node.right
} else {
if (!isObject(node.right)) {
throw new TypeError('Invalid type of right node.')
}
if (node.right.val !== undefined) {
hashRight = getHash(node.right.val, depth, index * 2 + 1)
} else {
hashRight = recursive(node.right, depth + 1, index * 2 + 1)
}
}
summingBuffer = new Uint8Array(64)
summingBuffer.set(hexadecimalToUint8Array(hashLeft))
summingBuffer.set(hexadecimalToUint8Array(hashRight), 32)
return hash(summingBuffer)
}
if (depth === 0 || rootBranch === 'left') {
throw new Error('Right leaf is missed in left branch of tree.')
}
summingBuffer = hexadecimalToUint8Array(hashLeft)
return hash(summingBuffer)
}
|
javascript
|
{
"resource": ""
}
|
q53812
|
setBit
|
train
|
function setBit (buffer, pos, bit) {
const byte = Math.floor(pos / 8)
const bitPos = pos % 8
if (bit === 0) {
const mask = 255 - (1 << bitPos)
buffer[byte] &= mask
} else {
const mask = (1 << bitPos)
buffer[byte] |= mask
}
}
|
javascript
|
{
"resource": ""
}
|
q53813
|
serializeKey
|
train
|
function serializeKey (serviceId, tableIndex) {
let buffer = []
Uint16.serialize(serviceId, buffer, buffer.length)
Uint16.serialize(tableIndex, buffer, buffer.length)
return buffer
}
|
javascript
|
{
"resource": ""
}
|
q53814
|
setAsyncContent
|
train
|
function setAsyncContent(event) {
that._content.innerHTML = event.response;
/**
* Event emitted when the content change.
* @event ch.Content#contentchange
* @private
*/
that.emit('_contentchange');
/**
* Event emitted if the content is loaded successfully.
* @event ch.Content#contentdone
* @ignore
*/
/**
* Event emitted when the content is loading.
* @event ch.Content#contentwaiting
* @example
* // Subscribe to "contentwaiting" event.
* component.on('contentwaiting', function (event) {
* // Some code here!
* });
*/
/**
* Event emitted if the content isn't loaded successfully.
* @event ch.Content#contenterror
* @example
* // Subscribe to "contenterror" event.
* component.on('contenterror', function (event) {
* // Some code here!
* });
*/
that.emit('content' + event.status, event);
}
|
javascript
|
{
"resource": ""
}
|
q53815
|
setContent
|
train
|
function setContent(content) {
if (content.nodeType !== undefined) {
that._content.innerHTML = '';
that._content.appendChild(content);
} else {
that._content.innerHTML = content;
}
that._options.cache = true;
/**
* Event emitted when the content change.
* @event ch.Content#contentchange
* @private
*/
that.emit('_contentchange');
/**
* Event emitted if the content is loaded successfully.
* @event ch.Content#contentdone
* @example
* // Subscribe to "contentdone" event.
* component.on('contentdone', function (event) {
* // Some code here!
* });
*/
that.emit('contentdone');
}
|
javascript
|
{
"resource": ""
}
|
q53816
|
getAsyncContent
|
train
|
function getAsyncContent(url, options) {
var requestCfg;
// Initial options to be merged with the user's options
options = tiny.extend({
'method': 'GET',
'params': '',
'waiting': '<div class="ch-loading-large"></div>'
}, defaults, options);
// Set loading
setAsyncContent({
'status': 'waiting',
'response': options.waiting
});
requestCfg = {
method: options.method,
success: function(resp) {
setAsyncContent({
'status': 'done',
'response': resp
});
},
error: function(err) {
setAsyncContent({
'status': 'error',
'response': '<p>Error on ajax call.</p>',
'data': err.message || JSON.stringify(err)
});
}
};
if (options.cache !== undefined) {
that._options.cache = options.cache;
}
if (options.cache === false && ['GET', 'HEAD'].indexOf(options.method.toUpperCase()) !== -1) {
requestCfg.cache = false;
}
if (options.params) {
if (['GET', 'HEAD'].indexOf(options.method.toUpperCase()) !== -1) {
url += (url.indexOf('?') !== -1 || options.params[0] === '?' ? '' : '?') + options.params;
} else {
requestCfg.data = options.params;
}
}
// Make a request
tiny.ajax(url, requestCfg);
}
|
javascript
|
{
"resource": ""
}
|
q53817
|
Positioner
|
train
|
function Positioner(options) {
if (options === undefined) {
throw new window.Error('ch.Positioner: Expected options defined.');
}
// Creates its private options
this._options = tiny.clone(this._defaults);
// Init
this._configure(options);
}
|
javascript
|
{
"resource": ""
}
|
q53818
|
train
|
function (shortcut, name, callback) {
if (this._collection[name] === undefined) {
this._collection[name] = {};
}
if (this._collection[name][shortcut] === undefined) {
this._collection[name][shortcut] = [];
}
this._collection[name][shortcut].push(callback);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53819
|
train
|
function (name, shortcut, callback) {
var evt,
evtCollection,
evtCollectionLenght;
if (name === undefined) {
throw new Error('Shortcuts - "remove(name, shortcut, callback)": "name" parameter must be defined.');
}
if (shortcut === undefined) {
delete this._collection[name];
return this;
}
if (callback === undefined) {
delete this._collection[name][shortcut];
return this;
}
evtCollection = this._collection[name][shortcut];
evtCollectionLenght = evtCollection.length;
for (evt = 0; evt < evtCollectionLenght; evt += 1) {
if (evtCollection[evt] === callback) {
evtCollection.splice(evt, 1);
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53820
|
Tooltip
|
train
|
function Tooltip(el, options) {
// TODO: Review what's going on here with options
/*
if (options === undefined && el !== undefined && el.nodeType !== undefined) {
options = el;
el = undefined;
}
*/
options = tiny.extend(tiny.clone(this._defaults), options);
return new ch.Layer(el, options);
}
|
javascript
|
{
"resource": ""
}
|
q53821
|
Transition
|
train
|
function Transition(el, options) {
if (el === undefined || options === undefined) {
options = {};
}
options.content = (function () {
var dummyElement = document.createElement('div'),
content = options.waiting || '';
// TODO: options.content could be a HTMLElement
dummyElement.innerHTML = '<div class="ch-loading-large"></div><p>' + content + '</p>';
return dummyElement.firstChild;
}());
// el is not defined
if (el === undefined) {
el = tiny.extend(tiny.clone(this._defaults), options);
// el is present as a object configuration
} else if (el.nodeType === undefined && typeof el === 'object') {
el = tiny.extend(tiny.clone(this._defaults), el);
} else if (options !== undefined) {
options = tiny.extend(tiny.clone(this._defaults), options);
}
return new ch.Modal(el, options);
}
|
javascript
|
{
"resource": ""
}
|
q53822
|
Countdown
|
train
|
function Countdown(el, options) {
/**
* Reference to context of an instance.
* @type {Object}
* @private
*/
var that = this;
this._init(el, options);
if (this.initialize !== undefined) {
/**
* If you define an initialize method, it will be executed when a new Countdown is created.
* @memberof! ch.Countdown.prototype
* @function
*/
this.initialize();
}
/**
* Event emitted when the component is ready to use.
* @event ch.Countdown#ready
* @example
* // Subscribe to "ready" event.
* countdown.on('ready', function () {
* // Some code here!
* });
*/
window.setTimeout(function () { that.emit('ready'); }, 50);
}
|
javascript
|
{
"resource": ""
}
|
q53823
|
cancelPointerOnScroll
|
train
|
function cancelPointerOnScroll() {
function blockPointer() {
ch.pointerCanceled = true;
function unblockPointer() {
ch.pointerCanceled = false;
}
tiny.once(document, 'touchend', unblockPointer);
}
tiny.on(document, 'touchmove', blockPointer);
}
|
javascript
|
{
"resource": ""
}
|
q53824
|
tmpl
|
train
|
function tmpl(str, data) {
return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
return data[key] || '';
});
}
|
javascript
|
{
"resource": ""
}
|
q53825
|
OAuthStrategy
|
train
|
function OAuthStrategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = undefined;
}
options = options || {};
if (!verify) { throw new TypeError('OAuthStrategy requires a verify callback'); }
if (!options.requestTokenURL) { throw new TypeError('OAuthStrategy requires a requestTokenURL option'); }
if (!options.accessTokenURL) { throw new TypeError('OAuthStrategy requires a accessTokenURL option'); }
if (!options.userAuthorizationURL) { throw new TypeError('OAuthStrategy requires a userAuthorizationURL option'); }
if (!options.consumerKey) { throw new TypeError('OAuthStrategy requires a consumerKey option'); }
if (options.consumerSecret === undefined) { throw new TypeError('OAuthStrategy requires a consumerSecret option'); }
passport.Strategy.call(this);
this.name = 'oauth';
this._verify = verify;
// NOTE: The _oauth property is considered "protected". Subclasses are
// allowed to use it when making protected resource requests to retrieve
// the user profile.
this._oauth = new OAuth(options.requestTokenURL, options.accessTokenURL,
options.consumerKey, options.consumerSecret,
'1.0', null, options.signatureMethod || 'HMAC-SHA1',
null, options.customHeaders);
this._userAuthorizationURL = options.userAuthorizationURL;
this._callbackURL = options.callbackURL;
this._key = options.sessionKey || 'oauth';
this._requestTokenStore = options.requestTokenStore || new SessionRequestTokenStore({ key: this._key });
this._trustProxy = options.proxy;
this._passReqToCallback = options.passReqToCallback;
this._skipUserProfile = (options.skipUserProfile === undefined) ? false : options.skipUserProfile;
}
|
javascript
|
{
"resource": ""
}
|
q53826
|
train
|
function (sagaStore) {
if (!sagaStore || !_.isObject(sagaStore)) {
var err = new Error('Please pass a valid sagaStore!');
debug(err);
throw err;
}
this.sagaStore = sagaStore;
}
|
javascript
|
{
"resource": ""
}
|
|
q53827
|
train
|
function (cmds, callback) {
if (!cmds || cmds.length === 0) {
return callback(null);
}
var self = this;
async.each(cmds, function (cmd, fn) {
if (dotty.exists(cmd, self.definitions.command.id)) {
return fn(null);
}
self.getNewId(function (err, id) {
if (err) {
debug(err);
return fn(err);
}
dotty.put(cmd, self.definitions.command.id, id);
fn(null);
});
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q53828
|
train
|
function (evt) {
for (var i = 0, len = this.containingProperties.length; i < len; i++) {
var prop = this.containingProperties[i];
if (!dotty.exists(evt, prop)) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q53829
|
train
|
function (fn) {
if (!fn || !_.isFunction(fn)) {
var err = new Error('Please pass a valid function!');
debug(err);
throw err;
}
if (fn.length === 3) {
this.shouldHandle = fn;
return this;
}
this.shouldHandle = function (evt, saga, callback) {
callback(null, fn(evt, saga));
};
var unwrappedShouldHandle = this.shouldHandle;
this.shouldHandle = function (evt, saga, clb) {
var wrappedCallback = function () {
try {
clb.apply(this, _.toArray(arguments));
} catch (e) {
debug(e);
process.emit('uncaughtException', e);
}
};
try {
unwrappedShouldHandle.call(this, evt, saga, wrappedCallback);
} catch (e) {
debug(e);
process.emit('uncaughtException', e);
}
};
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53830
|
train
|
function (evt, revInStore, callback) {
var evtId = dotty.get(evt, this.definition.id);
var revInEvt = dotty.get(evt, this.definition.revision);
var self = this;
var concatenatedId = this.getConcatenatedId(evt);
this.store.set(concatenatedId, revInEvt + 1, revInStore, function (err) {
if (err) {
debug(err);
if (err instanceof ConcurrencyError) {
var retryIn = randomBetween(0, self.options.retryOnConcurrencyTimeout || 800);
debug('retry in ' + retryIn + 'ms for [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt);
setTimeout(function() {
self.guard(evt, callback);
}, retryIn);
return;
}
return callback(err);
}
self.store.saveLastEvent(evt, function (err) {
if (err) {
debug('error while saving last event');
debug(err);
}
});
self.queue.remove(concatenatedId, evtId);
callback(null);
var pendingEvents = self.queue.get(concatenatedId);
if (!pendingEvents || pendingEvents.length === 0) return debug('no other pending event found [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt);
var nextEvent = _.find(pendingEvents, function (e) {
var revInNextEvt = dotty.get(e.payload, self.definition.revision);
return revInNextEvt === revInEvt + 1;
});
if (!nextEvent) return debug('no next pending event found [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt);
debug('found next pending event => guard [concatenatedId]=' + concatenatedId + ', [revInStore]=' + (revInStore || 'null') + ', [revInEvt]=' + revInEvt);
self.guard(nextEvent.payload, nextEvent.callback);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53831
|
train
|
function (id, objId, object, clb, fn) {
this.queue[id] = this.queue[id] || [];
var alreadyInQueue = _.find(this.queue[id], function (o) {
return o.id === objId;
});
if (alreadyInQueue) {
debug('event already handling [concatenatedId]=' + id + ', [evtId]=' + objId);
clb(new AlreadyHandlingError('Event: [id]=' + objId + ', [evtId]=' + objId + ' already handling!'), function (done) {
done(null);
});
return;
}
this.queue[id].push({ id: objId, payload: object, callback: clb });
this.retries[id] = this.retries[id] || {};
this.retries[id][objId] = this.retries[id][objId] || 0;
if (fn) {
var self = this;
(function wait () {
debug('wait called [concatenatedId]=' + id + ', [evtId]=' + objId);
setTimeout(function () {
var found = _.find(self.queue[id], function (o) {
return o.id === objId;
});
if (found) {
var loopCount = self.retries[id][objId]++;
fn(loopCount, wait);
}
}, self.options.queueTimeout);
})();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53832
|
train
|
function (id, objId) {
if (this.queue[id]) {
_.remove(this.queue[id], function (o) {
return o.id === objId;
});
}
if (objId && this.retries[id] && this.retries[id][objId]) {
this.retries[id][objId] = 0;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53833
|
train
|
function (fn) {
if (!fn || !_.isFunction(fn)) {
var err = new Error('Please pass a valid function!');
debug(err);
throw err;
}
this.onEventMissingHandle = fn;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q53834
|
train
|
function (callback) {
var self = this;
var warnings = null;
async.series([
// load saga files...
function (callback) {
if (self.options.sagaPath === '') {
self.sagas = {};
debug('empty sagaPath defined so no sagas will be loaded...');
return callback(null);
}
debug('load saga files...');
self.structureLoader(self.options.sagaPath, function (err, sagas, warns) {
if (err) {
return callback(err);
}
warnings = warns;
self.sagas = attachLookupFunctions(sagas);
callback(null);
});
},
// prepare infrastructure...
function (callback) {
debug('prepare infrastructure...');
async.parallel([
// prepare sagaStore...
function (callback) {
debug('prepare sagaStore...');
self.sagaStore.on('connect', function () {
self.emit('connect');
});
self.sagaStore.on('disconnect', function () {
self.emit('disconnect');
});
self.sagaStore.connect(callback);
},
// prepare revisionGuard...
function (callback) {
debug('prepare revisionGuard...');
if (!self.revisionGuardStore) {
return callback(null);
}
self.revisionGuardStore.on('connect', function () {
self.emit('connect');
});
self.revisionGuardStore.on('disconnect', function () {
self.emit('disconnect');
});
self.revisionGuardStore.connect(callback);
}
], callback);
},
// inject all needed dependencies...
function (callback) {
debug('inject all needed dependencies...');
if (self.revisionGuardStore) {
self.revisionGuard = new RevisionGuard(self.revisionGuardStore, self.options.revisionGuard);
self.revisionGuard.onEventMissing(function (info, evt) {
self.onEventMissingHandle(info, evt);
});
}
if (self.options.sagaPath !== '') {
self.eventDispatcher = new EventDispatcher(self.sagas, self.definitions.event);
self.sagas.defineOptions({}) // options???
.defineCommand(self.definitions.command)
.defineEvent(self.definitions.event)
.idGenerator(self.getNewId)
.useSagaStore(self.sagaStore);
}
if (self.revisionGuardStore) {
self.revisionGuard.defineEvent(self.definitions.event);
}
callback(null);
}
], function (err) {
if (err) {
debug(err);
}
if (callback) { callback(err, warnings); }
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53835
|
train
|
function (callback) {
if (self.options.sagaPath === '') {
self.sagas = {};
debug('empty sagaPath defined so no sagas will be loaded...');
return callback(null);
}
debug('load saga files...');
self.structureLoader(self.options.sagaPath, function (err, sagas, warns) {
if (err) {
return callback(err);
}
warnings = warns;
self.sagas = attachLookupFunctions(sagas);
callback(null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53836
|
train
|
function (callback) {
debug('prepare sagaStore...');
self.sagaStore.on('connect', function () {
self.emit('connect');
});
self.sagaStore.on('disconnect', function () {
self.emit('disconnect');
});
self.sagaStore.connect(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q53837
|
train
|
function (evt, callback) {
var self = this;
this.eventDispatcher.dispatch(evt, function (errs, sagaModels) {
var cmds = [];
if (!sagaModels || sagaModels.length === 0) {
if (callback) {
callback(errs, cmds, []);
}
return;
}
async.each(sagaModels, function (sagaModel, callback) {
var cmdsToSend = sagaModel.getUndispatchedCommands();
function setCommandToDispatched (c, clb) {
debug('set command to dispatched');
self.setCommandToDispatched(dotty.get(c, self.definitions.command.id), sagaModel.id, function (err) {
if (err) {
return clb(err);
}
cmds.push(c);
sagaModel.removeUnsentCommand(c);
clb(null);
});
}
async.each(cmdsToSend, function (cmd, callback) {
if (self.onCommandHandle) {
debug('publish a command');
self.onCommandHandle(cmd, function (err) {
if (err) {
debug(err);
return callback(err);
}
setCommandToDispatched(cmd, callback);
});
} else {
setCommandToDispatched(cmd, callback);
}
}, callback);
}, function (err) {
if (err) {
if (!errs) {
errs = [err];
} else if (_.isArray(errs)) {
errs.unshift(err);
}
debug(err);
}
if (callback) {
try {
callback(errs, cmds, sagaModels);
} catch (e) {
debug(e);
console.log(e.stack);
process.emit('uncaughtException', e);
}
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53838
|
train
|
function (evt, callback) {
if (!evt || !_.isObject(evt)) {
var err = new Error('Please pass a valid event!');
debug(err);
throw err;
}
var self = this;
var workWithRevisionGuard = false;
if (
this.revisionGuard &&
!!this.definitions.event.revision && dotty.exists(evt, this.definitions.event.revision) &&
!!this.definitions.event.aggregateId && dotty.exists(evt, this.definitions.event.aggregateId)
) {
workWithRevisionGuard = true;
}
if (dotty.get(evt, this.definitions.event.name) === this.options.commandRejectedEventName) {
workWithRevisionGuard = false;
}
if (!workWithRevisionGuard) {
return this.dispatch(evt, callback);
}
this.revisionGuard.guard(evt, function (err, done) {
if (err) {
debug(err);
if (callback) {
callback([err]);
}
return;
}
self.dispatch(evt, function (errs, cmds, sagaModels) {
if (errs) {
debug(errs);
if (callback) {
callback(errs, cmds, sagaModels);
}
return;
}
done(function (err) {
if (err) {
if (!errs) {
errs = [err];
} else if (_.isArray(errs)) {
errs.unshift(err);
}
debug(err);
}
if (callback) {
callback(errs, cmds, sagaModels);
}
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53839
|
train
|
function (date, callback) {
var self = this;
this.sagaStore.getOlderSagas(date, function (err, sagas) {
if (err) {
debug(err);
return callback(err);
}
var sagaModels = [];
sagas.forEach(function (s) {
var sagaModel = new SagaModel(s.id);
sagaModel.set(s);
sagaModel.actionOnCommit = 'update';
var calledRemoveTimeout = false;
var orgRemoveTimeout = sagaModel.removeTimeout;
sagaModel.removeTimeout = function () {
calledRemoveTimeout = true;
orgRemoveTimeout.bind(sagaModel)();
};
sagaModel.commit = function (clb) {
if (sagaModel.isDestroyed()) {
self.removeSaga(sagaModel, clb);
} else if (calledRemoveTimeout) {
sagaModel.setCommitStamp(new Date());
self.sagaStore.save(sagaModel.toJSON(), [], clb);
} else {
var err = new Error('Use commit only to remove a saga!');
debug(err);
if (clb) { return clb(err); }
throw err;
}
};
sagaModels.push(sagaModel);
});
callback(null, sagaModels);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q53840
|
train
|
function (options, callback) {
if (!callback) {
callback = options;
options = {};
}
this.sagaStore.getUndispatchedCommands(options, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q53841
|
train
|
function (saga, callback) {
var sagaId = saga.id || saga;
this.sagaStore.remove(sagaId, callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q53842
|
getDeclensions
|
train
|
function getDeclensions(callback, providedParams) {
const params = Object.assign({}, providedParams)
request.get(params, (err, res, body) => {
if (err || res.statusCode !== 200) {
return res.status(500).json({
error: 'A request to dev.phpbin.ja.is resulted in a error',
})
}
let $
const sanitisedBody = body.replace(/<!--[\s\S]*?-->/g, '')
try {
$ = cheerio.load(sanitisedBody)
} catch (error) {
return res.status(500).json({
error: 'Parsing the data from dev.phpbin.ja.is resulted in a error',
moreinfo: error,
})
}
// Links mean results!
const result = $('a')
// more than 1 result from request (ex: 'hús')
if (result.length > 1) {
// call recursively again with new url
const id = result[0].attribs.on_click.match(/\d+/)[0]
baseUrl.query = { id }
params.url = url.format(baseUrl)
return getDeclensions(callback, params)
}
// else just call func to return data
return callback($)
})
}
|
javascript
|
{
"resource": ""
}
|
q53843
|
runIDT
|
train
|
function runIDT(args) {
const cmd = 'bx dev ' + args.join(' ');
console.log(chalk.blue('Running:'), cmd);
cp.execSync(cmd, {stdio: 'inherit'});
}
|
javascript
|
{
"resource": ""
}
|
q53844
|
train
|
function(resource) {
var resource = Docs.escapeResourceName(resource);
if (resource == '') {
$('.resource ul.endpoints').slideUp();
return;
}
$('li#resource_' + resource).removeClass('active');
var elem = $('li#resource_' + resource + ' ul.endpoints');
elem.slideUp();
}
|
javascript
|
{
"resource": ""
}
|
|
q53845
|
runSingle
|
train
|
function runSingle(task, domain) {
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function () {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
|
javascript
|
{
"resource": ""
}
|
q53846
|
captureLine
|
train
|
function captureLine() {
if (!hasStacks) {
return;
}
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) {
return;
}
qFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
|
javascript
|
{
"resource": ""
}
|
q53847
|
Q
|
train
|
function Q(value) {
// If the object is already a Promise, return it directly. This enables
// the resolve function to both be used to created references from objects,
// but to tolerably coerce non-promises to promises.
if (value instanceof Promise) {
return value;
}
// assimilate thenables
if (isPromiseAlike(value)) {
return coerce(value);
} else {
return fulfill(value);
}
}
|
javascript
|
{
"resource": ""
}
|
q53848
|
continuer
|
train
|
function continuer(verb, arg) {
var result;
// Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only
// engine that has a deployed base of browsers that support generators.
// However, SM's generators use the Python-inspired semantics of
// outdated ES6 drafts. We would like to support ES6, but we'd also
// like to make it possible to use generators in deployed browsers, so
// we also support Python-style generators. At some point we can remove
// this block.
if (typeof StopIteration === "undefined") {
// ES6 Generators
try {
result = generator[verb](arg);
} catch (exception) {
return reject(exception);
}
if (result.done) {
return Q(result.value);
} else {
return when(result.value, callback, errback);
}
} else {
// SpiderMonkey Generators
// FIXME: Remove this case when SM does ES6 generators.
try {
result = generator[verb](arg);
} catch (exception) {
if (isStopIteration(exception)) {
return Q(exception.value);
} else {
return reject(exception);
}
}
return when(result, callback, errback);
}
}
|
javascript
|
{
"resource": ""
}
|
q53849
|
train
|
function(data){
if (data === undefined) {
data = '';
}
var $msgbar = $('#message-bar');
$msgbar.removeClass('message-fail');
$msgbar.addClass('message-success');
$msgbar.text(data);
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate($msgbar);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q53850
|
train
|
function(data) {
var h, headerArray, headers, i, l, len, o;
headers = {};
headerArray = data.getAllResponseHeaders().split('\r');
for (l = 0, len = headerArray.length; l < len; l++) {
i = headerArray[l];
h = i.match(/^([^:]*?):(.*)$/);
if (!h) {
h = [];
}
h.shift();
if (h[0] !== void 0 && h[1] !== void 0) {
headers[h[0].trim()] = h[1].trim();
}
}
o = {};
o.content = {};
o.content.data = data.responseText;
o.headers = headers;
o.request = {};
o.request.url = this.invocationUrl;
o.status = data.status;
return o;
}
|
javascript
|
{
"resource": ""
}
|
|
q53851
|
train
|
function(response) {
var prettyJson = JSON.stringify(response, null, '\t').replace(/\n/g, '<br>');
$('.response_body', $(this.el)).html(_.escape(prettyJson));
}
|
javascript
|
{
"resource": ""
}
|
|
q53852
|
train
|
function (event) {
var target = event.target;
var key = target.getAttribute('name');
var nextState = {};
nextState[key] = target.value;
this.setState(nextState);
}
|
javascript
|
{
"resource": ""
}
|
|
q53853
|
train
|
function (event) {
var id = event.target.parentNode.getAttribute('data-id');
// By getting collection through this.state you get an hash of the collection
this.setState(_.findWhere(this.state.collection, {id: id}));
}
|
javascript
|
{
"resource": ""
}
|
|
q53854
|
train
|
function (event) {
event.preventDefault();
var collection = this.getCollection();
var id = this.state.id;
var model;
if (id) {
// Update existing model
model = collection.get(id);
model.save(this.state, {wait: true});
} else {
// Create a new one
collection.create(this.state, {wait: true});
}
// Set initial state
this.replaceState(this.getInitialState());
}
|
javascript
|
{
"resource": ""
}
|
|
q53855
|
train
|
function () {
return (
React.DOM.div(null,
this.state.collection && this.state.collection.map(this.createPost),
this.createForm()
)
);
}
|
javascript
|
{
"resource": ""
}
|
|
q53856
|
validPath
|
train
|
function validPath(path, site) {
let reservedRoute;
if (path[0] !== '/') {
log('warn', `Cannot attach route '${path}' for site ${site.slug}. Path must begin with a slash.`);
return false;
}
reservedRoute = _.find(reservedRoutes, (route) => path.indexOf(route) === 1);
if (reservedRoute) {
log('warn', `Cannot attach route '${path}' for site ${site.slug}. Route prefix /${reservedRoute} is reserved by Amphora.`);
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q53857
|
normalizeRedirectPath
|
train
|
function normalizeRedirectPath(redirect, site) {
return site.path && !redirect.includes(site.path) ? `${site.path}${redirect}` : redirect;
}
|
javascript
|
{
"resource": ""
}
|
q53858
|
attachRedirect
|
train
|
function attachRedirect(router, { path, redirect }, site) {
redirect = normalizeRedirectPath(redirect, site);
return router.get(path, (req, res) => {
res.redirect(301, redirect);
});
}
|
javascript
|
{
"resource": ""
}
|
q53859
|
attachDynamicRoute
|
train
|
function attachDynamicRoute(router, { path, dynamicPage }) {
return router.get(path, render.renderDynamicRoute(dynamicPage));
}
|
javascript
|
{
"resource": ""
}
|
q53860
|
parseHandler
|
train
|
function parseHandler(router, routeObj, site) {
const { redirect, dynamicPage, path, middleware } = routeObj;
if (!validPath(path, site)) {
return;
}
if (middleware) {
router.use(path, middleware);
}
if (redirect) {
return attachRedirect(router, routeObj, site);
} else if (dynamicPage) {
return attachDynamicRoute(router, routeObj); // Pass in the page ID
} else {
return attachPlainRoute(router, routeObj);
}
}
|
javascript
|
{
"resource": ""
}
|
q53861
|
attachRoutes
|
train
|
function attachRoutes(router, routes = [], site) {
routes.forEach((route) => {
parseHandler(router, route, site);
});
return router;
}
|
javascript
|
{
"resource": ""
}
|
q53862
|
resolveComponentReferences
|
train
|
function resolveComponentReferences(data, locals, filter = referenceProperty) {
const referenceObjects = references.listDeepObjects(data, filter);
return bluebird.all(referenceObjects).each(referenceObject => {
return components.get(referenceObject[referenceProperty], locals)
.then(obj => {
// the thing we got back might have its own references
return resolveComponentReferences(obj, locals, filter).finally(() => {
_.assign(referenceObject, _.omit(obj, referenceProperty));
}).catch(function (error) {
const logObj = {
stack: error.stack,
cmpt: referenceObject[referenceProperty]
};
if (error.status) {
logObj.status = error.status;
}
log('error', `${error.message}`, logObj);
return bluebird.reject(error);
});
});
}).then(() => data);
}
|
javascript
|
{
"resource": ""
}
|
q53863
|
composePage
|
train
|
function composePage(pageData, locals) {
const layoutReference = pageData.layout,
pageDataNoConf = references.omitPageConfiguration(pageData);
return components.get(layoutReference)
.then(layoutData => mapLayoutToPageData(pageDataNoConf, layoutData))
.then(fullData => resolveComponentReferences(fullData, locals));
}
|
javascript
|
{
"resource": ""
}
|
q53864
|
mapLayoutToPageData
|
train
|
function mapLayoutToPageData(pageData, layoutData) {
// quickly (and shallowly) go through the layout's properties,
// finding strings that map to page properties
_.each(layoutData, function (list, key) {
if (_.isString(list)) {
if (_.isArray(pageData[key])) {
// if you find a match and the data exists,
// replace the property in the layout data
layoutData[key] = _.map(pageData[key], refToObj);
} else {
// otherwise replace it with an empty list
// as all layout properties are component lists
layoutData[key] = [];
}
}
});
return layoutData;
}
|
javascript
|
{
"resource": ""
}
|
q53865
|
del
|
train
|
function del(uri, user, locals) {
const callHooks = _.get(locals, 'hooks') !== 'false';
return db.get(uri).then(oldPageUri => {
return db.del(uri).then(() => {
const prefix = getPrefix(uri),
site = siteService.getSiteFromPrefix(prefix),
pageUrl = buf.decode(uri.split('/').pop());
if (!callHooks) {
return Promise.resolve(oldPageUri);
}
bus.publish('unpublishPage', { uri: oldPageUri, url: pageUrl, user });
notifications.notify(site, 'unpublished', { url: pageUrl, uri: oldPageUri });
return meta.unpublishPage(oldPageUri, user)
.then(() => oldPageUri);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q53866
|
aggregateTransforms
|
train
|
function aggregateTransforms(schemaVersion, currentVersion, upgradeFile) {
var transformVersions = generateVersionArray(upgradeFile),
applicableVersions = [];
for (let i = 0; i < transformVersions.length; i++) {
let version = transformVersions[i];
if (!currentVersion && schemaVersion || schemaVersion >= version && version > currentVersion) {
applicableVersions.push(transformVersions[i]);
}
}
return applicableVersions;
}
|
javascript
|
{
"resource": ""
}
|
q53867
|
runTransforms
|
train
|
function runTransforms(transforms, upgradeFile, ref, data, locals) {
log('debug', `Running ${transforms.length} transforms`);
return bluebird.reduce(transforms, function (acc, val) {
var key = val.toString();
// Parsefloat strips decimals with `.0` leaving just the int,
// let's add them back in
if (!_.includes(key, '.')) {
key += '.0';
}
return bluebird.try(upgradeFile[key].bind(null, ref, acc, locals))
.catch(e => {
log('error', `Error upgrading ${ref} to version ${key}: ${e.message}`, {
errStack: e.stack,
cmptData: JSON.stringify(acc)
});
return bluebird.reject(e);
});
}, data)
.then(function (resp) {
// Assign the version number automatically
resp._version = transforms[transforms.length - 1];
return resp;
});
}
|
javascript
|
{
"resource": ""
}
|
q53868
|
saveTransformedData
|
train
|
function saveTransformedData(uri) {
return function (data) {
return db.put(uri, JSON.stringify(data))
.then(function () {
// If the Promise resolves it means we saved,
// so let's return the data
return data;
});
};
}
|
javascript
|
{
"resource": ""
}
|
q53869
|
upgradeData
|
train
|
function upgradeData(schemaVersion, dataVersion, ref, data, locals) {
const name = isComponent(ref) ? getComponentName(ref) : getLayoutName(ref),
dir = isComponent(ref) ? files.getComponentPath(name) : files.getLayoutPath(name), // Get the component directory
upgradeFile = files.tryRequire(path.resolve(dir, 'upgrade')); // Grab the the upgrade.js file
var transforms = [];
log('debug', `Running upgrade for ${name}: ${ref}`);
// If no upgrade file exists, exit early
if (!upgradeFile) {
log('debug', `No upgrade file found for component: ${name}`);
return bluebird.resolve(data);
}
// find all the transforms that have to be performed (object.keys)
transforms = aggregateTransforms(schemaVersion, dataVersion, upgradeFile);
// If no transforms need to be run, exit early
if (!transforms.length) {
log('debug', `Upgrade tried to run, but no upgrade function was found for ${name}`, {
component: name,
currentVersion: dataVersion,
schemaVersion
});
return bluebird.resolve(data);
}
// pass through the transform
return runTransforms(transforms, upgradeFile, ref, data, locals)
.then(saveTransformedData(ref))
.catch(e => {
throw e;
});
}
|
javascript
|
{
"resource": ""
}
|
q53870
|
checkForUpgrade
|
train
|
function checkForUpgrade(ref, data, locals) {
return utils.getSchema(ref)
.then(schema => {
// If version does not match what's in the data
if (schema && schema._version && schema._version !== data._version) {
return module.exports.upgradeData(schema._version, data._version, ref, data, locals);
}
return bluebird.resolve(data);
});
}
|
javascript
|
{
"resource": ""
}
|
q53871
|
defer
|
train
|
function defer() {
const def = promiseDefer();
def.apply = function (err, result) {
if (err) {
def.reject(err);
} else {
def.resolve(result);
}
};
return def;
}
|
javascript
|
{
"resource": ""
}
|
q53872
|
list
|
train
|
function list(options = {}) {
options = _.defaults(options, {
limit: -1,
keys: true,
values: true,
fillCache: false,
json: true
});
// The prefix option is a shortcut for a greaterThan and lessThan range.
if (options.prefix) {
// \x00 is the first possible alphanumeric character, and \xFF is the last
options.gte = options.prefix + '\x00';
options.lte = options.prefix + '\xff';
}
let readStream,
transformOptions = {
objectMode: options.values,
isArray: options.isArray
};
// if keys but no values, or values but no keys, always return as array.
if (options.keys && !options.values || !options.keys && options.values) {
transformOptions.isArray = true;
}
readStream = module.exports.createReadStream(options);
if (_.isFunction(options.transforms)) {
options.transforms = options.transforms();
}
// apply all transforms
if (options.transforms) {
readStream = _.reduce(options.transforms, function (readStream, transform) {
return readStream.pipe(transform);
}, readStream);
}
if (options.json) {
readStream = readStream.pipe(jsonTransform(transformOptions));
}
return readStream;
}
|
javascript
|
{
"resource": ""
}
|
q53873
|
_checkForUrlProperty
|
train
|
function _checkForUrlProperty(uri, { url, customUrl }) {
if (!url && !customUrl) {
return bluebird.reject(new Error('Page does not have a `url` or `customUrl` property set'));
}
return bluebird.resolve(url || customUrl);
}
|
javascript
|
{
"resource": ""
}
|
q53874
|
_checkForDynamicPage
|
train
|
function _checkForDynamicPage(uri, { _dynamic }) {
if (!_dynamic || typeof _dynamic !== 'boolean') {
return bluebird.reject(new Error('Page is not dynamic and requires a url'));
}
return bluebird.resolve(_dynamic);
}
|
javascript
|
{
"resource": ""
}
|
q53875
|
_checkForArchived
|
train
|
function _checkForArchived(uri) {
return db.getMeta(replaceVersion(uri))
.then(meta => meta.archived)
.then(archived => archived
? bluebird.reject({ val: '', errors: { _checkForArchived: 'The page is archived and cannot be published' } })
: bluebird.resolve({ val: '', errors: {} })
);
}
|
javascript
|
{
"resource": ""
}
|
q53876
|
addToMeta
|
train
|
function addToMeta(meta, modifiers = [], uri, data) {
if (!modifiers.length) return meta;
return bluebird.reduce(modifiers, (acc, modify) => {
return bluebird.try(modify.bind(null, uri, data, acc))
.then(resp => Object.assign(acc, resp));
}, {}).then(acc => Object.assign(acc, meta));
}
|
javascript
|
{
"resource": ""
}
|
q53877
|
publishPageAtUrl
|
train
|
function publishPageAtUrl(url, uri, data, locals, site) { // eslint-disable-line
if (data._dynamic) {
locals.isDynamicPublishUrl = true;
return data;
}
// set the publishUrl for component's model.js files that
// may want to know about the URL of the page
locals.publishUrl = url;
return bluebird.resolve({ url })
.then(metaObj => storeUrlHistory(metaObj, uri, url))
.then(metaObj => addRedirects(metaObj, uri))
.then(metaObj => addToMeta(metaObj, site.assignToMetaOnPublish, uri, data));
}
|
javascript
|
{
"resource": ""
}
|
q53878
|
processPublishRules
|
train
|
function processPublishRules(publishingChain, uri, pageData, locals) {
// check whether page is archived, then run the rest of the publishing chain
return _checkForArchived(uri)
.then(initialObj => {
return bluebird.reduce(publishingChain, (acc, fn, index) => {
if (!acc.val) {
return bluebird.try(() => fn(uri, pageData, locals))
.then(val => {
acc.val = val;
return acc;
})
.catch(e => {
acc.errors[fn.name || index] = e.message;
return bluebird.resolve(acc);
});
}
return acc;
}, initialObj);
})
.catch(err => bluebird.resolve(err)); // err object constructed in _checkForArchived function above
}
|
javascript
|
{
"resource": ""
}
|
q53879
|
validatePublishRules
|
train
|
function validatePublishRules(uri, { val, errors }) {
let err, errMsg;
if (!val) {
errMsg = `Error publishing page: ${replaceVersion(uri)}`;
log('error', errMsg, { publishRuleErrors: errors });
err = new Error(errMsg);
err.status = 400;
return bluebird.reject(err);
}
return val;
}
|
javascript
|
{
"resource": ""
}
|
q53880
|
removePrefix
|
train
|
function removePrefix(str, prefixToken) {
const index = str.indexOf(prefixToken);
if (index > -1) {
str = str.substr(index + prefixToken.length).trim();
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q53881
|
notFound
|
train
|
function notFound(err, res) {
if (!(err instanceof Error) && err) {
res = err;
}
const message = 'Not Found',
code = 404;
// hide error from user of api.
sendDefaultResponseForCode(code, message, res);
}
|
javascript
|
{
"resource": ""
}
|
q53882
|
serverError
|
train
|
function serverError(err, res) {
// error is required to be logged
log('error', err.message, { stack: err.stack });
const message = err.message || 'Server Error', // completely hide these messages from outside
code = 500;
sendDefaultResponseForCode(code, message, res);
}
|
javascript
|
{
"resource": ""
}
|
q53883
|
expectText
|
train
|
function expectText(fn, res) {
bluebird.try(fn).then(result => {
res.set('Content-Type', 'text/plain');
res.send(result);
}).catch(handleError(res));
}
|
javascript
|
{
"resource": ""
}
|
q53884
|
checkArchivedToPublish
|
train
|
function checkArchivedToPublish(req, res, next) {
if (req.body.archived) {
return metaController.checkProps(req.uri, 'published')
.then(resp => {
if (resp === true) {
throw new Error('Client error, cannot modify archive while page is published'); // archived true, published true
} else next();
})
.catch(err => handleError(res)(err));
} else next();
}
|
javascript
|
{
"resource": ""
}
|
q53885
|
expectJSON
|
train
|
function expectJSON(fn, res) {
bluebird.try(fn).then(function (result) {
res.json(result);
}).catch(handleError(res));
}
|
javascript
|
{
"resource": ""
}
|
q53886
|
list
|
train
|
function list(options) {
return function (req, res) {
let list,
listOptions = _.assign({
prefix: req.uri,
values: false
}, options);
list = db.list(listOptions);
res.set('Content-Type', 'application/json');
list.pipe(res);
};
}
|
javascript
|
{
"resource": ""
}
|
q53887
|
listWithoutVersions
|
train
|
function listWithoutVersions() {
const options = {
transforms() {
return [filter({wantStrings: true}, function (str) {
return str.indexOf('@') === -1;
})];
}
};
return list(options);
}
|
javascript
|
{
"resource": ""
}
|
q53888
|
listWithPublishedVersions
|
train
|
function listWithPublishedVersions(req, res) {
const publishedString = '@published',
options = {
transforms() {
return [filter({ wantStrings: true }, function (str) {
return str.indexOf(publishedString) !== -1;
})];
}
};
// Trim the URI to `../pages` for the query to work
req.uri = req.uri.replace(`/${publishedString}`, '');
return list(options)(req, res);
}
|
javascript
|
{
"resource": ""
}
|
q53889
|
putRouteFromDB
|
train
|
function putRouteFromDB(req, res) {
expectJSON(function () {
return db.put(req.uri, JSON.stringify(req.body)).then(() => req.body);
}, res);
}
|
javascript
|
{
"resource": ""
}
|
q53890
|
deleteRouteFromDB
|
train
|
function deleteRouteFromDB(req, res) {
expectJSON(() => {
return db.get(req.uri)
.then(oldData => db.del(req.uri).then(() => oldData));
}, res);
}
|
javascript
|
{
"resource": ""
}
|
q53891
|
forceEditableInstance
|
train
|
function forceEditableInstance(code = 303) {
return (req, res) => {
res.redirect(code, `${res.locals.site.protocol}://${req.uri.replace('@published', '')}`);
};
}
|
javascript
|
{
"resource": ""
}
|
q53892
|
normalizePath
|
train
|
function normalizePath(urlPath) {
if (!urlPath) {
return '';
// make sure path starts with a /
} else if (_.head(urlPath) !== '/') {
urlPath = '/' + urlPath;
}
// make sure path does not end with a /
return _.trimEnd(urlPath, '/');
}
|
javascript
|
{
"resource": ""
}
|
q53893
|
normalizeDirectory
|
train
|
function normalizeDirectory(dir) {
if (!dir || dir === path.sep) {
dir = '.';
} else if (_.head(dir) === path.sep) {
dir = dir.substr(1);
}
if (dir.length > 1 && _.last(dir) === path.sep) {
dir = dir.substring(0, dir.length - 1);
}
return dir;
}
|
javascript
|
{
"resource": ""
}
|
q53894
|
getSite
|
train
|
function getSite(host, path) {
// note: uses the memoized version
return _.find(module.exports.sites(), function (site) {
return site.host === host && site.path === path;
});
}
|
javascript
|
{
"resource": ""
}
|
q53895
|
getSiteFromPrefix
|
train
|
function getSiteFromPrefix(prefix) {
var split = prefix.split('/'), // Split the url/uri by `/`
host = split.shift(), // The first value should be the host ('http://' is not included)
optPath = split.shift(), // The next value is the first part of the site's path OR the whole part
path = optPath ? `/${optPath}` : '',
length = split.length + 1, // We always need at least one pass through the for loop
site; // Initialize the return value to `undefined`
for (let i = 0; i < length; i++) {
site = getSite(host, path); // Try to get the site based on the host and path
if (site) { // If a site was found, break out of the loop
break;
} else {
path += `/${split.shift()}`; // Grab the next value and append it to the `path` value
}
}
return site; // Return the site
}
|
javascript
|
{
"resource": ""
}
|
q53896
|
userOrRobot
|
train
|
function userOrRobot(user) {
if (user && _.get(user, 'username') && _.get(user, 'provider')) {
return user;
} else {
// no actual user, this was an api key
return {
username: 'robot',
provider: 'clay',
imageUrl: 'clay-avatar', // kiln will supply a clay avatar
name: 'Clay',
auth: 'admin'
};
}
}
|
javascript
|
{
"resource": ""
}
|
q53897
|
publishPage
|
train
|
function publishPage(uri, publishMeta, user) {
const NOW = new Date().toISOString(),
update = {
published: true,
publishTime: NOW,
history: [{ action: 'publish', timestamp: NOW, users: [userOrRobot(user)] }]
};
return changeMetaState(uri, Object.assign(publishMeta, update));
}
|
javascript
|
{
"resource": ""
}
|
q53898
|
createPage
|
train
|
function createPage(ref, user) {
const NOW = new Date().toISOString(),
users = [userOrRobot(user)],
meta = {
createdAt: NOW,
archived: false,
published: false,
publishTime: null,
updateTime: null,
urlHistory: [],
firstPublishTime: null,
url: '',
title: '',
authors: [],
users,
history: [{action: 'create', timestamp: NOW, users }],
siteSlug: sitesService.getSiteFromPrefix(ref.substring(0, ref.indexOf('/_pages'))).slug
};
return putMeta(ref, meta);
}
|
javascript
|
{
"resource": ""
}
|
q53899
|
publishLayout
|
train
|
function publishLayout(uri, user) {
const NOW = new Date().toISOString(),
users = [userOrRobot(user)],
update = {
published: true,
publishTime: NOW,
history: [{ action: 'publish', timestamp: NOW, users }]
};
return changeMetaState(uri, update);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.