_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q23500
|
fadeLinesBut
|
train
|
function fadeLinesBut(exceptionItemId) {
let classToFade = 'g.legend-entry';
let entryLine = svg.select(`[data-item="${exceptionItemId}"]`);
if (entryLine.nodes().length){
svg.select('.legend-group')
.selectAll(classToFade)
.classed(isFadedClassName, true);
entryLine.classed(isFadedClassName, false);
}
}
|
javascript
|
{
"resource": ""
}
|
q23501
|
splitInLines
|
train
|
function splitInLines() {
let legendEntries = svg.selectAll('.legend-entry');
let numberOfEntries = legendEntries.size();
let lineHeight = (chartHeight / 2) * 1.7;
let newLine = svg.select('.legend-group')
.append('g')
.classed('legend-line', true)
.attr('transform', `translate(0, ${lineHeight})`);
let lastEntry = legendEntries.filter(`:nth-child(${numberOfEntries})`);
lastEntry.attr('transform', `translate(${markerSize},0)`);
newLine.append(() => lastEntry.node());
}
|
javascript
|
{
"resource": ""
}
|
q23502
|
writeEntryValues
|
train
|
function writeEntryValues() {
svg.select('.legend-group')
.selectAll('g.legend-line')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-value', true)
.text(getFormattedQuantity)
.attr('x', chartWidth - valueReservedSpace)
.style('font-size', `${textSize}px`)
.style('letter-spacing', `${numberLetterSpacing}px`)
.style('text-anchor', 'end')
.style('startOffset', '100%');
}
|
javascript
|
{
"resource": ""
}
|
q23503
|
cleanData
|
train
|
function cleanData({dataByTopic, dataByDate, data}) {
if (!dataByTopic && !data) {
throw new Error('Data needs to have a dataByTopic or data property. See more in http://eventbrite.github.io/britecharts/global.html#LineChartData__anchor');
}
// If dataByTopic or data are not present, we generate them
if (!dataByTopic) {
dataByTopic = d3Collection.nest()
.key(getVariableTopicName)
.entries(data)
.map(d => ({
topic: d.values[0]['name'],
topicName: d.key,
dates: d.values
})
);
} else {
data = dataByTopic.reduce((accum, topic) => {
topic.dates.forEach((date) => {
accum.push({
topicName: topic[topicNameLabel],
name: topic[topicLabel],
date: date[dateLabel],
value: date[valueLabel]
});
});
return accum;
}, []);
}
// Nest data by date and format
dataByDate = d3Collection.nest()
.key(getDate)
.entries(data)
.map((d) => {
return {
date: new Date(d.key),
topics: d.values
}
});
const normalizedDataByTopic = dataByTopic.reduce((accum, topic) => {
let {dates, ...restProps} = topic;
let newDates = dates.map(d => ({
date: new Date(d[dateLabel]),
value: +d[valueLabel]
}));
accum.push({ dates: newDates, ...restProps });
return accum;
}, []);
return {
dataByTopic: normalizedDataByTopic,
dataByDate
};
}
|
javascript
|
{
"resource": ""
}
|
q23504
|
drawAxis
|
train
|
function drawAxis(){
svg.select('.x-axis-group .axis.x')
.attr('transform', `translate(0, ${chartHeight})`)
.call(xAxis);
if (xAxisFormat !== 'custom') {
svg.select('.x-axis-group .month-axis')
.attr('transform', `translate(0, ${(chartHeight + monthAxisPadding)})`)
.call(xMonthAxis);
}
if (xAxisLabel) {
if (xAxisLabelEl) {
svg.selectAll('.x-axis-label').remove();
}
let xLabelXPosition = chartWidth/2;
let xLabelYPosition = chartHeight + monthAxisPadding + xAxisLabelPadding;
xAxisLabelEl = svg.select('.x-axis-group')
.append('text')
.attr('x', xLabelXPosition)
.attr('y', xLabelYPosition)
.attr('text-anchor', 'middle')
.attr('class', 'x-axis-label')
.text(xAxisLabel);
}
svg.select('.y-axis-group .axis.y')
.attr('transform', `translate(${-xAxisPadding.left}, 0)`)
.call(yAxis)
.call(adjustYTickLabels);
if (yAxisLabel) {
if (yAxisLabelEl) {
svg.selectAll('.y-axis-label').remove();
}
// Note this coordinates are rotated, so they are not what they look
let yLabelYPosition = -yAxisLabelPadding - xAxisPadding.left;
let yLabelXPosition = -chartHeight/2;
yAxisLabelEl = svg.select('.y-axis-group')
.append('text')
.attr('x', yLabelXPosition)
.attr('y', yLabelYPosition)
.attr('text-anchor', 'middle')
.attr('transform', 'rotate(270)')
.attr('class', 'y-axis-label')
.text(yAxisLabel);
}
}
|
javascript
|
{
"resource": ""
}
|
q23505
|
drawLines
|
train
|
function drawLines(){
let lines,
topicLine;
topicLine = d3Shape.line()
.curve(curveMap[lineCurve])
.x(({date}) => xScale(date))
.y(({value}) => yScale(value));
lines = svg.select('.chart-group').selectAll('.line')
.data(dataByTopic, getTopic);
paths = lines.enter()
.append('g')
.attr('class', 'topic')
.append('path')
.attr('class', 'line')
.merge(lines)
.attr('id', ({topic}) => topic)
.attr('d', ({dates}) => topicLine(dates))
.style('stroke', (d) => (
dataByTopic.length === 1 ? `url(#${lineGradientId})` : getLineColor(d)
));
lines
.exit()
.remove();
}
|
javascript
|
{
"resource": ""
}
|
q23506
|
drawAllDataPoints
|
train
|
function drawAllDataPoints() {
svg.select('.chart-group')
.selectAll('.data-points-container')
.remove();
const nodesById = paths.nodes().reduce((acc, node) => {
acc[node.id] = node
return acc;
}, {});
const allTopics = dataByDate.reduce((accum, dataPoint) => {
const dataPointTopics = dataPoint.topics.map(topic => ({
topic,
node: nodesById[topic.name]
}));
accum = [...accum, ...dataPointTopics];
return accum;
}, []);
let allDataPoints = svg.select('.chart-group')
.append('g')
.classed('data-points-container', true)
.selectAll('circle')
.data(allTopics)
.enter()
.append('circle')
.classed('data-point-mark', true)
.attr('r', highlightCircleRadius)
.style('stroke-width', highlightCircleStroke)
.style('stroke', (d) => topicColorMap[d.topic.name])
.style('cursor', 'pointer')
.attr('cx', d => xScale(new Date(d.topic.date)))
.attr('cy', d => getPathYFromX(xScale(new Date(d.topic.date)), d.node, d.topic.name));
}
|
javascript
|
{
"resource": ""
}
|
q23507
|
findOutNearestDate
|
train
|
function findOutNearestDate(x0, d0, d1){
return (new Date(x0).getTime() - new Date(d0.date).getTime()) > (new Date(d1.date).getTime() - new Date(x0).getTime()) ? d0 : d1;
}
|
javascript
|
{
"resource": ""
}
|
q23508
|
getPathYFromX
|
train
|
function getPathYFromX(x, path, name, error) {
const key = `${name}-${x}`;
if (key in pathYCache) {
return pathYCache[key];
}
error = error || 0.01;
const maxIterations = 100;
let lengthStart = 0;
let lengthEnd = path.getTotalLength();
let point = path.getPointAtLength((lengthEnd + lengthStart) / 2);
let iterations = 0;
while (x < point.x - error || x > point.x + error) {
const midpoint = (lengthStart + lengthEnd) / 2;
point = path.getPointAtLength(midpoint);
if (x < point.x) {
lengthEnd = midpoint;
} else {
lengthStart = midpoint;
}
iterations += 1;
if (maxIterations < iterations) {
break;
}
}
pathYCache[key] = point.y
return pathYCache[key]
}
|
javascript
|
{
"resource": ""
}
|
q23509
|
buildContainerGroups
|
train
|
function buildContainerGroups() {
let container = svg
.append('g')
.classed('container-group', true)
.attr('transform', `translate(${margin.left}, ${margin.top})`);
container
.append('g').classed('grid-lines-group', true);
container
.append('g').classed('chart-group', true);
container
.append('g').classed('axis-group', true);
container
.append('g').classed('metadata-group', true);
if (hasTitle()) {
container.selectAll('.chart-group')
.attr('transform', `translate(${legendSpacing}, 0)`);
}
}
|
javascript
|
{
"resource": ""
}
|
q23510
|
buildScales
|
train
|
function buildScales() {
const decidedRange = isReverse ? [chartWidth, 0] : [0, chartWidth];
xScale = d3Scale.scaleLinear()
.domain([0, Math.max(ranges[0], markers[0], measures[0])])
.rangeRound(decidedRange)
.nice();
// Derive width scales from x scales
barWidth = bulletWidth(xScale);
// set up opacity scale based on ranges and measures
rangeOpacityScale = ranges.map((d, i) => startMaxRangeOpacity - (i * rangeOpacifyDiff)).reverse();
measureOpacityScale = ranges.map((d, i) => 0.9 - (i * measureOpacifyDiff)).reverse();
// initialize range and measure bars and marker line colors
rangeColor = colorSchema[0];
measureColor = colorSchema[1];
}
|
javascript
|
{
"resource": ""
}
|
q23511
|
buildSVG
|
train
|
function buildSVG(container) {
if (!svg) {
svg = d3Selection.select(container)
.append('svg')
.classed('britechart bullet-chart', true);
buildContainerGroups();
}
svg
.attr('width', width)
.attr('height', height);
}
|
javascript
|
{
"resource": ""
}
|
q23512
|
bulletWidth
|
train
|
function bulletWidth(x) {
const x0 = x(0);
return function (d) {
return Math.abs(x(d) - x0);
}
}
|
javascript
|
{
"resource": ""
}
|
q23513
|
drawBullet
|
train
|
function drawBullet() {
if (rangesEl) {
rangesEl.remove();
measuresEl.remove();
markersEl.remove();
}
rangesEl = svg.select('.chart-group')
.selectAll('rect.range')
.data(ranges)
.enter()
.append('rect')
.attr('fill', rangeColor)
.attr('opacity', (d, i) => rangeOpacityScale[i])
.attr('class', (d, i) => `range r${i}`)
.attr('width', barWidth)
.attr('height', chartHeight)
.attr('x', isReverse ? xScale : 0);
measuresEl = svg.select('.chart-group')
.selectAll('rect.measure')
.data(measures)
.enter()
.append('rect')
.attr('fill', measureColor)
.attr('fill-opacity', (d, i) => measureOpacityScale[i])
.attr('class', (d, i) => `measure m${i}`)
.attr('width', barWidth)
.attr('height', getMeasureBarHeight)
.attr('x', isReverse ? xScale : 0)
.attr('y', getMeasureBarHeight);
markersEl = svg.select('.chart-group')
.selectAll('line.marker-line')
.data(markers)
.enter()
.append('line')
.attr('class', 'marker-line')
.attr('stroke', measureColor)
.attr('stroke-width', markerStrokeWidth)
.attr('opacity', measureOpacityScale[0])
.attr('x1', xScale)
.attr('x2', xScale)
.attr('y1', 0)
.attr('y2', chartHeight);
}
|
javascript
|
{
"resource": ""
}
|
q23514
|
drawTitles
|
train
|
function drawTitles() {
if (hasTitle()) {
// either use title provided from the data
// or customTitle provided via API method call
if (legendGroup) {
legendGroup.remove();
}
legendGroup = svg.select('.metadata-group')
.append('g')
.classed('legend-group', true)
.attr('transform', `translate(0, ${chartHeight / 2})`);
// override title with customTitle if given
if (customTitle) {
title = customTitle;
}
titleEl = legendGroup.selectAll('text.bullet-title')
.data([1])
.enter()
.append('text')
.attr('class', 'bullet-title x-axis-label')
.text(title);
// either use subtitle provided from the data
// or customSubtitle provided via API method call
if (subtitle || customSubtitle) {
// override subtitle with customSubtitle if given
if (customSubtitle) {
subtitle = customSubtitle;
}
titleEl = legendGroup.selectAll('text.bullet-subtitle')
.data([1])
.enter()
.append('text')
.attr('class', 'bullet-subtitle x-axis-label')
.attr('y', subtitleSpacing)
.text(subtitle);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23515
|
sortData
|
train
|
function sortData(unorderedData) {
let {data, dataZeroed} = unorderedData;
if (orderingFunction) {
data.sort(orderingFunction);
dataZeroed.sort(orderingFunction)
}
return { data, dataZeroed };
}
|
javascript
|
{
"resource": ""
}
|
q23516
|
drawAxisLabels
|
train
|
function drawAxisLabels() {
if (yAxisLabel) {
if (yAxisLabelEl) {
yAxisLabelEl.remove();
}
yAxisLabelEl = svg.select('.y-axis-label')
.append('text')
.classed('y-axis-label-text', true)
.attr('x', -chartHeight / 2)
.attr('y', yAxisLabelOffset)
.attr('text-anchor', 'middle')
.attr('transform', 'rotate(270 0 0)')
.text(yAxisLabel);
}
if (xAxisLabel) {
if (xAxisLabelEl) {
xAxisLabelEl.remove();
}
xAxisLabelEl = svg.select('.x-axis-label')
.append('text')
.attr('y', xAxisLabelOffset)
.attr('text-anchor', 'middle')
.classed('x-axis-label-text', true)
.attr('x', chartWidth / 2)
.text(xAxisLabel);
}
}
|
javascript
|
{
"resource": ""
}
|
q23517
|
drawAnimatedHorizontalBars
|
train
|
function drawAnimatedHorizontalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', 0)
.attr('y', chartHeight)
.attr('height', yScale.bandwidth())
.attr('width', ({value}) => xScale(value))
.on('mouseover', function(d, index, barList) {
handleMouseOver(this, d, barList, chartWidth, chartHeight);
})
.on('mousemove', function(d) {
handleMouseMove(this, d, chartWidth, chartHeight);
})
.on('mouseout', function(d, index, barList) {
handleMouseOut(this, d, barList, chartWidth, chartHeight);
})
.on('click', function(d) {
handleClick(this, d, chartWidth, chartHeight);
});
bars
.attr('x', 0)
.attr('y', ({name}) => yScale(name))
.attr('height', yScale.bandwidth())
.attr('fill', ({name}) => computeColor(name))
.transition()
.duration(animationDuration)
.delay(interBarDelay)
.ease(ease)
.attr('width', ({value}) => xScale(value));
}
|
javascript
|
{
"resource": ""
}
|
q23518
|
drawVerticalBars
|
train
|
function drawVerticalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', chartWidth)
.attr('y', ({value}) => yScale(value))
.attr('width', xScale.bandwidth())
.attr('height', ({value}) => chartHeight - yScale(value))
.on('mouseover', function(d, index, barList) {
handleMouseOver(this, d, barList, chartWidth, chartHeight);
})
.on('mousemove', function(d) {
handleMouseMove(this, d, chartWidth, chartHeight);
})
.on('mouseout', function(d, index, barList) {
handleMouseOut(this, d, barList, chartWidth, chartHeight);
})
.on('click', function(d) {
handleClick(this, d, chartWidth, chartHeight);
})
.merge(bars)
.attr('x', ({name}) => xScale(name))
.attr('y', ({value}) => yScale(value))
.attr('width', xScale.bandwidth())
.attr('height', ({value}) => chartHeight - yScale(value))
.attr('fill', ({name}) => computeColor(name));
}
|
javascript
|
{
"resource": ""
}
|
q23519
|
drawLabels
|
train
|
function drawLabels() {
let labelXPosition = isHorizontal ? _labelsHorizontalX : _labelsVerticalX;
let labelYPosition = isHorizontal ? _labelsHorizontalY : _labelsVerticalY;
let text = _labelsFormatValue
if (labelEl) {
svg.selectAll('.percentage-label-group').remove();
}
labelEl = svg.select('.metadata-group')
.append('g')
.classed('percentage-label-group', true)
.selectAll('text')
.data(data.reverse())
.enter()
.append('text');
labelEl
.classed('percentage-label', true)
.attr('x', labelXPosition)
.attr('y', labelYPosition)
.text(text)
.attr('font-size', labelsSize + 'px')
}
|
javascript
|
{
"resource": ""
}
|
q23520
|
drawBars
|
train
|
function drawBars() {
let bars;
if (isAnimated) {
bars = svg.select('.chart-group').selectAll('.bar')
.data(dataZeroed);
if (isHorizontal) {
drawHorizontalBars(bars);
} else {
drawVerticalBars(bars);
}
bars = svg.select('.chart-group').selectAll('.bar')
.data(data);
if (isHorizontal) {
drawAnimatedHorizontalBars(bars);
} else {
drawAnimatedVerticalBars(bars);
}
// Exit
bars.exit()
.transition()
.style('opacity', 0)
.remove();
} else {
bars = svg.select('.chart-group').selectAll('.bar')
.data(data);
if (isHorizontal) {
drawHorizontalBars(bars);
} else {
drawVerticalBars(bars);
}
// Exit
bars.exit()
.remove();
}
}
|
javascript
|
{
"resource": ""
}
|
q23521
|
drawHorizontalGridLines
|
train
|
function drawHorizontalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.vertical-grid-line')
.data(xScale.ticks(xTicks).slice(1))
.enter()
.append('line')
.attr('class', 'vertical-grid-line')
.attr('y1', (xAxisPadding.left))
.attr('y2', chartHeight)
.attr('x1', (d) => xScale(d))
.attr('x2', (d) => xScale(d))
drawVerticalExtendedLine();
}
|
javascript
|
{
"resource": ""
}
|
q23522
|
drawVerticalExtendedLine
|
train
|
function drawVerticalExtendedLine() {
baseLine = svg.select('.grid-lines-group')
.selectAll('line.extended-y-line')
.data([0])
.enter()
.append('line')
.attr('class', 'extended-y-line')
.attr('y1', (xAxisPadding.bottom))
.attr('y2', chartHeight)
.attr('x1', 0)
.attr('x2', 0);
}
|
javascript
|
{
"resource": ""
}
|
q23523
|
drawVerticalGridLines
|
train
|
function drawVerticalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.horizontal-grid-line')
.data(yScale.ticks(yTicks).slice(1))
.enter()
.append('line')
.attr('class', 'horizontal-grid-line')
.attr('x1', (xAxisPadding.left))
.attr('x2', chartWidth)
.attr('y1', (d) => yScale(d))
.attr('y2', (d) => yScale(d))
drawHorizontalExtendedLine();
}
|
javascript
|
{
"resource": ""
}
|
q23524
|
buildLayers
|
train
|
function buildLayers() {
layers = transformedData.map((item) => {
let ret = {};
groups.forEach((key) => {
ret[key] = item[key];
});
return assign({}, item, ret);
});
}
|
javascript
|
{
"resource": ""
}
|
q23525
|
cleanData
|
train
|
function cleanData(originalData) {
return originalData.reduce((acc, d) => {
d.value = +d[valueLabel];
d.group = d[groupLabel];
// for tooltip
d.topicName = getGroup(d);
d.name = d[nameLabel];
return [...acc, d];
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q23526
|
drawHorizontalBars
|
train
|
function drawHorizontalBars(layersSelection) {
let layerJoin = layersSelection
.data(layers);
layerElements = layerJoin
.enter()
.append('g')
.attr('transform', ({key}) => `translate(0,${yScale(key)})`)
.classed('layer', true);
let barJoin = layerElements
.selectAll('.bar')
.data(({values}) => values);
// Enter + Update
let bars = barJoin
.enter()
.append('rect')
.classed('bar', true)
.attr('x', 1)
.attr('y', (d) => yScale2(getGroup(d)))
.attr('height', yScale2.bandwidth())
.attr('fill', (({group}) => categoryColorMap[group]));
if (isAnimated) {
bars.style('opacity', barOpacity)
.transition()
.delay((_, i) => animationDelays[i])
.duration(animationDuration)
.ease(ease)
.tween('attr.width', horizontalBarsTween);
} else {
bars.attr('width', (d) => xScale(getValue(d)));
}
}
|
javascript
|
{
"resource": ""
}
|
q23527
|
handleBarsMouseOver
|
train
|
function handleBarsMouseOver(e, d) {
d3Selection.select(e)
.attr('fill', () => d3Color.color(categoryColorMap[d.group]).darker());
}
|
javascript
|
{
"resource": ""
}
|
q23528
|
handleBarsMouseOut
|
train
|
function handleBarsMouseOut(e, d) {
d3Selection.select(e)
.attr('fill', () => categoryColorMap[d.group])
}
|
javascript
|
{
"resource": ""
}
|
q23529
|
handleCustomClick
|
train
|
function handleCustomClick (e, d) {
let [mouseX, mouseY] = getMousePosition(e);
let dataPoint = isHorizontal ? getNearestDataPoint2(mouseY) : getNearestDataPoint(mouseX);
dispatcher.call('customClick', e, dataPoint, d3Selection.mouse(e));
}
|
javascript
|
{
"resource": ""
}
|
q23530
|
horizontalBarsTween
|
train
|
function horizontalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, xScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
return function (t) {
node.attr('width', i(t))
.style('opacity', j(t));
}
}
|
javascript
|
{
"resource": ""
}
|
q23531
|
prepareData
|
train
|
function prepareData(data) {
groups = uniq(data.map((d) => getGroup(d)));
transformedData = d3Collection.nest()
.key(getName)
.rollup(function (values) {
let ret = {};
values.forEach((entry) => {
if (entry && entry[groupLabel]) {
ret[entry[groupLabel]] = getValue(entry);
}
});
//for tooltip
ret.values = values;
return ret;
})
.entries(data)
.map(function (data) {
return assign({}, {
total: d3Array.sum(d3Array.permute(data.value, groups)),
key: data.key
}, data.value);
});
}
|
javascript
|
{
"resource": ""
}
|
q23532
|
verticalBarsTween
|
train
|
function verticalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, chartHeight - yScale(getValue(d))),
y = d3Interpolate.interpolateRound(chartHeight, yScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
return function (t) {
node.attr('y', y(t))
.attr('height', i(t)).style('opacity', j(t));
}
}
|
javascript
|
{
"resource": ""
}
|
q23533
|
jobNameValidator
|
train
|
function jobNameValidator(value) {
const response = { isValid: true, notification: { type: 'success', msg: '', title: '' } };
if (!value) {
response.isValid = false;
response.notification.type = 'error';
response.notification.msg = 'Value must be inserted';
response.notification.title = 'Requested Value';
} else if (value.length < 10) {
response.isValid = false;
response.notification.type = 'error';
response.notification.msg = 'Value must have 10+ characters';
response.notification.title = 'Invalid Value';
}
return response;
}
|
javascript
|
{
"resource": ""
}
|
q23534
|
getClearBonus
|
train
|
function getClearBonus(events, warriorScore, timeBonus) {
const lastEvent = getLastEvent(events);
if (!isFloorClear(lastEvent.floorMap)) {
return 0;
}
return Math.round((warriorScore + timeBonus) * 0.2);
}
|
javascript
|
{
"resource": ""
}
|
q23535
|
getLevelConfig
|
train
|
function getLevelConfig(tower, levelNumber, warriorName, epic) {
const level = tower.levels[levelNumber - 1];
if (!level) {
return null;
}
const levelConfig = cloneDeep(level);
const levels = epic ? tower.levels : tower.levels.slice(0, levelNumber);
const warriorAbilities = Object.assign(
{},
...levels.map(
({
floor: {
warrior: { abilities },
},
}) => abilities || {},
),
);
levelConfig.number = levelNumber;
levelConfig.floor.warrior.name = warriorName;
levelConfig.floor.warrior.abilities = warriorAbilities;
return levelConfig;
}
|
javascript
|
{
"resource": ""
}
|
q23536
|
parseArgs
|
train
|
function parseArgs(args) {
return yargs
.usage('Usage: $0 [options]')
.options({
d: {
alias: 'directory',
default: '.',
describe: 'Run under given directory',
type: 'string',
},
l: {
alias: 'level',
coerce: arg => {
const parsed = Number.parseInt(arg, 10);
if (Number.isNaN(parsed)) {
throw new Error('Invalid argument: level must be a number');
}
return parsed;
},
describe: 'Practice level (epic mode only)',
type: 'number',
},
s: {
alias: 'silent',
default: false,
describe: 'Suppress play log',
type: 'boolean',
},
t: {
alias: 'time',
coerce: arg => {
const parsed = Number.parseFloat(arg);
if (Number.isNaN(parsed)) {
throw new Error('Invalid argument: time must be a number');
}
return parsed;
},
default: 0.6,
describe: 'Delay each turn by seconds',
type: 'number',
},
y: {
alias: 'yes',
default: false,
describe: 'Assume yes in non-destructive confirmation dialogs',
type: 'boolean',
},
})
.version()
.help()
.strict()
.parse(args);
}
|
javascript
|
{
"resource": ""
}
|
q23537
|
printLogMessage
|
train
|
function printLogMessage(unit, message) {
const prompt = chalk.gray.dim('>');
const logMessage = getUnitStyle(unit)(`${unit.name} ${message}`);
printLine(`${prompt} ${logMessage}`);
}
|
javascript
|
{
"resource": ""
}
|
q23538
|
printLevelReport
|
train
|
function printLevelReport(
profile,
{ warrior: warriorScore, timeBonus, clearBonus },
totalScore,
grade,
) {
printLine(`Warrior Score: ${warriorScore}`);
printLine(`Time Bonus: ${timeBonus}`);
printLine(`Clear Bonus: ${clearBonus}`);
if (profile.isEpic()) {
printLine(`Level Grade: ${getGradeLetter(grade)}`);
printTotalScore(profile.currentEpicScore, totalScore);
} else {
printTotalScore(profile.score, totalScore);
}
}
|
javascript
|
{
"resource": ""
}
|
q23539
|
verifyRelativeDirection
|
train
|
function verifyRelativeDirection(direction) {
if (!RELATIVE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${FORWARD}', '${RIGHT}', '${BACKWARD}' or '${LEFT}'.`,
);
}
}
|
javascript
|
{
"resource": ""
}
|
q23540
|
loadAbilities
|
train
|
function loadAbilities(unit, abilities = {}) {
Object.entries(abilities).forEach(([abilityName, abilityCreator]) => {
const ability = abilityCreator(unit);
unit.addAbility(abilityName, ability);
});
}
|
javascript
|
{
"resource": ""
}
|
q23541
|
loadEffects
|
train
|
function loadEffects(unit, effects = {}) {
Object.entries(effects).forEach(([effectName, effectCreator]) => {
const effect = effectCreator(unit);
unit.addEffect(effectName, effect);
});
}
|
javascript
|
{
"resource": ""
}
|
q23542
|
loadWarrior
|
train
|
function loadWarrior(
{ name, character, color, maxHealth, abilities, effects, position },
floor,
playerCode,
) {
const warrior = new Warrior(name, character, color, maxHealth);
loadAbilities(warrior, abilities);
loadEffects(warrior, effects);
warrior.playTurn = playerCode ? loadPlayer(playerCode) : () => {};
floor.addWarrior(warrior, position);
}
|
javascript
|
{
"resource": ""
}
|
q23543
|
loadUnit
|
train
|
function loadUnit(
{
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
abilities,
effects,
playTurn,
position,
},
floor,
) {
const unit = new Unit(
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
);
loadAbilities(unit, abilities);
loadEffects(unit, effects);
unit.playTurn = playTurn;
floor.addUnit(unit, position);
}
|
javascript
|
{
"resource": ""
}
|
q23544
|
loadLevel
|
train
|
function loadLevel(
{
number,
description,
tip,
clue,
floor: { size, stairs, warrior, units = [] },
},
playerCode,
) {
const { width, height } = size;
const stairsLocation = [stairs.x, stairs.y];
const floor = new Floor(width, height, stairsLocation);
loadWarrior(warrior, floor, playerCode);
units.forEach(unit => loadUnit(unit, floor));
return new Level(number, description, tip, clue, floor);
}
|
javascript
|
{
"resource": ""
}
|
q23545
|
requestConfirmation
|
train
|
async function requestConfirmation(message, defaultAnswer = false) {
const answerName = 'requestConfirmation';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'confirm',
default: defaultAnswer,
},
]);
return answers[answerName];
}
|
javascript
|
{
"resource": ""
}
|
q23546
|
verifyAbsoluteDirection
|
train
|
function verifyAbsoluteDirection(direction) {
if (!ABSOLUTE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${NORTH}', '${EAST}', '${SOUTH}' or '${WEST}'.`,
);
}
}
|
javascript
|
{
"resource": ""
}
|
q23547
|
printTurnHeader
|
train
|
function printTurnHeader(turnNumber) {
printRow(chalk.gray.dim(` ${String(turnNumber).padStart(3, '0')} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
}
|
javascript
|
{
"resource": ""
}
|
q23548
|
printFloorMap
|
train
|
function printFloorMap(floorMap) {
printLine(
floorMap
.map(row =>
row
.map(({ character, unit }) => {
if (unit) {
return getUnitStyle(unit)(character);
}
return character;
})
.join(''),
)
.join('\n'),
);
}
|
javascript
|
{
"resource": ""
}
|
q23549
|
loadPlayer
|
train
|
function loadPlayer(playerCode) {
const sandbox = vm.createContext();
// Do not collect stack frames for errors in the player code.
vm.runInContext('Error.stackTraceLimit = 0;', sandbox);
try {
vm.runInContext(playerCode, sandbox, {
filename: playerCodeFilename,
timeout: playerCodeTimeout,
});
} catch (err) {
const error = new Error(`Check your syntax and try again!\n\n${err.stack}`);
error.code = 'InvalidPlayerCode';
throw error;
}
try {
const player = vm.runInContext('new Player();', sandbox, {
timeout: playerCodeTimeout,
});
assert(typeof player.playTurn === 'function', 'playTurn is not defined');
const playTurn = turn => {
try {
player.playTurn(turn);
} catch (err) {
const error = new Error(err.message);
error.code = 'InvalidPlayerCode';
throw error;
}
};
return playTurn;
} catch (err) {
if (err.message === 'Player is not defined') {
const error = new Error('You must define a Player class!');
error.code = 'InvalidPlayerCode';
throw error;
} else if (err.message === 'playTurn is not defined') {
const error = new Error(
'Your Player class must define a playTurn method!',
);
error.code = 'InvalidPlayerCode';
throw error;
}
throw err;
}
}
|
javascript
|
{
"resource": ""
}
|
q23550
|
printRow
|
train
|
function printRow(message, { position = 'start', padding = ' ' } = {}) {
const [screenWidth] = getScreenSize();
const rowWidth = screenWidth - 1; // Consider line break length.
const messageWidth = stringWidth(message);
const paddingWidth = (rowWidth - messageWidth) / 2;
const startPadding = padding.repeat(Math.floor(paddingWidth));
const endPadding = padding.repeat(Math.ceil(paddingWidth));
if (position === 'start') {
printLine(`${message}${startPadding}${endPadding}`);
} else if (position === 'middle') {
printLine(`${startPadding}${message}${endPadding}`);
} else if (position === 'end') {
printLine(`${startPadding}${endPadding}${message}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q23551
|
printTowerReport
|
train
|
function printTowerReport(profile) {
const averageGrade = profile.calculateAverageGrade();
if (!averageGrade) {
return;
}
const averageGradeLetter = getGradeLetter(averageGrade);
printLine(`Your average grade for this tower is: ${averageGradeLetter}\n`);
Object.keys(profile.currentEpicGrades)
.sort()
.forEach(levelNumber => {
const grade = profile.currentEpicGrades[levelNumber];
const gradeLetter = getGradeLetter(grade);
printLine(` Level ${levelNumber}: ${gradeLetter}`);
});
printLine('\nTo practice a level, use the -l option.');
}
|
javascript
|
{
"resource": ""
}
|
q23552
|
getLevelScore
|
train
|
function getLevelScore({ passed, events }, { timeBonus }) {
if (!passed) {
return null;
}
const warriorScore = getWarriorScore(events);
const remainingTimeBonus = getRemainingTimeBonus(events, timeBonus);
const clearBonus = getClearBonus(events, warriorScore, remainingTimeBonus);
return {
clearBonus,
timeBonus: remainingTimeBonus,
warrior: warriorScore,
};
}
|
javascript
|
{
"resource": ""
}
|
q23553
|
getExternalTowersInfo
|
train
|
function getExternalTowersInfo() {
const cliDir = findUp.sync('@warriorjs/cli', { cwd: __dirname });
if (!cliDir) {
return [];
}
const cliParentDir = path.resolve(cliDir, '..');
const towerSearchDir = findUp.sync('node_modules', { cwd: cliParentDir });
const towerPackageJsonPaths = globby.sync(
[officialTowerPackageJsonPattern, communityTowerPackageJsonPattern],
{ cwd: towerSearchDir },
);
const towerPackageNames = towerPackageJsonPaths.map(path.dirname);
return towerPackageNames.map(towerPackageName => ({
id: getTowerId(towerPackageName),
requirePath: resolve.sync(towerPackageName, { basedir: towerSearchDir }),
}));
}
|
javascript
|
{
"resource": ""
}
|
q23554
|
loadTowers
|
train
|
function loadTowers() {
const internalTowersInfo = getInternalTowersInfo();
const externalTowersInfo = getExternalTowersInfo();
return uniqBy(internalTowersInfo.concat(externalTowersInfo), 'id').map(
({ id, requirePath }) => {
const { name, description, levels } = require(requirePath); // eslint-disable-line global-require, import/no-dynamic-require
return new Tower(id, name, description, levels);
},
);
}
|
javascript
|
{
"resource": ""
}
|
q23555
|
rotateRelativeOffset
|
train
|
function rotateRelativeOffset([forward, right], direction) {
verifyRelativeDirection(direction);
if (direction === FORWARD) {
return [forward, right];
}
if (direction === RIGHT) {
return [-right, forward];
}
if (direction === BACKWARD) {
return [-forward, -right];
}
return [right, -forward];
}
|
javascript
|
{
"resource": ""
}
|
q23556
|
requestChoice
|
train
|
async function requestChoice(message, items) {
const answerName = 'requestChoice';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'list',
choices: getChoices(items),
},
]);
return answers[answerName];
}
|
javascript
|
{
"resource": ""
}
|
q23557
|
printBoard
|
train
|
function printBoard(floorMap, warriorStatus, offset) {
if (offset > 0) {
const floorMapRows = floorMap.length;
print(ansiEscapes.cursorUp(offset + floorMapRows + warriorStatusRows));
}
printWarriorStatus(warriorStatus);
printFloorMap(floorMap);
if (offset > 0) {
print(ansiEscapes.cursorDown(offset));
}
}
|
javascript
|
{
"resource": ""
}
|
q23558
|
getRemainingTimeBonus
|
train
|
function getRemainingTimeBonus(events, timeBonus) {
const turnCount = getTurnCount(events);
const remainingTimeBonus = timeBonus - turnCount;
return Math.max(remainingTimeBonus, 0);
}
|
javascript
|
{
"resource": ""
}
|
q23559
|
requestInput
|
train
|
async function requestInput(message, suggestions = []) {
const answerName = 'requestInput';
const answers = await inquirer.prompt([
{
message,
suggestions,
name: answerName,
type: suggestions.length ? 'suggest' : 'input',
},
]);
return answers[answerName];
}
|
javascript
|
{
"resource": ""
}
|
q23560
|
getLevel
|
train
|
function getLevel(levelConfig) {
const level = loadLevel(levelConfig);
return JSON.parse(JSON.stringify(level));
}
|
javascript
|
{
"resource": ""
}
|
q23561
|
printTotalScore
|
train
|
function printTotalScore(currentScore, addition) {
if (currentScore === 0) {
printLine(`Total Score: ${addition.toString()}`);
} else {
printLine(
`Total Score: ${currentScore} + ${addition} = ${currentScore + addition}`,
);
}
}
|
javascript
|
{
"resource": ""
}
|
q23562
|
printPlay
|
train
|
async function printPlay(events, delay) {
let turnNumber = 0;
let boardOffset = 0;
await sleep(delay);
// eslint-disable-next-line no-restricted-syntax
for (const turnEvents of events) {
turnNumber += 1;
boardOffset = 0;
printTurnHeader(turnNumber);
// eslint-disable-next-line no-restricted-syntax
for (const event of turnEvents) {
printBoard(event.floorMap, event.warriorStatus, boardOffset);
printLogMessage(event.unit, event.message);
boardOffset += 1;
await sleep(delay); // eslint-disable-line no-await-in-loop
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23563
|
isFloorClear
|
train
|
function isFloorClear(floorMap) {
const spaces = floorMap.reduce((acc, val) => acc.concat(val), []);
const unitCount = spaces.filter(space => !!space.unit).length;
return unitCount <= 1;
}
|
javascript
|
{
"resource": ""
}
|
q23564
|
printLevelHeader
|
train
|
function printLevelHeader(levelNumber) {
printRow(chalk.gray.dim(` level ${levelNumber} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
}
|
javascript
|
{
"resource": ""
}
|
q23565
|
train
|
function(err, res) {
if (_.isFunction(callback)) {
try {
res = callback(err, res);
err = null;
} catch(e) {
err = e;
}
}
if (err) {
deferred.reject(err);
} else {
deferred.resolve(res);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23566
|
train
|
function(params) {
params = _.extend({
response_type : "code",
client_id : this.clientId,
redirect_uri : this.redirectUri
}, params || {});
return this.authzServiceUrl +
(this.authzServiceUrl.indexOf('?') >= 0 ? "&" : "?") +
querystring.stringify(params);
}
|
javascript
|
{
"resource": ""
}
|
|
q23567
|
train
|
function(token, callback) {
return this._transport.httpRequest({
method : 'POST',
url : this.revokeServiceUrl,
body: querystring.stringify({ token: token }),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
if (response.statusCode >= 400) {
var res = querystring.parse(response.body);
if (!res || !res.error) {
res = { error: "ERROR_HTTP_"+response.statusCode, error_description: response.body };
}
var err = new Error(res.error_description);
err.name = res.error;
throw err;
}
}).thenCall(callback);
}
|
javascript
|
{
"resource": ""
}
|
|
q23568
|
createCacheKey
|
train
|
function createCacheKey(namespace, args) {
args = Array.prototype.slice.apply(args);
return namespace + '(' + _.map(args, function(a){ return JSON.stringify(a); }).join(',') + ')';
}
|
javascript
|
{
"resource": ""
}
|
q23569
|
train
|
function(conn, options) {
options = options || {};
this._conn = conn;
this.on('resume', function(err) { conn.emit('resume', err); });
this._responseType = options.responseType;
this._transport = options.transport || conn._transport;
this._noContentResponse = options.noContentResponse;
}
|
javascript
|
{
"resource": ""
}
|
|
q23570
|
injectBefore
|
train
|
function injectBefore(replServer, method, beforeFn) {
var _orig = replServer[method];
replServer[method] = function() {
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
beforeFn.apply(null, args.concat(function(err, res) {
if (err || res) {
callback(err, res);
} else {
_orig.apply(replServer, args.concat(callback));
}
}));
};
return replServer;
}
|
javascript
|
{
"resource": ""
}
|
q23571
|
promisify
|
train
|
function promisify(err, value, callback) {
if (err) { throw err; }
if (isPromiseLike(value)) {
value.then(function(v) {
callback(null, v);
}, function(err) {
callback(err);
});
} else {
callback(null, value);
}
}
|
javascript
|
{
"resource": ""
}
|
q23572
|
outputToStdout
|
train
|
function outputToStdout(prettyPrint) {
if (prettyPrint && !_.isNumber(prettyPrint)) {
prettyPrint = 4;
}
return function(err, value, callback) {
if (err) {
console.error(err);
} else {
var str = JSON.stringify(value, null, prettyPrint);
console.log(str);
}
callback(err, value);
};
}
|
javascript
|
{
"resource": ""
}
|
q23573
|
train
|
function(path) {
const { node } = path;
if (node.declarations.length < 2) {
return;
}
const inits = [];
const empty = [];
for (const decl of node.declarations) {
if (!decl.init) {
empty.push(decl);
} else {
inits.push(decl);
}
}
// This is based on exprimintation but there is a significant
// imrpovement when we place empty vars at the top in smaller
// files. Whereas it hurts in larger files.
if (this.fitsInSlidingWindow) {
node.declarations = empty.concat(inits);
} else {
node.declarations = inits.concat(empty);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23574
|
train
|
function(path) {
const { node } = path;
if (
!path.parentPath.parentPath.isFunction() ||
path.getSibling(path.key + 1).node
) {
return;
}
if (!node.argument) {
path.remove();
return;
}
if (t.isUnaryExpression(node.argument, { operator: "void" })) {
path.replaceWith(node.argument.argument);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23575
|
train
|
function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const consTestPairs = [];
let fallThru = [];
let defaultRet;
for (const switchCase of node.cases) {
if (switchCase.consequent.length > 1) {
return;
}
const cons = switchCase.consequent[0];
// default case
if (!switchCase.test) {
if (!t.isReturnStatement(cons)) {
return;
}
defaultRet = cons;
continue;
}
if (!switchCase.consequent.length) {
fallThru.push(switchCase.test);
continue;
}
// TODO: can we void it?
if (!t.isReturnStatement(cons)) {
return;
}
let test = t.binaryExpression(
"===",
node.discriminant,
switchCase.test
);
if (fallThru.length && !defaultRet) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
"||",
t.binaryExpression("===", node.discriminant, test),
right
),
test
);
}
fallThru = [];
consTestPairs.push([test, cons.argument || VOID_0]);
}
// Bail if we have any remaining fallthrough
if (fallThru.length) {
return;
}
// We need the default to be there to make sure there is an oppurtinity
// not to return.
if (!defaultRet) {
if (path.inList) {
const nextPath = path.getSibling(path.key + 1);
if (nextPath.isReturnStatement()) {
defaultRet = nextPath.node;
nextPath.remove();
} else if (
!nextPath.node &&
path.parentPath.parentPath.isFunction()
) {
// If this is the last statement in a function we just fake a void return.
defaultRet = t.returnStatement(VOID_0);
} else {
return;
}
} else {
return;
}
}
const cond = consTestPairs.reduceRight(
(alt, [test, cons]) => t.conditionalExpression(test, cons, alt),
defaultRet.argument || VOID_0
);
path.replaceWith(t.returnStatement(cond));
// Maybe now we can merge with some previous switch statement.
if (path.inList) {
const prev = path.getSibling(path.key - 1);
if (prev.isSwitchStatement()) {
prev.visit();
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23576
|
train
|
function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const exprTestPairs = [];
let fallThru = [];
let defaultExpr;
for (const switchCase of node.cases) {
if (!switchCase.test) {
if (switchCase.consequent.length !== 1) {
return;
}
if (!t.isExpressionStatement(switchCase.consequent[0])) {
return;
}
defaultExpr = switchCase.consequent[0].expression;
continue;
}
if (!switchCase.consequent.length) {
fallThru.push(switchCase.test);
continue;
}
const [cons, breakStatement] = switchCase.consequent;
if (switchCase === node.cases[node.cases.length - 1]) {
if (breakStatement && !t.isBreakStatement(breakStatement)) {
return;
}
} else if (!t.isBreakStatement(breakStatement)) {
return;
}
if (
!t.isExpressionStatement(cons) ||
switchCase.consequent.length > 2
) {
return;
}
let test = t.binaryExpression(
"===",
node.discriminant,
switchCase.test
);
if (fallThru.length && !defaultExpr) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
"||",
t.binaryExpression("===", node.discriminant, test),
right
),
test
);
}
fallThru = [];
exprTestPairs.push([test, cons.expression]);
}
if (fallThru.length) {
return;
}
const cond = exprTestPairs.reduceRight(
(alt, [test, cons]) => t.conditionalExpression(test, cons, alt),
defaultExpr || VOID_0
);
path.replaceWith(cond);
}
|
javascript
|
{
"resource": ""
}
|
|
q23577
|
toGuardedExpression
|
train
|
function toGuardedExpression(path) {
const { node } = path;
if (
node.consequent &&
!node.alternate &&
node.consequent.type === "ExpressionStatement"
) {
let op = "&&";
if (t.isUnaryExpression(node.test, { operator: "!" })) {
node.test = node.test.argument;
op = "||";
}
path.replaceWith(
t.expressionStatement(
t.logicalExpression(op, node.test, node.consequent.expression)
)
);
return REPLACED;
}
}
|
javascript
|
{
"resource": ""
}
|
q23578
|
toTernary
|
train
|
function toTernary(path) {
const { node } = path;
if (
t.isExpressionStatement(node.consequent) &&
t.isExpressionStatement(node.alternate)
) {
path.replaceWith(
t.conditionalExpression(
node.test,
node.consequent.expression,
node.alternate.expression
)
);
return REPLACED;
}
}
|
javascript
|
{
"resource": ""
}
|
q23579
|
removeUnnecessaryElse
|
train
|
function removeUnnecessaryElse(path) {
const { node } = path;
const consequent = path.get("consequent");
const alternate = path.get("alternate");
if (
consequent.node &&
alternate.node &&
(consequent.isReturnStatement() ||
(consequent.isBlockStatement() &&
t.isReturnStatement(
consequent.node.body[consequent.node.body.length - 1]
))) &&
// don't hoist declarations
// TODO: validate declarations after fixing scope issues
(alternate.isBlockStatement()
? !alternate
.get("body")
.some(
stmt =>
stmt.isVariableDeclaration({ kind: "let" }) ||
stmt.isVariableDeclaration({ kind: "const" })
)
: true)
) {
path.insertAfter(
alternate.isBlockStatement()
? alternate.node.body.map(el => t.clone(el))
: t.clone(alternate.node)
);
node.alternate = null;
return REPLACED;
}
}
|
javascript
|
{
"resource": ""
}
|
q23580
|
switchConsequent
|
train
|
function switchConsequent(path) {
const { node } = path;
if (!node.alternate) {
return;
}
if (!t.isIfStatement(node.consequent)) {
return;
}
if (t.isIfStatement(node.alternate)) {
return;
}
node.test = t.unaryExpression("!", node.test, true);
[node.alternate, node.consequent] = [node.consequent, node.alternate];
}
|
javascript
|
{
"resource": ""
}
|
q23581
|
conditionalReturnToGuards
|
train
|
function conditionalReturnToGuards(path) {
const { node } = path;
if (
!path.inList ||
!path.get("consequent").isBlockStatement() ||
node.alternate
) {
return;
}
let ret;
let test;
const exprs = [];
const statements = node.consequent.body;
for (let i = 0, statement; (statement = statements[i]); i++) {
if (t.isExpressionStatement(statement)) {
exprs.push(statement.expression);
} else if (t.isIfStatement(statement)) {
if (i < statements.length - 1) {
// This isn't the last statement. Bail.
return;
}
if (statement.alternate) {
return;
}
if (!t.isReturnStatement(statement.consequent)) {
return;
}
ret = statement.consequent;
test = statement.test;
} else {
return;
}
}
if (!test || !ret) {
return;
}
exprs.push(test);
const expr = exprs.length === 1 ? exprs[0] : t.sequenceExpression(exprs);
const replacement = t.logicalExpression("&&", node.test, expr);
path.replaceWith(t.ifStatement(replacement, ret, null));
}
|
javascript
|
{
"resource": ""
}
|
q23582
|
unpad
|
train
|
function unpad(str) {
const lines = str.split("\n");
const m = lines[1] && lines[1].match(/^\s+/);
if (!m) {
return str;
}
const spaces = m[0].length;
return lines
.map(line => line.slice(spaces))
.join("\n")
.trim();
}
|
javascript
|
{
"resource": ""
}
|
q23583
|
baseTypeStrictlyMatches
|
train
|
function baseTypeStrictlyMatches(left, right) {
let leftTypes, rightTypes;
if (t.isIdentifier(left)) {
leftTypes = customTypeAnnotation(left);
} else if (t.isIdentifier(right)) {
rightTypes = customTypeAnnotation(right);
}
// Early exit
if (t.isAnyTypeAnnotation(leftTypes) || t.isAnyTypeAnnotation(rightTypes)) {
return false;
}
leftTypes = [].concat(leftTypes, left.getTypeAnnotation());
rightTypes = [].concat(rightTypes, right.getTypeAnnotation());
leftTypes = t.createUnionTypeAnnotation(leftTypes);
rightTypes = t.createUnionTypeAnnotation(rightTypes);
if (
!t.isAnyTypeAnnotation(leftTypes) &&
t.isFlowBaseAnnotation(leftTypes)
) {
return leftTypes.type === rightTypes.type;
}
}
|
javascript
|
{
"resource": ""
}
|
q23584
|
removeUseStrict
|
train
|
function removeUseStrict(block) {
if (!block.isBlockStatement()) {
throw new Error(
`Received ${block.type}. Expected BlockStatement. ` +
`Please report at ${newIssueUrl}`
);
}
const useStricts = getUseStrictDirectives(block);
// early exit
if (useStricts.length < 1) return;
// only keep the first use strict
if (useStricts.length > 1) {
for (let i = 1; i < useStricts.length; i++) {
useStricts[i].remove();
}
}
// check if parent has an use strict
if (hasStrictParent(block)) {
useStricts[0].remove();
}
}
|
javascript
|
{
"resource": ""
}
|
q23585
|
tableStyle
|
train
|
function tableStyle() {
return {
chars: {
top: "",
"top-mid": "",
"top-left": "",
"top-right": "",
bottom: "",
"bottom-mid": "",
"bottom-left": "",
"bottom-right": "",
left: "",
"left-mid": "",
mid: "",
"mid-mid": "",
right: "",
"right-mid": "",
middle: " "
},
style: {
"padding-left": 0,
"padding-right": 0,
head: ["bold"]
}
};
}
|
javascript
|
{
"resource": ""
}
|
q23586
|
readStdin
|
train
|
async function readStdin() {
let code = "";
const stdin = process.stdin;
return new Promise(resolve => {
stdin.setEncoding("utf8");
stdin.on("readable", () => {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
stdin.on("end", () => {
resolve(code);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23587
|
shouldDeoptBasedOnScope
|
train
|
function shouldDeoptBasedOnScope(binding, refPath) {
if (binding.scope.path.isProgram() && refPath.scope !== binding.scope) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q23588
|
getSegmentedSubPaths
|
train
|
function getSegmentedSubPaths(paths) {
let segments = new Map();
// Get earliest Path in tree where paths intersect
paths[0].getDeepestCommonAncestorFrom(
paths,
(lastCommon, index, ancestries) => {
// found the LCA
if (!lastCommon.isProgram()) {
let fnParent;
if (
lastCommon.isFunction() &&
t.isBlockStatement(lastCommon.node.body)
) {
segments.set(lastCommon, paths);
return;
} else if (
!(fnParent = getFunctionParent(lastCommon)).isProgram() &&
t.isBlockStatement(fnParent.node.body)
) {
segments.set(fnParent, paths);
return;
}
}
// Deopt and construct segments otherwise
for (const ancestor of ancestries) {
const fnPath = getChildFuncion(ancestor);
if (fnPath === void 0) {
continue;
}
const validDescendants = paths.filter(p => {
return p.isDescendant(fnPath);
});
segments.set(fnPath, validDescendants);
}
}
);
return segments;
}
|
javascript
|
{
"resource": ""
}
|
q23589
|
toObject
|
train
|
function toObject(value) {
if (!Array.isArray(value)) {
return value;
}
const map = {};
for (let i = 0; i < value.length; i++) {
map[value[i]] = true;
}
return map;
}
|
javascript
|
{
"resource": ""
}
|
q23590
|
train
|
function(path) {
if (!path.inList) {
return;
}
const { node } = path;
let sibling = path.getSibling(path.key + 1);
let declarations = [];
while (sibling.isVariableDeclaration({ kind: node.kind })) {
declarations = declarations.concat(sibling.node.declarations);
sibling.remove();
sibling = path.getSibling(path.key + 1);
}
if (declarations.length > 0) {
path.replaceWith(
t.variableDeclaration(node.kind, [
...node.declarations,
...declarations
])
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23591
|
train
|
function(path) {
if (!path.inList) {
return;
}
const { node } = path;
if (node.kind !== "var") {
return;
}
const next = path.getSibling(path.key + 1);
if (!next.isForStatement()) {
return;
}
const init = next.get("init");
if (!init.isVariableDeclaration({ kind: node.kind })) {
return;
}
const declarations = node.declarations.concat(
init.node.declarations
);
// temporary workaround to forces babel recalculate scope,
// references and binding until babel/babel#4818 resolved
path.remove();
init.replaceWith(t.variableDeclaration("var", declarations));
}
|
javascript
|
{
"resource": ""
}
|
|
q23592
|
authorize
|
train
|
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q23593
|
train
|
function () {
var ambiguity_list = AMBIGUITIES[timezone_name],
length = ambiguity_list.length,
i = 0,
tz = ambiguity_list[0];
for (; i < length; i += 1) {
tz = ambiguity_list[i];
if (jstz.date_is_dst(jstz.dst_start_for(tz))) {
timezone_name = tz;
return;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23594
|
redirectToHttps
|
train
|
function redirectToHttps(req, res, target, ssl, log) {
req.url = req._url || req.url; // Get the original url since we are going to redirect.
var targetPort = ssl.redirectPort || ssl.port;
var hostname = req.headers.host.split(':')[0] + ( targetPort ? ':' + targetPort : '' );
var url = 'https://' + path.join(hostname, req.url);
log && log.info('Redirecting %s to %s', path.join(req.headers.host, req.url), url);
//
// We can use 301 for permanent redirect, but its bad for debugging, we may have it as
// a configurable option.
//
res.writeHead(302, { Location: url });
res.end();
}
|
javascript
|
{
"resource": ""
}
|
q23595
|
getFurthestAncestor
|
train
|
function getFurthestAncestor(node) {
var root = node;
while (root.parentNode != null) {
root = root.parentNode;
}
return root;
}
|
javascript
|
{
"resource": ""
}
|
q23596
|
isCollapsedLineBreak
|
train
|
function isCollapsedLineBreak(br) {
if (!isHtmlElement(br, "br")) {
return false;
}
// Add a zwsp after it and see if that changes the height of the nearest
// non-inline parent. Note: this is not actually reliable, because the
// parent might have a fixed height or something.
var ref = br.parentNode;
while (getComputedStyleProperty(ref, "display") == "inline") {
ref = ref.parentNode;
}
var refStyle = ref.hasAttribute("style") ? ref.getAttribute("style") : null;
ref.style.height = "auto";
ref.style.maxHeight = "none";
ref.style.minHeight = "0";
var space = document.createTextNode("\u200b");
var origHeight = ref.offsetHeight;
if (origHeight == 0) {
throw "isCollapsedLineBreak: original height is zero, bug?";
}
br.parentNode.insertBefore(space, br.nextSibling);
var finalHeight = ref.offsetHeight;
space.parentNode.removeChild(space);
if (refStyle === null) {
// Without the setAttribute() line, removeAttribute() doesn't work in
// Chrome 14 dev. I have no idea why.
ref.setAttribute("style", "");
ref.removeAttribute("style");
} else {
ref.setAttribute("style", refStyle);
}
// Allow some leeway in case the zwsp didn't create a whole new line, but
// only made an existing line slightly higher. Firefox 6.0a2 shows this
// behavior when the first line is bold.
return origHeight < finalHeight - 5;
}
|
javascript
|
{
"resource": ""
}
|
q23597
|
getEffectiveCommandValue
|
train
|
function getEffectiveCommandValue(node, context) {
var isElement = (node.nodeType == 1);
// "If neither node nor its parent is an Element, return null."
if (!isElement && (!node.parentNode || node.parentNode.nodeType != 1)) {
return null;
}
// "If node is not an Element, return the effective command value of its parent for command."
if (!isElement) {
return getEffectiveCommandValue(node.parentNode, context);
}
return context.command.getEffectiveValue(node, context);
}
|
javascript
|
{
"resource": ""
}
|
q23598
|
doSubstituteBuildVars
|
train
|
function doSubstituteBuildVars(file, buildVars) {
var contents = fs.readFileSync(file, FILE_ENCODING);
contents = contents.replace(/%%build:([^%]+)%%/g, function(matched, buildVarName) {
return buildVars[buildVarName];
});
// Now do replacements specified by build directives
contents = contents.replace(/\/\*\s?build:replaceWith\((.*?)\)\s?\*\/.*?\*\s?build:replaceEnd\s?\*\//g, "$1");
fs.writeFileSync(file, contents, FILE_ENCODING);
}
|
javascript
|
{
"resource": ""
}
|
q23599
|
isAncestor
|
train
|
function isAncestor(ancestor, descendant) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.