_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q16300
|
_changeHtml
|
train
|
function _changeHtml(html, onChangeTable) {
const $tempDiv = $(`<div>${html}</div>`);
const $tables = $tempDiv.find('table');
if ($tables.length) {
$tables.get().forEach(tableElement => {
const changedTableElement = onChangeTable(tableElement);
$(tableElement).replaceWith(changedTableElement);
});
html = $tempDiv.html();
}
return html;
}
|
javascript
|
{
"resource": ""
}
|
q16301
|
_snatchWysiwygCommand
|
train
|
function _snatchWysiwygCommand(commandWrapper) {
const {command} = commandWrapper;
if (!command.isWWType()) {
return;
}
switch (command.getName()) {
case 'AddRow':
commandWrapper.command = wwAddRow;
break;
case 'AddCol':
commandWrapper.command = wwAddCol;
break;
case 'RemoveRow':
commandWrapper.command = wwRemoveRow;
break;
case 'RemoveCol':
commandWrapper.command = wwRemoveCol;
break;
case 'AlignCol':
commandWrapper.command = wwAlignCol;
break;
default:
}
}
|
javascript
|
{
"resource": ""
}
|
q16302
|
_bindEvents
|
train
|
function _bindEvents(eventManager) {
eventManager.listen('convertorAfterMarkdownToHtmlConverted', html => _changeHtml(html, createMergedTable));
eventManager.listen('convertorBeforeHtmlToMarkdownConverted', html => _changeHtml(html, prepareTableUnmerge));
eventManager.listen('addCommandBefore', _snatchWysiwygCommand);
}
|
javascript
|
{
"resource": ""
}
|
q16303
|
incrementRemainingMarkdownListNumbers
|
train
|
function incrementRemainingMarkdownListNumbers(cm, pos) {
var startLine = pos.line, lookAhead = 0, skipCount = 0;
var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
do {
lookAhead += 1;
var nextLineNumber = startLine + lookAhead;
var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
if (nextItem) {
var nextIndent = nextItem[1];
var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);
var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;
if (startIndent === nextIndent && !isNaN(nextNumber)) {
if (newNumber === nextNumber) itemNumber = nextNumber + 1;
if (newNumber > nextNumber) itemNumber = newNumber + 1;
cm.replaceRange(
nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
{
line: nextLineNumber, ch: 0
}, {
line: nextLineNumber, ch: nextLine.length
});
} else {
if (startIndent.length > nextIndent.length) return;
// This doesn't run if the next line immediatley indents, as it is
// not clear of the users intention (new indented item or same level)
if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;
skipCount += 1;
}
}
} while (nextItem);
}
|
javascript
|
{
"resource": ""
}
|
q16304
|
fixNumber
|
train
|
function fixNumber(lineNumber, prevIndentLength, startIndex, cm) {
let indent, delimiter, text, indentLength;
let index = startIndex;
let lineText = cm.getLine(lineNumber);
do {
[, indent, , , delimiter, text] = listRE.exec(lineText);
indentLength = indent.length;
if (indentLength === prevIndentLength) {
// fix number
cm.replaceRange(`${indent}${index}${delimiter}${text}`, {
line: lineNumber,
ch: 0
}, {
line: lineNumber,
ch: lineText.length
});
index += 1;
lineNumber += 1;
} else if (indentLength > prevIndentLength) {
// nested list start
lineNumber = fixNumber(lineNumber, indentLength, 1, cm);
} else {
// nested list end
return lineNumber;
}
lineText = cm.getLine(lineNumber);
} while (listRE.test(lineText));
return lineNumber;
}
|
javascript
|
{
"resource": ""
}
|
q16305
|
findFirstListItem
|
train
|
function findFirstListItem(lineNumber, cm) {
let nextLineNumber = lineNumber;
let lineText = cm.getLine(lineNumber);
while (listRE.test(lineText)) {
nextLineNumber -= 1;
lineText = cm.getLine(nextLineNumber);
}
if (lineNumber === nextLineNumber) {
nextLineNumber = -1;
} else {
nextLineNumber += 1;
}
return nextLineNumber;
}
|
javascript
|
{
"resource": ""
}
|
q16306
|
styleStrike
|
train
|
function styleStrike(sq) {
if (sq.hasFormat('S')) {
sq.changeFormat(null, {tag: 'S'});
} else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) {
if (sq.hasFormat('code')) {
sq.changeFormat(null, {tag: 'code'});
}
sq.strikethrough();
}
}
|
javascript
|
{
"resource": ""
}
|
q16307
|
_createNewCell
|
train
|
function _createNewCell(rowData, rowIndex, colIndex, prevCell) {
const cellData = rowData[colIndex];
let newCell;
if (util.isExisty(cellData.colMergeWith)) {
const {colMergeWith} = cellData;
const merger = rowData[colMergeWith];
const lastMergedCellIndex = colMergeWith + merger.colspan - 1;
if (util.isExisty(merger.rowMergeWith) && prevCell) {
newCell = util.extend({}, prevCell);
} else if (lastMergedCellIndex > colIndex) {
merger.colspan += 1;
newCell = util.extend({}, cellData);
}
} else if (cellData.colspan > 1) {
cellData.colspan += 1;
newCell = _createColMergedCell(colIndex, cellData.nodeName);
}
if (!newCell) {
newCell = dataHandler.createBasicCell(rowIndex, colIndex + 1, cellData.nodeName);
}
return newCell;
}
|
javascript
|
{
"resource": ""
}
|
q16308
|
_updateRowspan
|
train
|
function _updateRowspan(tableData, startRowIndex, endRowIndex) {
util.range(startRowIndex, endRowIndex + 1).forEach(rowIndex => {
tableData[rowIndex].forEach((cell, cellIndex) => {
if (util.isExisty(cell.rowMergeWith)) {
const merger = tableData[cell.rowMergeWith][cellIndex];
if (merger.rowspan) {
merger.rowspan -= 1;
}
} else if (cell.rowspan > 1) {
const lastMergedRowIndex = rowIndex + cell.rowspan - 1;
cell.rowspan -= (endRowIndex - rowIndex + 1);
if (lastMergedRowIndex > endRowIndex) {
tableData[endRowIndex + 1][cellIndex] = util.extend({}, cell);
}
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16309
|
wrapTextAndGetRange
|
train
|
function wrapTextAndGetRange(pre, text, post) {
return {
result: `${pre}${text}${post}`,
from: pre.length,
to: pre.length + text.length
};
}
|
javascript
|
{
"resource": ""
}
|
q16310
|
changeDecColorsToHex
|
train
|
function changeDecColorsToHex(color) {
return color.replace(decimalColorRx, (colorValue, r, g, b) => {
const hr = changeDecColorToHex(r);
const hg = changeDecColorToHex(g);
const hb = changeDecColorToHex(b);
return `#${hr}${hg}${hb}`;
});
}
|
javascript
|
{
"resource": ""
}
|
q16311
|
changeDecColorToHex
|
train
|
function changeDecColorToHex(color) {
let hexColor = parseInt(color, 10);
hexColor = hexColor.toString(16);
hexColor = doubleZeroPad(hexColor);
return hexColor;
}
|
javascript
|
{
"resource": ""
}
|
q16312
|
removeUnnecessaryCodeInNextToRange
|
train
|
function removeUnnecessaryCodeInNextToRange(range) {
if (domUtils.getNodeName(range.startContainer.nextSibling) === 'CODE'
&& domUtils.getTextLength(range.startContainer.nextSibling) === 0
) {
$(range.startContainer.nextSibling).remove();
}
}
|
javascript
|
{
"resource": ""
}
|
q16313
|
styleCode
|
train
|
function styleCode(editor, sq) {
if (!sq.hasFormat('PRE') && sq.hasFormat('code')) {
sq.changeFormat(null, {tag: 'code'});
removeUnnecessaryCodeInNextToRange(editor.getSelection().cloneRange());
} else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) {
if (sq.hasFormat('b')) {
sq.removeBold();
} else if (sq.hasFormat('i')) {
sq.removeItalic();
}
sq.changeFormat({tag: 'code'});
const range = sq.getSelection().cloneRange();
range.setStart(range.endContainer, range.endOffset);
range.collapse(true);
sq.setSelection(range);
}
}
|
javascript
|
{
"resource": ""
}
|
q16314
|
sanitizeHtmlCode
|
train
|
function sanitizeHtmlCode(code) {
return code ? code.replace(/[<>&]/g, tag => tagEntities[tag] || tag) : '';
}
|
javascript
|
{
"resource": ""
}
|
q16315
|
_createCellHtml
|
train
|
function _createCellHtml(cell) {
let attrs = cell.colspan > 1 ? ` colspan="${cell.colspan}"` : '';
attrs += cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : '';
attrs += cell.align ? ` align="${cell.align}"` : '';
return `<${cell.nodeName}${attrs}>${cell.content}</${cell.nodeName}>`;
}
|
javascript
|
{
"resource": ""
}
|
q16316
|
_createTheadOrTbodyHtml
|
train
|
function _createTheadOrTbodyHtml(trs, wrapperNodeName) {
let html = '';
if (trs.length) {
html = trs.map(tr => {
const tdHtml = tr.map(_createCellHtml).join('');
return `<tr>${tdHtml}</tr>`;
}).join('');
html = `<${wrapperNodeName}>${html}</${wrapperNodeName}>`;
}
return html;
}
|
javascript
|
{
"resource": ""
}
|
q16317
|
createTableHtml
|
train
|
function createTableHtml(renderData) {
const thead = [renderData[0]];
const tbody = renderData.slice(1);
const theadHtml = _createTheadOrTbodyHtml(thead, 'THEAD');
const tbodyHtml = _createTheadOrTbodyHtml(tbody, 'TBODY');
const className = renderData.className ? ` class="${renderData.className}"` : '';
return `<table${className}>${theadHtml + tbodyHtml}</renderData>`;
}
|
javascript
|
{
"resource": ""
}
|
q16318
|
replaceTable
|
train
|
function replaceTable($table, tableData) {
const cellIndexData = tableDataHandler.createCellIndexData(tableData);
const renderData = tableDataHandler.createRenderData(tableData, cellIndexData);
const $newTable = $(createTableHtml(renderData));
$table.replaceWith($newTable);
return $newTable;
}
|
javascript
|
{
"resource": ""
}
|
q16319
|
focusToCell
|
train
|
function focusToCell(sq, range, targetCell) {
range.selectNodeContents(targetCell);
range.collapse(true);
sq.setSelection(range);
}
|
javascript
|
{
"resource": ""
}
|
q16320
|
_updateMergedCells
|
train
|
function _updateMergedCells(tableData, startRowIndex, startColIndex, rowspan, colspan) {
const limitRowIndex = startRowIndex + rowspan;
const limitColIndex = startColIndex + colspan;
const colRange = util.range(startColIndex, limitColIndex);
util.range(startRowIndex, limitRowIndex).forEach(rowIndex => {
const rowData = tableData[rowIndex];
const startIndex = (rowIndex === startRowIndex) ? 1 : 0;
colRange.slice(startIndex).forEach(colIndex => {
rowData[colIndex] = dataHandler.createBasicCell(rowIndex, colIndex, rowData[colIndex].nodeName);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16321
|
_updateColspan
|
train
|
function _updateColspan(tableData, startColIndex, endColIndex) {
tableData.forEach(rowData => {
util.range(startColIndex, endColIndex + 1).forEach(colIndex => {
const cellData = rowData [colIndex];
if (util.isExisty(cellData.colMergeWith)) {
const merger = rowData [cellData.colMergeWith];
if (merger.colspan) {
merger.colspan -= 1;
}
} else if (cellData.colspan > 1) {
const lastMergedCellIndex = colIndex + cellData.colspan - 1;
cellData.colspan -= (endColIndex - colIndex + 1);
if (lastMergedCellIndex > endColIndex) {
rowData [endColIndex + 1] = util.extend({}, cellData);
}
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16322
|
getRange
|
train
|
function getRange() {
const selection = window.getSelection();
let range;
if (selection && selection.rangeCount) {
range = selection.getRangeAt(0).cloneRange();
} else {
range = document.createRange();
range.selectNodeContents(this.preview.$el[0]);
range.collapse(true);
}
return range;
}
|
javascript
|
{
"resource": ""
}
|
q16323
|
removeMarkdownTaskFormatText
|
train
|
function removeMarkdownTaskFormatText(token) {
// '[X] ' length is 4
// FIXED: we don't need first space
token.content = token.content.slice(4);
token.children[0].content = token.children[0].content.slice(4);
}
|
javascript
|
{
"resource": ""
}
|
q16324
|
isChecked
|
train
|
function isChecked(token) {
var checked = false;
if (token.content.indexOf('[x]') === 0 || token.content.indexOf('[X]') === 0) {
checked = true;
}
return checked;
}
|
javascript
|
{
"resource": ""
}
|
q16325
|
setTokenAttribute
|
train
|
function setTokenAttribute(token, attributeName, attributeValue) {
var index = token.attrIndex(attributeName);
var attr = [attributeName, attributeValue];
if (index < 0) {
token.attrPush(attr);
} else {
token.attrs[index] = attr;
}
}
|
javascript
|
{
"resource": ""
}
|
q16326
|
isTaskListItemToken
|
train
|
function isTaskListItemToken(tokens, index) {
return tokens[index].type === 'inline'
&& tokens[index - 1].type === 'paragraph_open'
&& tokens[index - 2].type === 'list_item_open'
&& (tokens[index].content.indexOf('[ ]') === 0
|| tokens[index].content.indexOf('[x]') === 0
|| tokens[index].content.indexOf('[X]') === 0);
}
|
javascript
|
{
"resource": ""
}
|
q16327
|
getCellByRange
|
train
|
function getCellByRange(range) {
let cell = range.startContainer;
if (domUtils.getNodeName(cell) === 'TD' || domUtils.getNodeName(cell) === 'TH') {
cell = $(cell);
} else {
cell = $(cell).parentsUntil('tr');
}
return cell;
}
|
javascript
|
{
"resource": ""
}
|
q16328
|
removeMultipleColsByCells
|
train
|
function removeMultipleColsByCells($cells) {
const numberOfCells = $cells.length;
for (let i = 0; i < numberOfCells; i += 1) {
const $cellToDelete = $cells.eq(i);
if ($cellToDelete.length > 0) {
removeColByCell($cells.eq(i));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q16329
|
removeColByCell
|
train
|
function removeColByCell($cell) {
const index = $cell.index();
$cell.parents('table').find('tr').each((n, tr) => {
$(tr).children().eq(index).remove();
});
}
|
javascript
|
{
"resource": ""
}
|
q16330
|
focusToCell
|
train
|
function focusToCell(sq, $cell, tableMgr) {
const nextFocusCell = $cell.get(0);
if ($cell.length && $.contains(document, $cell)) {
const range = sq.getSelection();
range.selectNodeContents($cell[0]);
range.collapse(true);
sq.setSelection(range);
tableMgr.setLastCellNode(nextFocusCell);
}
}
|
javascript
|
{
"resource": ""
}
|
q16331
|
styleBold
|
train
|
function styleBold(sq) {
if (sq.hasFormat('b') || sq.hasFormat('strong')) {
sq.changeFormat(null, {tag: 'b'});
} else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) {
if (sq.hasFormat('code')) {
sq.changeFormat(null, {tag: 'code'});
}
sq.bold();
}
}
|
javascript
|
{
"resource": ""
}
|
q16332
|
any
|
train
|
function any(arr, contition) {
let result = false;
util.forEach(arr, item => {
result = contition(item);
return !result;
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q16333
|
getNumberOfCols
|
train
|
function getNumberOfCols(wwe) {
const selectionMgr = wwe.componentManager.getManager('tableSelection');
const $selectedCells = selectionMgr.getSelectedCells();
let length = 1;
if ($selectedCells.length > 0) {
const maxLength = $selectedCells.get(0).parentNode.querySelectorAll('td, th').length;
length = Math.min(maxLength, $selectedCells.length);
}
return length;
}
|
javascript
|
{
"resource": ""
}
|
q16334
|
addColToCellAfter
|
train
|
function addColToCellAfter($cell, numberOfCols = 1) {
const index = $cell.index();
let cellToAdd;
$cell.parents('table').find('tr').each((n, tr) => {
const isTBody = domUtils.getNodeName(tr.parentNode) === 'TBODY';
const isMSIE = util.browser.msie;
const cell = tr.children[index];
for (let i = 0; i < numberOfCols; i += 1) {
if (isTBody) {
cellToAdd = document.createElement('td');
} else {
cellToAdd = document.createElement('th');
}
if (!isMSIE) {
cellToAdd.appendChild(document.createElement('br'));
}
$(cellToAdd).insertAfter(cell);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16335
|
focusToNextCell
|
train
|
function focusToNextCell(sq, $cell) {
const range = sq.getSelection();
range.selectNodeContents($cell.next()[0]);
range.collapse(true);
sq.setSelection(range);
}
|
javascript
|
{
"resource": ""
}
|
q16336
|
umlExtension
|
train
|
function umlExtension(editor, options = {}) {
const {
rendererURL = DEFAULT_RENDERER_URL
} = options;
/**
* render html from uml
* @param {string} umlCode - plant uml code text
* @returns {string} - rendered html
*/
function plantUMLReplacer(umlCode) {
let renderedHTML;
try {
if (!plantumlEncoder) {
throw new Error('plantuml-encoder dependency required');
}
renderedHTML = `<img src="${rendererURL}${plantumlEncoder.encode(umlCode)}" />`;
} catch (err) {
renderedHTML = `Error occurred on encoding uml: ${err.message}`;
}
return renderedHTML;
}
const {codeBlockLanguages} = editor.options;
UML_LANGUAGES.forEach(umlLanguage => {
if (codeBlockLanguages.indexOf(umlLanguage) < 0) {
codeBlockLanguages.push(umlLanguage);
}
codeBlockManager.setReplacer(umlLanguage, plantUMLReplacer);
});
}
|
javascript
|
{
"resource": ""
}
|
q16337
|
plantUMLReplacer
|
train
|
function plantUMLReplacer(umlCode) {
let renderedHTML;
try {
if (!plantumlEncoder) {
throw new Error('plantuml-encoder dependency required');
}
renderedHTML = `<img src="${rendererURL}${plantumlEncoder.encode(umlCode)}" />`;
} catch (err) {
renderedHTML = `Error occurred on encoding uml: ${err.message}`;
}
return renderedHTML;
}
|
javascript
|
{
"resource": ""
}
|
q16338
|
_changeContent
|
train
|
function _changeContent(popupTableUtils) {
const POPUP_CONTENT = [
`<button type="button" class="te-table-add-row">${i18n.get('Add row')}</button>`,
`<button type="button" class="te-table-add-col">${i18n.get('Add col')}</button>`,
`<button type="button" class="te-table-remove-row">${i18n.get('Remove row')}</button>`,
`<button type="button" class="te-table-remove-col">${i18n.get('Remove col')}</button>`,
'<hr/>',
`<button type="button" class="te-table-merge">${i18n.get('Merge cells')}</button>`,
`<button type="button" class="te-table-unmerge">${i18n.get('Unmerge cells')}</button>`,
'<hr/>',
`<button type="button" class="te-table-col-align-left">${i18n.get('Align left')}</button>`,
`<button type="button" class="te-table-col-align-center">${i18n.get('Align center')}</button>`,
`<button type="button" class="te-table-col-align-right">${i18n.get('Align right')}</button>`,
'<hr/>',
`<button type="button" class="te-table-remove">${i18n.get('Remove table')}</button>`
].join('');
const $popupContent = $(POPUP_CONTENT);
popupTableUtils.setContent($popupContent);
}
|
javascript
|
{
"resource": ""
}
|
q16339
|
_bindEvents
|
train
|
function _bindEvents(popupTableUtils, eventManager, selectionManager) {
const $popupContent = popupTableUtils.$content;
const $mergeBtn = $($popupContent[5]);
const $unmergeBtn = $($popupContent[6]);
const $separator = $($popupContent[7]);
popupTableUtils.on('click .te-table-merge', () => {
eventManager.emit('command', 'MergeCells');
});
popupTableUtils.on('click .te-table-unmerge', () => {
eventManager.emit('command', 'UnmergeCells');
});
eventManager.listen('openPopupTableUtils', () => {
const $selectedCells = selectionManager.getSelectedCells();
const selectedCellCount = $selectedCells.length;
if (selectedCellCount) {
if (selectedCellCount < 2 || selectionManager.hasSelectedBothThAndTd($selectedCells)) {
$mergeBtn.hide();
} else {
$mergeBtn.show();
}
if ($selectedCells.is('[rowspan], [colspan]')) {
$unmergeBtn.show();
} else {
$unmergeBtn.hide();
}
$separator.show();
} else {
$mergeBtn.hide();
$unmergeBtn.hide();
$separator.hide();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16340
|
updateContextMenu
|
train
|
function updateContextMenu(popupTableUtils, eventManager, selectionManager) {
_changeContent(popupTableUtils);
_bindEvents(popupTableUtils, eventManager, selectionManager);
}
|
javascript
|
{
"resource": ""
}
|
q16341
|
_align
|
train
|
function _align(headRowData, startColIndex, endColIndex, alignDirection) {
util.range(startColIndex, endColIndex + 1).forEach(colIndex => {
const headCellData = headRowData[colIndex];
if (util.isExisty(headCellData.colMergeWith)) {
headRowData[headCellData.colMergeWith].align = alignDirection;
} else {
headCellData.align = alignDirection;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16342
|
focusToFirstCode
|
train
|
function focusToFirstCode($pre, wwe) {
const range = wwe.getEditor().getSelection().cloneRange();
$pre.removeClass(CODEBLOCK_CLASS_TEMP);
range.setStartBefore($pre.get(0).firstChild);
range.collapse(true);
wwe.getEditor().setSelection(range);
}
|
javascript
|
{
"resource": ""
}
|
q16343
|
getCodeBlockBody
|
train
|
function getCodeBlockBody(range, wwe) {
const mgr = wwe.componentManager.getManager('codeblock');
let codeBlock;
if (range.collapsed) {
codeBlock = '<br>';
} else {
const contents = range.extractContents();
const nodes = util.toArray(contents.childNodes);
const tempDiv = $('<div>').append(mgr.prepareToPasteOnCodeblock(nodes));
codeBlock = tempDiv.html();
}
return codeBlock;
}
|
javascript
|
{
"resource": ""
}
|
q16344
|
tableCellGenerator
|
train
|
function tableCellGenerator(amount, tagName) {
const brHTMLString = '<br />';
const cellString = `<${tagName}>${brHTMLString}</${tagName}>`;
let tdString = '';
for (let i = 0; i < amount; i += 1) {
tdString = tdString + cellString;
}
return tdString;
}
|
javascript
|
{
"resource": ""
}
|
q16345
|
_findIndex
|
train
|
function _findIndex(arr, onFind) {
let foundIndex = -1;
util.forEach(arr, (item, index) => {
let nextFind = true;
if (onFind(item, index)) {
foundIndex = index;
nextFind = false;
}
return nextFind;
});
return foundIndex;
}
|
javascript
|
{
"resource": ""
}
|
q16346
|
focusToFirstTh
|
train
|
function focusToFirstTh(sq, $table) {
const range = sq.getSelection();
range.selectNodeContents($table.find('th')[0]);
range.collapse(true);
sq.setSelection(range);
}
|
javascript
|
{
"resource": ""
}
|
q16347
|
makeHeader
|
train
|
function makeHeader(col, data) {
let header = '<thead><tr>';
let index = 0;
while (col) {
header += '<th>';
if (data) {
header += data[index];
index += 1;
}
header += '</th>';
col -= 1;
}
header += '</tr></thead>';
return header;
}
|
javascript
|
{
"resource": ""
}
|
q16348
|
makeBody
|
train
|
function makeBody(col, row, data) {
let body = '<tbody>';
let index = col;
for (let irow = 0; irow < row; irow += 1) {
body += '<tr>';
for (let icol = 0; icol < col; icol += 1) {
body += '<td>';
if (data) {
body += data[index];
index += 1;
}
body += '</td>';
}
body += '</tr>';
}
body += '</tbody>';
return body;
}
|
javascript
|
{
"resource": ""
}
|
q16349
|
getHeadingMarkdown
|
train
|
function getHeadingMarkdown(text, size) {
const foundedHeading = text.match(FIND_HEADING_RX);
let heading = '';
do {
heading += '#';
size -= 1;
} while (size > 0);
if (foundedHeading) {
[, text] = text.split(foundedHeading[0]);
}
return `${heading} ${text}`;
}
|
javascript
|
{
"resource": ""
}
|
q16350
|
parseCode2DataAndOptions
|
train
|
function parseCode2DataAndOptions(code, callback) {
code = trimKeepingTabs(code);
const [firstCode, secondCode] = code.split(/\n{2,}/);
// try to parse first code block as `options`
let options = parseCode2ChartOption(firstCode);
const url = options && options.editorChart && options.editorChart.url;
// if first code block is `options` and has `url` option, fetch data from url
let dataAndOptions;
if (util.isString(url)) {
// url option provided
// fetch data from url
const success = dataCode => {
dataAndOptions = _parseCode2DataAndOptions(dataCode, firstCode);
callback(dataAndOptions);
};
const fail = () => callback(null);
$.get(url).done(success).fail(fail);
} else {
// else first block is `data`
dataAndOptions = _parseCode2DataAndOptions(firstCode, secondCode);
callback(dataAndOptions);
}
}
|
javascript
|
{
"resource": ""
}
|
q16351
|
_parseCode2DataAndOptions
|
train
|
function _parseCode2DataAndOptions(dataCode, optionCode) {
const data = parseDSV2ChartData(dataCode);
const options = parseCode2ChartOption(optionCode);
return {
data,
options
};
}
|
javascript
|
{
"resource": ""
}
|
q16352
|
detectDelimiter
|
train
|
function detectDelimiter(code) {
code = trimKeepingTabs(code);
// chunk first max 10 lines to detect
const chunk = code.split(REGEX_LINE_ENDING).slice(0, 10).join('\n');
// calc delta for each delimiters
// then pick a delimiter having the minimum value delta
return DSV_DELIMITERS.map(delimiter => ({
delimiter,
delta: calcDSVDelta(chunk, delimiter)
})).sort((a, b) => (
a.delta - b.delta
))[0].delimiter;
}
|
javascript
|
{
"resource": ""
}
|
q16353
|
parseDSV2ChartData
|
train
|
function parseDSV2ChartData(code, delimiter) {
// trim all heading/trailing blank lines
code = trimKeepingTabs(code);
csv.COLUMN_SEPARATOR = delimiter || detectDelimiter(code);
let dsv = csv.parse(code);
// trim all values in 2D array
dsv = dsv.map(arr => arr.map(val => val.trim()));
// test a first row for legends. ['anything', '1', '2', '3'] === false, ['anything', 't1', '2', 't3'] === true
const hasLegends = dsv[0].filter((v, i) => i > 0).reduce((hasNaN, item) => hasNaN || !isNumeric(item), false);
const legends = hasLegends ? dsv.shift() : [];
// test a first column for categories
const hasCategories = dsv.slice(1).reduce((hasNaN, row) => hasNaN || !isNumeric(row[0]), false);
const categories = hasCategories ? dsv.map(arr => arr.shift()) : [];
if (hasCategories) {
legends.shift();
}
// transpose dsv, parse number
// [['1','2','3'] [[1,4,7]
// ['4','5','6'] => [2,5,8]
// ['7','8','9']] [3,6,9]]
dsv = dsv[0].map((t, i) => dsv.map(x => parseFloat(x[i])));
// make series
const series = dsv.map((data, i) => hasLegends ? {
name: legends[i],
data
} : {
data
});
return {
categories,
series
};
}
|
javascript
|
{
"resource": ""
}
|
q16354
|
parseURL2ChartData
|
train
|
function parseURL2ChartData(url, callback) {
const success = code => {
const chartData = parseDSV2ChartData(code);
callback(chartData);
};
const fail = () => callback(null);
$.get(url).done(success).fail(fail);
}
|
javascript
|
{
"resource": ""
}
|
q16355
|
parseCode2ChartOption
|
train
|
function parseCode2ChartOption(optionCode) {
const reservedKeys = ['type', 'url'];
let options = {};
if (util.isUndefined(optionCode)) {
return options;
}
const optionLines = optionCode.split(REGEX_LINE_ENDING);
optionLines.forEach(line => {
let [keyString, ...values] = line.split(OPTION_DELIMITER);
let value = values.join(OPTION_DELIMITER);
keyString = keyString.trim();
if (value.length === 0) {
return;
}
try {
value = JSON.parse(value.trim());
} catch (e) {
value = value.trim();
}
// parse keys
let [...keys] = keyString.split('.');
let topKey = keys[0];
if (util.inArray(topKey, reservedKeys) >= 0) {
// reserved keys for chart plugin option
keys.unshift('editorChart');
} else if (keys.length === 1) {
// short names for `chart`
keys.unshift('chart');
} else if (topKey === 'x' || topKey === 'y') {
// short-handed keys
keys[0] = `${topKey}Axis`;
}
let option = options;
for (let i = 0; i < keys.length; i += 1) {
let key = keys[i];
option[key] = option[key] || (keys.length - 1 === i ? value : {});
option = option[key];
}
});
return options;
}
|
javascript
|
{
"resource": ""
}
|
q16356
|
setDefaultOptions
|
train
|
function setDefaultOptions(chartOptions, extensionOptions, chartContainer) {
// chart options scaffolding
chartOptions = util.extend({
editorChart: {},
chart: {},
chartExportMenu: {},
usageStatistics: extensionOptions.usageStatistics
}, chartOptions);
// set default extension options
extensionOptions = util.extend(DEFAULT_CHART_OPTIONS, extensionOptions);
// determine width, height
let {width, height} = chartOptions.chart;
const isWidthUndefined = util.isUndefined(width);
const isHeightUndefined = util.isUndefined(height);
if (isWidthUndefined || isHeightUndefined) {
// if no width or height specified, set width and height to container width
const {
width: containerWidth
} = chartContainer.getBoundingClientRect();
width = isWidthUndefined ? extensionOptions.width : width;
height = isHeightUndefined ? extensionOptions.height : height;
width = width === 'auto' ? containerWidth : width;
height = height === 'auto' ? containerWidth : height;
}
width = Math.min(extensionOptions.maxWidth, width);
height = Math.min(extensionOptions.maxHeight, height);
chartOptions.chart.width = Math.max(extensionOptions.minWidth, width);
chartOptions.chart.height = Math.max(extensionOptions.minHeight, height);
// default chart type
chartOptions.editorChart.type = chartOptions.editorChart.type ? `${chartOptions.editorChart.type}Chart` : 'columnChart';
// default visibility of export menu
chartOptions.chartExportMenu.visible = chartOptions.chartExportMenu.visible || false;
return chartOptions;
}
|
javascript
|
{
"resource": ""
}
|
q16357
|
chartReplacer
|
train
|
function chartReplacer(codeBlockChartDataAndOptions, extensionOptions) {
const randomId = `chart-${Math.random().toString(36).substr(2, 10)}`;
let renderedHTML = `<div id="${randomId}" class="chart" />`;
setTimeout(() => {
const chartContainer = document.querySelector(`#${randomId}`);
try {
parseCode2DataAndOptions(codeBlockChartDataAndOptions, ({data, options: chartOptions}) => {
chartOptions = setDefaultOptions(chartOptions, extensionOptions, chartContainer);
const chartType = chartOptions.editorChart.type;
if (SUPPORTED_CHART_TYPES.indexOf(chartType) < 0) {
chartContainer.innerHTML = `invalid chart type. type: bar, column, line, area, pie`;
} else if (CATEGORY_CHART_TYPES.indexOf(chartType) > -1 &&
data.categories.length !== data.series[0].data.length) {
chartContainer.innerHTML = 'invalid chart data';
} else {
chart[chartType](chartContainer, data, chartOptions);
}
});
} catch (e) {
chartContainer.innerHTML = 'invalid chart data';
}
}, 0);
return renderedHTML;
}
|
javascript
|
{
"resource": ""
}
|
q16358
|
_reduceToTSV
|
train
|
function _reduceToTSV(arr) {
// 2D array => quoted TSV row array
// [['a', 'b b'], [1, 2]] => ['a\t"b b"', '1\t2']
return arr.reduce((acc, row) => {
// ['a', 'b b', 'c c'] => ['a', '"b b"', '"c c"']
const quoted = row.map(text => {
if (!isNumeric(text) && text.indexOf(' ') >= 0) {
text = `"${text}"`;
}
return text;
});
// ['a', '"b b"', '"c c"'] => 'a\t"b b"\t"c c"'
acc.push(quoted.join('\t'));
return acc;
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q16359
|
_setWwCodeBlockManagerForChart
|
train
|
function _setWwCodeBlockManagerForChart(editor) {
const componentManager = editor.wwEditor.componentManager;
componentManager.removeManager('codeblock');
componentManager.addManager(class extends WwCodeBlockManager {
/**
* Convert table nodes into code block as TSV
* @memberof WwCodeBlockManager
* @param {Array.<Node>} nodes Node array
* @returns {HTMLElement} Code block element
*/
convertNodesToText(nodes) {
if (nodes.length !== 1 || nodes[0].tagName !== 'TABLE') {
return super.convertNodesToText(nodes);
}
const node = nodes.shift();
let str = '';
// convert table to 2-dim array
const cells = [].slice.call(node.rows).map(
row => [].slice.call(row.cells).map(
cell => cell.innerText.trim()
)
);
const tsvRows = _reduceToTSV(cells);
str += tsvRows.reduce((acc, row) => acc + `${row}\n`, []);
return str;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16360
|
_onMDPasteBefore
|
train
|
function _onMDPasteBefore(cm, {source, data: eventData}) {
if (!_isFromCodeBlockInCodeMirror(cm, source, eventData)) {
return;
}
const code = eventData.text.join('\n');
const delta = calcDSVDelta(code, '\t');
if (delta === 0) {
csv.COLUMN_SEPARATOR = '\t';
const parsed = _reduceToTSV(csv.parse(code));
eventData.update(eventData.from, eventData.to, parsed);
}
}
|
javascript
|
{
"resource": ""
}
|
q16361
|
getSelectedRowsLength
|
train
|
function getSelectedRowsLength(wwe) {
const selectionMgr = wwe.componentManager.getManager('tableSelection');
const $selectedCells = selectionMgr.getSelectedCells();
let length = 1;
if ($selectedCells.length > 1) {
const first = $selectedCells.first().get(0);
const last = $selectedCells.last().get(0);
const range = selectionMgr.getSelectionRangeFromTable(first, last);
length = range.to.row - range.from.row + 1;
}
return length;
}
|
javascript
|
{
"resource": ""
}
|
q16362
|
getNewRow
|
train
|
function getNewRow($tr) {
const cloned = $tr.clone();
const htmlString = util.browser.msie ? '' : '<br />';
cloned.find('td').html(htmlString);
return cloned;
}
|
javascript
|
{
"resource": ""
}
|
q16363
|
leaveOnlyWhitelistAttribute
|
train
|
function leaveOnlyWhitelistAttribute($html) {
$html.find('*').each((index, node) => {
const attrs = node.attributes;
const blacklist = util.toArray(attrs).filter(attr => {
const isHTMLAttr = attr.name.match(HTML_ATTR_LIST_RX);
const isSVGAttr = attr.name.match(SVG_ATTR_LIST_RX);
return !isHTMLAttr && !isSVGAttr;
});
util.forEachArray(blacklist, attr => {
// Edge svg attribute name returns uppercase bug. error guard.
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5579311/
if (attrs.getNamedItem(attr.name)) {
attrs.removeNamedItem(attr.name);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16364
|
finalizeHtml
|
train
|
function finalizeHtml($html, needHtmlText) {
let returnValue;
if (needHtmlText) {
returnValue = $html[0].innerHTML;
} else {
const frag = document.createDocumentFragment();
const childNodes = util.toArray($html[0].childNodes);
const {length} = childNodes;
for (let i = 0; i < length; i += 1) {
frag.appendChild(childNodes[i]);
}
returnValue = frag;
}
return returnValue;
}
|
javascript
|
{
"resource": ""
}
|
q16365
|
_findUnmergedRange
|
train
|
function _findUnmergedRange(tableData, $start, $end) {
const cellIndexData = tableDataHandler.createCellIndexData(tableData);
const startCellIndex = tableDataHandler.findCellIndex(cellIndexData, $start);
const endCellIndex = tableDataHandler.findCellIndex(cellIndexData, $end);
let startRowIndex, endRowIndex, startColIndex, endColIndex;
if (startCellIndex.rowIndex > endCellIndex.rowIndex) {
startRowIndex = endCellIndex.rowIndex;
endRowIndex = startCellIndex.rowIndex;
} else {
startRowIndex = startCellIndex.rowIndex;
endRowIndex = endCellIndex.rowIndex;
}
if (startCellIndex.colIndex > endCellIndex.colIndex) {
startColIndex = endCellIndex.colIndex;
endColIndex = startCellIndex.colIndex;
} else {
startColIndex = startCellIndex.colIndex;
endColIndex = endCellIndex.colIndex;
}
return {
start: {
rowIndex: startRowIndex,
colIndex: startColIndex
},
end: {
rowIndex: endRowIndex,
colIndex: endColIndex
}
};
}
|
javascript
|
{
"resource": ""
}
|
q16366
|
_expandRowMergedRange
|
train
|
function _expandRowMergedRange(tableData, tableRange, rangeType) {
const {rowIndex} = tableRange[rangeType];
const rowData = tableData[rowIndex];
util.range(tableRange.start.colIndex, tableRange.end.colIndex + 1).forEach(colIndex => {
const cellData = rowData[colIndex];
const {rowMergeWith} = cellData;
let lastRowMergedIndex = -1;
if (util.isExisty(rowMergeWith)) {
if (rowMergeWith < tableRange.start.rowIndex) {
tableRange.start.rowIndex = rowMergeWith;
}
lastRowMergedIndex = rowMergeWith + tableData[rowMergeWith][colIndex].rowspan - 1;
} else if (cellData.rowspan > 1) {
lastRowMergedIndex = rowIndex + cellData.rowspan - 1;
}
if (lastRowMergedIndex > tableRange.end.rowIndex) {
tableRange.end.rowIndex = lastRowMergedIndex;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16367
|
_expandColMergedRange
|
train
|
function _expandColMergedRange(tableData, tableRange, rowIndex, colIndex) {
const rowData = tableData[rowIndex];
const cellData = rowData[colIndex];
const {colMergeWith} = cellData;
let lastColMergedIndex = -1;
if (util.isExisty(colMergeWith)) {
if (colMergeWith < tableRange.start.colIndex) {
tableRange.start.colIndex = colMergeWith;
}
lastColMergedIndex = colMergeWith + rowData[colMergeWith].colspan - 1;
} else if (cellData.colspan > 1) {
lastColMergedIndex = colIndex + cellData.colspan - 1;
}
if (lastColMergedIndex > tableRange.end.colIndex) {
tableRange.end.colIndex = lastColMergedIndex;
}
}
|
javascript
|
{
"resource": ""
}
|
q16368
|
_expandMergedRange
|
train
|
function _expandMergedRange(tableData, tableRange) {
let rangeStr = '';
while (rangeStr !== JSON.stringify(tableRange)) {
rangeStr = JSON.stringify(tableRange);
_expandRowMergedRange(tableData, tableRange, 'start');
_expandRowMergedRange(tableData, tableRange, 'end');
util.range(tableRange.start.rowIndex, tableRange.end.rowIndex + 1).forEach(rowIndex => {
_expandColMergedRange(tableData, tableRange, rowIndex, tableRange.start.colIndex);
_expandColMergedRange(tableData, tableRange, rowIndex, tableRange.end.colIndex);
});
}
return tableRange;
}
|
javascript
|
{
"resource": ""
}
|
q16369
|
getTableSelectionRange
|
train
|
function getTableSelectionRange(tableData, $selectedCells, $startContainer) {
const cellIndexData = tableDataHandler.createCellIndexData(tableData);
const tableRange = {};
if ($selectedCells.length) {
const startRange = tableDataHandler.findCellIndex(cellIndexData, $selectedCells.first());
const endRange = util.extend({}, startRange);
$selectedCells.each((index, cell) => {
const cellIndex = tableDataHandler.findCellIndex(cellIndexData, $(cell));
const cellData = tableData[cellIndex.rowIndex][cellIndex.colIndex];
const lastRowMergedIndex = cellIndex.rowIndex + cellData.rowspan - 1;
const lastColMergedIndex = cellIndex.colIndex + cellData.colspan - 1;
endRange.rowIndex = Math.max(endRange.rowIndex, lastRowMergedIndex);
endRange.colIndex = Math.max(endRange.colIndex, lastColMergedIndex);
});
tableRange.start = startRange;
tableRange.end = endRange;
} else {
const cellIndex = tableDataHandler.findCellIndex(cellIndexData, $startContainer);
tableRange.start = cellIndex;
tableRange.end = util.extend({}, cellIndex);
}
return tableRange;
}
|
javascript
|
{
"resource": ""
}
|
q16370
|
setAlignAttributeToTableCells
|
train
|
function setAlignAttributeToTableCells($table, alignDirection, selectionInformation) {
const isDivided = selectionInformation.isDivided || false;
const start = selectionInformation.startColumnIndex;
const end = selectionInformation.endColumnIndex;
const columnLength = $table.find('tr').eq(0).find('td,th').length;
$table.find('tr').each((n, tr) => {
$(tr).children('td,th').each((index, cell) => {
if (isDivided &&
((start <= index && index <= columnLength) || (index <= end))
) {
$(cell).attr('align', alignDirection);
} else if ((start <= index && index <= end)) {
$(cell).attr('align', alignDirection);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q16371
|
getSelectionInformation
|
train
|
function getSelectionInformation($table, rangeInformation) {
const columnLength = $table.find('tr').eq(0).find('td,th').length;
const {
from,
to
} = rangeInformation;
let startColumnIndex, endColumnIndex, isDivided;
if (from.row === to.row) {
startColumnIndex = from.cell;
endColumnIndex = to.cell;
} else if (from.row < to.row) {
if (from.cell <= to.cell) {
startColumnIndex = 0;
endColumnIndex = columnLength - 1;
} else {
startColumnIndex = from.cell;
endColumnIndex = to.cell;
isDivided = true;
}
}
return {
startColumnIndex,
endColumnIndex,
isDivided
};
}
|
javascript
|
{
"resource": ""
}
|
q16372
|
getRangeInformation
|
train
|
function getRangeInformation(range, selectionMgr) {
const $selectedCells = selectionMgr.getSelectedCells();
let rangeInformation, startCell;
if ($selectedCells.length) {
rangeInformation = selectionMgr.getSelectionRangeFromTable($selectedCells.first().get(0),
$selectedCells.last().get(0));
} else {
const {startContainer} = range;
startCell = domUtil.isTextNode(startContainer) ? $(startContainer).parent('td,th')[0] : startContainer;
rangeInformation = selectionMgr.getSelectionRangeFromTable(startCell, startCell);
}
return rangeInformation;
}
|
javascript
|
{
"resource": ""
}
|
q16373
|
taskCounterExtension
|
train
|
function taskCounterExtension(editor) {
editor.getTaskCount = () => {
let found, count;
if (editor.isViewer()) {
count = editor.preview.$el.find('.task-list-item').length;
} else if (editor.isMarkdownMode()) {
found = editor.mdEditor.getValue().match(FIND_TASK_RX);
count = found ? found.length : 0;
} else {
count = editor.wwEditor.get$Body().find('.task-list-item').length;
}
return count;
};
editor.getCheckedTaskCount = () => {
let found, count;
if (editor.isViewer()) {
count = editor.preview.$el.find('.task-list-item.checked').length;
} else if (editor.isMarkdownMode()) {
found = editor.mdEditor.getValue().match(FIND_CHECKED_TASK_RX);
count = found ? found.length : 0;
} else {
count = editor.wwEditor.get$Body().find('.task-list-item.checked').length;
}
return count;
};
}
|
javascript
|
{
"resource": ""
}
|
q16374
|
changeButtonVisiblityStateIfNeed
|
train
|
function changeButtonVisiblityStateIfNeed() {
if (editor.mdPreviewStyle === 'vertical' && editor.currentMode === 'markdown') {
button.$el.show();
$divider.show();
} else {
button.$el.hide();
$divider.hide();
}
}
|
javascript
|
{
"resource": ""
}
|
q16375
|
getHelper
|
train
|
function getHelper() {
let helper;
if (editor.isViewer()) {
helper = vmh;
} else if (editor.isWysiwygMode()) {
helper = wmh;
} else {
helper = mmh;
}
return helper;
}
|
javascript
|
{
"resource": ""
}
|
q16376
|
updateMarkWhenResizing
|
train
|
function updateMarkWhenResizing() {
const helper = getHelper();
ml.getAll().forEach(marker => {
helper.updateMarkerWithExtraInfo(marker);
});
editor.eventManager.emit('markerUpdated', ml.getAll());
}
|
javascript
|
{
"resource": ""
}
|
q16377
|
getTagHead
|
train
|
async function getTagHead(tagName, execaOpts) {
try {
return await execa.stdout('git', ['rev-list', '-1', tagName], execaOpts);
} catch (error) {
debug(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q16378
|
getTags
|
train
|
async function getTags(execaOpts) {
return (await execa.stdout('git', ['tag'], execaOpts))
.split('\n')
.map(tag => tag.trim())
.filter(Boolean);
}
|
javascript
|
{
"resource": ""
}
|
q16379
|
isRefInHistory
|
train
|
async function isRefInHistory(ref, execaOpts) {
try {
await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], execaOpts);
return true;
} catch (error) {
if (error.code === 1) {
return false;
}
debug(error);
throw error;
}
}
|
javascript
|
{
"resource": ""
}
|
q16380
|
fetch
|
train
|
async function fetch(repositoryUrl, execaOpts) {
try {
await execa('git', ['fetch', '--unshallow', '--tags', repositoryUrl], execaOpts);
} catch (error) {
await execa('git', ['fetch', '--tags', repositoryUrl], execaOpts);
}
}
|
javascript
|
{
"resource": ""
}
|
q16381
|
repoUrl
|
train
|
async function repoUrl(execaOpts) {
try {
return await execa.stdout('git', ['config', '--get', 'remote.origin.url'], execaOpts);
} catch (error) {
debug(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q16382
|
isGitRepo
|
train
|
async function isGitRepo(execaOpts) {
try {
return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).code === 0;
} catch (error) {
debug(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q16383
|
verifyAuth
|
train
|
async function verifyAuth(repositoryUrl, branch, execaOpts) {
try {
await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts);
} catch (error) {
debug(error);
throw error;
}
}
|
javascript
|
{
"resource": ""
}
|
q16384
|
verifyTagName
|
train
|
async function verifyTagName(tagName, execaOpts) {
try {
return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).code === 0;
} catch (error) {
debug(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q16385
|
isBranchUpToDate
|
train
|
async function isBranchUpToDate(branch, execaOpts) {
const remoteHead = await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts);
try {
return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts);
} catch (error) {
debug(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q16386
|
Doc
|
train
|
function Doc(runner, options) {
Base.call(this, runner, options);
var indents = 2;
function indent() {
return Array(indents).join(' ');
}
runner.on(EVENT_SUITE_BEGIN, function(suite) {
if (suite.root) {
return;
}
++indents;
console.log('%s<section class="suite">', indent());
++indents;
console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
console.log('%s<dl>', indent());
});
runner.on(EVENT_SUITE_END, function(suite) {
if (suite.root) {
return;
}
console.log('%s</dl>', indent());
--indents;
console.log('%s</section>', indent());
--indents;
});
runner.on(EVENT_TEST_PASS, function(test) {
console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
var code = utils.escape(utils.clean(test.body));
console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
});
runner.on(EVENT_TEST_FAIL, function(test, err) {
console.log(
'%s <dt class="error">%s</dt>',
indent(),
utils.escape(test.title)
);
var code = utils.escape(utils.clean(test.body));
console.log(
'%s <dd class="error"><pre><code>%s</code></pre></dd>',
indent(),
code
);
console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err));
});
}
|
javascript
|
{
"resource": ""
}
|
q16387
|
multiple
|
train
|
function multiple(err) {
if (emitted) {
return;
}
emitted = true;
var msg = 'done() called multiple times';
if (err && err.message) {
err.message += " (and Mocha's " + msg + ')';
self.emit('error', err);
} else {
self.emit('error', new Error(msg));
}
}
|
javascript
|
{
"resource": ""
}
|
q16388
|
train
|
function() {
// If user hasn't responded yet... "No notification for you!" (Seinfeld)
Promise.race([promise, Promise.resolve(undefined)])
.then(canNotify)
.then(function() {
display(runner);
})
.catch(notPermitted);
}
|
javascript
|
{
"resource": ""
}
|
|
q16389
|
isPermitted
|
train
|
function isPermitted() {
var permitted = {
granted: function allow() {
return Promise.resolve(true);
},
denied: function deny() {
return Promise.resolve(false);
},
default: function ask() {
return Notification.requestPermission().then(function(permission) {
return permission === 'granted';
});
}
};
return permitted[Notification.permission]();
}
|
javascript
|
{
"resource": ""
}
|
q16390
|
display
|
train
|
function display(runner) {
var stats = runner.stats;
var symbol = {
cross: '\u274C',
tick: '\u2705'
};
var logo = require('../../package').notifyLogo;
var _message;
var message;
var title;
if (stats.failures) {
_message = stats.failures + ' of ' + stats.tests + ' tests failed';
message = symbol.cross + ' ' + _message;
title = 'Failed';
} else {
_message = stats.passes + ' tests passed in ' + stats.duration + 'ms';
message = symbol.tick + ' ' + _message;
title = 'Passed';
}
// Send notification
var options = {
badge: logo,
body: message,
dir: 'ltr',
icon: logo,
lang: 'en-US',
name: 'mocha',
requireInteraction: false,
timestamp: Date.now()
};
var notification = new Notification(title, options);
// Autoclose after brief delay (makes various browsers act same)
var FORCE_DURATION = 4000;
setTimeout(notification.close.bind(notification), FORCE_DURATION);
}
|
javascript
|
{
"resource": ""
}
|
q16391
|
Suite
|
train
|
function Suite(title, parentContext, isRoot) {
if (!utils.isString(title)) {
throw createInvalidArgumentTypeError(
'Suite argument "title" must be a string. Received type "' +
typeof title +
'"',
'title',
'string'
);
}
this.title = title;
function Context() {}
Context.prototype = parentContext;
this.ctx = new Context();
this.suites = [];
this.tests = [];
this.pending = false;
this._beforeEach = [];
this._beforeAll = [];
this._afterEach = [];
this._afterAll = [];
this.root = isRoot === true;
this._timeout = 2000;
this._enableTimeouts = true;
this._slow = 75;
this._bail = false;
this._retries = -1;
this._onlyTests = [];
this._onlySuites = [];
this.delayed = false;
this.on('newListener', function(event) {
if (deprecatedEvents[event]) {
utils.deprecate(
'Event "' +
event +
'" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm'
);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q16392
|
JSONReporter
|
train
|
function JSONReporter(runner, options) {
Base.call(this, runner, options);
var self = this;
var tests = [];
var pending = [];
var failures = [];
var passes = [];
runner.on(EVENT_TEST_END, function(test) {
tests.push(test);
});
runner.on(EVENT_TEST_PASS, function(test) {
passes.push(test);
});
runner.on(EVENT_TEST_FAIL, function(test) {
failures.push(test);
});
runner.on(EVENT_TEST_PENDING, function(test) {
pending.push(test);
});
runner.once(EVENT_RUN_END, function() {
var obj = {
stats: self.stats,
tests: tests.map(clean),
pending: pending.map(clean),
failures: failures.map(clean),
passes: passes.map(clean)
};
runner.testResults = obj;
process.stdout.write(JSON.stringify(obj, null, 2));
});
}
|
javascript
|
{
"resource": ""
}
|
q16393
|
clean
|
train
|
function clean(test) {
var err = test.err || {};
if (err instanceof Error) {
err = errorJSON(err);
}
return {
title: test.title,
fullTitle: test.fullTitle(),
duration: test.duration,
currentRetry: test.currentRetry(),
err: cleanCycles(err)
};
}
|
javascript
|
{
"resource": ""
}
|
q16394
|
XUnit
|
train
|
function XUnit(runner, options) {
Base.call(this, runner, options);
var stats = this.stats;
var tests = [];
var self = this;
// the name of the test suite, as it will appear in the resulting XML file
var suiteName;
// the default name of the test suite if none is provided
var DEFAULT_SUITE_NAME = 'Mocha Tests';
if (options && options.reporterOptions) {
if (options.reporterOptions.output) {
if (!fs.createWriteStream) {
throw createUnsupportedError('file output not supported in browser');
}
mkdirp.sync(path.dirname(options.reporterOptions.output));
self.fileStream = fs.createWriteStream(options.reporterOptions.output);
}
// get the suite name from the reporter options (if provided)
suiteName = options.reporterOptions.suiteName;
}
// fall back to the default suite name
suiteName = suiteName || DEFAULT_SUITE_NAME;
runner.on(EVENT_TEST_PENDING, function(test) {
tests.push(test);
});
runner.on(EVENT_TEST_PASS, function(test) {
tests.push(test);
});
runner.on(EVENT_TEST_FAIL, function(test) {
tests.push(test);
});
runner.once(EVENT_RUN_END, function() {
self.write(
tag(
'testsuite',
{
name: suiteName,
tests: stats.tests,
failures: 0,
errors: stats.failures,
skipped: stats.tests - stats.failures - stats.passes,
timestamp: new Date().toUTCString(),
time: stats.duration / 1000 || 0
},
false
)
);
tests.forEach(function(t) {
self.test(t);
});
self.write('</testsuite>');
});
}
|
javascript
|
{
"resource": ""
}
|
q16395
|
Base
|
train
|
function Base(runner, options) {
var failures = (this.failures = []);
if (!runner) {
throw new TypeError('Missing runner argument');
}
this.options = options || {};
this.runner = runner;
this.stats = runner.stats; // assigned so Reporters keep a closer reference
runner.on(EVENT_TEST_PASS, function(test) {
if (test.duration > test.slow()) {
test.speed = 'slow';
} else if (test.duration > test.slow() / 2) {
test.speed = 'medium';
} else {
test.speed = 'fast';
}
});
runner.on(EVENT_TEST_FAIL, function(test, err) {
if (showDiff(err)) {
stringifyDiffObjs(err);
}
test.err = err;
failures.push(test);
});
}
|
javascript
|
{
"resource": ""
}
|
q16396
|
errorDiff
|
train
|
function errorDiff(actual, expected) {
return diff
.diffWordsWithSpace(actual, expected)
.map(function(str) {
if (str.added) {
return colorLines('diff added', str.value);
}
if (str.removed) {
return colorLines('diff removed', str.value);
}
return str.value;
})
.join('');
}
|
javascript
|
{
"resource": ""
}
|
q16397
|
colorLines
|
train
|
function colorLines(name, str) {
return str
.split('\n')
.map(function(str) {
return color(name, str);
})
.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q16398
|
TAP
|
train
|
function TAP(runner, options) {
Base.call(this, runner, options);
var self = this;
var n = 1;
var tapVersion = '12';
if (options && options.reporterOptions) {
if (options.reporterOptions.tapVersion) {
tapVersion = options.reporterOptions.tapVersion.toString();
}
}
this._producer = createProducer(tapVersion);
runner.once(EVENT_RUN_BEGIN, function() {
var ntests = runner.grepTotal(runner.suite);
self._producer.writeVersion();
self._producer.writePlan(ntests);
});
runner.on(EVENT_TEST_END, function() {
++n;
});
runner.on(EVENT_TEST_PENDING, function(test) {
self._producer.writePending(n, test);
});
runner.on(EVENT_TEST_PASS, function(test) {
self._producer.writePass(n, test);
});
runner.on(EVENT_TEST_FAIL, function(test, err) {
self._producer.writeFail(n, test, err);
});
runner.once(EVENT_RUN_END, function() {
self._producer.writeEpilogue(runner.stats);
});
}
|
javascript
|
{
"resource": ""
}
|
q16399
|
println
|
train
|
function println(format, varArgs) {
var vargs = Array.from(arguments);
vargs[0] += '\n';
process.stdout.write(sprintf.apply(null, vargs));
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.