_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q15200
|
train
|
function (point) {
var rect = this.getRect();
var axis = this.getAxis();
var orient = axis.orient;
if (orient === 'horizontal') {
return axis.contain(axis.toLocalCoord(point[0]))
&& (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
}
else {
return axis.contain(axis.toLocalCoord(point[1]))
&& (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15201
|
train
|
function (val) {
var axis = this.getAxis();
var rect = this.getRect();
var pt = [];
var idx = axis.orient === 'horizontal' ? 0 : 1;
if (val instanceof Array) {
val = val[0];
}
pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
return pt;
}
|
javascript
|
{
"resource": ""
}
|
|
q15202
|
train
|
function (data, width, height, normalize, colorFunc, isInRange) {
var brush = this._getBrush();
var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
var r = this.pointSize + this.blurSize;
var canvas = this.canvas;
var ctx = canvas.getContext('2d');
var len = data.length;
canvas.width = width;
canvas.height = height;
for (var i = 0; i < len; ++i) {
var p = data[i];
var x = p[0];
var y = p[1];
var value = p[2];
// calculate alpha using value
var alpha = normalize(value);
// draw with the circle brush with alpha
ctx.globalAlpha = alpha;
ctx.drawImage(brush, x - r, y - r);
}
if (!canvas.width || !canvas.height) {
// Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
// 'CanvasRenderingContext2D': The source height is 0."
return canvas;
}
// colorize the canvas using alpha value and set with gradient
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var pixels = imageData.data;
var offset = 0;
var pixelLen = pixels.length;
var minOpacity = this.minOpacity;
var maxOpacity = this.maxOpacity;
var diffOpacity = maxOpacity - minOpacity;
while (offset < pixelLen) {
var alpha = pixels[offset + 3] / 256;
var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
// Simple optimize to ignore the empty data
if (alpha > 0) {
var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
// Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
pixels[offset++] = gradient[gradientOffset];
pixels[offset++] = gradient[gradientOffset + 1];
pixels[offset++] = gradient[gradientOffset + 2];
pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
}
else {
offset += 4;
}
}
ctx.putImageData(imageData, 0, 0);
return canvas;
}
|
javascript
|
{
"resource": ""
}
|
|
q15203
|
train
|
function () {
var brushCanvas = this._brushCanvas || (this._brushCanvas = zrUtil.createCanvas());
// set brush size
var r = this.pointSize + this.blurSize;
var d = r * 2;
brushCanvas.width = d;
brushCanvas.height = d;
var ctx = brushCanvas.getContext('2d');
ctx.clearRect(0, 0, d, d);
// in order to render shadow without the distinct circle,
// draw the distinct circle in an invisible place,
// and use shadowOffset to draw shadow in the center of the canvas
ctx.shadowOffsetX = d;
ctx.shadowBlur = this.blurSize;
// draw the shadow in black, and use alpha and shadow blur to generate
// color in color map
ctx.shadowColor = '#000';
// draw circle in the left to the canvas
ctx.beginPath();
ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
return brushCanvas;
}
|
javascript
|
{
"resource": ""
}
|
|
q15204
|
train
|
function (data, colorFunc, state) {
var gradientPixels = this._gradientPixels;
var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
var color = [0, 0, 0, 0];
var off = 0;
for (var i = 0; i < 256; i++) {
colorFunc[state](i / 255, true, color);
pixelsSingleState[off++] = color[0];
pixelsSingleState[off++] = color[1];
pixelsSingleState[off++] = color[2];
pixelsSingleState[off++] = color[3];
}
return pixelsSingleState;
}
|
javascript
|
{
"resource": ""
}
|
|
q15205
|
getViewRect
|
train
|
function getViewRect(seriesModel, api) {
return layout.getLayoutRect(
seriesModel.getBoxLayoutParams(), {
width: api.getWidth(),
height: api.getHeight()
}
);
}
|
javascript
|
{
"resource": ""
}
|
q15206
|
computeNodeValues
|
train
|
function computeNodeValues(nodes) {
zrUtil.each(nodes, function (node) {
var value1 = sum(node.outEdges, getEdgeValue);
var value2 = sum(node.inEdges, getEdgeValue);
var value = Math.max(value1, value2);
node.setLayout({value: value}, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q15207
|
computeNodeBreadths
|
train
|
function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
// Used to mark whether the edge is deleted. if it is deleted,
// the value is 0, otherwise it is 1.
var remainEdges = [];
// Storage each node's indegree.
var indegreeArr = [];
//Used to storage the node with indegree is equal to 0.
var zeroIndegrees = [];
var nextTargetNode = [];
var x = 0;
var kx = 0;
for (var i = 0; i < edges.length; i++) {
remainEdges[i] = 1;
}
for (i = 0; i < nodes.length; i++) {
indegreeArr[i] = nodes[i].inEdges.length;
if (indegreeArr[i] === 0) {
zeroIndegrees.push(nodes[i]);
}
}
var maxNodeDepth = -1;
// Traversing nodes using topological sorting to calculate the
// horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
// position of the nodes.
while (zeroIndegrees.length) {
for (var idx = 0; idx < zeroIndegrees.length; idx++) {
var node = zeroIndegrees[idx];
var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
var isItemDepth = item.depth != null && item.depth >= 0;
if (isItemDepth && item.depth > maxNodeDepth) {
maxNodeDepth = item.depth;
}
node.setLayout({depth: isItemDepth ? item.depth : x}, true);
orient === 'vertical'
? node.setLayout({dy: nodeWidth}, true)
: node.setLayout({dx: nodeWidth}, true);
for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
var edge = node.outEdges[edgeIdx];
var indexEdge = edges.indexOf(edge);
remainEdges[indexEdge] = 0;
var targetNode = edge.node2;
var nodeIndex = nodes.indexOf(targetNode);
if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
nextTargetNode.push(targetNode);
}
}
}
++x;
zeroIndegrees = nextTargetNode;
nextTargetNode = [];
}
for (i = 0; i < remainEdges.length; i++) {
if (remainEdges[i] === 1) {
throw new Error('Sankey is a DAG, the original data has cycle!');
}
}
var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
if (nodeAlign && nodeAlign !== 'left') {
adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
}
var kx = orient === 'vertical'
? (height - nodeWidth) / maxDepth
: (width - nodeWidth) / maxDepth;
scaleNodeBreadths(nodes, kx, orient);
}
|
javascript
|
{
"resource": ""
}
|
q15208
|
moveSinksRight
|
train
|
function moveSinksRight(nodes, maxDepth) {
zrUtil.each(nodes, function (node) {
if (!isNodeDepth(node) && !node.outEdges.length) {
node.setLayout({depth: maxDepth}, true);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q15209
|
scaleNodeBreadths
|
train
|
function scaleNodeBreadths(nodes, kx, orient) {
zrUtil.each(nodes, function (node) {
var nodeDepth = node.getLayout().depth * kx;
orient === 'vertical'
? node.setLayout({y: nodeDepth}, true)
: node.setLayout({x: nodeDepth}, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q15210
|
initializeNodeDepth
|
train
|
function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
var minKy = Infinity;
zrUtil.each(nodesByBreadth, function (nodes) {
var n = nodes.length;
var sum = 0;
zrUtil.each(nodes, function (node) {
sum += node.getLayout().value;
});
var ky = orient === 'vertical'
? (width - (n - 1) * nodeGap) / sum
: (height - (n - 1) * nodeGap) / sum;
if (ky < minKy) {
minKy = ky;
}
});
zrUtil.each(nodesByBreadth, function (nodes) {
zrUtil.each(nodes, function (node, i) {
var nodeDy = node.getLayout().value * minKy;
if (orient === 'vertical') {
node.setLayout({x: i}, true);
node.setLayout({dx: nodeDy}, true);
}
else {
node.setLayout({y: i}, true);
node.setLayout({dy: nodeDy}, true);
}
});
});
zrUtil.each(edges, function (edge) {
var edgeDy = +edge.getValue() * minKy;
edge.setLayout({dy: edgeDy}, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q15211
|
relaxRightToLeft
|
train
|
function relaxRightToLeft(nodesByBreadth, alpha, orient) {
zrUtil.each(nodesByBreadth.slice().reverse(), function (nodes) {
zrUtil.each(nodes, function (node) {
if (node.outEdges.length) {
var y = sum(node.outEdges, weightedTarget, orient)
/ sum(node.outEdges, getEdgeValue, orient);
if (orient === 'vertical') {
var nodeX = node.getLayout().x + (y - center(node, orient)) * alpha;
node.setLayout({x: nodeX}, true);
}
else {
var nodeY = node.getLayout().y + (y - center(node, orient)) * alpha;
node.setLayout({y: nodeY}, true);
}
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q15212
|
train
|
function (date) {
date = numberUtil.parseDate(date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? '0' + m : m;
var d = date.getDate();
d = d < 10 ? '0' + d : d;
var day = date.getDay();
day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
return {
y: y,
m: m,
d: d,
day: day,
time: date.getTime(),
formatedDate: y + '-' + m + '-' + d,
date: date
};
}
|
javascript
|
{
"resource": ""
}
|
|
q15213
|
train
|
function (nthWeek, day, range) {
var rangeInfo = this._getRangeInfo(range);
if (nthWeek > rangeInfo.weeks
|| (nthWeek === 0 && day < rangeInfo.fweek)
|| (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
) {
return false;
}
var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
var date = new Date(rangeInfo.start.time);
date.setDate(rangeInfo.start.d + nthDay);
return this.getDateInfo(date);
}
|
javascript
|
{
"resource": ""
}
|
|
q15214
|
train
|
function (axisModel, ecModel, api, payload, force) {
updateAxisPointer(this, axisModel, ecModel, api, payload, false);
}
|
javascript
|
{
"resource": ""
}
|
|
q15215
|
getSymbolMeta
|
train
|
function getSymbolMeta(data, dataIndex, itemModel, opt) {
var layout = data.getItemLayout(dataIndex);
var symbolRepeat = itemModel.get('symbolRepeat');
var symbolClip = itemModel.get('symbolClip');
var symbolPosition = itemModel.get('symbolPosition') || 'start';
var symbolRotate = itemModel.get('symbolRotate');
var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
var isAnimationEnabled = itemModel.isAnimationEnabled();
var symbolMeta = {
dataIndex: dataIndex,
layout: layout,
itemModel: itemModel,
symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
color: data.getItemVisual(dataIndex, 'color'),
symbolClip: symbolClip,
symbolRepeat: symbolRepeat,
symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
symbolPatternSize: symbolPatternSize,
rotation: rotation,
animationModel: isAnimationEnabled ? itemModel : null,
hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
z2: itemModel.getShallow('z', true) || 0
};
prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
prepareSymbolSize(
data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
);
prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
var symbolSize = symbolMeta.symbolSize;
var symbolOffset = itemModel.get('symbolOffset');
if (zrUtil.isArray(symbolOffset)) {
symbolOffset = [
parsePercent(symbolOffset[0], symbolSize[0]),
parsePercent(symbolOffset[1], symbolSize[1])
];
}
prepareLayoutInfo(
itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
opt, symbolMeta
);
return symbolMeta;
}
|
javascript
|
{
"resource": ""
}
|
q15216
|
prepareBarLength
|
train
|
function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
var valueDim = opt.valueDim;
var symbolBoundingData = itemModel.get('symbolBoundingData');
var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
var boundingLength;
if (zrUtil.isArray(symbolBoundingData)) {
var symbolBoundingExtent = [
convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
];
symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
boundingLength = symbolBoundingExtent[pxSignIdx];
}
else if (symbolBoundingData != null) {
boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
}
else if (symbolRepeat) {
boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
}
else {
boundingLength = layout[valueDim.wh];
}
output.boundingLength = boundingLength;
if (symbolRepeat) {
output.repeatCutLength = layout[valueDim.wh];
}
output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
}
|
javascript
|
{
"resource": ""
}
|
q15217
|
createOrUpdateBarRect
|
train
|
function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
var rectShape = zrUtil.extend({}, symbolMeta.barRectShape);
var barRect = bar.__pictorialBarRect;
if (!barRect) {
barRect = bar.__pictorialBarRect = new graphic.Rect({
z2: 2,
shape: rectShape,
silent: true,
style: {
stroke: 'transparent',
fill: 'transparent',
lineWidth: 0
}
});
bar.add(barRect);
}
else {
updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
}
}
|
javascript
|
{
"resource": ""
}
|
q15218
|
centerGraphic
|
train
|
function centerGraphic(rect, boundingRect) {
// Set rect to center, keep width / height ratio.
var aspect = boundingRect.width / boundingRect.height;
var width = rect.height * aspect;
var height;
if (width <= rect.width) {
height = rect.height;
}
else {
width = rect.width;
height = width / aspect;
}
var cx = rect.x + rect.width / 2;
var cy = rect.y + rect.height / 2;
return {
x: cx - width / 2,
y: cy - height / 2,
width: width,
height: height
};
}
|
javascript
|
{
"resource": ""
}
|
q15219
|
setTextStyleCommon
|
train
|
function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
// Consider there will be abnormal when merge hover style to normal style if given default value.
opt = opt || EMPTY_OBJ;
if (opt.isRectText) {
var textPosition = textStyleModel.getShallow('position')
|| (isEmphasis ? null : 'inside');
// 'outside' is not a valid zr textPostion value, but used
// in bar series, and magric type should be considered.
textPosition === 'outside' && (textPosition = 'top');
textStyle.textPosition = textPosition;
textStyle.textOffset = textStyleModel.getShallow('offset');
var labelRotate = textStyleModel.getShallow('rotate');
labelRotate != null && (labelRotate *= Math.PI / 180);
textStyle.textRotation = labelRotate;
textStyle.textDistance = zrUtil.retrieve2(
textStyleModel.getShallow('distance'), isEmphasis ? null : 5
);
}
var ecModel = textStyleModel.ecModel;
var globalTextStyle = ecModel && ecModel.option.textStyle;
// Consider case:
// {
// data: [{
// value: 12,
// label: {
// rich: {
// // no 'a' here but using parent 'a'.
// }
// }
// }],
// rich: {
// a: { ... }
// }
// }
var richItemNames = getRichItemNames(textStyleModel);
var richResult;
if (richItemNames) {
richResult = {};
for (var name in richItemNames) {
if (richItemNames.hasOwnProperty(name)) {
// Cascade is supported in rich.
var richTextStyle = textStyleModel.getModel(['rich', name]);
// In rich, never `disableBox`.
// FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
// the default color `'blue'` will not be adopted if no color declared in `rich`.
// That might confuses users. So probably we should put `textStyleModel` as the
// root ancestor of the `richTextStyle`. But that would be a break change.
setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
}
}
}
textStyle.rich = richResult;
setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
if (opt.forceRich && !opt.textStyle) {
opt.textStyle = {};
}
return textStyle;
}
|
javascript
|
{
"resource": ""
}
|
q15220
|
applyDefaultTextStyle
|
train
|
function applyDefaultTextStyle(textStyle) {
var opt = textStyle.insideRollbackOpt;
// Only `insideRollbackOpt` created (in `setTextStyleCommon`),
// applyDefaultTextStyle works.
if (!opt || textStyle.textFill != null) {
return;
}
var useInsideStyle = opt.useInsideStyle;
var textPosition = textStyle.insideRawTextPosition;
var insideRollback;
var autoColor = opt.autoColor;
if (useInsideStyle !== false
&& (useInsideStyle === true
|| (opt.isRectText
&& textPosition
// textPosition can be [10, 30]
&& typeof textPosition === 'string'
&& textPosition.indexOf('inside') >= 0
)
)
) {
insideRollback = {
textFill: null,
textStroke: textStyle.textStroke,
textStrokeWidth: textStyle.textStrokeWidth
};
textStyle.textFill = '#fff';
// Consider text with #fff overflow its container.
if (textStyle.textStroke == null) {
textStyle.textStroke = autoColor;
textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
}
}
else if (autoColor != null) {
insideRollback = {textFill: null};
textStyle.textFill = autoColor;
}
// Always set `insideRollback`, for clearing previous.
if (insideRollback) {
textStyle.insideRollback = insideRollback;
}
}
|
javascript
|
{
"resource": ""
}
|
q15221
|
groupSeries
|
train
|
function groupSeries(ecModel) {
var seriesGroupByCategoryAxis = {};
var otherSeries = [];
var meta = [];
ecModel.eachRawSeries(function (seriesModel) {
var coordSys = seriesModel.coordinateSystem;
if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
var baseAxis = coordSys.getBaseAxis();
if (baseAxis.type === 'category') {
var key = baseAxis.dim + '_' + baseAxis.index;
if (!seriesGroupByCategoryAxis[key]) {
seriesGroupByCategoryAxis[key] = {
categoryAxis: baseAxis,
valueAxis: coordSys.getOtherAxis(baseAxis),
series: []
};
meta.push({
axisDim: baseAxis.dim,
axisIndex: baseAxis.index
});
}
seriesGroupByCategoryAxis[key].series.push(seriesModel);
}
else {
otherSeries.push(seriesModel);
}
}
else {
otherSeries.push(seriesModel);
}
});
return {
seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
other: otherSeries,
meta: meta
};
}
|
javascript
|
{
"resource": ""
}
|
q15222
|
assembleSeriesWithCategoryAxis
|
train
|
function assembleSeriesWithCategoryAxis(series) {
var tables = [];
zrUtil.each(series, function (group, key) {
var categoryAxis = group.categoryAxis;
var valueAxis = group.valueAxis;
var valueAxisDim = valueAxis.dim;
var headers = [' '].concat(zrUtil.map(group.series, function (series) {
return series.name;
}));
var columns = [categoryAxis.model.getCategories()];
zrUtil.each(group.series, function (series) {
columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
return val;
}));
});
// Assemble table content
var lines = [headers.join(ITEM_SPLITER)];
for (var i = 0; i < columns[0].length; i++) {
var items = [];
for (var j = 0; j < columns.length; j++) {
items.push(columns[j][i]);
}
lines.push(items.join(ITEM_SPLITER));
}
tables.push(lines.join('\n'));
});
return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
}
|
javascript
|
{
"resource": ""
}
|
q15223
|
assembleOtherSeries
|
train
|
function assembleOtherSeries(series) {
return zrUtil.map(series, function (series) {
var data = series.getRawData();
var lines = [series.name];
var vals = [];
data.each(data.dimensions, function () {
var argLen = arguments.length;
var dataIndex = arguments[argLen - 1];
var name = data.getName(dataIndex);
for (var i = 0; i < argLen - 1; i++) {
vals[i] = arguments[i];
}
lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
});
return lines.join('\n');
}).join('\n\n' + BLOCK_SPLITER + '\n\n');
}
|
javascript
|
{
"resource": ""
}
|
q15224
|
isTSVFormat
|
train
|
function isTSVFormat(block) {
// Simple method to find out if a block is tsv format
var firstLine = block.slice(0, block.indexOf('\n'));
if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
return true;
}
}
|
javascript
|
{
"resource": ""
}
|
q15225
|
cloneListForMapAndSample
|
train
|
function cloneListForMapAndSample(original, excludeDimensions) {
var allDimensions = original.dimensions;
var list = new List(
zrUtil.map(allDimensions, original.getDimensionInfo, original),
original.hostModel
);
// FIXME If needs stackedOn, value may already been stacked
transferProperties(list, original);
var storage = list._storage = {};
var originalStorage = original._storage;
// Init storage
for (var i = 0; i < allDimensions.length; i++) {
var dim = allDimensions[i];
if (originalStorage[dim]) {
// Notice that we do not reset invertedIndicesMap here, becuase
// there is no scenario of mapping or sampling ordinal dimension.
if (zrUtil.indexOf(excludeDimensions, dim) >= 0) {
storage[dim] = cloneDimStore(originalStorage[dim]);
list._rawExtent[dim] = getInitialExtent();
list._extent[dim] = null;
}
else {
// Direct reference for other dimensions
storage[dim] = originalStorage[dim];
}
}
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
q15226
|
train
|
function (x, y, width, height) {
this._rect = new BoundingRect(x, y, width, height);
return this._rect;
}
|
javascript
|
{
"resource": ""
}
|
|
q15227
|
train
|
function (x, y, width, height) {
var rect = this.getBoundingRect();
var rawTransform = this._rawTransformable;
rawTransform.transform = rect.calculateTransform(
new BoundingRect(x, y, width, height)
);
rawTransform.decomposeTransform();
this._updateTransform();
}
|
javascript
|
{
"resource": ""
}
|
|
q15228
|
train
|
function () {
// Rect before any transform
var rawRect = this.getBoundingRect();
var cx = rawRect.x + rawRect.width / 2;
var cy = rawRect.y + rawRect.height / 2;
return [cx, cy];
}
|
javascript
|
{
"resource": ""
}
|
|
q15229
|
train
|
function () {
var roamTransformable = this._roamTransformable;
var rawTransformable = this._rawTransformable;
rawTransformable.parent = roamTransformable;
roamTransformable.updateTransform();
rawTransformable.updateTransform();
matrix.copy(this.transform || (this.transform = []), rawTransformable.transform || matrix.create());
this._rawTransform = rawTransformable.getLocalTransform();
this.invTransform = this.invTransform || [];
matrix.invert(this.invTransform, this.transform);
this.decomposeTransform();
}
|
javascript
|
{
"resource": ""
}
|
|
q15230
|
train
|
function (node, startAngle) {
if (!node) {
return;
}
var endAngle = startAngle;
// Render self
if (node !== virtualRoot) {
// Tree node is virtual, so it doesn't need to be drawn
var value = node.getValue();
var angle = (sum === 0 && stillShowZeroSum)
? unitRadian : (value * unitRadian);
if (angle < minAngle) {
angle = minAngle;
restAngle -= minAngle;
}
else {
valueSumLargerThanMinAngle += value;
}
endAngle = startAngle + dir * angle;
var depth = node.depth - rootDepth
- (renderRollupNode ? -1 : 1);
var rStart = r0 + rPerLevel * depth;
var rEnd = r0 + rPerLevel * (depth + 1);
var itemModel = node.getModel();
if (itemModel.get('r0') != null) {
rStart = parsePercent(itemModel.get('r0'), size / 2);
}
if (itemModel.get('r') != null) {
rEnd = parsePercent(itemModel.get('r'), size / 2);
}
node.setLayout({
angle: angle,
startAngle: startAngle,
endAngle: endAngle,
clockwise: clockwise,
cx: cx,
cy: cy,
r0: rStart,
r: rEnd
});
}
// Render children
if (node.children && node.children.length) {
// currentAngle = startAngle;
var siblingAngle = 0;
zrUtil.each(node.children, function (node) {
siblingAngle += renderNode(node, startAngle + siblingAngle);
});
}
return endAngle - startAngle;
}
|
javascript
|
{
"resource": ""
}
|
|
q15231
|
initChildren
|
train
|
function initChildren(node, isAsc) {
var children = node.children || [];
node.children = sort(children, isAsc);
// Init children recursively
if (children.length) {
zrUtil.each(node.children, function (child) {
initChildren(child, isAsc);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q15232
|
sort
|
train
|
function sort(children, sortOrder) {
if (typeof sortOrder === 'function') {
return children.sort(sortOrder);
}
else {
var isAsc = sortOrder === 'asc';
return children.sort(function (a, b) {
var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
return diff === 0
? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
: diff;
});
}
}
|
javascript
|
{
"resource": ""
}
|
q15233
|
initChildren
|
train
|
function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
var viewChildren = node.children || [];
var orderBy = options.sort;
orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
// leafDepth has higher priority.
if (hideChildren && !overLeafDepth) {
return (node.viewChildren = []);
}
// Sort children, order by desc.
viewChildren = zrUtil.filter(viewChildren, function (child) {
return !child.isRemoved();
});
sort(viewChildren, orderBy);
var info = statistic(nodeModel, viewChildren, orderBy);
if (info.sum === 0) {
return (node.viewChildren = []);
}
info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
if (info.sum === 0) {
return (node.viewChildren = []);
}
// Set area to each child.
for (var i = 0, len = viewChildren.length; i < len; i++) {
var area = viewChildren[i].getValue() / info.sum * totalArea;
// Do not use setLayout({...}, true), because it is needed to clear last layout.
viewChildren[i].setLayout({area: area});
}
if (overLeafDepth) {
viewChildren.length && node.setLayout({isLeafRoot: true}, true);
viewChildren.length = 0;
}
node.viewChildren = viewChildren;
node.setLayout({dataExtent: info.dataExtent}, true);
return viewChildren;
}
|
javascript
|
{
"resource": ""
}
|
q15234
|
filterByThreshold
|
train
|
function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
// visibleMin is not supported yet when no option.sort.
if (!orderBy) {
return sum;
}
var visibleMin = nodeModel.get('visibleMin');
var len = orderedChildren.length;
var deletePoint = len;
// Always travel from little value to big value.
for (var i = len - 1; i >= 0; i--) {
var value = orderedChildren[
orderBy === 'asc' ? len - i - 1 : i
].getValue();
if (value / sum * totalArea < visibleMin) {
deletePoint = i;
sum -= value;
}
}
orderBy === 'asc'
? orderedChildren.splice(0, len - deletePoint)
: orderedChildren.splice(deletePoint, len - deletePoint);
return sum;
}
|
javascript
|
{
"resource": ""
}
|
q15235
|
position
|
train
|
function position(row, rowFixedLength, rect, halfGapWidth, flush) {
// When rowFixedLength === rect.width,
// it is horizontal subdivision,
// rowFixedLength is the width of the subdivision,
// rowOtherLength is the height of the subdivision,
// and nodes will be positioned from left to right.
// wh[idx0WhenH] means: when horizontal,
// wh[idx0WhenH] => wh[0] => 'width'.
// xy[idx1WhenH] => xy[1] => 'y'.
var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
var idx1WhenH = 1 - idx0WhenH;
var xy = ['x', 'y'];
var wh = ['width', 'height'];
var last = rect[xy[idx0WhenH]];
var rowOtherLength = rowFixedLength
? row.area / rowFixedLength : 0;
if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
}
for (var i = 0, rowLen = row.length; i < rowLen; i++) {
var node = row[i];
var nodeLayout = {};
var step = rowOtherLength
? node.getLayout().area / rowOtherLength : 0;
var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax(rowOtherLength - 2 * halfGapWidth, 0);
// We use Math.max/min to avoid negative width/height when considering gap width.
var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax(modWH - 2 * halfGapWidth, 0);
nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin(halfGapWidth, wh1 / 2);
nodeLayout[xy[idx0WhenH]] = last + mathMin(halfGapWidth, wh0 / 2);
last += modWH;
node.setLayout(nodeLayout, true);
}
rect[xy[idx1WhenH]] += rowOtherLength;
rect[wh[idx1WhenH]] -= rowOtherLength;
}
|
javascript
|
{
"resource": ""
}
|
q15236
|
calculateRootPosition
|
train
|
function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
if (rootRect) {
return {x: rootRect.x, y: rootRect.y};
}
var defaultPosition = {x: 0, y: 0};
if (!targetInfo) {
return defaultPosition;
}
// If targetInfo is fetched by 'retrieveTargetInfo',
// old tree and new tree are the same tree,
// so the node still exists and we can visit it.
var targetNode = targetInfo.node;
var layout = targetNode.getLayout();
if (!layout) {
return defaultPosition;
}
// Transform coord from local to container.
var targetCenter = [layout.width / 2, layout.height / 2];
var node = targetNode;
while (node) {
var nodeLayout = node.getLayout();
targetCenter[0] += nodeLayout.x;
targetCenter[1] += nodeLayout.y;
node = node.parentNode;
}
return {
x: layoutInfo.width / 2 - targetCenter[0],
y: layoutInfo.height / 2 - targetCenter[1]
};
}
|
javascript
|
{
"resource": ""
}
|
q15237
|
prunning
|
train
|
function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
var nodeLayout = node.getLayout();
var nodeInViewAbovePath = viewAbovePath[depth];
var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
if (
(nodeInViewAbovePath && !isAboveViewRoot)
|| (depth === viewAbovePath.length && node !== viewRoot)
) {
return;
}
node.setLayout({
// isInView means: viewRoot sub tree + viewAbovePath
isInView: true,
// invisible only means: outside view clip so that the node can not
// see but still layout for animation preparation but not render.
invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
isAboveViewRoot: isAboveViewRoot
}, true);
// Transform to child coordinate.
var childClipRect = new BoundingRect(
clipRect.x - nodeLayout.x,
clipRect.y - nodeLayout.y,
clipRect.width,
clipRect.height
);
each(node.viewChildren || [], function (child) {
prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
});
}
|
javascript
|
{
"resource": ""
}
|
q15238
|
executeShifts
|
train
|
function executeShifts(node) {
var children = node.children;
var n = children.length;
var shift = 0;
var change = 0;
while (--n >= 0) {
var child = children[n];
child.hierNode.prelim += shift;
child.hierNode.modifier += shift;
change += child.hierNode.change;
shift += child.hierNode.shift + change;
}
}
|
javascript
|
{
"resource": ""
}
|
q15239
|
nextRight
|
train
|
function nextRight(node) {
var children = node.children;
return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
}
|
javascript
|
{
"resource": ""
}
|
q15240
|
elSetState
|
train
|
function elSetState(el, state, highlightDigit) {
if (el) {
el.trigger(state, highlightDigit);
if (el.isGroup
// Simple optimize.
&& !graphicUtil.isHighDownDispatcher(el)
) {
for (var i = 0, len = el.childCount(); i < len; i++) {
elSetState(el.childAt(i), state, highlightDigit);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q15241
|
train
|
function (parallelModel, ecModel, api) {
var dimensions = parallelModel.dimensions;
var parallelAxisIndex = parallelModel.parallelAxisIndex;
each(dimensions, function (dim, idx) {
var axisIndex = parallelAxisIndex[idx];
var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
var axis = this._axesMap.set(dim, new ParallelAxis(
dim,
axisHelper.createScaleByModel(axisModel),
[0, 0],
axisModel.get('type'),
axisIndex
));
var isCategory = axis.type === 'category';
axis.onBand = isCategory && axisModel.get('boundaryGap');
axis.inverse = axisModel.get('inverse');
// Injection
axisModel.axis = axis;
axis.model = axisModel;
axis.coordinateSystem = axisModel.coordinateSystem = this;
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q15242
|
train
|
function (parallelModel, ecModel) {
ecModel.eachSeries(function (seriesModel) {
if (!parallelModel.contains(seriesModel, ecModel)) {
return;
}
var data = seriesModel.getData();
each(this.dimensions, function (dim) {
var axis = this._axesMap.get(dim);
axis.scale.unionExtentFromData(data, data.mapDimension(dim));
axisHelper.niceScaleExtent(axis.scale, axis.model);
}, this);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q15243
|
train
|
function (parallelModel, api) {
this._rect = layoutUtil.getLayoutRect(
parallelModel.getBoxLayoutParams(),
{
width: api.getWidth(),
height: api.getHeight()
}
);
this._layoutAxes();
}
|
javascript
|
{
"resource": ""
}
|
|
q15244
|
train
|
function (data, callback, start, end) {
start == null && (start = 0);
end == null && (end = data.count());
var axesMap = this._axesMap;
var dimensions = this.dimensions;
var dataDimensions = [];
var axisModels = [];
zrUtil.each(dimensions, function (axisDim) {
dataDimensions.push(data.mapDimension(axisDim));
axisModels.push(axesMap.get(axisDim).model);
});
var hasActiveSet = this.hasAxisBrushed();
for (var dataIndex = start; dataIndex < end; dataIndex++) {
var activeState;
if (!hasActiveSet) {
activeState = 'normal';
}
else {
activeState = 'active';
var values = data.getValues(dataDimensions, dataIndex);
for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
var state = axisModels[j].getActiveState(values[j]);
if (state === 'inactive') {
activeState = 'inactive';
break;
}
}
}
callback(activeState, dataIndex);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15245
|
train
|
function () {
var dimensions = this.dimensions;
var axesMap = this._axesMap;
var hasActiveSet = false;
for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
hasActiveSet = true;
}
}
return hasActiveSet;
}
|
javascript
|
{
"resource": ""
}
|
|
q15246
|
train
|
function (opt, ignoreUpdateRangeUsg) {
var option = this.option;
each([['start', 'startValue'], ['end', 'endValue']], function (names) {
// If only one of 'start' and 'startValue' is not null/undefined, the other
// should be cleared, which enable clear the option.
// If both of them are not set, keep option with the original value, which
// enable use only set start but not set end when calling `dispatchAction`.
// The same as 'end' and 'endValue'.
if (opt[names[0]] != null || opt[names[1]] != null) {
option[names[0]] = opt[names[0]];
option[names[1]] = opt[names[1]];
}
}, this);
!ignoreUpdateRangeUsg && updateRangeUse(this, opt);
}
|
javascript
|
{
"resource": ""
}
|
|
q15247
|
resizePolar
|
train
|
function resizePolar(polar, polarModel, api) {
var center = polarModel.get('center');
var width = api.getWidth();
var height = api.getHeight();
polar.cx = parsePercent(center[0], width);
polar.cy = parsePercent(center[1], height);
var radiusAxis = polar.getRadiusAxis();
var size = Math.min(width, height) / 2;
var radius = parsePercent(polarModel.get('radius'), size);
radiusAxis.inverse
? radiusAxis.setExtent(radius, 0)
: radiusAxis.setExtent(0, radius);
}
|
javascript
|
{
"resource": ""
}
|
q15248
|
setAxis
|
train
|
function setAxis(axis, axisModel) {
axis.type = axisModel.get('type');
axis.scale = createScaleByModel(axisModel);
axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
axis.inverse = axisModel.get('inverse');
if (axisModel.mainType === 'angleAxis') {
axis.inverse ^= axisModel.get('clockwise');
var startAngle = axisModel.get('startAngle');
axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
}
// Inject axis instance
axisModel.axis = axis;
axis.model = axisModel;
}
|
javascript
|
{
"resource": ""
}
|
q15249
|
createParallelIfNeeded
|
train
|
function createParallelIfNeeded(option) {
if (option.parallel) {
return;
}
var hasParallelSeries = false;
zrUtil.each(option.series, function (seriesOpt) {
if (seriesOpt && seriesOpt.type === 'parallel') {
hasParallelSeries = true;
}
});
if (hasParallelSeries) {
option.parallel = [{}];
}
}
|
javascript
|
{
"resource": ""
}
|
q15250
|
updateCache
|
train
|
function updateCache(dataIndexInside) {
dataIndexInside == null && (dataIndexInside = currDataIndexInside);
if (currDirty) {
currItemModel = data.getItemModel(dataIndexInside);
currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
currVisualColor = data.getItemVisual(dataIndexInside, 'color');
currDirty = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q15251
|
train
|
function () {
var handle = this._handle;
if (!handle) {
return;
}
var payloadInfo = this._payloadInfo;
var axisModel = this._axisModel;
this._api.dispatchAction({
type: 'updateAxisPointer',
x: payloadInfo.cursorPoint[0],
y: payloadInfo.cursorPoint[1],
tooltipOption: payloadInfo.tooltipOption,
axesInfo: [{
axisDim: axisModel.axis.dim,
axisIndex: axisModel.componentIndex
}]
});
}
|
javascript
|
{
"resource": ""
}
|
|
q15252
|
getLabelDefaultText
|
train
|
function getLabelDefaultText(idx, opt) {
return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
}
|
javascript
|
{
"resource": ""
}
|
q15253
|
train
|
function (activeState) {
var coordSys = this.coordinateSystem;
var data = this.getData();
var indices = [];
coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
if (activeState === theActiveState) {
indices.push(data.getRawIndex(dataIndex));
}
});
return indices;
}
|
javascript
|
{
"resource": ""
}
|
|
q15254
|
getScales
|
train
|
function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
var sizeCurr = getSize(xyMinMaxCurr);
var sizeOrigin = getSize(xyMinMaxOrigin);
var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
|
javascript
|
{
"resource": ""
}
|
q15255
|
converDataValue
|
train
|
function converDataValue(value, dimInfo) {
// Performance sensitive.
var dimType = dimInfo && dimInfo.type;
if (dimType === 'ordinal') {
// If given value is a category string
var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
return ordinalMeta
? ordinalMeta.parseAndCollect(value)
: value;
}
if (dimType === 'time'
// spead up when using timestamp
&& typeof value !== 'number'
&& value != null
&& value !== '-'
) {
value = +parseDate(value);
}
// dimType defaults 'number'.
// If dimType is not ordinal and value is null or undefined or NaN or '-',
// parse to NaN.
return (value == null || value === '')
? NaN
// If string (like '-'), using '+' parse to NaN
// If object, also parse to NaN
: +value;
}
|
javascript
|
{
"resource": ""
}
|
q15256
|
train
|
function (condition) {
var mainType = condition.mainType;
if (!mainType) {
return [];
}
var index = condition.index;
var id = condition.id;
var name = condition.name;
var cpts = this._componentsMap.get(mainType);
if (!cpts || !cpts.length) {
return [];
}
var result;
if (index != null) {
if (!isArray(index)) {
index = [index];
}
result = filter(map(index, function (idx) {
return cpts[idx];
}), function (val) {
return !!val;
});
}
else if (id != null) {
var isIdArray = isArray(id);
result = filter(cpts, function (cpt) {
return (isIdArray && indexOf(id, cpt.id) >= 0)
|| (!isIdArray && cpt.id === id);
});
}
else if (name != null) {
var isNameArray = isArray(name);
result = filter(cpts, function (cpt) {
return (isNameArray && indexOf(name, cpt.name) >= 0)
|| (!isNameArray && cpt.name === name);
});
}
else {
// Return all components with mainType
result = cpts.slice();
}
return filterBySubType(result, condition);
}
|
javascript
|
{
"resource": ""
}
|
|
q15257
|
train
|
function (condition) {
var query = condition.query;
var mainType = condition.mainType;
var queryCond = getQueryCond(query);
var result = queryCond
? this.queryComponents(queryCond)
: this._componentsMap.get(mainType);
return doFilter(filterBySubType(result, condition));
function getQueryCond(q) {
var indexAttr = mainType + 'Index';
var idAttr = mainType + 'Id';
var nameAttr = mainType + 'Name';
return q && (
q[indexAttr] != null
|| q[idAttr] != null
|| q[nameAttr] != null
)
? {
mainType: mainType,
// subType will be filtered finally.
index: q[indexAttr],
id: q[idAttr],
name: q[nameAttr]
}
: null;
}
function doFilter(res) {
return condition.filter
? filter(res, condition.filter)
: res;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15258
|
train
|
function (cb, context) {
assertSeriesInitialized(this);
each(this._seriesIndices, function (rawSeriesIndex) {
var series = this._componentsMap.get('series')[rawSeriesIndex];
cb.call(context, series, rawSeriesIndex);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
|
q15259
|
train
|
function (targetNode, layoutParam, textStyleModel) {
for (var node = targetNode; node; node = node.parentNode) {
var text = node.getModel().get('name');
var textRect = textStyleModel.getTextRect(text);
var itemWidth = Math.max(
textRect.width + TEXT_PADDING * 2,
layoutParam.emptyItemWidth
);
layoutParam.totalWidth += itemWidth + ITEM_GAP;
layoutParam.renderList.push({node: node, text: text, width: itemWidth});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15260
|
packEventData
|
train
|
function packEventData(el, seriesModel, itemNode) {
el.eventData = {
componentType: 'series',
componentSubType: 'treemap',
componentIndex: seriesModel.componentIndex,
seriesIndex: seriesModel.componentIndex,
seriesName: seriesModel.name,
seriesType: 'treemap',
selfType: 'breadcrumb', // Distinguish with click event on treemap node.
nodeData: {
dataIndex: itemNode && itemNode.dataIndex,
name: itemNode && itemNode.name
},
treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
};
}
|
javascript
|
{
"resource": ""
}
|
q15261
|
train
|
function (opt) {
var dataExtent = this._dataExtent;
var axisModel = this.getAxisModel();
var scale = axisModel.axis.scale;
var rangePropMode = this._dataZoomModel.getRangePropMode();
var percentExtent = [0, 100];
var percentWindow = [];
var valueWindow = [];
var hasPropModeValue;
each(['start', 'end'], function (prop, idx) {
var boundPercent = opt[prop];
var boundValue = opt[prop + 'Value'];
// Notice: dataZoom is based either on `percentProp` ('start', 'end') or
// on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
// but not min/max of axis, which will be calculated by data window then).
// The former one is suitable for cases that a dataZoom component controls multiple
// axes with different unit or extent, and the latter one is suitable for accurate
// zoom by pixel (e.g., in dataZoomSelect).
// we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
// only when setOption or dispatchAction, otherwise it remains its original value.
// (Why not only record `percentProp` and always map to `valueProp`? Because
// the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
// `valueProp`. consider two axes constrolled by one dataZoom. They have different
// data extent. All of values that are overflow the `dataExtent` will be calculated
// to percent '100%').
if (rangePropMode[idx] === 'percent') {
boundPercent == null && (boundPercent = percentExtent[idx]);
// Use scale.parse to math round for category or time axis.
boundValue = scale.parse(numberUtil.linearMap(
boundPercent, percentExtent, dataExtent
));
}
else {
hasPropModeValue = true;
boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue);
// Calculating `percent` from `value` may be not accurate, because
// This calculation can not be inversed, because all of values that
// are overflow the `dataExtent` will be calculated to percent '100%'
boundPercent = numberUtil.linearMap(
boundValue, dataExtent, percentExtent
);
}
// valueWindow[idx] = round(boundValue);
// percentWindow[idx] = round(boundPercent);
valueWindow[idx] = boundValue;
percentWindow[idx] = boundPercent;
});
asc(valueWindow);
asc(percentWindow);
// The windows from user calling of `dispatchAction` might be out of the extent,
// or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
// by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
// where API is able to initialize/modify the window size even though `zoomLock`
// specified.
var spans = this._minMaxSpan;
hasPropModeValue
? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false)
: restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
var suffix = toValue ? 'Span' : 'ValueSpan';
sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
for (var i = 0; i < 2; i++) {
toWindow[i] = numberUtil.linearMap(fromWindow[i], fromExtent, toExtent, true);
toValue && (toWindow[i] = scale.parse(toWindow[i]));
}
}
return {
valueWindow: valueWindow,
percentWindow: percentWindow
};
}
|
javascript
|
{
"resource": ""
}
|
|
q15262
|
prepareView
|
train
|
function prepareView(ecIns, type, ecModel, scheduler) {
var isComponent = type === 'component';
var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
var zr = ecIns._zr;
var api = ecIns._api;
for (var i = 0; i < viewList.length; i++) {
viewList[i].__alive = false;
}
isComponent
? ecModel.eachComponent(function (componentType, model) {
componentType !== 'series' && doPrepare(model);
})
: ecModel.eachSeries(doPrepare);
function doPrepare(model) {
// Consider: id same and type changed.
var viewId = '_ec_' + model.id + '_' + model.type;
var view = viewMap[viewId];
if (!view) {
var classType = parseClassType(model.type);
var Clazz = isComponent
? ComponentView.getClass(classType.main, classType.sub)
: ChartView.getClass(classType.sub);
if (__DEV__) {
assert(Clazz, classType.sub + ' does not exist.');
}
view = new Clazz();
view.init(ecModel, api);
viewMap[viewId] = view;
viewList.push(view);
zr.add(view.group);
}
model.__viewId = view.__id = viewId;
view.__alive = true;
view.__model = model;
view.group.__ecComponentInfo = {
mainType: model.mainType,
index: model.componentIndex
};
!isComponent && scheduler.prepareView(view, model, ecModel, api);
}
for (var i = 0; i < viewList.length;) {
var view = viewList[i];
if (!view.__alive) {
!isComponent && view.renderTask.dispose();
zr.remove(view.group);
view.dispose(ecModel, api);
viewList.splice(i, 1);
delete viewMap[view.__id];
view.__id = view.group.__ecComponentInfo = null;
}
else {
i++;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q15263
|
renderSeries
|
train
|
function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
// Render all charts
var scheduler = ecIns._scheduler;
var unfinished;
ecModel.eachSeries(function (seriesModel) {
var chartView = ecIns._chartsMap[seriesModel.__viewId];
chartView.__alive = true;
var renderTask = chartView.renderTask;
scheduler.updatePayload(renderTask, payload);
if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
renderTask.dirty();
}
unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
chartView.group.silent = !!seriesModel.get('silent');
updateZ(seriesModel, chartView);
updateBlend(seriesModel, chartView);
});
scheduler.unfinished |= unfinished;
// If use hover layer
updateHoverLayerStatus(ecIns._zr, ecModel);
// Add aria
aria(ecIns._zr.dom, ecModel);
}
|
javascript
|
{
"resource": ""
}
|
q15264
|
updateBlend
|
train
|
function updateBlend(seriesModel, chartView) {
var blendMode = seriesModel.get('blendMode') || null;
if (__DEV__) {
if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
console.warn('Only canvas support blendMode');
}
}
chartView.group.traverse(function (el) {
// FIXME marker and other components
if (!el.isGroup) {
// Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
if (el.style.blend !== blendMode) {
el.setStyle('blend', blendMode);
}
}
if (el.eachPendingDisplayable) {
el.eachPendingDisplayable(function (displayable) {
displayable.setStyle('blend', blendMode);
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q15265
|
themeRiverLayout
|
train
|
function themeRiverLayout(data, seriesModel, height) {
if (!data.count()) {
return;
}
var coordSys = seriesModel.coordinateSystem;
// the data in each layer are organized into a series.
var layerSeries = seriesModel.getLayerSeries();
// the points in each layer.
var timeDim = data.mapDimension('single');
var valueDim = data.mapDimension('value');
var layerPoints = zrUtil.map(layerSeries, function (singleLayer) {
return zrUtil.map(singleLayer.indices, function (idx) {
var pt = coordSys.dataToPoint(data.get(timeDim, idx));
pt[1] = data.get(valueDim, idx);
return pt;
});
});
var base = computeBaseline(layerPoints);
var baseLine = base.y0;
var ky = height / base.max;
// set layout information for each item.
var n = layerSeries.length;
var m = layerSeries[0].indices.length;
var baseY0;
for (var j = 0; j < m; ++j) {
baseY0 = baseLine[j] * ky;
data.setItemLayout(layerSeries[0].indices[j], {
layerIndex: 0,
x: layerPoints[0][j][0],
y0: baseY0,
y: layerPoints[0][j][1] * ky
});
for (var i = 1; i < n; ++i) {
baseY0 += layerPoints[i - 1][j][1] * ky;
data.setItemLayout(layerSeries[i].indices[j], {
layerIndex: i,
x: layerPoints[i][j][0],
y0: baseY0,
y: layerPoints[i][j][1] * ky
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q15266
|
computeBaseline
|
train
|
function computeBaseline(data) {
var layerNum = data.length;
var pointNum = data[0].length;
var sums = [];
var y0 = [];
var max = 0;
var temp;
var base = {};
for (var i = 0; i < pointNum; ++i) {
for (var j = 0, temp = 0; j < layerNum; ++j) {
temp += data[j][i][1];
}
if (temp > max) {
max = temp;
}
sums.push(temp);
}
for (var k = 0; k < pointNum; ++k) {
y0[k] = (max - sums[k]) / 2;
}
max = 0;
for (var l = 0; l < pointNum; ++l) {
var sum = sums[l] + y0[l];
if (sum > max) {
max = sum;
}
}
base.y0 = y0;
base.max = max;
return base;
}
|
javascript
|
{
"resource": ""
}
|
q15267
|
train
|
function (ecModel, api) {
/**
* @private
* @type {module:echarts/data/Tree}
*/
this._oldTree;
/**
* @private
* @type {module:zrender/container/Group}
*/
this._mainGroup = new graphic.Group();
/**
* @private
* @type {module:echarts/componet/helper/RoamController}
*/
this._controller = new RoamController(api.getZr());
this._controllerHost = {target: this.group};
this.group.add(this._mainGroup);
}
|
javascript
|
{
"resource": ""
}
|
|
q15268
|
doGuessOrdinal
|
train
|
function doGuessOrdinal(
data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
) {
var result;
// Experience value.
var maxLoop = 5;
if (isTypedArray(data)) {
return false;
}
// When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
// always exists in source.
var dimName;
if (dimensionsDefine) {
dimName = dimensionsDefine[dimIndex];
dimName = isObject(dimName) ? dimName.name : dimName;
}
if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
var sample = data[dimIndex];
for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
if ((result = detectValue(sample[startIndex + i])) != null) {
return result;
}
}
}
else {
for (var i = 0; i < data.length && i < maxLoop; i++) {
var row = data[startIndex + i];
if (row && (result = detectValue(row[dimIndex])) != null) {
return result;
}
}
}
}
else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
if (!dimName) {
return;
}
for (var i = 0; i < data.length && i < maxLoop; i++) {
var item = data[i];
if (item && (result = detectValue(item[dimName])) != null) {
return result;
}
}
}
else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
if (!dimName) {
return;
}
var sample = data[dimName];
if (!sample || isTypedArray(sample)) {
return false;
}
for (var i = 0; i < sample.length && i < maxLoop; i++) {
if ((result = detectValue(sample[i])) != null) {
return result;
}
}
}
else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
for (var i = 0; i < data.length && i < maxLoop; i++) {
var item = data[i];
var val = getDataItemValue(item);
if (!isArray(val)) {
return false;
}
if ((result = detectValue(val[dimIndex])) != null) {
return result;
}
}
}
function detectValue(val) {
// Consider usage convenience, '1', '2' will be treated as "number".
// `isFinit('')` get `true`.
if (val != null && isFinite(val) && val !== '') {
return false;
}
else if (isString(val) && val !== '-') {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q15269
|
train
|
function (tooltipModel, ecModel, api, payload) {
var seriesIndex = payload.seriesIndex;
var dataIndex = payload.dataIndex;
var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
return;
}
var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
if (!seriesModel) {
return;
}
var data = seriesModel.getData();
var tooltipModel = buildTooltipModel([
data.getItemModel(dataIndex),
seriesModel,
(seriesModel.coordinateSystem || {}).model,
tooltipModel
]);
if (tooltipModel.get('trigger') !== 'axis') {
return;
}
api.dispatchAction({
type: 'updateAxisPointer',
seriesIndex: seriesIndex,
dataIndex: dataIndex,
position: payload.position
});
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q15270
|
train
|
function (dataByCoordSys) {
var lastCoordSys = this._lastDataByCoordSys;
var contentNotChanged = !!lastCoordSys
&& lastCoordSys.length === dataByCoordSys.length;
contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
var thisItem = thisDataByAxis[indexAxis] || {};
var lastIndices = lastItem.seriesDataIndices || [];
var newIndices = thisItem.seriesDataIndices || [];
contentNotChanged
&= lastItem.value === thisItem.value
&& lastItem.axisType === thisItem.axisType
&& lastItem.axisId === thisItem.axisId
&& lastIndices.length === newIndices.length;
contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
var newIdxItem = newIndices[j];
contentNotChanged
&= lastIdxItem.seriesIndex === newIdxItem.seriesIndex
&& lastIdxItem.dataIndex === newIdxItem.dataIndex;
});
});
});
this._lastDataByCoordSys = dataByCoordSys;
return !!contentNotChanged;
}
|
javascript
|
{
"resource": ""
}
|
|
q15271
|
SunburstPiece
|
train
|
function SunburstPiece(node, seriesModel, ecModel) {
graphic.Group.call(this);
var sector = new graphic.Sector({
z2: DEFAULT_SECTOR_Z
});
sector.seriesIndex = seriesModel.seriesIndex;
var text = new graphic.Text({
z2: DEFAULT_TEXT_Z,
silent: node.getModel('label').get('silent')
});
this.add(sector);
this.add(text);
this.updateData(true, node, 'normal', seriesModel, ecModel);
// Hover to change label and labelLine
function onEmphasis() {
text.ignore = text.hoverIgnore;
}
function onNormal() {
text.ignore = text.normalIgnore;
}
this.on('emphasis', onEmphasis)
.on('normal', onNormal)
.on('mouseover', onEmphasis)
.on('mouseout', onNormal);
}
|
javascript
|
{
"resource": ""
}
|
q15272
|
getNodeColor
|
train
|
function getNodeColor(node, seriesModel, ecModel) {
// Color from visualMap
var visualColor = node.getVisual('color');
var visualMetaList = node.getVisual('visualMeta');
if (!visualMetaList || visualMetaList.length === 0) {
// Use first-generation color if has no visualMap
visualColor = null;
}
// Self color or level color
var color = node.getModel('itemStyle').get('color');
if (color) {
return color;
}
else if (visualColor) {
// Color mapping
return visualColor;
}
else if (node.depth === 0) {
// Virtual root node
return ecModel.option.color[0];
}
else {
// First-generation color
var length = ecModel.option.color.length;
color = ecModel.option.color[getRootId(node) % length];
}
return color;
}
|
javascript
|
{
"resource": ""
}
|
q15273
|
getRootId
|
train
|
function getRootId(node) {
var ancestor = node;
while (ancestor.depth > 1) {
ancestor = ancestor.parentNode;
}
var virtualRoot = node.getAncestors()[0];
return zrUtil.indexOf(virtualRoot.children, ancestor);
}
|
javascript
|
{
"resource": ""
}
|
q15274
|
fillDefaultColor
|
train
|
function fillDefaultColor(node, seriesModel, color) {
var data = seriesModel.getData();
data.setItemVisual(node.dataIndex, 'color', color);
}
|
javascript
|
{
"resource": ""
}
|
q15275
|
train
|
function (graphicModel) {
var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
if (!elOptionsToUpdate) {
return;
}
var elMap = this._elMap;
var rootGroup = this.group;
// Top-down tranverse to assign graphic settings to each elements.
zrUtil.each(elOptionsToUpdate, function (elOption) {
var $action = elOption.$action;
var id = elOption.id;
var existEl = elMap.get(id);
var parentId = elOption.parentId;
var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
var elOptionStyle = elOption.style;
if (elOption.type === 'text' && elOptionStyle) {
// In top/bottom mode, textVerticalAlign should not be used, which cause
// inaccurately locating.
if (elOption.hv && elOption.hv[1]) {
elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
}
// Compatible with previous setting: both support fill and textFill,
// stroke and textStroke.
!elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
elOptionStyle.textFill = elOptionStyle.fill
);
!elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
elOptionStyle.textStroke = elOptionStyle.stroke
);
}
// Remove unnecessary props to avoid potential problems.
var elOptionCleaned = getCleanedElOption(elOption);
// For simple, do not support parent change, otherwise reorder is needed.
if (__DEV__) {
existEl && zrUtil.assert(
targetElParent === existEl.parent,
'Changing parent is not supported.'
);
}
if (!$action || $action === 'merge') {
existEl
? existEl.attr(elOptionCleaned)
: createEl(id, targetElParent, elOptionCleaned, elMap);
}
else if ($action === 'replace') {
removeEl(existEl, elMap);
createEl(id, targetElParent, elOptionCleaned, elMap);
}
else if ($action === 'remove') {
removeEl(existEl, elMap);
}
var el = elMap.get(id);
if (el) {
el.__ecGraphicWidth = elOption.width;
el.__ecGraphicHeight = elOption.height;
setEventData(el, graphicModel, elOption);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q15276
|
train
|
function (graphicModel, api) {
var elOptions = graphicModel.option.elements;
var rootGroup = this.group;
var elMap = this._elMap;
// Bottom-up tranvese all elements (consider ec resize) to locate elements.
for (var i = elOptions.length - 1; i >= 0; i--) {
var elOption = elOptions[i];
var el = elMap.get(elOption.id);
if (!el) {
continue;
}
var parentEl = el.parent;
var containerInfo = parentEl === rootGroup
? {
width: api.getWidth(),
height: api.getHeight()
}
: { // Like 'position:absolut' in css, default 0.
width: parentEl.__ecGraphicWidth || 0,
height: parentEl.__ecGraphicHeight || 0
};
layoutUtil.positionElement(
el, elOption, containerInfo, null,
{hv: elOption.hv, boundingMode: elOption.bounding}
);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15277
|
train
|
function () {
var elMap = this._elMap;
elMap.each(function (el) {
removeEl(el, elMap);
});
this._elMap = zrUtil.createHashMap();
}
|
javascript
|
{
"resource": ""
}
|
|
q15278
|
getCleanedElOption
|
train
|
function getCleanedElOption(elOption) {
elOption = zrUtil.extend({}, elOption);
zrUtil.each(
['id', 'parentId', '$action', 'hv', 'bounding'].concat(layoutUtil.LOCATION_PARAMS),
function (name) {
delete elOption[name];
}
);
return elOption;
}
|
javascript
|
{
"resource": ""
}
|
q15279
|
makeLabelsByCustomizedCategoryInterval
|
train
|
function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
var ordinalScale = axis.scale;
var labelFormatter = makeLabelFormatter(axis);
var result = [];
zrUtil.each(ordinalScale.getTicks(), function (tickValue) {
var rawLabel = ordinalScale.getLabel(tickValue);
if (categoryInterval(tickValue, rawLabel)) {
result.push(onlyTick
? tickValue
: {
formattedLabel: labelFormatter(tickValue),
rawLabel: rawLabel,
tickValue: tickValue
}
);
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q15280
|
fixAngleOverlap
|
train
|
function fixAngleOverlap(list) {
var firstItem = list[0];
var lastItem = list[list.length - 1];
if (firstItem
&& lastItem
&& Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
) {
list.pop();
}
}
|
javascript
|
{
"resource": ""
}
|
q15281
|
train
|
function (axisModel, opt) {
/**
* @readOnly
*/
this.opt = opt;
/**
* @readOnly
*/
this.axisModel = axisModel;
// Default value
defaults(
opt,
{
labelOffset: 0,
nameDirection: 1,
tickDirection: 1,
labelDirection: 1,
silent: true
}
);
/**
* @readOnly
*/
this.group = new graphic.Group();
// FIXME Not use a seperate text group?
var dumbGroup = new graphic.Group({
position: opt.position.slice(),
rotation: opt.rotation
});
// this.group.add(dumbGroup);
// this._dumbGroup = dumbGroup;
dumbGroup.updateTransform();
this._transform = dumbGroup.transform;
this._dumbGroup = dumbGroup;
}
|
javascript
|
{
"resource": ""
}
|
|
q15282
|
train
|
function () {
// FIXME
// Move this logic to ec main?
var container = this._container;
var stl = container.currentStyle
|| document.defaultView.getComputedStyle(container);
var domStyle = container.style;
if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
domStyle.position = 'relative';
}
// Hide the tooltip
// PENDING
// this.hide();
}
|
javascript
|
{
"resource": ""
}
|
|
q15283
|
getLinkedData
|
train
|
function getLinkedData(dataType) {
var mainData = this[MAIN_DATA];
return (dataType == null || mainData == null)
? mainData
: mainData[DATAS][dataType];
}
|
javascript
|
{
"resource": ""
}
|
q15284
|
train
|
function (ecModel, api) {
ecModel.eachComponent('dataZoom', function (dataZoomModel) {
// We calculate window and reset axis here but not in model
// init stage and not after action dispatch handler, because
// reset should be called after seriesData.restoreData.
dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
});
// Caution: data zoom filtering is order sensitive when using
// percent range and no min/max/scale set on axis.
// For example, we have dataZoom definition:
// [
// {xAxisIndex: 0, start: 30, end: 70},
// {yAxisIndex: 0, start: 20, end: 80}
// ]
// In this case, [20, 80] of y-dataZoom should be based on data
// that have filtered by x-dataZoom using range of [30, 70],
// but should not be based on full raw data. Thus sliding
// x-dataZoom will change both ranges of xAxis and yAxis,
// while sliding y-dataZoom will only change the range of yAxis.
// So we should filter x-axis after reset x-axis immediately,
// and then reset y-axis and filter y-axis.
dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
});
});
ecModel.eachComponent('dataZoom', function (dataZoomModel) {
// Fullfill all of the range props so that user
// is able to get them from chart.getOption().
var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
var percentRange = axisProxy.getDataPercentWindow();
var valueRange = axisProxy.getDataValueWindow();
dataZoomModel.setRawRange({
start: percentRange[0],
end: percentRange[1],
startValue: valueRange[0],
endValue: valueRange[1]
}, true);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q15285
|
train
|
function (point) {
var coord = this.pointToCoord(point);
return this._radiusAxis.contain(coord[0])
&& this._angleAxis.contain(coord[1]);
}
|
javascript
|
{
"resource": ""
}
|
|
q15286
|
train
|
function (scaleType) {
var axes = [];
var angleAxis = this._angleAxis;
var radiusAxis = this._radiusAxis;
angleAxis.scale.type === scaleType && axes.push(angleAxis);
radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
return axes;
}
|
javascript
|
{
"resource": ""
}
|
|
q15287
|
drawNonMono
|
train
|
function drawNonMono(
ctx, points, start, segLen, allLen,
dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
) {
var prevIdx = 0;
var idx = start;
for (var k = 0; k < segLen; k++) {
var p = points[idx];
if (idx >= allLen || idx < 0) {
break;
}
if (isPointNull(p)) {
if (connectNulls) {
idx += dir;
continue;
}
break;
}
if (idx === start) {
ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
v2Copy(cp0, p);
}
else {
if (smooth > 0) {
var nextIdx = idx + dir;
var nextP = points[nextIdx];
if (connectNulls) {
// Find next point not null
while (nextP && isPointNull(points[nextIdx])) {
nextIdx += dir;
nextP = points[nextIdx];
}
}
var ratioNextSeg = 0.5;
var prevP = points[prevIdx];
var nextP = points[nextIdx];
// Last point
if (!nextP || isPointNull(nextP)) {
v2Copy(cp1, p);
}
else {
// If next data is null in not connect case
if (isPointNull(nextP) && !connectNulls) {
nextP = p;
}
vec2.sub(v, nextP, prevP);
var lenPrevSeg;
var lenNextSeg;
if (smoothMonotone === 'x' || smoothMonotone === 'y') {
var dim = smoothMonotone === 'x' ? 0 : 1;
lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
lenNextSeg = Math.abs(p[dim] - nextP[dim]);
}
else {
lenPrevSeg = vec2.dist(p, prevP);
lenNextSeg = vec2.dist(p, nextP);
}
// Use ratio of seg length
ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
scaleAndAdd(cp1, p, v, -smooth * (1 - ratioNextSeg));
}
// Smooth constraint
vec2Min(cp0, cp0, smoothMax);
vec2Max(cp0, cp0, smoothMin);
vec2Min(cp1, cp1, smoothMax);
vec2Max(cp1, cp1, smoothMin);
ctx.bezierCurveTo(
cp0[0], cp0[1],
cp1[0], cp1[1],
p[0], p[1]
);
// cp0 of next segment
scaleAndAdd(cp0, p, v, smooth * ratioNextSeg);
}
else {
ctx.lineTo(p[0], p[1]);
}
}
prevIdx = idx;
idx += dir;
}
return k;
}
|
javascript
|
{
"resource": ""
}
|
q15288
|
getColorVisual
|
train
|
function getColorVisual(seriesModel, visualMapModel, value, valueState) {
var mappings = visualMapModel.targetVisuals[valueState];
var visualTypes = VisualMapping.prepareVisualTypes(mappings);
var resultVisual = {
color: seriesModel.getData().getVisual('color') // default color.
};
for (var i = 0, len = visualTypes.length; i < len; i++) {
var type = visualTypes[i];
var mapping = mappings[
type === 'opacity' ? '__alphaForOpacity' : type
];
mapping && mapping.applyVisual(value, getVisual, setVisual);
}
return resultVisual.color;
function getVisual(key) {
return resultVisual[key];
}
function setVisual(key, value) {
resultVisual[key] = value;
}
}
|
javascript
|
{
"resource": ""
}
|
q15289
|
vuexInit
|
train
|
function vuexInit () {
var options = this.$options;
// store injection
if (options.store) {
this.$store = typeof options.store === 'function'
? options.store()
: options.store;
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store;
}
}
|
javascript
|
{
"resource": ""
}
|
q15290
|
forEachValue
|
train
|
function forEachValue (obj, fn) {
Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
}
|
javascript
|
{
"resource": ""
}
|
q15291
|
Module
|
train
|
function Module (rawModule, runtime) {
this.runtime = runtime;
// Store some children item
this._children = Object.create(null);
// Store the origin module object which passed by programmer
this._rawModule = rawModule;
var rawState = rawModule.state;
// Store the origin module's state
this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
}
|
javascript
|
{
"resource": ""
}
|
q15292
|
normalizeNamespace
|
train
|
function normalizeNamespace (fn) {
return function (namespace, map) {
if (typeof namespace !== 'string') {
map = namespace;
namespace = '';
} else if (namespace.charAt(namespace.length - 1) !== '/') {
namespace += '/';
}
return fn(namespace, map)
}
}
|
javascript
|
{
"resource": ""
}
|
q15293
|
getModuleByNamespace
|
train
|
function getModuleByNamespace (store, helper, namespace) {
const module = store._modulesNamespaceMap[namespace]
if (process.env.NODE_ENV !== 'production' && !module) {
console.error(`[vuex] module namespace not found in ${helper}(): ${namespace}`)
}
return module
}
|
javascript
|
{
"resource": ""
}
|
q15294
|
makeLocalContext
|
train
|
function makeLocalContext (store, namespace, path) {
const noNamespace = namespace === ''
const local = {
dispatch: noNamespace ? store.dispatch : (_type, _payload, _options) => {
const args = unifyObjectStyle(_type, _payload, _options)
const { payload, options } = args
let { type } = args
if (!options || !options.root) {
type = namespace + type
if (process.env.NODE_ENV !== 'production' && !store._actions[type]) {
console.error(`[vuex] unknown local action type: ${args.type}, global type: ${type}`)
return
}
}
return store.dispatch(type, payload)
},
commit: noNamespace ? store.commit : (_type, _payload, _options) => {
const args = unifyObjectStyle(_type, _payload, _options)
const { payload, options } = args
let { type } = args
if (!options || !options.root) {
type = namespace + type
if (process.env.NODE_ENV !== 'production' && !store._mutations[type]) {
console.error(`[vuex] unknown local mutation type: ${args.type}, global type: ${type}`)
return
}
}
store.commit(type, payload, options)
}
}
// getters and state object must be gotten lazily
// because they will be changed by vm update
Object.defineProperties(local, {
getters: {
get: noNamespace
? () => store.getters
: () => makeLocalGetters(store, namespace)
},
state: {
get: () => getNestedState(store.state, path)
}
})
return local
}
|
javascript
|
{
"resource": ""
}
|
q15295
|
migrateExpiration
|
train
|
function migrateExpiration (store) {
const request = store.openCursor()
request.onsuccess = (event) => {
const cursor = event.target.result
if (!cursor) {
return
}
const entry = cursor.value
entry.expires = Date.now() + DEFAULT_EXPIRY
cursor.update(entry)
}
}
|
javascript
|
{
"resource": ""
}
|
q15296
|
debounce
|
train
|
function debounce (fn) {
let calling = null
let latestArgs = null
return (...args) => {
latestArgs = args
if (!calling) {
calling = Promise.resolve().then(() => {
calling = null
// At this point `args` may be different from the most
// recent state, if multiple calls happened since this task
// was queued. So we use the `latestArgs`, which definitely
// is the most recent call.
return fn(...latestArgs)
})
}
return calling
}
}
|
javascript
|
{
"resource": ""
}
|
q15297
|
validateParams
|
train
|
function validateParams (params) {
if (!params) {
throw new Error('Transloadit: The `params` option is required.')
}
if (typeof params === 'string') {
try {
params = JSON.parse(params)
} catch (err) {
// Tell the user that this is not an Uppy bug!
err.message = 'Transloadit: The `params` option is a malformed JSON string: ' +
err.message
throw err
}
}
if (!params.auth || !params.auth.key) {
throw new Error('Transloadit: The `params.auth.key` option is required. ' +
'You can find your Transloadit API key at https://transloadit.com/account/api-settings.')
}
}
|
javascript
|
{
"resource": ""
}
|
q15298
|
FileIcon
|
train
|
function FileIcon () {
return <View style={styles.itemIconContainer}>
<Image
style={styles.itemIcon}
source={require('./assets/file-icon.png')}
/>
</View>
}
|
javascript
|
{
"resource": ""
}
|
q15299
|
authorized
|
train
|
function authorized (req, res) {
const { params, uppy } = req
const providerName = params.providerName
if (!uppy.providerTokens || !uppy.providerTokens[providerName]) {
return res.json({ authenticated: false })
}
const token = uppy.providerTokens[providerName]
uppy.provider.list({ token, uppy }, (err, response, body) => {
const notAuthenticated = Boolean(err)
if (notAuthenticated) {
logger.debug(`${providerName} failed authorizarion test err:${err}`, 'provider.auth.check')
}
return res.json({ authenticated: !notAuthenticated })
})
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.