_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q5800
|
login
|
train
|
function login (opener, prompter, opts) {
validate('FFO', arguments)
opts = ProfileConfig(opts)
return loginWeb(opener, opts).catch(er => {
if (er instanceof WebLoginNotSupported) {
process.emit('log', 'verbose', 'web login not supported, trying couch')
return prompter(opts.creds)
.then(data => loginCouch(data.username, data.password, opts))
} else {
throw er
}
})
}
|
javascript
|
{
"resource": ""
}
|
q5801
|
train
|
function( actual, expected, message ) {
message = message || "HTML should not be equal";
this.notDeepEqual( serializeHtml( actual ), serializeHtml( expected ), message );
}
|
javascript
|
{
"resource": ""
}
|
|
q5802
|
isIgnore
|
train
|
function isIgnore (ignore, str) {
let result = false
let i = 0
while (!result && i < ignore.length) {
if (ignore[i] === str) {
result = true
}
i++
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q5803
|
cryptor
|
train
|
function cryptor (simpleCryptoJS, doc, ignore, isIncoming) {
const resultDoc = {}
Object.keys(doc).map(function (objectKey, index) {
if (isIgnore(ignore, objectKey)) {
resultDoc[objectKey] = doc[objectKey]
} else {
const preKeyText = 'encrypted_'
switch (isIncoming) {
case true:
resultDoc[`${preKeyText}${objectKey}`] =
simpleCryptoJS.encrypt(
JSON.stringify(doc[objectKey])
)
break
case false:
resultDoc[`${objectKey.replace(preKeyText, '')}`] =
JSON.parse(
simpleCryptoJS.decrypt(
doc[objectKey]
)
)
break
}
}
})
return resultDoc
}
|
javascript
|
{
"resource": ""
}
|
q5804
|
doCreate
|
train
|
function doCreate(data) {
console.log('create called', data);
var i, keys = false;
if (data instanceof Array) {
if (typeof data[0] === 'undefined') {
return Promise.reject(new Error('Can\'t have undefined keys'));
}
// Check if a key is the first element
if (keyTypes.indexOf(typeof data[0]) !== -1) {
// Check for an even amount of elements
if (data.length % 2) {
return Promise.reject(new Error('uneven number of key/values given to create'));
}
// Check every second item are keys
for (i = 2; i < data.length; i = i + 2) {
if (keyTypes.indexOf(typeof data[i]) === -1) {
return Promise.reject(new Error('Invalid key value for key ' + (i + 1)
+ ' (' + typeof data[i] + ' given)'));
}
}
keys = true;
} else {
if (!this.options.id) {
return Promise.reject('Can\'t give an array of data objects if not key has been specified');
}
// Check if each object value has or doesn't have an id
for (i = 0; i < data.length; i++) {
if (typeof data[i][this.options.id] === 'undefined') {
return Promise.reject(new Error('Can\'t have objects in array without a key'));
}
}
}
return this.save.call(this, {
keys: keys,
data: data,
replace: false
});
} else if (data instanceof Object) {
// Find and update
return this.save.call(this, {
keys: true,
data: data,
replace: false
});
} else {
return Promise.reject(new Error('Unknown data type given'));
}
}
|
javascript
|
{
"resource": ""
}
|
q5805
|
doUpdate
|
train
|
function doUpdate(data, filter) {
console.log('update called', data, filter);
var i, keys = false;
if (data instanceof Array) {
if (typeof data[0] === 'undefined') {
return Promise.reject(new Error('Can\'t have undefined keys'));
}
// Check if a key is the first element
if (keyTypes.indexOf(typeof data[0]) !== -1) {
// Check for an even amount of elements
if (data.length % 2) {
return Promise.reject(new Error('uneven number of key/values given to update'));
}
// Check every second item are keys
for (i = 2; i < data.length; i = i + 2) {
if (keyTypes.indexOf(typeof data[i]) === -1) {
return Promise.reject(new Error('Invalid key value for key ' + ((i/2) + 1)
+ ' (' + typeof data[i] + ' given)'));
}
}
keys = true;
} else {
if (!this.options.id) {
return Promise.reject(new Error('Can\'t give an array of data objects if not key has been specified'));
}
// Check if each object value has or doesn't have an id
for (i = 0; i < data.length; i++) {
if (typeof data[i][this.options.id] === 'undefined') {
return Promise.reject(new Error('Can\'t have objects in array without a key'));
}
}
}
// Check if given a filter object
if (typeof filter === 'object') {
return Promise.reject(new Error('can\'t use a filter with an array keyed objects'));
}
return this.save.call(this, {
keys: keys,
replace: filter === true ? true : undefined,
data: data
});
} else if(data instanceof Object) {
if (this.options.id && typeof data[this.options.id] !== 'undefined') {
return Promise.reject(new Error('Can\'t include key value when updating with object'));
}
if (typeof filter === 'boolean') {
// Object of key value pairs to put into database
return this.save.call(this, {
keys: true,
replace: filter ? true : undefined,
data: data
});
} else if (typeof filter === 'object') {
// Object of fields to update in object values selected with a filter
return this.save.call(this, {
data: data,
filter: filter
});
} else {
// Object of fields to update in all object values
return this.save.call(this, {
data: data
});
}
} else {
return Promise.reject(new Error('Unknown data type given'));
}
}
|
javascript
|
{
"resource": ""
}
|
q5806
|
train
|
function (callback) {
getData.takeSnapshot(page, ph, function (error, page, ph, dom) {
if (error) {
callback (error);
return;
}
originalDom = dom;
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q5807
|
train
|
function (callback) {
async.until(
// conditions for stopping the poll
function () {
waitTimeOver = elapsed > constants.WAIT_TIMEOUT;
return waitTimeOver || domHasChanged;
},
function (callback) {
// polls the page at an interval
setTimeout(function () {
elapsed += constants.POLL_INTERVAL;
getData.takeSnapshot(page, ph, function (error, page, ph, newDom) {
if (error) {
callback(error);
return;
}
domHasChanged = helpers.domIsDifferent(originalDom, newDom);
callback();
});
}, constants.POLL_INTERVAL);
},
function (error) {
if (waitTimeOver) {
callback('Timeout while waiting for dom to change');
return;
}
callback(error);
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q5808
|
ajaxCallback
|
train
|
function ajaxCallback(page, ph, oldUrl, options, callback) {
// callback for page change
switch(options) {
case 1:
// expect ajax
pageDomHasChanged(page, ph, function (error, page, ph) {
callback(error, page, ph);
});
break;
case 2:
// expect navigation
pageHasChanged(page, oldUrl, function (error) {
callback(error, page, ph);
});
break;
default:
// callback immediately
callback(null, page, ph);
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q5809
|
waitForString
|
train
|
function waitForString(page, ph, str, callback) {
var elapsed = 0;
var currentDom = '';
var timeout = false;
async.until(
function () {
timeout = elapsed > constants.WAIT_TIMEOUT;
return currentDom.indexOf(str) > -1 || timeout;
},
function (callback) {
setTimeout(function () {
getData.takeSnapshot(page, ph, function (error, page, ph, dom) {
if (error) {
callback(error);
return;
}
currentDom = dom;
elapsed += constants.POLL_INTERVAL;
callback();
})
}, constants.POLL_INTERVAL);
},
function (error) {
if (error) {
callback(error, page, ph);
return;
}
if (timeout) {
callback('Timeout while waiting for string', page, ph);
return;
}
callback(null, page, ph);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q5810
|
querySelectorOnBrowser
|
train
|
function querySelectorOnBrowser(selector) {
// stupid error catching here to stop the browser from printing null cannot be found to stdout
var query;
try {
// do this to simulate a scroll to the bottom of the page to trigger loading of certain ajax elements
//todo somehow this still doesnt work
document.body.scrollTop = 0;
document.body.scrollTop = 9999999999;
//window.document.body.scrollTop = document.body.scrollHeight;
query = document.querySelector(selector).innerHTML;
} catch (exception) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q5811
|
train
|
function (objectPath) {
var levels = objectPath.split('.');
var currentValue = values;
if (levels.length > 0) {
for (var i = 0; i < levels.length; i++) {
currentValue = currentValue[levels[i]];
}
return currentValue
}
return undefined
}
|
javascript
|
{
"resource": ""
}
|
|
q5812
|
train
|
function (msgctxt, msgid) {
var message;
if (this.$i18n.getLocaleMessage(this.$i18n.activeLocale)[msgctxt]) {
message = this.$i18n.getLocaleMessage(this.$i18n.activeLocale)[msgctxt][msgid];
}
if (!message) {
return msgid
} else {
return message.msgstr[0] || message.msgid
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5813
|
train
|
function (context, type, value, options) {
var FORMATTER;
switch (type) {
case 'number':
FORMATTER = {
constructor: Intl.NumberFormat,
cachedInstance: context.$i18n.NUMBER_FORMATTER
};
break
case 'currency':
FORMATTER = {
constructor: Intl.CurrencyFormat,
cachedInstance: context.$i18n.CURRENCY_FORMATTER
};
break
case 'date':
FORMATTER = {
constructor: Intl.DateTimeFormat,
cachedInstance: context.$i18n.DATE_TIME_FORMATTER
};
break
}
if (FORMATTER && value !== undefined && value !== null && value !== false) {
if (typeof options === 'object') {
options = Object.assign(context.$i18n[(type + "Format")], options);
} else {
options = undefined;
}
return options ? new FORMATTER.constructor(context.$i18n.activeLocale, options).format(value) : FORMATTER.cachedInstance.format(value)
} else {
return value
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5814
|
train
|
function (name, params) {
return {
name: name || to.name,
params: params ? Object.assign(to.params, params) : to.params,
hash: to.hash,
query: to.query
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5815
|
train
|
function (_changeLocale) {
// If the saved locale is equal to the default locale make sure that the URL format is correct.
if (to.meta.localized && !config.defaultLocaleInRoutes) {
var _next = defineNext(to.meta.seedRoute.name);
if (_changeLocale) {
router.go(_next);
} else {
next(_next);
}
} else if (!to.meta.localized && config.defaultLocaleInRoutes) {
var _next$1 = defineNext('__locale:' + to.meta.i18nId);
if (_changeLocale) {
router.go(_next$1);
} else {
next(_next$1);
}
} else if (_changeLocale) {
router.go(defineNext());
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5816
|
train
|
function (newLocale) {
if (config.storageMethod !== 'custom') {
switchMethods[config.storageMethod].save(config.storageKey, newLocale, savedLocale, config.cookieExpirationInDays);
} else {
config.storageFunctions.save(config.storageKey, newLocale, savedLocale);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5817
|
train
|
function (location) {
if (typeof location === 'string') {
var isRelative = location.charAt(0) !== '/';
var toPath;
if (this.$i18n.routeAutoPrefix) {
toPath = pathToRegexp_1.compile(_path('/:_locale?/' + location));
} else {
toPath = pathToRegexp_1.compile(location.replace('$locale', ':_locale?'));
}
var path = toPath({ _locale: this.$i18n.activeLocale === this.$i18n.defaultLocale ? (this.$i18n.defaultLocaleInRoutes ? this.$i18n.activeLocale : undefined) : this.$i18n.activeLocale });
return path === '' ? '/' : isRelative ? path.substr(1) : path
} else {
return location
}
// TODO: Add support when the object contains name and/or path.
}
|
javascript
|
{
"resource": ""
}
|
|
q5818
|
train
|
function (options) {
var _options = {
messages: options.messages || {},
numberFormat: options.numberFormat || {},
currencyFormat: options.currencyFormat || {},
dateFormat: options.dateFormat || {},
numberFormats: options.numberFormats || {},
currencyFormats: options.currencyFormats || {},
currencyLocaleFormats: options.currencyLocaleFormats || {},
dateFormats: options.dateFormats || {},
defaultCurrency: options.defaultCurrency || 'USD',
currencies: options.currencies || {},
persistCurrency: options.persistCurrency === undefined ? true : options.persistCurrency,
defaultLocale: options.defaultLocale || 'en',
allLocales: options.allLocales || (options.defaultLocale ? [options.defaultLocale] : ['en']),
forceReloadOnSwitch: options.forceReloadOnSwitch === undefined ? true : options.forceReloadOnSwitch,
usingRouter: options.usingRouter === undefined ? false : options.usingRouter,
defaultLocaleInRoutes: options.defaultLocaleInRoutes === undefined ? false : options.defaultLocaleInRoutes,
routingStyle: options.routingStyle || 'changeLocale',
routeAutoPrefix: options.routeAutoPrefix === undefined ? true : options.routeAutoPrefix,
// TODO: Implement better storageMethod parsing.
storageMethod: typeof options.storageMethod !== 'object' ? (['session', 'local', 'cookie'].includes(options.storageMethod.trim()) ? options.storageMethod.trim() : 'local') : 'custom',
storageKey: options.storageKey || '_vue_i18n_gettext_locale',
cookieExpirationInDays: options.cookieExpirationInDays || 30,
customOnLoad: options.customOnLoad
};
if (_options.storageMethod === 'custom') {
_options.storageFunctions = options.storageMethod;
}
return _options
}
|
javascript
|
{
"resource": ""
}
|
|
q5819
|
train
|
function (task, argument, callback) {
var self = this;
var queueArgument = {
task: task,
argument: argument
};
return promiseOrCallback(callback, function (resolve, reject) {
self.taskQueue.push(queueArgument, function (error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q5820
|
promiseOrCallback
|
train
|
function promiseOrCallback (callback, executor) {
var promise = new Promise(executor);
// no callback: do not attach
if (typeof callback !== 'function') {
return promise;
}
return promise.then(function (value) {
setImmediate(function () {
callback(null, value);
});
return value;
}, function (error) {
setImmediate(function () {
callback(error);
});
throw error;
});
}
|
javascript
|
{
"resource": ""
}
|
q5821
|
loadConfig
|
train
|
function loadConfig(config, props) {
// The calling module's path. Unfortunately, because modules are cached,
// module.parent is the FIRST calling module parent, not necessarily the
// current one.
var callerPath = path.dirname(stackTrace.get(loadConfig)[1].getFileName());
// If no config defined, resolve to nearest package.json to the calling lib. If not found, throw an error.
if (config == null) {
config = findup('package.json', {cwd: callerPath});
if (config == null) {
throw new Error('No package.json found.');
}
}
// If filename was specified with no path parts, make the path absolute so
// that resolve doesn't look in node_module directories for it.
else if (typeof config === 'string' && !/[\\\/]/.test(config)) {
config = path.join(callerPath, config);
}
// If package is a string, try to require it.
if (typeof config === 'string') {
config = require(resolve(config, {basedir: callerPath}));
}
// If config is not an object yet, something is amiss.
if (typeof config !== 'object') {
throw new Error('Invalid configuration specified.');
}
// For all specified props, populate result object.
var result = {};
props.forEach(function(prop) {
result[prop] = config[prop] ? Object.keys(config[prop]) : [];
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q5822
|
Participant
|
train
|
function Participant(name) {
this.name = name;
var container = document.createElement('div');
container.className = isPresentMainParticipant() ? PARTICIPANT_CLASS : PARTICIPANT_MAIN_CLASS;
container.id = name;
var span = document.createElement('span');
var video = document.createElement('video');
var rtcPeer;
container.appendChild(video);
container.appendChild(span);
container.onclick = switchContainerClass;
document.getElementById('participants').appendChild(container);
span.appendChild(document.createTextNode(name));
video.id = 'video-' + name;
video.autoplay = true;
video.controls = false;
this.getElement = function() {
return container;
}
this.getVideoElement = function() {
return video;
}
function switchContainerClass() {
if (container.className === PARTICIPANT_CLASS) {
var elements = Array.prototype.slice.call(document.getElementsByClassName(PARTICIPANT_MAIN_CLASS));
elements.forEach(function(item) {
item.className = PARTICIPANT_CLASS;
});
container.className = PARTICIPANT_MAIN_CLASS;
} else {
container.className = PARTICIPANT_CLASS;
}
}
function isPresentMainParticipant() {
return ((document.getElementsByClassName(PARTICIPANT_MAIN_CLASS)).length != 0);
}
this.offerToReceiveVideo = function(offerSdp, wp){
console.log('Invoking SDP offer callback function');
var msg = { id : "receiveVideoFrom",
sender : name,
sdpOffer : offerSdp
};
sendMessage('receiveVideoFrom', msg);
}
Object.defineProperty(this, 'rtcPeer', { writable: true});
this.dispose = function() {
console.log('Disposing participant ' + this.name);
this.rtcPeer.dispose();
container.parentNode.removeChild(container);
};
}
|
javascript
|
{
"resource": ""
}
|
q5823
|
SimpleColorPicker
|
train
|
function SimpleColorPicker(options) {
// Options
options = options || {};
// Properties
this.color = null;
this.width = 0;
this.widthUnits = 'px';
this.height = 0;
this.heightUnits = 'px';
this.hue = 0;
this.position = {x: 0, y: 0};
this.huePosition = 0;
this.saturationWidth = 0;
this.hueHeight = 0;
this.maxHue = 0;
this.inputIsNumber = false;
// Bind methods to scope (if needed)
this._onSaturationMouseDown = this._onSaturationMouseDown.bind(this);
this._onSaturationMouseMove = this._onSaturationMouseMove.bind(this);
this._onSaturationMouseUp = this._onSaturationMouseUp.bind(this);
this._onHueMouseDown = this._onHueMouseDown.bind(this);
this._onHueMouseMove = this._onHueMouseMove.bind(this);
this._onHueMouseUp = this._onHueMouseUp.bind(this);
// Register window and document references in case this is instantiated inside of an iframe
this.window = options.window || window;
this.document = this.window.document
// Create DOM
this.$el = this.document.createElement('div');
this.$el.className = 'Scp';
this.$el.innerHTML = [
'<div class="Scp-saturation">',
'<div class="Scp-brightness"></div>',
'<div class="Scp-sbSelector"></div>',
'</div>',
'<div class="Scp-hue">',
'<div class="Scp-hSelector"></div>',
'</div>'
].join('');
// DOM accessors
this.$saturation = this.$el.querySelector('.Scp-saturation');
this.$hue = this.$el.querySelector('.Scp-hue');
this.$sbSelector = this.$el.querySelector('.Scp-sbSelector');
this.$hSelector = this.$el.querySelector('.Scp-hSelector');
// Event listeners
this.$saturation.addEventListener('mousedown', this._onSaturationMouseDown);
this.$saturation.addEventListener('touchstart', this._onSaturationMouseDown);
this.$hue.addEventListener('mousedown', this._onHueMouseDown);
this.$hue.addEventListener('touchstart', this._onHueMouseDown);
// Some styling and DOMing from options
if (options.el) {
this.appendTo(options.el);
}
if (options.background) {
this.setBackgroundColor(options.background);
}
if (options.widthUnits) {
this.widthUnits = options.widthUnits;
}
if (options.heightUnits) {
this.heightUnits = options.heightUnits;
}
this.setSize(options.width || 175, options.height || 150);
this.setColor(options.color);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q5824
|
has
|
train
|
function has(key) {
if (options.cacheValues) {
return Promise.resolve((cachedData[key] !== undefined));
} else if (options.cacheKeys) {
return Promise.resolve((cachedKeys.indexOf(key) !== -1));
} else {
return readData().then(function(data) {
return (data[key] !== undefined);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q5825
|
close
|
train
|
function close() {
if (file !== false && options.listen) {
fs.unwatch(file, listener);
}
return Promise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
q5826
|
parse
|
train
|
function parse (pattern, comment) {
const match = pattern.exec(comment)
if (match == null) {
return null
}
const type = match[1]
const rules = (match[2] || '')
.split(',')
.map(s => s.trim())
.filter(Boolean)
return { type, rules }
}
|
javascript
|
{
"resource": ""
}
|
q5827
|
enable
|
train
|
function enable (context, loc, group, rules) {
if (rules.length === 0) {
context.report({ loc, message: '++ {{group}}', data: { group }})
} else {
context.report({ loc, message: '+ {{group}} {{rules}}', data: { group, rules: rules.join(' ') }})
}
}
|
javascript
|
{
"resource": ""
}
|
q5828
|
processBlock
|
train
|
function processBlock (context, comment) {
const parsed = parse(COMMENT_DIRECTIVE_B, comment.value)
if (parsed != null) {
if (parsed.type === 'eslint-disable') {
disable(context, comment.loc.start, 'block', parsed.rules)
} else {
enable(context, comment.loc.start, 'block', parsed.rules)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q5829
|
processLine
|
train
|
function processLine (context, comment) {
const parsed = parse(COMMENT_DIRECTIVE_L, comment.value)
if (parsed != null && comment.loc.start.line === comment.loc.end.line) {
const line = comment.loc.start.line + (parsed.type === 'eslint-disable-line' ? 0 : 1)
const column = -1
disable(context, { line, column }, 'line', parsed.rules)
enable(context, { line: line + 1, column }, 'line', parsed.rules)
}
}
|
javascript
|
{
"resource": ""
}
|
q5830
|
getCurrentUrl
|
train
|
function getCurrentUrl(page, ph, callback) {
page.get('url', function (url) {
callback(null, page, ph, url);
});
}
|
javascript
|
{
"resource": ""
}
|
q5831
|
takeSnapshot
|
train
|
function takeSnapshot(page, ph, callback) {
page.evaluate(function () {
return document.documentElement.outerHTML;
}, function (document) {
if (document) {
callback(null, page, ph, document);
} else {
callback('Nothing retrieved', page, ph, null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q5832
|
getInnerHtmlFromElement
|
train
|
function getInnerHtmlFromElement(page, ph, selector, callback) {
function getInnerHtml(selector) {
return document.querySelector(selector).innerHTML;
}
page.evaluate(getInnerHtml, function (result) {
if (result) {
callback(null, page, ph, result);
} else {
var errorString = 'Error finding innerHTML';
callback(errorString, page, ph, null);
}
}, selector);
}
|
javascript
|
{
"resource": ""
}
|
q5833
|
getSelectorValue
|
train
|
function getSelectorValue(page, ph, selector, callback) {
page.evaluate(function (selector) {
try {
return [null, document.querySelector(selector).value];
} catch (error) {
return [error];
}
}, function (result) {
var error = result[0];
var selectorValue = result[1];
if (error) {
callback(error, page, ph);
return;
}
callback(null, page, ph, selectorValue);
}, selector);
}
|
javascript
|
{
"resource": ""
}
|
q5834
|
downloadFromUrl
|
train
|
function downloadFromUrl(page, ph, url, callback) {
async.waterfall([
function (callback) {
page.getCookies(function (cookie) {
callback(null, page, ph, cookie);
});
},
function (page, ph, cookies, callback) {
var cookieString = helpers.cookieToHeader(cookies);
var headers = { Cookie: cookieString };
request.get({
url: url,
headers: headers,
encoding: null
}, function (error, response, downloadedBytes) {
callback(error, page, ph, downloadedBytes);
});
}
], callback);
}
|
javascript
|
{
"resource": ""
}
|
q5835
|
downloadFromClick
|
train
|
function downloadFromClick(page, ph, selector, callback) {
const HREF_KEY = 'href';
async.waterfall([
function (callback) {
getSelectorAttribute(page, ph, [selector, HREF_KEY], callback);
},
function (page, ph, relativeHref, callback) {
getCurrentUrl(page, ph, function (error, page, ph, currentUrl) {
if (error) {
callback(error, page, ph);
return;
}
callback(null, page, ph, currentUrl + relativeHref);
});
},
function (page, ph, url, callback) {
downloadFromUrl(page, ph, url, callback);
}
], callback);
}
|
javascript
|
{
"resource": ""
}
|
q5836
|
isBeginningOfLine
|
train
|
function isBeginningOfLine (node, index, nodes) {
if (node != null) {
for (let i = index - 1; i >= 0; --i) {
const prevNode = nodes[i]
if (prevNode == null) {
continue
}
return node.loc.start.line !== prevNode.loc.end.line
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q5837
|
isClosingToken
|
train
|
function isClosingToken (token) {
return token != null && (
token.type === 'HTMLEndTagOpen' ||
token.type === 'VExpressionEnd' ||
(
token.type === 'Punctuator' &&
(
token.value === ')' ||
token.value === '}' ||
token.value === ']'
)
)
)
}
|
javascript
|
{
"resource": ""
}
|
q5838
|
isTrivialToken
|
train
|
function isTrivialToken (token) {
return token != null && (
(token.type === 'Punctuator' && TRIVIAL_PUNCTUATOR.test(token.value)) ||
token.type === 'HTMLTagOpen' ||
token.type === 'HTMLEndTagOpen' ||
token.type === 'HTMLTagClose' ||
token.type === 'HTMLSelfClosingTagClose'
)
}
|
javascript
|
{
"resource": ""
}
|
q5839
|
setBaseline
|
train
|
function setBaseline (token, hardTabAdditional) {
const offsetInfo = offsets.get(token)
if (offsetInfo != null) {
offsetInfo.baseline = true
}
}
|
javascript
|
{
"resource": ""
}
|
q5840
|
processTopLevelNode
|
train
|
function processTopLevelNode (node, expectedIndent) {
const token = tokenStore.getFirstToken(node)
const offsetInfo = offsets.get(token)
if (offsetInfo != null) {
offsetInfo.expectedIndent = expectedIndent
} else {
offsets.set(token, { baseToken: null, offset: 0, baseline: false, expectedIndent })
}
}
|
javascript
|
{
"resource": ""
}
|
q5841
|
processIgnores
|
train
|
function processIgnores (visitor) {
for (const ignorePattern of options.ignores) {
const key = `${ignorePattern}:exit`
if (visitor.hasOwnProperty(key)) {
const handler = visitor[key]
visitor[key] = function (node) {
const ret = handler.apply(this, arguments)
ignore(node)
return ret
}
} else {
visitor[key] = ignore
}
}
return visitor
}
|
javascript
|
{
"resource": ""
}
|
q5842
|
getExpectedIndent
|
train
|
function getExpectedIndent (tokens) {
const trivial = isTrivialToken(tokens[0])
let expectedIndent = Number.MAX_SAFE_INTEGER
for (let i = 0; i < tokens.length; ++i) {
const token = tokens[i]
const offsetInfo = offsets.get(token)
// If the first token is not trivial then ignore trivial following tokens.
if (offsetInfo != null && (trivial || !isTrivialToken(token))) {
if (offsetInfo.expectedIndent != null) {
expectedIndent = Math.min(expectedIndent, offsetInfo.expectedIndent)
} else {
const baseOffsetInfo = offsets.get(offsetInfo.baseToken)
if (baseOffsetInfo != null && baseOffsetInfo.expectedIndent != null && (i === 0 || !baseOffsetInfo.baseline)) {
expectedIndent = Math.min(expectedIndent, baseOffsetInfo.expectedIndent + offsetInfo.offset * options.indentSize)
if (baseOffsetInfo.baseline) {
break
}
}
}
}
}
return expectedIndent
}
|
javascript
|
{
"resource": ""
}
|
q5843
|
getIndentText
|
train
|
function getIndentText (firstToken) {
const text = sourceCode.text
let i = firstToken.range[0] - 1
while (i >= 0 && !LT_CHAR.test(text[i])) {
i -= 1
}
return text.slice(i + 1, firstToken.range[0])
}
|
javascript
|
{
"resource": ""
}
|
q5844
|
validateCore
|
train
|
function validateCore (token, expectedIndent, optionalExpectedIndent) {
const line = token.loc.start.line
const indentText = getIndentText(token)
// If there is no line terminator after the `<script>` start tag,
// `indentText` contains non-whitespace characters.
// In that case, do nothing in order to prevent removing the `<script>` tag.
if (indentText.trim() !== '') {
return
}
const actualIndent = token.loc.start.column
const unit = (options.indentChar === '\t' ? 'tab' : 'space')
for (let i = 0; i < indentText.length; ++i) {
if (indentText[i] !== options.indentChar) {
context.report({
loc: {
start: { line, column: i },
end: { line, column: i + 1 }
},
message: 'Expected {{expected}} character, but found {{actual}} character.',
data: {
expected: JSON.stringify(options.indentChar),
actual: JSON.stringify(indentText[i])
},
fix: defineFix(token, actualIndent, expectedIndent)
})
return
}
}
if (actualIndent !== expectedIndent && (optionalExpectedIndent === undefined || actualIndent !== optionalExpectedIndent)) {
context.report({
loc: {
start: { line, column: 0 },
end: { line, column: actualIndent }
},
message: 'Expected indentation of {{expectedIndent}} {{unit}}{{expectedIndentPlural}} but found {{actualIndent}} {{unit}}{{actualIndentPlural}}.',
data: {
expectedIndent,
actualIndent,
unit,
expectedIndentPlural: (expectedIndent === 1) ? '' : 's',
actualIndentPlural: (actualIndent === 1) ? '' : 's'
},
fix: defineFix(token, actualIndent, expectedIndent)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q5845
|
getCommentExpectedIndents
|
train
|
function getCommentExpectedIndents (nextToken, nextExpectedIndent, lastExpectedIndent) {
if (typeof lastExpectedIndent === 'number' && isClosingToken(nextToken)) {
if (nextExpectedIndent === lastExpectedIndent) {
// For solo comment. E.g.,
// <div>
// <!-- comment -->
// </div>
return {
primary: nextExpectedIndent + options.indentSize,
secondary: undefined
}
}
// For last comment. E.g.,
// <div>
// <div></div>
// <!-- comment -->
// </div>
return { primary: lastExpectedIndent, secondary: nextExpectedIndent }
}
// Adjust to next normally. E.g.,
// <div>
// <!-- comment -->
// <div></div>
// </div>
return { primary: nextExpectedIndent, secondary: undefined }
}
|
javascript
|
{
"resource": ""
}
|
q5846
|
validate
|
train
|
function validate (tokens, comments, lastToken) {
// Calculate and save expected indentation.
const firstToken = tokens[0]
const actualIndent = firstToken.loc.start.column
const expectedIndent = getExpectedIndent(tokens)
if (expectedIndent === Number.MAX_SAFE_INTEGER) {
return
}
// Debug log
// console.log('line', firstToken.loc.start.line, '=', { actualIndent, expectedIndent }, 'from:')
// for (const token of tokens) {
// const offsetInfo = offsets.get(token)
// if (offsetInfo == null) {
// console.log(' ', JSON.stringify(sourceCode.getText(token)), 'is unknown.')
// } else if (offsetInfo.expectedIndent != null) {
// console.log(' ', JSON.stringify(sourceCode.getText(token)), 'is fixed at', offsetInfo.expectedIndent, '.')
// } else {
// const baseOffsetInfo = offsets.get(offsetInfo.baseToken)
// console.log(' ', JSON.stringify(sourceCode.getText(token)), 'is', offsetInfo.offset, 'offset from ', JSON.stringify(sourceCode.getText(offsetInfo.baseToken)), '( line:', offsetInfo.baseToken && offsetInfo.baseToken.loc.start.line, ', indent:', baseOffsetInfo && baseOffsetInfo.expectedIndent, ', baseline:', baseOffsetInfo && baseOffsetInfo.baseline, ')')
// }
// }
// Save.
const baseline = new Set()
for (const token of tokens) {
const offsetInfo = offsets.get(token)
if (offsetInfo != null) {
if (offsetInfo.baseline) {
// This is a baseline token, so the expected indent is the column of this token.
if (options.indentChar === ' ') {
offsetInfo.expectedIndent = Math.max(0, token.loc.start.column + expectedIndent - actualIndent)
} else {
// In hard-tabs mode, it cannot align tokens strictly, so use one additional offset.
// But the additional offset isn't needed if it's at the beginning of the line.
offsetInfo.expectedIndent = expectedIndent + (token === tokens[0] ? 0 : 1)
}
baseline.add(token)
} else if (baseline.has(offsetInfo.baseToken)) {
// The base token is a baseline token on this line, so inherit it.
offsetInfo.expectedIndent = offsets.get(offsetInfo.baseToken).expectedIndent
baseline.add(token)
} else {
// Otherwise, set the expected indent of this line.
offsetInfo.expectedIndent = expectedIndent
}
}
}
// Calculate the expected indents for comments.
// It allows the same indent level with the previous line.
const lastOffsetInfo = offsets.get(lastToken)
const lastExpectedIndent = lastOffsetInfo && lastOffsetInfo.expectedIndent
const commentExpectedIndents = getCommentExpectedIndents(firstToken, expectedIndent, lastExpectedIndent)
// Validate.
for (const comment of comments) {
validateCore(comment, commentExpectedIndents.primary, commentExpectedIndents.secondary)
}
validateCore(firstToken, expectedIndent)
}
|
javascript
|
{
"resource": ""
}
|
q5847
|
isValidElement
|
train
|
function isValidElement (node) {
const name = node.name
return (
name === 'input' ||
name === 'select' ||
name === 'textarea' ||
(
name !== 'keep-alive' &&
name !== 'slot' &&
name !== 'transition' &&
name !== 'transition-group' &&
utils.isCustomComponent(node)
)
)
}
|
javascript
|
{
"resource": ""
}
|
q5848
|
getVariable
|
train
|
function getVariable (name, leafNode) {
let node = leafNode
while (node != null) {
const variables = node.variables
const variable = variables && variables.find(v => v.id.name === name)
if (variable != null) {
return variable
}
node = node.parent
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q5849
|
parseOptions
|
train
|
function parseOptions (options) {
return {
[ELEMENT_TYPE.NORMAL]: (options && options.html && options.html.normal) || 'always',
[ELEMENT_TYPE.VOID]: (options && options.html && options.html.void) || 'never',
[ELEMENT_TYPE.COMPONENT]: (options && options.html && options.html.component) || 'always',
[ELEMENT_TYPE.SVG]: (options && options.svg) || 'always',
[ELEMENT_TYPE.MATH]: (options && options.math) || 'always'
}
}
|
javascript
|
{
"resource": ""
}
|
q5850
|
getElementType
|
train
|
function getElementType (node) {
if (utils.isCustomComponent(node)) {
return ELEMENT_TYPE.COMPONENT
}
if (utils.isHtmlElementNode(node)) {
if (utils.isHtmlVoidElementName(node.name)) {
return ELEMENT_TYPE.VOID
}
return ELEMENT_TYPE.NORMAL
}
if (utils.isSvgElementNode(node)) {
return ELEMENT_TYPE.SVG
}
if (utils.isMathMLElementNode(node)) {
return ELEMENT_TYPE.MATH
}
return 'unknown elements'
}
|
javascript
|
{
"resource": ""
}
|
q5851
|
isEmpty
|
train
|
function isEmpty (node, sourceCode) {
const start = node.startTag.range[1]
const end = (node.endTag != null) ? node.endTag.range[0] : node.range[1]
return sourceCode.text.slice(start, end).trim() === ''
}
|
javascript
|
{
"resource": ""
}
|
q5852
|
writeFile
|
train
|
function writeFile (outDir, vars, file) {
return function (done) {
const fileName = file.path
const inFile = file.fullPath
const parentDir = file.parentDir
const outFile = path.join(outDir, maxstache(removeUnderscore(fileName), vars))
mkdirp(path.join(outDir, maxstache(parentDir, vars)), function (err) {
if (err) return done(err)
const rs = fs.createReadStream(inFile)
const ts = maxstacheStream(vars)
const ws = fs.createWriteStream(outFile)
pump(rs, ts, ws, done)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q5853
|
removeUnderscore
|
train
|
function removeUnderscore (filepath) {
const parts = filepath.split(path.sep)
const filename = parts.pop().replace(/^_/, '')
return parts.concat([filename]).join(path.sep)
}
|
javascript
|
{
"resource": ""
}
|
q5854
|
train
|
function(requestId, fieldNames) {
return protocol.implodeMessage(requestId,
metadataMethods.GET_SCHEMA,
protocol.implodeDataArray(fieldNames));
}
|
javascript
|
{
"resource": ""
}
|
|
q5855
|
train
|
function(requestId, itemNames) {
return protocol.implodeMessage(requestId,
metadataMethods.GET_ITEMS,
protocol.implodeDataArray(itemNames));
}
|
javascript
|
{
"resource": ""
}
|
|
q5856
|
train
|
function(requestId, itemData) {
var i, payload = [], item;
for (i = 0; i < itemData.length; i = i + 1) {
payload.push(types.INT);
payload.push(protocol.encodeInteger(itemData[i].distinctSnapLen));
payload.push(types.DOUBLE);
payload.push(protocol.encodeDouble(itemData[i].minSourceFreq));
payload.push(types.MODE);
payload.push(protocol.encodePubModes(itemData[i].allowedModes));
}
return protocol.implodeMessage(requestId, metadataMethods.GET_ITEM_DATA,
protocol.implodeArray(payload));
}
|
javascript
|
{
"resource": ""
}
|
|
q5857
|
train
|
function(requestId, userItemData) {
var i, payload = [], item;
for (i = 0; i < userItemData.length; i = i + 1) {
payload.push(types.INT);
payload.push(protocol.encodeInteger(userItemData[i].allowedBufferSize));
payload.push(types.DOUBLE);
payload.push(protocol.encodeDouble(userItemData[i].allowedMaxItemFreq));
payload.push(types.MODE);
payload.push(protocol.encodePubModes(userItemData[i].allowedModes));
}
return protocol.implodeMessage(requestId, metadataMethods.GET_USER_ITEM_DATA,
protocol.implodeArray(payload));
}
|
javascript
|
{
"resource": ""
}
|
|
q5858
|
train
|
function(requestId, maxBandwidth, notifyTables) {
return protocol.implodeMessage(requestId, metadataMethods.NOTIFY_USER,
types.DOUBLE, protocol.encodeDouble(maxBandwidth),
types.BOOLEAN, protocol.encodeBoolean(notifyTables));
}
|
javascript
|
{
"resource": ""
}
|
|
q5859
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_USER, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5860
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_USER_AUTH, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5861
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_USER_MESSAGE, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5862
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_NEW_SESSION, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5863
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_NEW_TABLES, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5864
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_MPN_DEVICE_ACCESS, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5865
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_MPN_SUBSCRIPTION_ACTIVATION, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5866
|
train
|
function(requestId, exceptionMessage, exceptionType, exceptionData) {
return writeExtendedException(requestId, metadataMethods.NOTIFY_MPN_DEVICE_TOKEN_CHANGE, exceptionMessage, exceptionType, exceptionData);
}
|
javascript
|
{
"resource": ""
}
|
|
q5867
|
writeDefaultException
|
train
|
function writeDefaultException(requestId, requestType, exceptionMessage) {
return protocol.implodeMessage(requestId, requestType,
exceptions.GENERIC,
protocol.encodeString(exceptionMessage));
}
|
javascript
|
{
"resource": ""
}
|
q5868
|
writeSimpleException
|
train
|
function writeSimpleException(requestId, requestType, exceptionMessage, exceptionType) {
return protocol.implodeMessage(requestId, requestType,
protocol.encodeMetadataException(exceptionType),
protocol.encodeString(exceptionMessage));
}
|
javascript
|
{
"resource": ""
}
|
q5869
|
writeExtendedException
|
train
|
function writeExtendedException(requestId, requestType, exceptionMessage, exceptionType, exceptionData) {
var encodedExc = protocol.encodeMetadataException(exceptionType);
if (encodedExc == exceptions.CREDITS) {
return protocol.implodeMessage(requestId, requestType, encodedExc,
protocol.encodeString(exceptionMessage),
protocol.encodeString(exceptionData.clientCode),
protocol.encodeString(exceptionData.clientMessage));
} else if (encodedExc === exceptions.CONFLICTING_SESSION) {
return protocol.implodeMessage(requestId, requestType, encodedExc,
protocol.encodeString(exceptionMessage),
protocol.encodeString(exceptionData.clientCode),
protocol.encodeString(exceptionData.clientMessage),
protocol.encodeString(exceptionData.conflictingSessionId));
} else {
return protocol.implodeMessage(requestId, requestType, encodedExc,
protocol.encodeString(exceptionMessage));
}
}
|
javascript
|
{
"resource": ""
}
|
q5870
|
readInit
|
train
|
function readInit(message, tokens) {
var i;
message.parameters = {};
for (i = 0; i < tokens.length; i = i + 4) {
message.parameters[protocol.decodeString(tokens[i + 1])] = protocol.decodeString(tokens[i + 3]);
}
}
|
javascript
|
{
"resource": ""
}
|
q5871
|
readGetSchema
|
train
|
function readGetSchema(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.groupName = protocol.decodeString(tokens[3]);
message.schemaName = protocol.decodeString(tokens[5]);
message.sessionId = protocol.decodeString(tokens[7]);
}
|
javascript
|
{
"resource": ""
}
|
q5872
|
readGetItemData
|
train
|
function readGetItemData(message, tokens) {
message.itemNames = [];
for (var i = 0; i < tokens.length; i = i + 2) {
message.itemNames.push(protocol.decodeString(tokens[i + 1]));
}
}
|
javascript
|
{
"resource": ""
}
|
q5873
|
readNotifyUser
|
train
|
function readNotifyUser(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.userPassword = protocol.decodeString(tokens[3]);
readNotifyUserHeaders(message, tokens.slice(4));
}
|
javascript
|
{
"resource": ""
}
|
q5874
|
readNotifyUserAuth
|
train
|
function readNotifyUserAuth(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.userPassword = protocol.decodeString(tokens[3]);
message.clientPrincipal = protocol.decodeString(tokens[5]);
readNotifyUserHeaders(message, tokens.slice(6));
}
|
javascript
|
{
"resource": ""
}
|
q5875
|
readNotifyUserHeaders
|
train
|
function readNotifyUserHeaders(message, tokens) {
var i;
message.headers = {};
for (i = 0; i < tokens.length; i = i + 4) {
message.headers[protocol.decodeString(tokens[i + 1])] = protocol.decodeString(tokens[i + 3]);
}
}
|
javascript
|
{
"resource": ""
}
|
q5876
|
readNotifyUserMessage
|
train
|
function readNotifyUserMessage(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.sessionId = protocol.decodeString(tokens[3]);
message.userMessage = protocol.decodeString(tokens[5]);
}
|
javascript
|
{
"resource": ""
}
|
q5877
|
readNotifyNewSession
|
train
|
function readNotifyNewSession(message, tokens) {
var i;
message.userName = protocol.decodeString(tokens[1]);
message.sessionId = protocol.decodeString(tokens[3]);
message.contextProperties = {};
tokens = tokens.slice(4);
for (i = 0; i < tokens.length; i = i + 4) {
message.contextProperties[protocol.decodeString(tokens[i + 1])] = protocol.decodeString(tokens[i + 3]);
}
}
|
javascript
|
{
"resource": ""
}
|
q5878
|
readNotifyNewTables
|
train
|
function readNotifyNewTables(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.sessionId = protocol.decodeString(tokens[3]);
readTableInfos(message, tokens.slice(4));
}
|
javascript
|
{
"resource": ""
}
|
q5879
|
readNotifyTablesClose
|
train
|
function readNotifyTablesClose(message, tokens) {
message.sessionId = protocol.decodeString(tokens[1]);
readTableInfos(message, tokens.slice(2));
}
|
javascript
|
{
"resource": ""
}
|
q5880
|
readNotifyMpnDeviceAccess
|
train
|
function readNotifyMpnDeviceAccess(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.sessionId = protocol.decodeString(tokens[3]);
message.device = {};
message.device.mpnPlatformType = protocol.decodeString(tokens[5]);
message.device.applicationId = protocol.decodeString(tokens[7]);
message.device.deviceToken = protocol.decodeString(tokens[9]);
}
|
javascript
|
{
"resource": ""
}
|
q5881
|
readNotifyMpnSubscriptionActivation
|
train
|
function readNotifyMpnSubscriptionActivation(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.sessionId = protocol.decodeString(tokens[3]);
message.tableInfo = readTableInfo(tokens.slice(4), true);
var base = 16;
message.mpnSubscription = {};
message.mpnSubscription.device = {};
message.mpnSubscription.device.mpnPlatformType = protocol.decodeString(tokens[base + 1]);
message.mpnSubscription.device.applicationId = protocol.decodeString(tokens[base + 3]);
message.mpnSubscription.device.deviceToken = protocol.decodeString(tokens[base + 5]);
message.mpnSubscription.trigger = protocol.decodeString(tokens[base + 7]);
message.mpnSubscription.notificationFormat = protocol.decodeString(tokens[base + 9]);
}
|
javascript
|
{
"resource": ""
}
|
q5882
|
readNotifyMpnDeviceTokenChange
|
train
|
function readNotifyMpnDeviceTokenChange(message, tokens) {
message.userName = protocol.decodeString(tokens[1]);
message.sessionId = protocol.decodeString(tokens[3]);
message.device = {};
message.device.mpnPlatformType = protocol.decodeString(tokens[5]);
message.device.applicationId = protocol.decodeString(tokens[7]);
message.device.deviceToken = protocol.decodeString(tokens[9]);
message.newDeviceToken = protocol.decodeString(tokens[11]);
}
|
javascript
|
{
"resource": ""
}
|
q5883
|
readTableInfos
|
train
|
function readTableInfos(message, tokens) {
var tableInfo, i;
message.tableInfos = [];
while (tokens.length >= 14) {
tableInfo = readTableInfo(tokens);
message.tableInfos.push(tableInfo);
tokens = tokens.slice(14);
}
}
|
javascript
|
{
"resource": ""
}
|
q5884
|
readTableInfo
|
train
|
function readTableInfo(tokens, skipSelector) {
var tableInfo = {};
tableInfo.winIndex = protocol.decodeInteger(tokens[1]);
tableInfo.pubModes = protocol.decodePubModes(tokens[3]);
tableInfo.groupName = protocol.decodeString(tokens[5]);
tableInfo.schemaName = protocol.decodeString(tokens[7]);
tableInfo.firstItemIndex = protocol.decodeInteger(tokens[9]);
tableInfo.lastItemIndex = protocol.decodeInteger(tokens[11]);
if (!skipSelector)
tableInfo.selector = protocol.decodeString(tokens[13]);
return tableInfo;
}
|
javascript
|
{
"resource": ""
}
|
q5885
|
train
|
function(requestId, exceptionMessage, exceptionType) {
if (exceptionType === "data") {
return protocol.implodeMessage(requestId, dataMethods.DATA_INIT,
exceptions.DATA, protocol.encodeString(exceptionMessage));
} else {
return protocol.implodeMessage(requestId, dataMethods.DATA_INIT,
exceptions.GENERIC, protocol.encodeString(exceptionMessage));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5886
|
train
|
function(requestId, exceptionMessage, exceptionType) {
if (exceptionType === "subscription") {
return protocol.implodeMessage(requestId, dataMethods.UNSUBSCRIBE,
exceptions.SUBSCRIPTION, protocol.encodeString(exceptionMessage));
} else {
return protocol.implodeMessage(requestId, dataMethods.UNSUBSCRIBE,
exceptions.GENERIC, protocol.encodeString(exceptionMessage));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5887
|
train
|
function(exception){
return protocol.implodeMessage(protocol.timestamp(), dataMethods.FAILURE,
exceptions.GENERIC, protocol.encodeString(exception));
}
|
javascript
|
{
"resource": ""
}
|
|
q5888
|
train
|
function(requestId, itemName) {
return protocol.implodeMessage(protocol.timestamp(), dataMethods.END_OF_SNAPSHOT,
types.STRING, protocol.encodeString(itemName),
types.STRING, requestId);
}
|
javascript
|
{
"resource": ""
}
|
|
q5889
|
train
|
function(requestId, itemName, isSnapshot, data) {
return protocol.implodeMessage(protocol.timestamp(), dataMethods.UPDATE_BY_MAP,
types.STRING, protocol.encodeString(itemName),
types.STRING, requestId,
types.BOOLEAN, protocol.encodeBoolean(isSnapshot),
protocol.implodeData(data));
}
|
javascript
|
{
"resource": ""
}
|
|
q5890
|
openPage
|
train
|
function openPage(url, callback, options) {
// set up default values
const MAX_RETRIES = 5;
if (options) {
var maxAttempts = options['retries'] || MAX_RETRIES;
var flags = options['flags'];
} else {
maxAttempts = MAX_RETRIES;
flags = [];
}
// finds an unused port so that if we queue up multiple phantom instances sequentially with async
// the exception EADDRINUSE will not be triggered because phantom runs on a separate process (I think)
findUnusedPort(function (port) {
// creates new Phantom instance
var phantomOptions = {
onStdout: function (data) {
// uncomment this to print the phantom stdout to the console
//return console.log('PHANTOM STDOUT: ' + data);
},
port: port
};
if (helpers.platformIsWindows()) {
phantomOptions['dnodeOpts'] = {
weak: false
}
}
var doAfterCreate = function(ph) {
// create a new page
ph.createPage(function (page) {
// sets a user agent
// somehow this causes the stdout for the browser to be printed to the console, so we temporarily disable
// setting of the user agent.
page.set('settings.userAgent', USER_AGENT);
// SOMEHOW commenting this out stops the random phantomjs assertion error
// set up the log to print errors
//page.set('onResourceError', function (resourceError) {
// page.set('errorReason', resourceError);
//});
async.retry(
maxAttempts,
function (callback) {
page.open(url, function (status) {
if (status === "fail") {
page.get('errorReason', function (errorReason) {
if (errorReason) {
var errorReasonString = JSON.stringify(errorReason);
} else {
errorReasonString = '';
}
callback('Failed to open: ' + url + ' REASON: ' + errorReasonString, [undefined, ph]);
});
} else {
// success
// check if url is valid here, so that the phantom process and page is returned
if (!url) {
callback('Url is not valid', [page, ph]);
return;
}
// success, execute callback
callback(null, [page, ph]);
}
});
},
function (error, results) {
callback(error, results[0], results[1]);
}
)
});
};
var phantomParams = flags.concat([phantomOptions, doAfterCreate]);
phantom.create.apply(this, phantomParams);
});
}
|
javascript
|
{
"resource": ""
}
|
q5891
|
navigateToUrl
|
train
|
function navigateToUrl(page, ph, url, callback) {
var oldUrl;
async.waterfall([
function (callback) {
page.get('url', function (url) {
oldUrl = url;
callback();
});
},
function (callback) {
page.evaluate(function (url) {
try {
window.location.href = url;
} catch (exception) {
return exception;
}
}, function (error) {
// do this because if there is no error, the error is still something so we can't simply do callback(error);
if (error) {
callback(error);
return;
}
callback();
}, url);
},
function (callback) {
checks.pageHasChanged(page, oldUrl, function (error) {
callback(error);
});
}
], function (error) {
callback(error, page, ph);
});
}
|
javascript
|
{
"resource": ""
}
|
q5892
|
thinkCache
|
train
|
function thinkCache(name, value, config) {
assert(name && helper.isString(name), 'cache.name must be a string');
if (config) {
config = helper.parseAdapterConfig(this.config('cache'), config);
} else {
config = helper.parseAdapterConfig(this.config('cache'));
}
const Handle = config.handle;
assert(helper.isFunction(Handle), 'cache.handle must be a function');
delete config.handle;
const instance = new Handle(config);
// delete cache
if (value === null) {
return Promise.resolve(instance.delete(name));
}
// get cache
if (value === undefined) {
return debounceInstance.debounce(name, () => {
return instance.get(name);
});
}
// get cache when value is function
if (helper.isFunction(value)) {
return debounceInstance.debounce(name, () => {
let cacheData;
return instance.get(name).then(data => {
if (data === undefined) {
return value(name);
}
cacheData = data;
}).then(data => {
if (data !== undefined) {
cacheData = data;
return instance.set(name, data);
}
}).then(() => {
return cacheData;
});
});
}
// set cache
return Promise.resolve(instance.set(name, value));
}
|
javascript
|
{
"resource": ""
}
|
q5893
|
findCreateReactApp
|
train
|
function findCreateReactApp() {
var done = this.async();
var spinner = ora('Finding create-react-app').start();
checkCommmand('create-react-app', function (isInstalled) {
if (!isInstalled) {
spinner.fail('Missing create-react-app - \'npm install -g create-react-app\'');
process.exit(1);
}
spinner.succeed('Found create-react-app');
done();
});
}
|
javascript
|
{
"resource": ""
}
|
q5894
|
resolvePathname
|
train
|
function resolvePathname(to) {
var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var toParts = to && to.split('/') || [];
var fromParts = from && from.split('/') || [];
var isToAbs = to && isAbsolute(to);
var isFromAbs = from && isAbsolute(from);
var mustEndAbs = isToAbs || isFromAbs;
if (to && isAbsolute(to)) {
// to is absolute
fromParts = toParts;
} else if (toParts.length) {
// to is relative, drop the filename
fromParts.pop();
fromParts = fromParts.concat(toParts);
}
if (!fromParts.length) { return '/'; }
var hasTrailingSlash = void 0;
if (fromParts.length) {
var last = fromParts[fromParts.length - 1];
hasTrailingSlash = last === '.' || last === '..' || last === '';
} else {
hasTrailingSlash = false;
}
var up = 0;
for (var i = fromParts.length; i >= 0; i--) {
var part = fromParts[i];
if (part === '.') {
spliceOne(fromParts, i);
} else if (part === '..') {
spliceOne(fromParts, i);
up++;
} else if (up) {
spliceOne(fromParts, i);
up--;
}
}
if (!mustEndAbs) { for (; up--; up) {
fromParts.unshift('..');
} }if (mustEndAbs && fromParts[0] !== '' && (!fromParts[0] || !isAbsolute(fromParts[0]))) { fromParts.unshift(''); }
var result = fromParts.join('/');
if (hasTrailingSlash && result.substr(-1) !== '/') { result += '/'; }
return result;
}
|
javascript
|
{
"resource": ""
}
|
q5895
|
kebabCase
|
train
|
function kebabCase (str) {
return str
.replace(/([a-z])([A-Z])/g, match => match[0] + '-' + match[1])
.replace(invalidChars, '-')
.toLowerCase()
}
|
javascript
|
{
"resource": ""
}
|
q5896
|
snakeCase
|
train
|
function snakeCase (str) {
return str
.replace(/([a-z])([A-Z])/g, match => match[0] + '_' + match[1])
.replace(invalidChars, '_')
.toLowerCase()
}
|
javascript
|
{
"resource": ""
}
|
q5897
|
parseRstr
|
train
|
function parseRstr(rstr){
var startOfAssertion = rstr.indexOf('<Assertion ');
var endOfAssertion = rstr.indexOf('</Assertion>') + '</Assertion>'.length;
var token = rstr.substring(startOfAssertion, endOfAssertion);
return token;
}
|
javascript
|
{
"resource": ""
}
|
q5898
|
propHasDefault
|
train
|
function propHasDefault (prop) {
const propDefaultNode = prop.value.properties
.find(p => p.key && p.key.name === 'default')
return Boolean(propDefaultNode)
}
|
javascript
|
{
"resource": ""
}
|
q5899
|
updateDisplayCount
|
train
|
function updateDisplayCount() {
let visibleCount = 0;
let totalCount = Object.keys(receivers).length;
let trs = Array.from(tbody.getElementsByTagName('tr'));
trs.forEach(function(tr) {
if(tr.style.display === '') {
visibleCount++;
}
});
displayCount.value = visibleCount + ' of ' + totalCount;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.