_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q20200 | collapse_all | train | function collapse_all(min_lines) {
var elts = document.getElementsByTagName("div");
for (var i=0; i<elts.length; i++) {
var elt = elts[i];
var split = elt.id.indexOf("-");
if (split > 0)
if (elt.id.substring(split, elt.id.length) == "-expanded")
if (num_lines(elt.innerHTML) > min_lines)
... | javascript | {
"resource": ""
} |
q20201 | train | function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');... | javascript | {
"resource": ""
} | |
q20202 | train | function() {
var togglers = $('img.toggler').click(function() {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
console.log($('tr.cg-' + idnum).toggle());
if (src.substr(-9) == 'minus.png')
$(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
... | javascript | {
"resource": ""
} | |
q20203 | scrollTreeToPipeline | train | function scrollTreeToPipeline(pipelineIdOrElement) {
var element = pipelineIdOrElement;
if (!(pipelineIdOrElement instanceof jQuery)) {
element = $(getTreePipelineElementId(pipelineIdOrElement));
}
$('#sidebar').scrollTop(element.attr('offsetTop'));
$('#sidebar').scrollLeft(element.attr('offsetLeft'));
} | javascript | {
"resource": ""
} |
q20204 | expandTreeToPipeline | train | function expandTreeToPipeline(pipelineId) {
if (pipelineId == null) {
return;
}
var elementId = getTreePipelineElementId(pipelineId);
var parents = $(elementId).parents('.expandable');
if (parents.size() > 0) {
// The toggle function will scroll to highlight the pipeline.
parents.children('.hitare... | javascript | {
"resource": ""
} |
q20205 | handleTreeToggle | train | function handleTreeToggle(index, element) {
var parentItem = $(element).parent();
var collapsing = parentItem.hasClass('expandable');
if (collapsing) {
} else {
// When expanded be sure the pipeline and its children are showing.
scrollTreeToPipeline(parentItem);
}
} | javascript | {
"resource": ""
} |
q20206 | countChildren | train | function countChildren(pipelineId) {
var current = STATUS_MAP.pipelines[pipelineId];
if (!current) {
return [0, 0];
}
var total = 1;
var done = 0;
if (current.status == 'done') {
done += 1;
}
for (var i = 0, n = current.children.length; i < n; i++) {
var parts = countChildren(current.childre... | javascript | {
"resource": ""
} |
q20207 | prettyName | train | function prettyName(name, sidebar) {
var adjustedName = name;
if (sidebar) {
var adjustedName = name;
var parts = name.split('.');
if (parts.length > 0) {
adjustedName = parts[parts.length - 1];
}
}
return adjustedName.replace(/\./, '.<wbr>');
} | javascript | {
"resource": ""
} |
q20208 | generateSidebar | train | function generateSidebar(statusMap, nextPipelineId, rootElement) {
var currentElement = null;
if (nextPipelineId) {
currentElement = $('<li>');
// Value should match return of getTreePipelineElementId
currentElement.attr('id', 'item-pipeline-' + nextPipelineId);
} else {
currentElement = rootElem... | javascript | {
"resource": ""
} |
q20209 | findActivePipeline | train | function findActivePipeline(pipelineId, isRoot) {
var infoMap = STATUS_MAP.pipelines[pipelineId];
if (!infoMap) {
return null;
}
// This is an active leaf node.
if (infoMap.children.length == 0 && infoMap.status != 'done') {
return pipelineId;
}
// Sort children by start time only.
var childre... | javascript | {
"resource": ""
} |
q20210 | filterTimeseriesesByLine | train | function filterTimeseriesesByLine(timeseriesesByLine) {
const result = [];
for (const {lineDescriptor, timeserieses} of timeseriesesByLine) {
const filteredTimeserieses = timeserieses.filter(ts => ts);
if (filteredTimeserieses.length === 0) continue;
result.push({lineDescriptor, timeserieses: filteredTi... | javascript | {
"resource": ""
} |
q20211 | getIcon | train | function getIcon(datum) {
if (!datum.alert) return {};
if (datum.alert.improvement) {
return {
icon: 'cp:thumb-up',
iconColor: 'var(--improvement-color, green)',
};
}
return {
icon: 'cp:error',
iconColor: datum.alert.bugId ?
'var(--neutral-color-dark, grey)' : 'var(--error-colo... | javascript | {
"resource": ""
} |
q20212 | listConfigs | train | function listConfigs(resultFunc) {
$.ajax({
type: 'GET',
url: 'command/list_configs',
dataType: 'text',
error: function(request, textStatus) {
getResponseDataJson(textStatus);
},
success: function(data, textStatus, request) {
var response = getResponseDataJson(null, data);
if... | javascript | {
"resource": ""
} |
q20213 | listJobs | train | function listJobs(cursor, resultFunc) {
// If the user is paging then they scrolled down so let's
// help them by scrolling the window back to the top.
var jumpToTop = !!cursor;
cursor = cursor ? cursor : '';
setButter('Loading');
$.ajax({
type: 'GET',
url: 'command/list_jobs?cursor=' + cursor,
... | javascript | {
"resource": ""
} |
q20214 | cleanUpJob | train | function cleanUpJob(name, mapreduce_id) {
if (!confirm('Clean up job "' + name +
'" with ID "' + mapreduce_id + '"?')) {
return;
}
$.ajax({
async: false,
type: 'POST',
url: 'command/cleanup_job',
data: {'mapreduce_id': mapreduce_id},
dataType: 'text',
error: function(re... | javascript | {
"resource": ""
} |
q20215 | getJobDetail | train | function getJobDetail(jobId, resultFunc) {
$.ajax({
type: 'GET',
url: 'command/get_job_detail',
dataType: 'text',
data: {'mapreduce_id': jobId},
statusCode: {
404: function() {
setButter('job ' + jobId + ' was not found.', true);
}
},
error: function(request, textStatus... | javascript | {
"resource": ""
} |
q20216 | getSortedKeys | train | function getSortedKeys(obj) {
var keys = [];
$.each(obj, function(key, value) {
keys.push(key);
});
keys.sort();
return keys;
} | javascript | {
"resource": ""
} |
q20217 | getElapsedTimeString | train | function getElapsedTimeString(start_timestamp_ms, updated_timestamp_ms) {
var updatedDiff = updated_timestamp_ms - start_timestamp_ms;
var updatedDays = Math.floor(updatedDiff / 86400000.0);
updatedDiff -= (updatedDays * 86400000.0);
var updatedHours = Math.floor(updatedDiff / 3600000.0);
updatedDiff -= (upda... | javascript | {
"resource": ""
} |
q20218 | addParameters | train | function addParameters(params, prefix) {
if (!params) {
return;
}
var sortedParams = getSortedKeys(params);
$.each(sortedParams, function(index, key) {
var value = params[key];
var paramId = 'job-' + prefix + key + '-param';
var paramP = $('<p class="editable-inp... | javascript | {
"resource": ""
} |
q20219 | setCell | train | function setCell(map, key, columnCount, columnIndex, value) {
if (!map.has(key)) map.set(key, new Array(columnCount));
map.get(key)[columnIndex] = value;
} | javascript | {
"resource": ""
} |
q20220 | getDescriptorParts | train | function getDescriptorParts(lineDescriptor, descriptorFlags) {
const descriptorParts = [];
if (descriptorFlags.suite) {
descriptorParts.push(lineDescriptor.suites.map(breakWords).join('\n'));
}
if (descriptorFlags.measurement) {
descriptorParts.push(breakWords(lineDescriptor.measurement));
}
if (des... | javascript | {
"resource": ""
} |
q20221 | findLowIndexInSortedArray | train | function findLowIndexInSortedArray(ary, getKey, loVal) {
if (ary.length === 0) return 1;
let low = 0;
let high = ary.length - 1;
let i;
let comparison;
let hitPos = -1;
while (low <= high) {
i = Math.floor((low + high) / 2);
comparison = getKey(ary[i]) - loVal;
if (comparison < 0) {
low... | javascript | {
"resource": ""
} |
q20222 | createLogDump | train | function createLogDump(
userComments, constants, events, polledData, tabData, numericDate) {
var logDump = {
'userComments': userComments,
'constants': constants,
'events': events,
'polledData': polledData,
'tabData': tabData
};
// Not technically client info, but it's u... | javascript | {
"resource": ""
} |
q20223 | onUpdateAllCompleted | train | function onUpdateAllCompleted(userComments, callback, polledData) {
var logDump = createLogDump(
userComments, Constants,
EventsTracker.getInstance().getAllCapturedEvents(), polledData,
getTabData_(), timeutil.getCurrentTime());
callback(JSON.stringify(logDump));
} | javascript | {
"resource": ""
} |
q20224 | createLogDumpAsync | train | function createLogDumpAsync(userComments, callback) {
g_browser.updateAllInfo(
onUpdateAllCompleted.bind(null, userComments, callback));
} | javascript | {
"resource": ""
} |
q20225 | getTabData_ | train | function getTabData_() {
var tabData = {};
var tabSwitcher = MainView.getInstance().tabSwitcher();
var tabIdToView = tabSwitcher.getAllTabViews();
for (var tabId in tabIdToView) {
var view = tabIdToView[tabId];
if (view.saveState)
tabData[tabId] = view.saveState();
}
} | javascript | {
"resource": ""
} |
q20226 | loadLogFile | train | function loadLogFile(logFileContents, fileName) {
// Try and parse the log dump as a single JSON string. If this succeeds,
// it's most likely a full log dump. Otherwise, it may be a dump created by
// --log-net-log.
var parsedDump = null;
var errorString = '';
try {
parsedDump = JSON.pa... | javascript | {
"resource": ""
} |
q20227 | isRelated | train | function isRelated(a, b) {
if (a.measurementAvg === b.measurementAvg) return true;
if (a.relatedNames &&
a.relatedNames.has(b.measurementAvg)) {
return true;
}
if (b.relatedNames &&
b.relatedNames.has(a.measurementAvg)) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q20228 | superPropertiesClass | train | function superPropertiesClass(constructor) {
const superCtor = Object.getPrototypeOf(constructor);
// Note, the `PropertiesMixin` class below only refers to the class
// generated by this call to the mixin; the instanceof test only works
// because the mixin is deduped and guaranteed only to apply once, he... | javascript | {
"resource": ""
} |
q20229 | makeSrcFile | train | function makeSrcFile(path, srcDir, name) {
if (JSDOC.opt.s) return;
if (!name) {
name = path.replace(/\.\.?[\\\/]/g, "").replace(/[\\\/]/g, "_");
name = name.replace(/\:/g, "_");
}
var src = {path: path, name:name, charset: IO.encoding, hilited: ""};
if (defined(JSDOC.PluginManager)) {
JSDOC.PluginMana... | javascript | {
"resource": ""
} |
q20230 | makeSignature | train | function makeSignature(params) {
if (!params) return "()";
var signature = "("
+
params.filter(
function($) {
return $.name.indexOf(".") == -1; // don't show config params in signature
}
).map(
function($) {
return $.name;
}
).join(", ")
+
")";
return signature;
} | javascript | {
"resource": ""
} |
q20231 | getIso8601String | train | function getIso8601String(timeMs) {
var time = new Date();
time.setTime(timeMs);
return '' +
time.getUTCFullYear() + '-' +
leftPadNumber(time.getUTCMonth() + 1, 2, '0') + '-' +
leftPadNumber(time.getUTCDate(), 2, '0') + 'T' +
leftPadNumber(time.getUTCHours(), 2, '0') + ':' +
leftPadN... | javascript | {
"resource": ""
} |
q20232 | getElapsedTimeString | train | function getElapsedTimeString(startTimestampMs, updatedTimestampMs) {
var updatedDiff = Math.max(0, updatedTimestampMs - startTimestampMs);
var updatedDays = Math.floor(updatedDiff / 86400000.0);
updatedDiff -= (updatedDays * 86400000.0);
var updatedHours = Math.floor(updatedDiff / 3600000.0);
updatedDiff -= ... | javascript | {
"resource": ""
} |
q20233 | setButter | train | function setButter(message, error, traceback, asHtml) {
var butter = $('#butter');
// Prevent flicker on butter update by hiding it first.
butter.css('display', 'none');
if (error) {
butter.removeClass('info').addClass('error');
} else {
butter.removeClass('error').addClass('info');
}
butter.child... | javascript | {
"resource": ""
} |
q20234 | completeProcess | train | function completeProcess(messages) {
var html = outputHTMLString(messages);
var file = new Blob([html], {type: 'text/html'});
var url = URL.createObjectURL(file);
var a = document.getElementById('button');
a.className = 'download';
a.innerHTML = 'Download';
a.href = url;
a.download = "snap-it.html";
} | javascript | {
"resource": ""
} |
q20235 | outputHTMLString | train | function outputHTMLString(messages) {
var rootIndex = 0;
for (var i = 1; i < messages.length; i++) {
rootIndex = messages[i].frameIndex === '0' ? i : rootIndex;
}
fillRemainingHolesAndMinimizeStyles(messages, rootIndex);
return messages[rootIndex].html.join('');
} | javascript | {
"resource": ""
} |
q20236 | minimizeStyles | train | function minimizeStyles(message) {
var nestingDepth = message.frameIndex.split('.').length - 1;
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.setAttribute(
'style',
`height: ${message.windowHeight}px;` +
`width: ${message.windowWidth}px;`);
var ht... | javascript | {
"resource": ""
} |
q20237 | minimizePseudoElementStyle | train | function minimizePseudoElementStyle(
message,
doc,
selector,
finalPseudoElements) {
var maxNumberOfIterations = 5;
var match = selector.match(/^#(.*):(:.*)$/);
var id = match[1];
var type = match[2];
var element = doc.getElementById(id);
if (element) {
var originalStyleMap = message.pseu... | javascript | {
"resource": ""
} |
q20238 | minimizeStyle | train | function minimizeStyle(message, doc, element, id, index) {
var originalStyleAttribute = element.getAttribute('style');
var originalStyleMap = message.idToStyleMap[id];
var requiredStyleMap = {};
var maxNumberOfIterations = 5;
// We compare the computed style before and after removing the style attribute
//... | javascript | {
"resource": ""
} |
q20239 | updateMinimizedStyleMap | train | function updateMinimizedStyleMap(
doc,
element,
originalStyleMap,
minimizedStyleMap,
pseudo) {
var currentComputedStyle = doc.defaultView.getComputedStyle(element, pseudo);
var foundNewRequiredStyle = false;
for (var property in originalStyleMap) {
var originalValue = originalStyleMap[prop... | javascript | {
"resource": ""
} |
q20240 | buildStyleAttribute | train | function buildStyleAttribute(styleMap) {
var styleAttribute = [];
for (var property in styleMap) {
styleAttribute.push(property + ': ' + styleMap[property] + ';');
}
return styleAttribute.join(' ');
} | javascript | {
"resource": ""
} |
q20241 | unescapeHTML | train | function unescapeHTML(html, nestingDepth) {
var div = document.createElement('div');
for (var i = 0; i < nestingDepth; i++) {
div.innerHTML = `<iframe srcdoc="${html}"></iframe>`;
html = div.childNodes[0].attributes.srcdoc.value;
}
return html;
} | javascript | {
"resource": ""
} |
q20242 | MainView | train | function MainView() {
assertFirstConstructorCall(MainView);
if (hasTouchScreen()) {
document.body.classList.add('touch');
}
// This must be initialized before the tabs, so they can register as
// observers.
g_browser = BrowserBridge.getInstance();
// This must be the first constants... | javascript | {
"resource": ""
} |
q20243 | areValidConstants | train | function areValidConstants(receivedConstants) {
return typeof(receivedConstants) === 'object' &&
typeof(receivedConstants.logEventTypes) === 'object' &&
typeof(receivedConstants.clientInfo) === 'object' &&
typeof(receivedConstants.logEventPhase) === 'object' &&
typeof(receivedConstants.logSour... | javascript | {
"resource": ""
} |
q20244 | expandShorthandAndAntiAlias | train | function expandShorthandAndAntiAlias(property, value, result) {
if (isNotAnimatable(property)) {
return;
}
var longProperties = shorthandToLonghand[property];
if (longProperties) {
shorthandExpanderElem.style[property] = value;
for (var i in longProperties) {
var longProperty =... | javascript | {
"resource": ""
} |
q20245 | createSchemaContentWithLocales | train | async function createSchemaContentWithLocales(localizedSchema, mainSchemaPath) {
// eslint-disable-next-line func-style
const traverse = async (obj) => {
const objectKeys = Object.keys(obj);
await Promise.all(
objectKeys.map(async (key) => {
if (typeof obj[key].t === 'string') {
obj[... | javascript | {
"resource": ""
} |
q20246 | combineLocales | train | async function combineLocales(localesPath) {
const localesFiles = await fs.readdir(localesPath);
const jsonFiles = localesFiles.filter((fileName) =>
fileName.endsWith('.json'),
);
return jsonFiles.reduce(async (promise, file) => {
const accumulator = await promise;
const localeCode = path
.ba... | javascript | {
"resource": ""
} |
q20247 | _getLocalizedValues | train | async function _getLocalizedValues(key, localizedSchema) {
const combinedTranslationsObject = {};
await Promise.all(
// eslint-disable-next-line array-callback-return
Object.keys(localizedSchema).map((language) => {
combinedTranslationsObject[language] = _.get(
localizedSchema[language],
... | javascript | {
"resource": ""
} |
q20248 | getAvailablePortSeries | train | function getAvailablePortSeries(start, quantity, increment = 1) {
const startPort = start;
const endPort = start + (quantity - 1);
return findAPortInUse(startPort, endPort, '127.0.0.1').then((port) => {
if (typeof port === 'number') {
return getAvailablePortSeries(port + increment, quantity);
}
... | javascript | {
"resource": ""
} |
q20249 | create | train | function create({values, name, root} = {}) {
const envName = _getFileName(name);
const envPath = path.resolve(
root || config.get('env.rootDirectory'),
envName,
);
const envContents = _getFileContents(values);
fs.writeFileSync(envPath, envContents);
} | javascript | {
"resource": ""
} |
q20250 | _getFileName | train | function _getFileName(name) {
if (typeof name === 'undefined' || name.trim() === '') {
return config.get('env.basename');
}
return `${config.get('env.basename')}.${name}`;
} | javascript | {
"resource": ""
} |
q20251 | _getFileContents | train | function _getFileContents(values) {
const env = getDefaultSlateEnv();
for (const key in values) {
if (values.hasOwnProperty(key) && env.hasOwnProperty(key)) {
env[key] = values[key];
}
}
return Object.entries(env)
.map((keyValues) => {
return `${keyValues.join('=')}\r\n`;
})
.j... | javascript | {
"resource": ""
} |
q20252 | assign | train | function assign(name) {
const envFileName = _getFileName(name);
const envPath = path.resolve(config.get('env.rootDirectory'), envFileName);
const result = dotenv.config({path: envPath});
if (typeof name !== 'undefined' && result.error) {
throw result.error;
}
_setEnvName(name);
} | javascript | {
"resource": ""
} |
q20253 | validate | train | function validate() {
const errors = [].concat(
_validateStore(),
_validatePassword(),
_validateThemeId(),
);
return {
errors,
isValid: errors.length === 0,
};
} | javascript | {
"resource": ""
} |
q20254 | getSlateEnv | train | function getSlateEnv() {
const env = {};
SLATE_ENV_VARS.forEach((key) => {
env[key] = process.env[key];
});
return env;
} | javascript | {
"resource": ""
} |
q20255 | installThemeDeps | train | function installThemeDeps(root, options) {
if (options.skipInstall) {
console.log('Skipping theme dependency installation...');
return Promise.resolve();
}
const prevDir = process.cwd();
console.log('Installing theme dependencies...');
process.chdir(root);
const cmd = utils.shouldUseYarn()
? ... | javascript | {
"resource": ""
} |
q20256 | copyFromDir | train | function copyFromDir(starter, root) {
if (!fs.existsSync(starter)) {
throw new Error(`starter ${starter} doesn't exist`);
}
// Chmod with 755.
// 493 = parseInt('755', 8)
return fs.mkdirp(root, {mode: 493}).then(() => {
console.log(
`Creating new theme from local starter: ${chalk.green(starter)... | javascript | {
"resource": ""
} |
q20257 | cloneFromGit | train | function cloneFromGit(hostInfo, root, ssh) {
const branch = hostInfo.committish ? `-b ${hostInfo.committish}` : '';
let url;
if (ssh) {
url = hostInfo.ssh({noCommittish: true});
} else {
url = hostInfo.https({noCommittish: true, noGitPlus: true});
}
console.log(`Cloning theme from a git repo: ${ch... | javascript | {
"resource": ""
} |
q20258 | CustomError | train | function CustomError (message, cause) {
Error.call(this)
if (Error.captureStackTrace)
Error.captureStackTrace(this, arguments.callee)
init.call(this, 'CustomError', message, cause)
} | javascript | {
"resource": ""
} |
q20259 | doVisitFull | train | function doVisitFull(visit, node) {
if(node.left) {
var v = doVisitFull(visit, node.left)
if(v) { return v }
}
var v = visit(node.key, node.value)
if(v) { return v }
if(node.right) {
return doVisitFull(visit, node.right)
}
} | javascript | {
"resource": ""
} |
q20260 | doVisitHalf | train | function doVisitHalf(lo, compare, visit, node) {
var l = compare(lo, node.key)
if(l <= 0) {
if(node.left) {
var v = doVisitHalf(lo, compare, visit, node.left)
if(v) { return v }
}
var v = visit(node.key, node.value)
if(v) { return v }
}
if(node.right) {
return doVisitHalf(lo, com... | javascript | {
"resource": ""
} |
q20261 | doVisit | train | function doVisit(lo, hi, compare, visit, node) {
var l = compare(lo, node.key)
var h = compare(hi, node.key)
var v
if(l <= 0) {
if(node.left) {
v = doVisit(lo, hi, compare, visit, node.left)
if(v) { return v }
}
if(h > 0) {
v = visit(node.key, node.value)
if(v) { return v }
... | javascript | {
"resource": ""
} |
q20262 | swapNode | train | function swapNode(n, v) {
n.key = v.key
n.value = v.value
n.left = v.left
n.right = v.right
n._color = v._color
n._count = v._count
} | javascript | {
"resource": ""
} |
q20263 | collate | train | function collate(a, b) {
if (a === b) {
return 0;
}
a = normalizeKey(a);
b = normalizeKey(b);
var ai = collationIndex(a);
var bi = collationIndex(b);
if ((ai - bi) !== 0) {
return ai - bi;
}
switch (typeof a) {
case 'number':
return a - b;
case 'boolean':
return a < b ? ... | javascript | {
"resource": ""
} |
q20264 | pop | train | function pop(stack, metaStack) {
var obj = stack.pop();
if (metaStack.length) {
var lastMetaElement = metaStack[metaStack.length - 1];
if (obj === lastMetaElement.element) {
// popping a meta-element, e.g. an object whose value is another object
metaStack.pop();
lastMetaElement = metaStac... | javascript | {
"resource": ""
} |
q20265 | getHost | train | function getHost(name, opts) {
// encode db name if opts.prefix is a url (#5574)
if (hasUrlPrefix(opts)) {
var dbName = opts.name.substr(opts.prefix.length);
name = opts.prefix + encodeURIComponent(dbName);
}
// Prase the URI into all its little bits
var uri = pouchdbUtils.parseUri(name);
// Stor... | javascript | {
"resource": ""
} |
q20266 | genUrl | train | function genUrl(opts, path) {
// If the host already has a path, then we need to have a path delimiter
// Otherwise, the path delimiter is the empty string
var pathDel = !opts.path ? '' : '/';
// If the host already has a path, then we need to have a path delimiter
// Otherwise, the path delimiter is the emp... | javascript | {
"resource": ""
} |
q20267 | train | function (since, callback) {
if (opts.aborted) {
return;
}
params.since = since;
// "since" can be any kind of json object in Coudant/CouchDB 2.x
/* istanbul ignore next */
if (typeof params.since === "object") {
params.since = JSON.stringify(params.since);
}
... | javascript | {
"resource": ""
} | |
q20268 | decodeDoc | train | function decodeDoc(doc) {
if (!doc) {
return doc;
}
var idx = doc._doc_id_rev.lastIndexOf(':');
doc._id = doc._doc_id_rev.substring(0, idx - 1);
doc._rev = doc._doc_id_rev.substring(idx + 1);
delete doc._doc_id_rev;
return doc;
} | javascript | {
"resource": ""
} |
q20269 | readBlobData | train | function readBlobData(body, type, asBlob, callback) {
if (asBlob) {
if (!body) {
callback(pouchdbBinaryUtils.blob([''], {type: type}));
} else if (typeof body !== 'string') { // we have blob support
callback(body);
} else { // no blob support
callback(pouchdbBinaryUtils.base64StringToBlo... | javascript | {
"resource": ""
} |
q20270 | postProcessAttachments | train | function postProcessAttachments(results, asBlob) {
return Promise.all(results.map(function (row) {
if (row.doc && row.doc._attachments) {
var attNames = Object.keys(row.doc._attachments);
return Promise.all(attNames.map(function (att) {
var attObj = row.doc._attachments[att];
if (!('bo... | javascript | {
"resource": ""
} |
q20271 | insertAttachmentMappings | train | function insertAttachmentMappings(docInfo, seq, callback) {
var attsAdded = 0;
var attsToAdd = Object.keys(docInfo.data._attachments || {});
if (!attsToAdd.length) {
return callback();
}
function checkDone() {
if (++attsAdded === attsToAdd.length) {
callback();
}
}
... | javascript | {
"resource": ""
} |
q20272 | fetchDocAsynchronously | train | function fetchDocAsynchronously(metadata, row, winningRev$$1) {
var key = metadata.id + "::" + winningRev$$1;
docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
row.doc = decodeDoc(e.target.result);
if (opts.conflicts) {
var conflicts = pouchdbMerge.collectConflicts(metadata);
... | javascript | {
"resource": ""
} |
q20273 | createSchema | train | function createSchema(db) {
var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});
db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})
.createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});
db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});
db.createObjectStore(META_STO... | javascript | {
"resource": ""
} |
q20274 | addDeletedOrLocalIndex | train | function addDeletedOrLocalIndex(txn, callback) {
var docStore = txn.objectStore(DOC_STORE);
docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
docStore.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
var metadata = cur... | javascript | {
"resource": ""
} |
q20275 | verifyAttachment | train | function verifyAttachment(digest, callback) {
txn.get(stores.attachmentStore, digest, function (levelErr) {
if (levelErr) {
var err = pouchdbErrors.createError(pouchdbErrors.MISSING_STUB,
'unknown stub attachment with digest ' +
dig... | javascript | {
"resource": ""
} |
q20276 | fromList | train | function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret =... | javascript | {
"resource": ""
} |
q20277 | fromListPartial | train | function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = l... | javascript | {
"resource": ""
} |
q20278 | writeOrBuffer | train | function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk)) encoding = 'buffer';
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we ... | javascript | {
"resource": ""
} |
q20279 | normalizeEncoding | train | function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
} | javascript | {
"resource": ""
} |
q20280 | utf8FillLast | train | function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(... | javascript | {
"resource": ""
} |
q20281 | utf8Text | train | function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
} | javascript | {
"resource": ""
} |
q20282 | utf16End | train | function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
} | javascript | {
"resource": ""
} |
q20283 | through2 | train | function through2 (construct) {
return function (options, transform, flush) {
if (typeof options == 'function') {
flush = transform
transform = options
options = {}
}
if (typeof transform != 'function')
transform = noop
if (typeof flush != 'function')
flush = null... | javascript | {
"resource": ""
} |
q20284 | parseDoc | train | function parseDoc(doc, newEdits) {
var nRevNum;
var newRevId;
var revInfo;
var opts = {status: 'available'};
if (doc._deleted) {
opts.deleted = true;
}
if (newEdits) {
if (!doc._id) {
doc._id = pouchdbUtils.uuid();
}
newRevId = pouchdbUtils.uuid(32, 16).toLowerCase();
if (doc._... | javascript | {
"resource": ""
} |
q20285 | readAsBinaryString | train | function readAsBinaryString(blob, callback) {
if (typeof FileReader === 'undefined') {
// fix for Firefox in a web worker
// https://bugzilla.mozilla.org/show_bug.cgi?id=901097
return callback(arrayBufferToBinaryString(
new FileReaderSync().readAsArrayBuffer(blob)));
}
var reader = new FileRead... | javascript | {
"resource": ""
} |
q20286 | yankError | train | function yankError(callback) {
return function (err, results) {
if (err || (results[0] && results[0].error)) {
callback(err || results[0]);
} else {
callback(null, results.length ? results[0] : results);
}
};
} | javascript | {
"resource": ""
} |
q20287 | cleanDocs | train | function cleanDocs(docs) {
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
if (doc._deleted) {
delete doc._attachments; // ignore atts for deleted docs
} else if (doc._attachments) {
// filter out extraneous keys from _attachments
var atts = Object.keys(doc._attachments);
... | javascript | {
"resource": ""
} |
q20288 | compareByIdThenRev | train | function compareByIdThenRev(a, b) {
var idCompare = compare(a._id, b._id);
if (idCompare !== 0) {
return idCompare;
}
var aStart = a._revisions ? a._revisions.start : 0;
var bStart = b._revisions ? b._revisions.start : 0;
return compare(aStart, bStart);
} | javascript | {
"resource": ""
} |
q20289 | computeHeight | train | function computeHeight(revs) {
var height = {};
var edges = [];
pouchdbMerge.traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
var rev = pos + "-" + id;
if (isLeaf) {
height[rev] = 0;
}
if (prnt !== undefined) {
edges.push({from: prnt, to: rev});
}
return rev;
});
e... | javascript | {
"resource": ""
} |
q20290 | doNextCompaction | train | function doNextCompaction(self) {
var task = self._compactionQueue[0];
var opts = task.opts;
var callback = task.callback;
self.get('_local/compaction').catch(function () {
return false;
}).then(function (doc) {
if (doc && doc.last_seq) {
opts.last_seq = doc.last_seq;
}
self._compact(opt... | javascript | {
"resource": ""
} |
q20291 | createFieldSorter | train | function createFieldSorter(sort) {
function getFieldValuesAsArray(doc) {
return sort.map(function (sorting) {
var fieldName = getKey(sorting);
var parsedField = parseField(fieldName);
var docFieldValue = getFieldFromDoc(doc, parsedField);
return docFieldValue;
});
}
return functi... | javascript | {
"resource": ""
} |
q20292 | checkFieldInIndex | train | function checkFieldInIndex(index, field) {
var indexFields = index.def.fields.map(getKey);
for (var i = 0, len = indexFields.length; i < len; i++) {
var indexField = indexFields[i];
if (field === indexField) {
return true;
}
}
return false;
} | javascript | {
"resource": ""
} |
q20293 | sortFieldsByIndex | train | function sortFieldsByIndex(userFields, index) {
var indexFields = index.def.fields.map(getKey);
return userFields.slice().sort(function (a, b) {
var aIdx = indexFields.indexOf(a);
var bIdx = indexFields.indexOf(b);
if (aIdx === -1) {
aIdx = Number.MAX_VALUE;
}
if (bIdx === -1) {
bId... | javascript | {
"resource": ""
} |
q20294 | getBasicInMemoryFields | train | function getBasicInMemoryFields(index, selector, userFields) {
userFields = sortFieldsByIndex(userFields, index);
// check if any of the user selectors lose precision
var needToFilterInMemory = false;
for (var i = 0, len = userFields.length; i < len; i++) {
var field = userFields[i];
if (needToFilterI... | javascript | {
"resource": ""
} |
q20295 | checkIndexFieldsMatch | train | function checkIndexFieldsMatch(indexFields, sortOrder, fields) {
if (sortOrder) {
// array has to be a strict subarray of index array. furthermore,
// the sortOrder fields need to all be represented in the index
var sortMatches = utils.oneArrayIsStrictSubArrayOfOther(sortOrder, indexFields);
var selec... | javascript | {
"resource": ""
} |
q20296 | findBestMatchingIndex | train | function findBestMatchingIndex(selector, userFields, sortOrder, indexes) {
var matchingIndexes = findMatchingIndexes(selector, userFields, sortOrder, indexes);
if (matchingIndexes.length === 0) {
//return `all_docs` as a default index;
//I'm assuming that _all_docs is always first
var defaultIndex = i... | javascript | {
"resource": ""
} |
q20297 | massageSort | train | function massageSort(sort) {
if (!Array.isArray(sort)) {
throw new Error('invalid sort json - should be an array');
}
return sort.map(function (sorting) {
if (typeof sorting === 'string') {
var obj = {};
obj[sorting] = 'asc';
return obj;
} else {
return sorting;
}
});
} | javascript | {
"resource": ""
} |
q20298 | filterInclusiveStart | train | function filterInclusiveStart(rows, targetValue, index) {
var indexFields = index.def.fields;
for (var i = 0, len = rows.length; i < len; i++) {
var row = rows[i];
// shave off any docs at the beginning that are <= the
// target value
var docKey = getKeyFromDoc(row.doc, index);
if (indexFields... | javascript | {
"resource": ""
} |
q20299 | generateReplicationId | train | function generateReplicationId(src, target, opts) {
var docIds = opts.doc_ids ? opts.doc_ids.sort(pouchdbCollate.collate) : '';
var filterFun = opts.filter ? opts.filter.toString() : '';
var queryParams = '';
var filterViewName = '';
var selector = '';
// possibility for checkpoints to be lost here as beh... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.