_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)
collapse(elt.id.substring(0, split));
}
}
|
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');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
}
|
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');
else
$(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_MODINDEX) {
togglers.click();
}
}
|
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('.hitarea').click();
} else {
// No children, so just scroll.
scrollTreeToPipeline(pipelineId);
}
}
|
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.children[i]);
total += parts[0];
done += parts[1];
}
return [total, done];
}
|
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 = rootElement;
nextPipelineId = statusMap.rootPipelineId;
}
var parentInfoMap = statusMap.pipelines[nextPipelineId];
currentElement.append(
constructStageNode(nextPipelineId, parentInfoMap, true));
if (statusMap.pipelines[nextPipelineId]) {
var children = statusMap.pipelines[nextPipelineId].children;
if (children.length > 0) {
var treeElement = null;
if (rootElement) {
treeElement =
$('<ul id="pipeline-tree" class="treeview-black treeview">');
} else {
treeElement = $('<ul>');
}
$.each(children, function(index, childPipelineId) {
var childElement = generateSidebar(statusMap, childPipelineId);
treeElement.append(childElement);
});
currentElement.append(treeElement);
}
}
return currentElement;
}
|
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 children = infoMap.children.slice(0);
children.sort(function(a, b) {
var infoMapA = STATUS_MAP.pipelines[a];
var infoMapB = STATUS_MAP.pipelines[b];
if (!infoMapA || !infoMapB) {
return 0;
}
if (infoMapA.startTimeMs && infoMapB.startTimeMs) {
return infoMapA.startTimeMs - infoMapB.startTimeMs;
} else {
return 0;
}
});
for (var i = 0; i < children.length; ++i) {
var foundPipelineId = findActivePipeline(children[i], false);
if (foundPipelineId != null) {
return foundPipelineId;
}
}
return null;
}
|
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: filteredTimeserieses});
}
return result;
}
|
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-color, red)',
};
}
|
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 (response) {
resultFunc(response.configs);
}
}
});
}
|
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,
dataType: 'text',
error: function(request, textStatus) {
getResponseDataJson(textStatus);
},
success: function(data, textStatus, request) {
var response = getResponseDataJson(null, data);
if (response) {
resultFunc(response.jobs, response.cursor);
if (jumpToTop) {
window.scrollTo(0, 0);
}
hideButter(); // Hide the loading message.
}
}
});
}
|
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(request, textStatus) {
getResponseDataJson(textStatus);
},
success: function(data, textStatus, request) {
var response = getResponseDataJson(null, data);
if (response) {
setButter(response.status);
if (!response.status.error) {
$('#row-' + mapreduce_id).remove();
}
}
}
});
}
|
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) {
getResponseDataJson(textStatus);
},
success: function(data, textStatus, request) {
var response = getResponseDataJson(null, data);
if (response) {
resultFunc(jobId, response);
}
}
});
}
|
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 -= (updatedHours * 3600000.0);
var updatedMinutes = Math.floor(updatedDiff / 60000.0);
updatedDiff -= (updatedMinutes * 60000.0);
var updatedSeconds = Math.floor(updatedDiff / 1000.0);
var updatedString = '';
if (updatedDays == 1) {
updatedString = '1 day, ';
} else if (updatedDays > 1) {
updatedString = '' + updatedDays + ' days, ';
}
updatedString +=
leftPadNumber(updatedHours, 2, '0') + ':' +
leftPadNumber(updatedMinutes, 2, '0') + ':' +
leftPadNumber(updatedSeconds, 2, '0');
return updatedString;
}
|
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-input">');
// Deal with the case in which the value is an object rather than
// just the default value string.
var prettyKey = key;
if (value && value['human_name']) {
prettyKey = value['human_name'];
}
if (value && value['default_value']) {
value = value['default_value'];
}
$('<label>')
.attr('for', paramId)
.text(prettyKey)
.appendTo(paramP);
$('<span>').text(': ').appendTo(paramP);
$('<input type="text">')
.attr('id', paramId)
.attr('name', prefix + key)
.attr('value', value)
.appendTo(paramP);
paramP.appendTo(jobForm);
});
}
|
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 (descriptorFlags.bot) {
descriptorParts.push(lineDescriptor.bots.map(breakWords).join('\n'));
}
if (descriptorFlags.cases) {
descriptorParts.push(lineDescriptor.cases.map(breakWords).join('\n'));
}
if (descriptorFlags.buildType) {
descriptorParts.push(lineDescriptor.buildType);
}
return descriptorParts;
}
|
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 = i + 1; continue;
} else if (comparison > 0) {
high = i - 1; continue;
} else {
hitPos = i;
high = i - 1;
}
}
// return where we hit, or failing that the low pos
return hitPos !== -1 ? hitPos : 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 used at the same point in the code.
if (numericDate && constants.clientInfo) {
constants.clientInfo.numericDate = numericDate;
}
return logDump;
}
|
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.parse(logFileContents);
} catch (error) {
try {
// We may have a --log-net-log=blah log dump. If so, remove the comma
// after the final good entry, and add the necessary close brackets.
var end = Math.max(
logFileContents.lastIndexOf(',\n'),
logFileContents.lastIndexOf(',\r'));
if (end != -1) {
parsedDump = JSON.parse(logFileContents.substring(0, end) + ']}');
errorString += 'Log file truncated. Events may be missing.\n';
}
} catch (error2) {
}
}
if (!parsedDump)
return 'Unable to parse log dump as JSON file.';
return errorString + loadLogDump(parsedDump, fileName);
}
|
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, hence
// all constructors in a proto chain will see the same `PropertiesMixin`
return (superCtor.prototype instanceof PropertiesMixin) ?
/** @type {PropertiesMixinConstructor} */ (superCtor) : null;
}
|
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.PluginManager.run("onPublishSrc", src);
}
if (src.hilited) {
IO.saveFile(srcDir, name+publish.conf.ext, src.hilited);
}
}
|
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') + ':' +
leftPadNumber(time.getUTCMinutes(), 2, '0') + ':' +
leftPadNumber(time.getUTCSeconds(), 2, '0') + 'Z';
}
|
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 -= (updatedHours * 3600000.0);
var updatedMinutes = Math.floor(updatedDiff / 60000.0);
updatedDiff -= (updatedMinutes * 60000.0);
var updatedSeconds = Math.floor(updatedDiff / 1000.0);
updatedDiff -= (updatedSeconds * 1000.0);
var updatedMs = Math.floor(updatedDiff / 1.0);
var updatedString = '';
if (updatedMinutes > 0) {
if (updatedDays == 1) {
updatedString = '1 day, ';
} else if (updatedDays > 1) {
updatedString = '' + updatedDays + ' days, ';
}
updatedString +=
leftPadNumber(updatedHours, 2, '0') + ':' +
leftPadNumber(updatedMinutes, 2, '0') + ':' +
leftPadNumber(updatedSeconds, 2, '0');
if (updatedMs > 0) {
updatedString += '.' + leftPadNumber(updatedMs, 3, '0');
}
} else {
updatedString += updatedSeconds;
updatedString += '.' + leftPadNumber(updatedMs, 3, '0');
updatedString += ' seconds';
}
return updatedString;
}
|
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.children().remove();
if (asHtml) {
butter.append($('<div>').html(message));
} else {
butter.append($('<div>').text(message));
}
function centerButter() {
butter.css('left', ($(window).width() - $(butter).outerWidth()) / 2);
}
if (traceback) {
var showDetail = $('<a href="">').text('Detail');
showDetail.click(function(event) {
$('#butter-detail').toggle();
centerButter();
event.preventDefault();
});
var butterDetail = $('<pre id="butter-detail">').text(traceback);
butterDetail.css('display', 'none');
butter.append(showDetail);
butter.append(butterDetail);
}
centerButter();
butter.css('display', null);
}
|
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 html = message.html.join('');
html = unescapeHTML(html, nestingDepth);
iframe.contentDocument.documentElement.innerHTML = html;
var doc = iframe.contentDocument;
// Remove entry in |message.html| where extra style element was specified.
message.html[message.pseudoElementTestingStyleIndex] = '';
var finalPseudoElements = [];
for (var selector in message.pseudoElementSelectorToCSSMap) {
minimizePseudoElementStyle(message, doc, selector, finalPseudoElements);
}
if (finalPseudoElements.length > 0) {
message.html[message.pseudoElementPlaceHolderIndex] =
`<style>${finalPseudoElements.join(' ')}</style>`;
}
if (message.rootStyleIndex) {
minimizeStyle(
message,
doc,
doc.documentElement,
message.rootId,
message.rootStyleIndex);
}
for (var id in message.idToStyleIndex) {
var index = message.idToStyleIndex[id];
var element = doc.getElementById(id);
if (element) {
minimizeStyle(message, doc, element, id, index);
}
}
iframe.remove();
}
|
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.pseudoElementSelectorToCSSMap[selector];
var requiredStyleMap = {};
// We compare the computed style before and after removing the pseudo
// element and accumulate the differences in |requiredStyleMap|. The pseudo
// element is removed by changing the element id. Because some properties
// affect other properties, such as border-style: solid causing a change in
// border-width, we do this iteratively until a fixed-point is reached (or
// |maxNumberOfIterations| is hit).
// TODO(sfine): Unify this logic with minimizeStyles.
for (var i = 0; i < maxNumberOfIterations; i++) {
var currentPseudoElement = ['#' + message.unusedId + ':' + type + '{'];
currentPseudoElement.push(buildStyleAttribute(requiredStyleMap));
currentPseudoElement.push('}');
element.setAttribute('id', message.unusedId);
var style = doc.getElementById(message.pseudoElementTestingStyleId);
style.innerHTML = currentPseudoElement.join(' ');
var foundNewRequiredStyle = updateMinimizedStyleMap(
doc,
element,
originalStyleMap,
requiredStyleMap,
type);
if (!foundNewRequiredStyle) {
break;
}
}
element.setAttribute('id', id);
finalPseudoElements.push('#' + id + ':' + type + '{');
var finalPseudoElement = buildStyleAttribute(requiredStyleMap);
var nestingDepth = message.frameIndex.split('.').length - 1;
finalPseudoElement = finalPseudoElement.replace(
/"/g,
escapedQuote(nestingDepth));
finalPseudoElements.push(finalPseudoElement);
finalPseudoElements.push('}');
}
}
|
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
// and accumulate the differences in |requiredStyleMap|. Because some
// properties affect other properties, such as boder-style: solid causing a
// change in border-width, we do this iteratively until a fixed-point is
// reached (or |maxNumberOfIterations| is hit).
for (var i = 0; i < maxNumberOfIterations; i++) {
element.setAttribute('style', buildStyleAttribute(requiredStyleMap));
var foundNewRequiredStyle = updateMinimizedStyleMap(
doc,
element,
originalStyleMap,
requiredStyleMap,
null);
element.setAttribute('style', buildStyleAttribute(originalStyleMap));
if (!foundNewRequiredStyle) {
break;
}
}
var finalStyleAttribute = buildStyleAttribute(requiredStyleMap);
if (finalStyleAttribute) {
var nestingDepth = message.frameIndex.split('.').length - 1;
finalStyleAttribute = finalStyleAttribute.replace(
/"/g,
escapedQuote(nestingDepth + 1));
var quote = escapedQuote(nestingDepth);
message.html[index] = `style=${quote}${finalStyleAttribute}${quote} `;
} else {
message.html[index] = '';
}
}
|
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[property];
if (originalValue != currentComputedStyle.getPropertyValue(property)) {
minimizedStyleMap[property] = originalValue;
foundNewRequiredStyle = true;
}
}
return foundNewRequiredStyle;
}
|
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 observer, so other constants observers
// can safely use the globals, rather than depending on walking through
// the constants themselves.
g_browser.addConstantsObserver(new ConstantsObserver());
// Create the tab switcher.
this.initTabs_();
// Cut out a small vertical strip at the top of the window, to display
// a high level status (i.e. if we are displaying a log file or not).
// Below it we will position the main tabs and their content area.
this.topBarView_ = TopBarView.getInstance(this);
const verticalSplitView =
new VerticalSplitView(this.topBarView_, this.tabSwitcher_);
superClass.call(this, verticalSplitView);
// Trigger initial layout.
this.resetGeometry();
window.onhashchange = this.onUrlHashChange_.bind(this);
// Select the initial view based on the current URL.
window.onhashchange();
// No log file loaded yet so set the status bar to that state.
this.topBarView_.switchToSubView('loaded').setFileName(
'No log to display.');
// TODO(rayraymond): Follow-up is to completely remove all code from
// g_browser that interacts with sending/receiving messages from
// browser.
g_browser.disable();
}
|
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.logSourceType) === 'object' &&
typeof(receivedConstants.loadFlag) === 'object' &&
typeof(receivedConstants.netError) === 'object' &&
typeof(receivedConstants.addressFamily) === 'object' &&
isNetLogNumber(receivedConstants.timeTickOffset) &&
typeof(receivedConstants.logFormatVersion) === 'number';
}
|
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 = longProperties[i];
var longhandValue = shorthandExpanderElem.style[longProperty];
result[longProperty] = antiAlias(longProperty, longhandValue);
}
} else {
result[property] = antiAlias(property, value);
}
}
|
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[key] = await _getLocalizedValues(obj[key].t, localizedSchema);
} else if (typeof obj[key] === 'object') {
await traverse(obj[key]);
}
}),
);
return JSON.stringify(obj, null, 2);
};
const mainSchema = await fs.readJSON(mainSchemaPath, 'utf-8');
return traverse(mainSchema);
}
|
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
.basename(file)
.split('.')
.shift();
const fileContents = JSON.parse(
await fs.readFile(path.resolve(localesPath, file), 'utf-8'),
);
accumulator[localeCode] = fileContents;
return accumulator;
}, Promise.resolve({}));
}
|
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],
key,
);
}),
);
return combinedTranslationsObject;
}
|
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);
}
const ports = [];
for (let i = startPort; i <= endPort; i += increment) {
ports.push(i);
}
return ports;
});
}
|
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`;
})
.join('\r\n\r\n');
}
|
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()
? utils.spawn('yarnpkg')
: utils.spawn('npm install');
return cmd.then(() => process.chdir(prevDir));
}
|
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)}`,
);
return fs.copy(starter, root, {
filter: (file) =>
!/^\.(git|hg)$/.test(path.basename(file)) && !/node_modules/.test(file),
});
});
}
|
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: ${chalk.green(url)}`);
return utils
.spawn(`git clone ${branch} ${url} "${root}" --single-branch`, {
stdio: 'pipe',
})
.then(() => {
return fs.remove(path.join(root, '.git'));
})
.catch((error) => {
console.log();
console.log(chalk.red('There was an error while cloning the git repo:'));
console.log('');
console.log(chalk.red(error));
process.exit(1);
});
}
|
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, compare, visit, node.right)
}
}
|
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 }
}
}
if(h > 0 && node.right) {
return doVisit(lo, hi, compare, visit, node.right)
}
}
|
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 ? -1 : 1;
case 'string':
return stringCollate(a, b);
}
return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(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 = metaStack[metaStack.length - 1];
}
var element = lastMetaElement.element;
var lastElementIndex = lastMetaElement.index;
if (Array.isArray(element)) {
element.push(obj);
} else if (lastElementIndex === stack.length - 2) { // obj with key+value
var key = stack.pop();
element[key] = obj;
} else {
stack.push(obj); // obj with key only
}
}
}
|
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);
// Store the user and password as a separate auth object
if (uri.user || uri.password) {
uri.auth = {username: uri.user, password: uri.password};
}
// Split the path part of the URI into parts using '/' as the delimiter
// after removing any leading '/' and any trailing '/'
var parts = uri.path.replace(/(^\/|\/$)/g, '').split('/');
// Store the first part as the database name and remove it from the parts
// array
uri.db = parts.pop();
// Prevent double encoding of URI component
if (uri.db.indexOf('%') === -1) {
uri.db = encodeURIComponent(uri.db);
}
// Restore the path by joining all the remaining parts (all the parts
// except for the database name) with '/'s
uri.path = parts.join('/');
return uri;
}
|
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 empty string
return opts.protocol + '://' + opts.host +
(opts.port ? (':' + opts.port) : '') +
'/' + opts.path + pathDel + path;
}
|
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);
}
if (opts.descending) {
if (limit) {
params.limit = leftToFetch;
}
} else {
params.limit = (!limit || leftToFetch > batchSize) ?
batchSize : leftToFetch;
}
// Set the options for the ajax call
var xhrOpts = {
method: method,
url: genDBUrl(host, '_changes' + paramsToStr(params)),
timeout: opts.timeout,
body: body
};
lastFetchedSeq = since;
/* istanbul ignore if */
if (opts.aborted) {
return;
}
// Get the changes
setup().then(function () {
xhr = ajax(opts, xhrOpts, callback);
}).catch(callback);
}
|
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.base64StringToBlobOrBuffer(body, type));
}
} else { // as base64 string
if (!body) {
callback('');
} else if (typeof body !== 'string') { // we have blob support
pouchdbBinaryUtils.readAsBinaryString(body, function (binary) {
callback(pouchdbBinaryUtils.btoa(binary));
});
} else { // no blob support
callback(body);
}
}
}
|
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 (!('body' in attObj)) { // already processed
return;
}
var body = attObj.body;
var type = attObj.content_type;
return new Promise(function (resolve) {
readBlobData(body, type, asBlob, function (data) {
row.doc._attachments[att] = pouchdbUtils.assign(
pouchdbUtils.pick(attObj, ['digest', 'content_type']),
{data: data}
);
resolve();
});
});
}));
}
}));
}
|
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();
}
}
function add(att) {
var digest = docInfo.data._attachments[att].digest;
var req = attachAndSeqStore.put({
seq: seq,
digestSeq: digest + '::' + seq
});
req.onsuccess = checkDone;
req.onerror = function (e) {
// this callback is for a constaint error, which we ignore
// because this docid/rev has already been associated with
// the digest (e.g. when new_edits == false)
e.preventDefault(); // avoid transaction abort
e.stopPropagation(); // avoid transaction onerror
checkDone();
};
}
for (var i = 0; i < attsToAdd.length; i++) {
add(attsToAdd[i]); // do in parallel
}
}
|
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);
if (conflicts.length) {
row.doc._conflicts = conflicts;
}
}
fetchAttachmentsIfNecessary(row.doc, opts, txn);
};
}
|
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_STORE, {keyPath: 'id', autoIncrement: false});
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
// added in v2
docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});
// added in v3
db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});
// added in v4
var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,
{autoIncrement: true});
attAndSeqStore.createIndex('seq', 'seq');
attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});
}
|
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 = cursor.value;
var deleted = pouchdbMerge.isDeleted(metadata);
metadata.deletedOrLocal = deleted ? "1" : "0";
docStore.put(metadata);
cursor.continue();
} else {
callback();
}
};
}
|
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 ' +
digest);
callback(err);
} else {
callback();
}
});
}
|
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 = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return 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 = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
|
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 must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
|
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(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
|
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
return construct(options, transform, flush)
}
}
|
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._rev) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
doc._rev_tree = [{
pos: revInfo.prefix,
ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
}];
nRevNum = revInfo.prefix + 1;
} else {
doc._rev_tree = [{
pos: 1,
ids : [newRevId, opts, []]
}];
nRevNum = 1;
}
} else {
if (doc._revisions) {
doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
nRevNum = doc._revisions.start;
newRevId = doc._revisions.ids[0];
}
if (!doc._rev_tree) {
revInfo = parseRevisionInfo(doc._rev);
if (revInfo.error) {
return revInfo;
}
nRevNum = revInfo.prefix;
newRevId = revInfo.id;
doc._rev_tree = [{
pos: nRevNum,
ids: [newRevId, opts, []]
}];
}
}
pouchdbUtils.invalidIdError(doc._id);
doc._rev = nRevNum + '-' + newRevId;
var result = {metadata : {}, data : {}};
for (var key in doc) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(doc, key)) {
var specialKey = key[0] === '_';
if (specialKey && !reservedWords[key]) {
var error = pouchdbErrors.createError(pouchdbErrors.DOC_VALIDATION, key);
error.message = pouchdbErrors.DOC_VALIDATION.message + ': ' + key;
throw error;
} else if (specialKey && !dataWords[key]) {
result.metadata[key.slice(1)] = doc[key];
} else {
result.data[key] = doc[key];
}
}
}
return result;
}
|
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 FileReader();
var hasBinaryString = typeof reader.readAsBinaryString === 'function';
reader.onloadend = function (e) {
var result = e.target.result || '';
if (hasBinaryString) {
return callback(result);
}
callback(arrayBufferToBinaryString(result));
};
if (hasBinaryString) {
reader.readAsBinaryString(blob);
} else {
reader.readAsArrayBuffer(blob);
}
}
|
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);
for (var j = 0; j < atts.length; j++) {
var att = atts[j];
doc._attachments[att] = pouchdbUtils.pick(doc._attachments[att],
['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
}
}
}
}
|
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;
});
edges.reverse();
edges.forEach(function (edge) {
if (height[edge.from] === undefined) {
height[edge.from] = 1 + height[edge.to];
} else {
height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
}
});
return height;
}
|
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(opts, function (err, res) {
/* istanbul ignore if */
if (err) {
callback(err);
} else {
callback(null, res);
}
pouchdbUtils.nextTick(function () {
self._compactionQueue.shift();
if (self._compactionQueue.length) {
doNextCompaction(self);
}
});
});
});
}
|
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 function (aRow, bRow) {
var aFieldValues = getFieldValuesAsArray(aRow.doc);
var bFieldValues = getFieldValuesAsArray(bRow.doc);
var collation = collate(aFieldValues, bFieldValues);
if (collation !== 0) {
return collation;
}
// this is what mango seems to do
return utils.compare(aRow.doc._id, bRow.doc._id);
};
}
|
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) {
bIdx = Number.MAX_VALUE;
}
return utils.compare(aIdx, bIdx);
});
}
|
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 (needToFilterInMemory || !checkFieldInIndex(index, field)) {
return userFields.slice(i);
}
if (i < len - 1 && userOperatorLosesPrecision(selector, field)) {
needToFilterInMemory = true;
}
}
return [];
}
|
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 selectorMatches = utils.oneArrayIsSubArrayOfOther(fields, indexFields);
return sortMatches && selectorMatches;
}
// all of the user's specified fields still need to be
// on the left side of the index array, although the order
// doesn't matter
return utils.oneSetIsSubArrayOfOther(fields, indexFields);
}
|
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 = indexes[0];
defaultIndex.defaultUsed = true;
return defaultIndex;
}
if (matchingIndexes.length === 1) {
return matchingIndexes[0];
}
var userFieldsMap = utils.arrayToObject(userFields);
function scoreIndex(index) {
var indexFields = index.def.fields.map(getKey);
var score = 0;
for (var i = 0, len = indexFields.length; i < len; i++) {
var indexField = indexFields[i];
if (userFieldsMap[indexField]) {
score++;
}
}
return score;
}
return utils.max(matchingIndexes, scoreIndex);
}
|
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.length === 1) {
docKey = docKey[0]; // only one field, not multi-field
} else { // more than one field in index
// in the case where e.g. the user is searching {$gt: {a: 1}}
// but the index is [a, b], then we need to shorten the doc key
while (docKey.length > targetValue.length) {
docKey.pop();
}
}
//ABS as we just looking for values that don't match
if (Math.abs(collate.collate(docKey, targetValue)) > 0) {
// no need to filter any further; we're past the key
break;
}
}
return i > 0 ? rows.slice(i) : rows;
}
|
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 behaviour of
// JSON.stringify is not stable (see #6226)
/* istanbul ignore if */
if (opts.selector) {
selector = JSON.stringify(opts.selector);
}
if (opts.filter && opts.query_params) {
queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));
}
if (opts.filter && opts.filter === '_view') {
filterViewName = opts.view.toString();
}
return Promise.all([src.id(), target.id()]).then(function (res) {
var queryData = res[0] + res[1] + filterFun + filterViewName +
queryParams + docIds + selector;
return new Promise(function (resolve) {
pouchdbMd5.binaryMd5(queryData, resolve);
});
}).then(function (md5sum) {
// can't use straight-up md5 alphabet, because
// the char '/' is interpreted as being for attachments,
// and + is also not url-safe
md5sum = md5sum.replace(/\//g, '.').replace(/\+/g, '_');
return '_local/' + md5sum;
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.