text:
/**
 * @classDescription The base function which all other series types inherit from. The data in the series is stored
 * in various arrays.
 *
 * - First, series.options.data contains all the original config options for
 * each point whether added by options or methods like series.addPoint.
 * - Next, series.data contains those values converted to points, but in case the series data length
 * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
 * only contains the points that have been created on demand.
 * - Then there's series.points that contains all currently visible point objects. In case of cropping,
 * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
 * compared to series.data and series.options.data. If however the series data is grouped, these can't
 * be correlated one to one.
 * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
 * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
 *
 * @param {Object} chart
 * @param {Object} options
 */
var Series = Highcharts.Series = function () {};

Series.prototype = {

	isCartesian: true,
	type: 'line',
	pointClass: Point,
	sorted: true, // requires the data to be sorted
	requireSorting: true,
	pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
		stroke: 'lineColor',
		'stroke-width': 'lineWidth',
		fill: 'fillColor',
		r: 'radius'
	},
	axisTypes: ['xAxis', 'yAxis'],
	colorCounter: 0,
	parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
	init: function (chart, options) {
		var series = this,
			eventType,
			events,
			chartSeries = chart.series,
			sortByIndex = function (a, b) {
				return pick(a.options.index, a._i) - pick(b.options.index, b._i);
			};

		series.chart = chart;
		series.options = options = series.setOptions(options); // merge with plotOptions
		series.linkedSeries = [];

		// bind the axes
		series.bindAxes();

		// set some variables
		extend(series, {
			name: options.name,
			state: NORMAL_STATE,
			pointAttr: {},
			visible: options.visible !== false, // true by default
			selected: options.selected === true // false by default
		});

		// special
		if (useCanVG) {
			options.animation = false;
		}

		// register event listeners
		events = options.events;
		for (eventType in events) {
			addEvent(series, eventType, events[eventType]);
		}
		if (
			(events && events.click) ||
			(options.point && options.point.events && options.point.events.click) ||
			options.allowPointSelect
		) {
			chart.runTrackerClick = true;
		}

		series.getColor();
		series.getSymbol();

		// Set the data
		each(series.parallelArrays, function (key) {
			series[key + 'Data'] = [];
		});
		series.setData(options.data, false);

		// Mark cartesian
		if (series.isCartesian) {
			chart.hasCartesianSeries = true;
		}

		// Register it in the chart
		chartSeries.push(series);
		series._i = chartSeries.length - 1;

		// Sort series according to index option (#248, #1123, #2456)
		stableSort(chartSeries, sortByIndex);
		if (this.yAxis) {
			stableSort(this.yAxis.series, sortByIndex);
		}

		each(chartSeries, function (series, i) {
			series.index = i;
			series.name = series.name || 'Series ' + (i + 1);
		});

	},

	/**
	 * Set the xAxis and yAxis properties of cartesian series, and register the series
	 * in the axis.series array
	 */
	bindAxes: function () {
		var series = this,
			seriesOptions = series.options,
			chart = series.chart,
			axisOptions;

		each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis

			each(chart[AXIS], function (axis) { // loop through the chart's axis objects
				axisOptions = axis.options;

				// apply if the series xAxis or yAxis option mathches the number of the
				// axis, or if undefined, use the first axis
				if ((seriesOptions[AXIS] === axisOptions.index) ||
						(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
						(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {

					// register this series in the axis.series lookup
					axis.series.push(series);

					// set this series.xAxis or series.yAxis reference
					series[AXIS] = axis;

					// mark dirty for redraw
					axis.isDirty = true;
				}
			});

			// The series needs an X and an Y axis
			if (!series[AXIS] && series.optionalAxis !== AXIS) {
				error(18, true);
			}

		});
	},

	/**
	 * For simple series types like line and column, the data values are held in arrays like
	 * xData and yData for quick lookup to find extremes and more. For multidimensional series
	 * like bubble and map, this can be extended with arrays like zData and valueData by
	 * adding to the series.parallelArrays array.
	 */
	updateParallelArrays: function (point, i) {
		var series = point.series,
			args = arguments,
			fn = typeof i === 'number' ?
				 // Insert the value in the given position
				function (key) {
					var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
					series[key + 'Data'][i] = val;
				} :
				// Apply the method specified in i with the following arguments as arguments
				function (key) {
					Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
				};

		each(series.parallelArrays, fn);
	},

	/**
	 * Return an auto incremented x value based on the pointStart and pointInterval options.
	 * This is only used if an x value is not given for the point that calls autoIncrement.
	 */
	autoIncrement: function () {

		var options = this.options,
			xIncrement = this.xIncrement,
			date,
			pointInterval,
			pointIntervalUnit = options.pointIntervalUnit;

		xIncrement = pick(xIncrement, options.pointStart, 0);

		this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);

		// Added code for pointInterval strings
		if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') {
			date = new Date(xIncrement);
			date = (pointIntervalUnit === 'month') ?
				+date[setMonth](date[getMonth]() + pointInterval) :
				+date[setFullYear](date[getFullYear]() + pointInterval);
			pointInterval = date - xIncrement;
		}

		this.xIncrement = xIncrement + pointInterval;
		return xIncrement;
	},

	/**
	 * Divide the series data into segments divided by null values.
	 */
	getSegments: function () {
		var series = this,
			lastNull = -1,
			segments = [],
			i,
			points = series.points,
			pointsLength = points.length;

		if (pointsLength) { // no action required for []

			// if connect nulls, just remove null points
			if (series.options.connectNulls) {
				i = pointsLength;
				while (i--) {
					if (points[i].y === null) {
						points.splice(i, 1);
					}
				}
				if (points.length) {
					segments = [points];
				}

			// else, split on null points
			} else {
				each(points, function (point, i) {
					if (point.y === null) {
						if (i > lastNull + 1) {
							segments.push(points.slice(lastNull + 1, i));
						}
						lastNull = i;
					} else if (i === pointsLength - 1) { // last value
						segments.push(points.slice(lastNull + 1, i + 1));
					}
				});
			}
		}

		// register it
		series.segments = segments;
	},

	/**
	 * Set the series options by merging from the options tree
	 * @param {Object} itemOptions
	 */
	setOptions: function (itemOptions) {
		var chart = this.chart,
			chartOptions = chart.options,
			plotOptions = chartOptions.plotOptions,
			userOptions = chart.userOptions || {},
			userPlotOptions = userOptions.plotOptions || {},
			typeOptions = plotOptions[this.type],
			options,
			zones;

		this.userOptions = itemOptions;

		// General series options take precedence over type options because otherwise, default
		// type options like column.animation would be overwritten by the general option.
		// But issues have been raised here (#3881), and the solution may be to distinguish
		// between default option and userOptions like in the tooltip below.
		options = merge(
			typeOptions,
			plotOptions.series,
			itemOptions
		);

		// The tooltip options are merged between global and series specific options
		this.tooltipOptions = merge(
			defaultOptions.tooltip,
			defaultOptions.plotOptions[this.type].tooltip,
			userOptions.tooltip,
			userPlotOptions.series && userPlotOptions.series.tooltip,
			userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
			itemOptions.tooltip
		);

		// Delete marker object if not allowed (#1125)
		if (typeOptions.marker === null) {
			delete options.marker;
		}

		// Handle color zones
		this.zoneAxis = options.zoneAxis;
		zones = this.zones = (options.zones || []).slice();
		if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
			zones.push({
				value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
				color: options.negativeColor,
				fillColor: options.negativeFillColor
			});
		}
		if (zones.length) { // Push one extra zone for the rest
			if (defined(zones[zones.length - 1].value)) {
				zones.push({
					color: this.color,
					fillColor: this.fillColor
				});
			}
		}
		return options;
	},

	getCyclic: function (prop, value, defaults) {
		var i,
			userOptions = this.userOptions,
			indexName = '_' + prop + 'Index',
			counterName = prop + 'Counter';

		if (!value) {
			if (defined(userOptions[indexName])) { // after Series.update()
				i = userOptions[indexName];
			} else {
				userOptions[indexName] = i = this.chart[counterName] % defaults.length;
				this.chart[counterName] += 1;
			}
			value = defaults[i];
		}
		this[prop] = value;
	},

	/**
	 * Get the series' color
	 */
	getColor: function () {
		if (!this.options.colorByPoint) {
			this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors);
		}
	},
	/**
	 * Get the series' symbol
	 */
	getSymbol: function () {
		var seriesMarkerOption = this.options.marker;

		this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);

		// don't substract radius in image symbols (#604)
		if (/^url/.test(this.symbol)) {
			seriesMarkerOption.radius = 0;
		}
	},

	drawLegendSymbol: LegendSymbolMixin.drawLineMarker,

	/**
	 * Replace the series data with a new set of data
	 * @param {Object} data
	 * @param {Object} redraw
	 */
	setData: function (data, redraw, animation, updatePoints) {
		var series = this,
			oldData = series.points,
			oldDataLength = (oldData && oldData.length) || 0,
			dataLength,
			options = series.options,
			chart = series.chart,
			firstPoint = null,
			xAxis = series.xAxis,
			hasCategories = xAxis && !!xAxis.categories,
			i,
			turboThreshold = options.turboThreshold,
			pt,
			xData = this.xData,
			yData = this.yData,
			pointArrayMap = series.pointArrayMap,
			valueCount = pointArrayMap && pointArrayMap.length;

		data = data || [];
		dataLength = data.length;
		redraw = pick(redraw, true);

		// If the point count is the same as is was, just run Point.update which is
		// cheaper, allows animation, and keeps references to points.
		if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
			each(data, function (point, i) {
				if (oldData[i].update) { // Linked, previously hidden series (#3709)
					oldData[i].update(point, false, null, false);
				}
			});

		} else {

			// Reset properties
			series.xIncrement = null;
			series.pointRange = hasCategories ? 1 : options.pointRange;

			series.colorCounter = 0; // for series with colorByPoint (#1547)

			// Update parallel arrays
			each(this.parallelArrays, function (key) {
				series[key + 'Data'].length = 0;
			});

			// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
			// first value is tested, and we assume that all the rest are defined the same
			// way. Although the 'for' loops are similar, they are repeated inside each
			// if-else conditional for max performance.
			if (turboThreshold && dataLength > turboThreshold) {

				// find the first non-null point
				i = 0;
				while (firstPoint === null && i < dataLength) {
					firstPoint = data[i];
					i++;
				}

				if (isNumber(firstPoint)) { // assume all points are numbers
					var x = pick(options.pointStart, 0),
						pointInterval = pick(options.pointInterval, 1);

					for (i = 0; i < dataLength; i++) {
						xData[i] = x;
						yData[i] = data[i];
						x += pointInterval;
					}
					series.xIncrement = x;
				} else if (isArray(firstPoint)) { // assume all points are arrays
					if (valueCount) { // [x, low, high] or [x, o, h, l, c]
						for (i = 0; i < dataLength; i++) {
							pt = data[i];
							xData[i] = pt[0];
							yData[i] = pt.slice(1, valueCount + 1);
						}
					} else { // [x, y]
						for (i = 0; i < dataLength; i++) {
							pt = data[i];
							xData[i] = pt[0];
							yData[i] = pt[1];
						}
					}
				} else {
					error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
				}
			} else {
				for (i = 0; i < dataLength; i++) {
					if (data[i] !== UNDEFINED) { // stray commas in oldIE
						pt = { series: series };
						series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
						series.updateParallelArrays(pt, i);
						if (hasCategories && pt.name) {
							xAxis.names[pt.x] = pt.name; // #2046
						}
					}
				}
			}

			// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
			if (isString(yData[0])) {
				error(14, true);
			}

			series.data = [];
			series.options.data = data;
			//series.zData = zData;

			// destroy old points
			i = oldDataLength;
			while (i--) {
				if (oldData[i] && oldData[i].destroy) {
					oldData[i].destroy();
				}
			}

			// reset minRange (#878)
			if (xAxis) {
				xAxis.minRange = xAxis.userMinRange;
			}

			// redraw
			series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
			animation = false;
		}

		if (redraw) {
			chart.redraw(animation);
		}
	},

	/**
	 * Process the data by cropping away unused data points if the series is longer
	 * than the crop threshold. This saves computing time for lage series.
	 */
	processData: function (force) {
		var series = this,
			processedXData = series.xData, // copied during slice operation below
			processedYData = series.yData,
			dataLength = processedXData.length,
			croppedData,
			cropStart = 0,
			cropped,
			distance,
			closestPointRange,
			xAxis = series.xAxis,
			i, // loop variable
			options = series.options,
			cropThreshold = options.cropThreshold,
			isCartesian = series.isCartesian,
			xExtremes,
			min,
			max;

		// If the series data or axes haven't changed, don't go through this. Return false to pass
		// the message on to override methods like in data grouping.
		if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
			return false;
		}

		if (xAxis) {
			xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
			min = xExtremes.min;
			max = xExtremes.max;
		}

		// optionally filter out points outside the plot area
		if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {

			// it's outside current extremes
			if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
				processedXData = [];
				processedYData = [];

			// only crop if it's actually spilling out
			} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
				croppedData = this.cropData(series.xData, series.yData, min, max);
				processedXData = croppedData.xData;
				processedYData = croppedData.yData;
				cropStart = croppedData.start;
				cropped = true;
			}
		}

		// Find the closest distance between processed points
		for (i = processedXData.length - 1; i >= 0; i--) {
			distance = processedXData[i] - processedXData[i - 1];

			if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
				closestPointRange = distance;

			// Unsorted data is not supported by the line tooltip, as well as data grouping and
			// navigation in Stock charts (#725) and width calculation of columns (#1900)
			} else if (distance < 0 && series.requireSorting) {
				error(15);
			}
		}

		// Record the properties
		series.cropped = cropped; // undefined or true
		series.cropStart = cropStart;
		series.processedXData = processedXData;
		series.processedYData = processedYData;

		if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
			series.pointRange = closestPointRange || 1;
		}
		series.closestPointRange = closestPointRange;

	},

	/**
	 * Iterate over xData and crop values between min and max. Returns object containing crop start/end
	 * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
	 */
	cropData: function (xData, yData, min, max) {
		var dataLength = xData.length,
			cropStart = 0,
			cropEnd = dataLength,
			cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
			i;

		// iterate up to find slice start
		for (i = 0; i < dataLength; i++) {
			if (xData[i] >= min) {
				cropStart = mathMax(0, i - cropShoulder);
				break;
			}
		}

		// proceed to find slice end
		for (; i < dataLength; i++) {
			if (xData[i] > max) {
				cropEnd = i + cropShoulder;
				break;
			}
		}

		return {
			xData: xData.slice(cropStart, cropEnd),
			yData: yData.slice(cropStart, cropEnd),
			start: cropStart,
			end: cropEnd
		};
	},

	/**
	 * Generate the data point after the data has been processed by cropping away
	 * unused points and optionally grouped in Highcharts Stock.
	 */
	generatePoints: function () {
		var series = this,
			options = series.options,
			dataOptions = options.data,
			data = series.data,
			dataLength,
			processedXData = series.processedXData,
			processedYData = series.processedYData,
			pointClass = series.pointClass,
			processedDataLength = processedXData.length,
			cropStart = series.cropStart || 0,
			cursor,
			hasGroupedData = series.hasGroupedData,
			point,
			points = [],
			i;

		if (!data && !hasGroupedData) {
			var arr = [];
			arr.length = dataOptions.length;
			data = series.data = arr;
		}

		for (i = 0; i < processedDataLength; i++) {
			cursor = cropStart + i;
			if (!hasGroupedData) {
				if (data[cursor]) {
					point = data[cursor];
				} else if (dataOptions[cursor] !== UNDEFINED) { // #970
					data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
				}
				points[i] = point;
			} else {
				// splat the y data in case of ohlc data array
				points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
			}
			points[i].index = cursor; // For faster access in Point.update
		}

		// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
		// swithching view from non-grouped data to grouped data (#637)
		if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
			for (i = 0; i < dataLength; i++) {
				if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
					i += processedDataLength;
				}
				if (data[i]) {
					data[i].destroyElements();
					data[i].plotX = UNDEFINED; // #1003
				}
			}
		}

		series.data = data;
		series.points = points;
	},

	/**
	 * Calculate Y extremes for visible data
	 */
	getExtremes: function (yData) {
		var xAxis = this.xAxis,
			yAxis = this.yAxis,
			xData = this.processedXData,
			yDataLength,
			activeYData = [],
			activeCounter = 0,
			xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
			xMin = xExtremes.min,
			xMax = xExtremes.max,
			validValue,
			withinRange,
			x,
			y,
			i,
			j;

		yData = yData || this.stackedYData || this.processedYData;
		yDataLength = yData.length;

		for (i = 0; i < yDataLength; i++) {

			x = xData[i];
			y = yData[i];

			// For points within the visible range, including the first point outside the
			// visible range, consider y extremes
			validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
			withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped ||
				((xData[i + 1] || x) >= xMin &&	(xData[i - 1] || x) <= xMax);

			if (validValue && withinRange) {

				j = y.length;
				if (j) { // array, like ohlc or range data
					while (j--) {
						if (y[j] !== null) {
							activeYData[activeCounter++] = y[j];
						}
					}
				} else {
					activeYData[activeCounter++] = y;
				}
			}
		}
		this.dataMin = arrayMin(activeYData);
		this.dataMax = arrayMax(activeYData);
	},

	/**
	 * Translate data points from raw data values to chart specific positioning data
	 * needed later in drawPoints, drawGraph and drawTracker.
	 */
	translate: function () {
		if (!this.processedXData) { // hidden series
			this.processData();
		}
		this.generatePoints();
		var series = this,
			options = series.options,
			stacking = options.stacking,
			xAxis = series.xAxis,
			categories = xAxis.categories,
			yAxis = series.yAxis,
			points = series.points,
			dataLength = points.length,
			hasModifyValue = !!series.modifyValue,
			i,
			pointPlacement = options.pointPlacement,
			dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
			threshold = options.threshold,
			stackThreshold = options.startFromThreshold ? threshold : 0,
			plotX,
			plotY,
			lastPlotX,
			closestPointRangePx = Number.MAX_VALUE;

		// Translate each point
		for (i = 0; i < dataLength; i++) {
			var point = points[i],
				xValue = point.x,
				yValue = point.y,
				yBottom = point.low,
				stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey],
				pointStack,
				stackValues;

			// Discard disallowed y values for log axes (#3434)
			if (yAxis.isLog && yValue !== null && yValue <= 0) {
				point.y = yValue = null;
				error(10);
			}

			// Get the plotX translation
			point.plotX = plotX = mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5); // #3923

			// Calculate the bottom y value for stacked series
			if (stacking && series.visible && stack && stack[xValue]) {

				pointStack = stack[xValue];
				stackValues = pointStack.points[series.index + ',' + i];
				yBottom = stackValues[0];
				yValue = stackValues[1];

				if (yBottom === stackThreshold) {
					yBottom = pick(threshold, yAxis.min);
				}
				if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
					yBottom = null;
				}

				point.total = point.stackTotal = pointStack.total;
				point.percentage = pointStack.total && (point.y / pointStack.total * 100);
				point.stackY = yValue;

				// Place the stack label
				pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);

			}

			// Set translated yBottom or remove it
			point.yBottom = defined(yBottom) ?
				yAxis.translate(yBottom, 0, 1, 0, 1) :
				null;

			// general hook, used for Highstock compare mode
			if (hasModifyValue) {
				yValue = series.modifyValue(yValue, point);
			}

			// Set the the plotY value, reset it for redraws
			point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
				mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
				UNDEFINED;
			point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519
				plotX >= 0 && plotX <= xAxis.len;

			// Set client related positions for mouse tracking
			point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514

			point.negative = point.y < (threshold || 0);

			// some API data
			point.category = categories && categories[point.x] !== UNDEFINED ?
				categories[point.x] : point.x;

			// Determine auto enabling of markers (#3635)
			if (i) {
				closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX));
			}
			lastPlotX = plotX;

		}

		series.closestPointRangePx = closestPointRangePx;

		// now that we have the cropped data, build the segments
		series.getSegments();
	},

	/**
	 * Set the clipping for the series. For animated series it is called twice, first to initiate
	 * animating the clip then the second time without the animation to set the final clip.
	 */
	setClip: function (animation) {
		var chart = this.chart,
			renderer = chart.renderer,
			inverted = chart.inverted,
			seriesClipBox = this.clipBox,
			clipBox = seriesClipBox || chart.clipBox,
			sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height].join(','),
			clipRect = chart[sharedClipKey],
			markerClipRect = chart[sharedClipKey + 'm'];

		// If a clipping rectangle with the same properties is currently present in the chart, use that.
		if (!clipRect) {

			// When animation is set, prepare the initial positions
			if (animation) {
				clipBox.width = 0;

				chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
					-99, // include the width of the first marker
					inverted ? -chart.plotLeft : -chart.plotTop,
					99,
					inverted ? chart.chartWidth : chart.chartHeight
				);
			}
			chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);

		}
		if (animation) {
			clipRect.count += 1;
		}

		if (this.options.clip !== false) {
			this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
			this.markerGroup.clip(markerClipRect);
			this.sharedClipKey = sharedClipKey;
		}

		// Remove the shared clipping rectangle when all series are shown
		if (!animation) {
			clipRect.count -= 1;
			if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) {
				if (!seriesClipBox) {
					chart[sharedClipKey] = chart[sharedClipKey].destroy();
				}
				if (chart[sharedClipKey + 'm']) {
					chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
				}
			}
		}
	},

	/**
	 * Animate in the series
	 */
	animate: function (init) {
		var series = this,
			chart = series.chart,
			clipRect,
			animation = series.options.animation,
			sharedClipKey;

		// Animation option is set to true
		if (animation && !isObject(animation)) {
			animation = defaultPlotOptions[series.type].animation;
		}

		// Initialize the animation. Set up the clipping rectangle.
		if (init) {

			series.setClip(animation);

		// Run the animation
		} else {
			sharedClipKey = this.sharedClipKey;
			clipRect = chart[sharedClipKey];
			if (clipRect) {
				clipRect.animate({
					width: chart.plotSizeX
				}, animation);
			}
			if (chart[sharedClipKey + 'm']) {
				chart[sharedClipKey + 'm'].animate({
					width: chart.plotSizeX + 99
				}, animation);
			}

			// Delete this function to allow it only once
			series.animate = null;

		}
	},

	/**
	 * This runs after animation to land on the final plot clipping
	 */
	afterAnimate: function () {
		this.setClip();
		fireEvent(this, 'afterAnimate');
	},

	/**
	 * Draw the markers
	 */
	drawPoints: function () {
		var series = this,
			pointAttr,
			points = series.points,
			chart = series.chart,
			plotX,
			plotY,
			i,
			point,
			radius,
			symbol,
			isImage,
			graphic,
			options = series.options,
			seriesMarkerOptions = options.marker,
			seriesPointAttr = series.pointAttr[''],
			pointMarkerOptions,
			hasPointMarker,
			enabled,
			isInside,
			markerGroup = series.markerGroup,
			xAxis = series.xAxis,
			globallyEnabled = pick(
				seriesMarkerOptions.enabled,
				xAxis.isRadial,
				series.closestPointRangePx > 2 * seriesMarkerOptions.radius
			);

		if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {

			i = points.length;
			while (i--) {
				point = points[i];
				plotX = mathFloor(point.plotX); // #1843
				plotY = point.plotY;
				graphic = point.graphic;
				pointMarkerOptions = point.marker || {};
				hasPointMarker = !!point.marker;
				enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
				isInside = point.isInside;

				// only draw the point if y is defined
				if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {

					// shortcuts
					pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr;
					radius = pointAttr.r;
					symbol = pick(pointMarkerOptions.symbol, series.symbol);
					isImage = symbol.indexOf('url') === 0;

					if (graphic) { // update
						graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
							.animate(extend({
								x: plotX - radius,
								y: plotY - radius
							}, graphic.symbolName ? { // don't apply to image symbols #507
								width: 2 * radius,
								height: 2 * radius
							} : {}));
					} else if (isInside && (radius > 0 || isImage)) {
						point.graphic = graphic = chart.renderer.symbol(
							symbol,
							plotX - radius,
							plotY - radius,
							2 * radius,
							2 * radius,
							hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
						)
						.attr(pointAttr)
						.add(markerGroup);
					}

				} else if (graphic) {
					point.graphic = graphic.destroy(); // #1269
				}
			}
		}

	},

	/**
	 * Convert state properties from API naming conventions to SVG attributes
	 *
	 * @param {Object} options API options object
	 * @param {Object} base1 SVG attribute object to inherit from
	 * @param {Object} base2 Second level SVG attribute object to inherit from
	 */
	convertAttribs: function (options, base1, base2, base3) {
		var conversion = this.pointAttrToOptions,
			attr,
			option,
			obj = {};

		options = options || {};
		base1 = base1 || {};
		base2 = base2 || {};
		base3 = base3 || {};

		for (attr in conversion) {
			option = conversion[attr];
			obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
		}
		return obj;
	},

	/**
	 * Get the state attributes. Each series type has its own set of attributes
	 * that are allowed to change on a point's state change. Series wide attributes are stored for
	 * all series, and additionally point specific attributes are stored for all
	 * points with individual marker options. If such options are not defined for the point,
	 * a reference to the series wide attributes is stored in point.pointAttr.
	 */
	getAttribs: function () {
		var series = this,
			seriesOptions = series.options,
			normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
			stateOptions = normalOptions.states,
			stateOptionsHover = stateOptions[HOVER_STATE],
			pointStateOptionsHover,
			seriesColor = series.color,
			seriesNegativeColor = series.options.negativeColor,
			normalDefaults = {
				stroke: seriesColor,
				fill: seriesColor
			},
			points = series.points || [], // #927
			i,
			point,
			seriesPointAttr = [],
			pointAttr,
			pointAttrToOptions = series.pointAttrToOptions,
			hasPointSpecificOptions = series.hasPointSpecificOptions,
			defaultLineColor = normalOptions.lineColor,
			defaultFillColor = normalOptions.fillColor,
			turboThreshold = seriesOptions.turboThreshold,
			zones = series.zones,
			zoneAxis = series.zoneAxis || 'y',
			attr,
			key;

		// series type specific modifications
		if (seriesOptions.marker) { // line, spline, area, areaspline, scatter

			// if no hover radius is given, default to normal radius + 2
			stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus;
			stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus;

		} else { // column, bar, pie

			// if no hover color is given, brighten the normal color
			stateOptionsHover.color = stateOptionsHover.color ||
				Color(stateOptionsHover.color || seriesColor)
					.brighten(stateOptionsHover.brightness).get();

			// if no hover negativeColor is given, brighten the normal negativeColor
			stateOptionsHover.negativeColor = stateOptionsHover.negativeColor ||
				Color(stateOptionsHover.negativeColor || seriesNegativeColor)
					.brighten(stateOptionsHover.brightness).get();
		}

		// general point attributes for the series normal state
		seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);

		// HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
		each([HOVER_STATE, SELECT_STATE], function (state) {
			seriesPointAttr[state] =
					series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
		});

		// set it
		series.pointAttr = seriesPointAttr;

		// Generate the point-specific attribute collections if specific point
		// options are given. If not, create a referance to the series wide point
		// attributes
		i = points.length;
		if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) {
			while (i--) {
				point = points[i];
				normalOptions = (point.options && point.options.marker) || point.options;
				if (normalOptions && normalOptions.enabled === false) {
					normalOptions.radius = 0;
				}

				if (zones.length) {
					var j = 0,
						threshold = zones[j];
					while (point[zoneAxis] >= threshold.value) {
						threshold = zones[++j];
					}

					point.color = point.fillColor = threshold.color;
				}

				hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868

				// check if the point has specific visual options
				if (point.options) {
					for (key in pointAttrToOptions) {
						if (defined(normalOptions[pointAttrToOptions[key]])) {
							hasPointSpecificOptions = true;
						}
					}
				}

				// a specific marker config object is defined for the individual point:
				// create it's own attribute collection
				if (hasPointSpecificOptions) {
					normalOptions = normalOptions || {};
					pointAttr = [];
					stateOptions = normalOptions.states || {}; // reassign for individual point
					pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};

					// Handle colors for column and pies
					if (!seriesOptions.marker) { // column, bar, point
						// If no hover color is given, brighten the normal color. #1619, #2579
						pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) ||
							Color(point.color)
								.brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness)
								.get();
					}

					// normal point state inherits series wide normal state
					attr = { color: point.color }; // #868
					if (!defaultFillColor) { // Individual point color or negative color markers (#2219)
						attr.fillColor = point.color;
					}
					if (!defaultLineColor) {
						attr.lineColor = point.color; // Bubbles take point color, line markers use white
					}
					// Color is explicitly set to null or undefined (#1288, #4068)
					if (normalOptions.hasOwnProperty('color') && !normalOptions.color) {
						delete normalOptions.color;
					}
					pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]);

					// inherit from point normal and series hover
					pointAttr[HOVER_STATE] = series.convertAttribs(
						stateOptions[HOVER_STATE],
						seriesPointAttr[HOVER_STATE],
						pointAttr[NORMAL_STATE]
					);

					// inherit from point normal and series hover
					pointAttr[SELECT_STATE] = series.convertAttribs(
						stateOptions[SELECT_STATE],
						seriesPointAttr[SELECT_STATE],
						pointAttr[NORMAL_STATE]
					);

				// no marker config object is created: copy a reference to the series-wide
				// attribute collection
				} else {
					pointAttr = seriesPointAttr;
				}

				point.pointAttr = pointAttr;
			}
		}
	},

	/**
	 * Clear DOM objects and free up memory
	 */
	destroy: function () {
		var series = this,
			chart = series.chart,
			issue134 = /AppleWebKit\/533/.test(userAgent),
			destroy,
			i,
			data = series.data || [],
			point,
			prop,
			axis;

		// add event hook
		fireEvent(series, 'destroy');

		// remove all events
		removeEvent(series);

		// erase from axes
		each(series.axisTypes || [], function (AXIS) {
			axis = series[AXIS];
			if (axis) {
				erase(axis.series, series);
				axis.isDirty = axis.forceRedraw = true;
			}
		});

		// remove legend items
		if (series.legendItem) {
			series.chart.legend.destroyItem(series);
		}

		// destroy all points with their elements
		i = data.length;
		while (i--) {
			point = data[i];
			if (point && point.destroy) {
				point.destroy();
			}
		}
		series.points = null;

		// Clear the animation timeout if we are destroying the series during initial animation
		clearTimeout(series.animationTimeout);

		// Destroy all SVGElements associated to the series
		for (prop in series) {
			if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying

				// issue 134 workaround
				destroy = issue134 && prop === 'group' ?
					'hide' :
					'destroy';

				series[prop][destroy]();
			}
		}

		// remove from hoverSeries
		if (chart.hoverSeries === series) {
			chart.hoverSeries = null;
		}
		erase(chart.series, series);

		// clear all members
		for (prop in series) {
			delete series[prop];
		}
	},

	/**
	 * Return the graph path of a segment
	 */
	getSegmentPath: function (segment) {
		var series = this,
			segmentPath = [],
			step = series.options.step;

		// build the segment line
		each(segment, function (point, i) {

			var plotX = point.plotX,
				plotY = point.plotY,
				lastPoint;

			if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
				segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));

			} else {

				// moveTo or lineTo
				segmentPath.push(i ? L : M);

				// step line?
				if (step && i) {
					lastPoint = segment[i - 1];
					if (step === 'right') {
						segmentPath.push(
							lastPoint.plotX,
							plotY
						);

					} else if (step === 'center') {
						segmentPath.push(
							(lastPoint.plotX + plotX) / 2,
							lastPoint.plotY,
							(lastPoint.plotX + plotX) / 2,
							plotY
						);

					} else {
						segmentPath.push(
							plotX,
							lastPoint.plotY
						);
					}
				}

				// normal line to next point
				segmentPath.push(
					point.plotX,
					point.plotY
				);
			}
		});

		return segmentPath;
	},

	/**
	 * Get the graph path
	 */
	getGraphPath: function () {
		var series = this,
			graphPath = [],
			segmentPath,
			singlePoints = []; // used in drawTracker

		// Divide into segments and build graph and area paths
		each(series.segments, function (segment) {

			segmentPath = series.getSegmentPath(segment);

			// add the segment to the graph, or a single point for tracking
			if (segment.length > 1) {
				graphPath = graphPath.concat(segmentPath);
			} else {
				singlePoints.push(segment[0]);
			}
		});

		// Record it for use in drawGraph and drawTracker, and return graphPath
		series.singlePoints = singlePoints;
		series.graphPath = graphPath;

		return graphPath;

	},

	/**
	 * Draw the actual graph
	 */
	drawGraph: function () {
		var series = this,
			options = this.options,
			props = [['graph', options.lineColor || this.color, options.dashStyle]],
			lineWidth = options.lineWidth,
			roundCap = options.linecap !== 'square',
			graphPath = this.getGraphPath(),
			fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph
			zones = this.zones;

		each(zones, function (threshold, i) {
			props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]);
		});

		// Draw the graph
		each(props, function (prop, i) {
			var graphKey = prop[0],
				graph = series[graphKey],
				attribs;

			if (graph) {
				stop(graph); // cancel running animations, #459
				graph.animate({ d: graphPath });

			} else if ((lineWidth || fillColor) && graphPath.length) { // #1487
				attribs = {
					stroke: prop[1],
					'stroke-width': lineWidth,
					fill: fillColor,
					zIndex: 1 // #1069
				};
				if (prop[2]) {
					attribs.dashstyle = prop[2];
				} else if (roundCap) {
					attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
				}

				series[graphKey] = series.chart.renderer.path(graphPath)
					.attr(attribs)
					.add(series.group)
					.shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932
			}
		});
	},

	/**
	 * Clip the graphs into the positive and negative coloured graphs
	 */
	applyZones: function () {
		var series = this,
			chart = this.chart,
			renderer = chart.renderer,
			zones = this.zones,
			translatedFrom,
			translatedTo,
			clips = this.clips || [],
			clipAttr,
			graph = this.graph,
			area = this.area,
			chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight),
			zoneAxis = this.zoneAxis || 'y',
			axis = this[zoneAxis + 'Axis'],
			extremes,
			reversed = axis.reversed,
			inverted = chart.inverted,
			horiz = axis.horiz,
			pxRange,
			pxPosMin,
			pxPosMax,
			ignoreZones = false;

		if (zones.length && (graph || area)) {
			// The use of the Color Threshold assumes there are no gaps
			// so it is safe to hide the original graph and area
			if (graph) {
				graph.hide();
			}
			if (area) {
				area.hide();
			}

			// Create the clips
			extremes = axis.getExtremes();
			each(zones, function (threshold, i) {

				translatedFrom = reversed ?
					(horiz ? chart.plotWidth : 0) :
					(horiz ? 0 : axis.toPixels(extremes.min));
				translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax);
				translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax);

				if (ignoreZones) {
					translatedFrom = translatedTo = axis.toPixels(extremes.max);
				}

				pxRange = Math.abs(translatedFrom - translatedTo);
				pxPosMin = mathMin(translatedFrom, translatedTo);
				pxPosMax = mathMax(translatedFrom, translatedTo);
				if (axis.isXAxis) {
					clipAttr = {
						x: inverted ? pxPosMax : pxPosMin,
						y: 0,
						width: pxRange,
						height: chartSizeMax
					};
					if (!horiz) {
						clipAttr.x = chart.plotHeight - clipAttr.x;
					}
				} else {
					clipAttr = {
						x: 0,
						y: inverted ? pxPosMax : pxPosMin,
						width: chartSizeMax,
						height: pxRange
					};
					if (horiz) {
						clipAttr.y = chart.plotWidth - clipAttr.y;
					}
				}

				/// VML SUPPPORT
				if (chart.inverted && renderer.isVML) {
					if (axis.isXAxis) {
						clipAttr = {
							x: 0,
							y: reversed ? pxPosMin : pxPosMax,
							height: clipAttr.width,
							width: chart.chartWidth
						};
					} else {
						clipAttr = {
							x: clipAttr.y - chart.plotLeft - chart.spacingBox.x,
							y: 0,
							width: clipAttr.height,
							height: chart.chartHeight
						};
					}
				}
				/// END OF VML SUPPORT

				if (clips[i]) {
					clips[i].animate(clipAttr);
				} else {
					clips[i] = renderer.clipRect(clipAttr);

					if (graph) {
						series['zoneGraph' + i].clip(clips[i]);
					}

					if (area) {
						series['zoneArea' + i].clip(clips[i]);
					}
				}
				// if this zone extends out of the axis, ignore the others
				ignoreZones = threshold.value > extremes.max;
			});
			this.clips = clips;
		}
	},

	/**
	 * Initialize and perform group inversion on series.group and series.markerGroup
	 */
	invertGroups: function () {
		var series = this,
			chart = series.chart;

		// Pie, go away (#1736)
		if (!series.xAxis) {
			return;
		}

		// A fixed size is needed for inversion to work
		function setInvert() {
			var size = {
				width: series.yAxis.len,
				height: series.xAxis.len
			};

			each(['group', 'markerGroup'], function (groupName) {
				if (series[groupName]) {
					series[groupName].attr(size).invert();
				}
			});
		}

		addEvent(chart, 'resize', setInvert); // do it on resize
		addEvent(series, 'destroy', function () {
			removeEvent(chart, 'resize', setInvert);
		});

		// Do it now
		setInvert(); // do it now

		// On subsequent render and redraw, just do setInvert without setting up events again
		series.invertGroups = setInvert;
	},

	/**
	 * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
	 * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
	 */
	plotGroup: function (prop, name, visibility, zIndex, parent) {
		var group = this[prop],
			isNew = !group;

		// Generate it on first call
		if (isNew) {
			this[prop] = group = this.chart.renderer.g(name)
				.attr({
					visibility: visibility,
					zIndex: zIndex || 0.1 // IE8 needs this
				})
				.add(parent);
		}
		// Place it on first and subsequent (redraw) calls
		group[isNew ? 'attr' : 'animate'](this.getPlotBox());
		return group;
	},

	/**
	 * Get the translation and scale for the plot area of this series
	 */
	getPlotBox: function () {
		var chart = this.chart,
			xAxis = this.xAxis,
			yAxis = this.yAxis;

		// Swap axes for inverted (#2339)
		if (chart.inverted) {
			xAxis = yAxis;
			yAxis = this.xAxis;
		}
		return {
			translateX: xAxis ? xAxis.left : chart.plotLeft,
			translateY: yAxis ? yAxis.top : chart.plotTop,
			scaleX: 1, // #1623
			scaleY: 1
		};
	},

	/**
	 * Render the graph and markers
	 */
	render: function () {
		var series = this,
			chart = series.chart,
			group,
			options = series.options,
			animation = options.animation,
			// Animation doesn't work in IE8 quirks when the group div is hidden,
			// and looks bad in other oldIE
			animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0,
			visibility = series.visible ? VISIBLE : HIDDEN,
			zIndex = options.zIndex,
			hasRendered = series.hasRendered,
			chartSeriesGroup = chart.seriesGroup;

		// the group
		group = series.plotGroup(
			'group',
			'series',
			visibility,
			zIndex,
			chartSeriesGroup
		);

		series.markerGroup = series.plotGroup(
			'markerGroup',
			'markers',
			visibility,
			zIndex,
			chartSeriesGroup
		);

		// initiate the animation
		if (animDuration) {
			series.animate(true);
		}

		// cache attributes for shapes
		series.getAttribs();

		// SVGRenderer needs to know this before drawing elements (#1089, #1795)
		group.inverted = series.isCartesian ? chart.inverted : false;

		// draw the graph if any
		if (series.drawGraph) {
			series.drawGraph();
			series.applyZones();
		}

		each(series.points, function (point) {
			if (point.redraw) {
				point.redraw();
			}
		});

		// draw the data labels (inn pies they go before the points)
		if (series.drawDataLabels) {
			series.drawDataLabels();
		}

		// draw the points
		if (series.visible) {
			series.drawPoints();
		}

		// draw the mouse tracking area
		if (series.drawTracker && series.options.enableMouseTracking !== false) {
			series.drawTracker();
		}

		// Handle inverted series and tracker groups
		if (chart.inverted) {
			series.invertGroups();
		}

		// Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839).
		if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
			group.clip(chart.clipRect);
		}

		// Run the animation
		if (animDuration) {
			series.animate();
		}

		// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
		// which should be available to the user).
		if (!hasRendered) {
			if (animDuration) {
				series.animationTimeout = setTimeout(function () {
					series.afterAnimate();
				}, animDuration);
			} else {
				series.afterAnimate();
			}
		}

		series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
		// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
		series.hasRendered = true;
	},

	/**
	 * Redraw the series after an update in the axes.
	 */
	redraw: function () {
		var series = this,
			chart = series.chart,
			wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
			wasDirty = series.isDirty,
			group = series.group,
			xAxis = series.xAxis,
			yAxis = series.yAxis;

		// reposition on resize
		if (group) {
			if (chart.inverted) {
				group.attr({
					width: chart.plotWidth,
					height: chart.plotHeight
				});
			}

			group.animate({
				translateX: pick(xAxis && xAxis.left, chart.plotLeft),
				translateY: pick(yAxis && yAxis.top, chart.plotTop)
			});
		}

		series.translate();
		series.render();
		if (wasDirtyData) {
			fireEvent(series, 'updatedData');
		}
		if (wasDirty || wasDirtyData) {			// #3945 recalculate the kdtree when dirty
			delete this.kdTree; // #3868 recalculate the kdtree with dirty data
		}
	},

	/**
	 * KD Tree && PointSearching Implementation
	 */

	kdDimensions: 1,
	kdAxisArray: ['clientX', 'plotY'],

	searchPoint: function (e, compareX) {
		var series = this,
			xAxis = series.xAxis,
			yAxis = series.yAxis,
			inverted = series.chart.inverted;

		return this.searchKDTree({
			clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos,
			plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos
		}, compareX);
	},

	buildKDTree: function () {
		var series = this,
			dimensions = series.kdDimensions;

		// Internal function
		function _kdtree(points, depth, dimensions) {
			var axis, median, length = points && points.length;

			if (length) {

				// alternate between the axis
				axis = series.kdAxisArray[depth % dimensions];

				// sort point array
				points.sort(function(a, b) {
					return a[axis] - b[axis];
				});

				median = Math.floor(length / 2);

				// build and return nod
				return {
					point: points[median],
					left: _kdtree(points.slice(0, median), depth + 1, dimensions),
					right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
				};

			}
		}

		// Start the recursive build process with a clone of the points array and null points filtered out (#3873)
		function startRecursive() {
			var points = grep(series.points, function (point) {
				return point.y !== null;
			});

			series.kdTree = _kdtree(points, dimensions, dimensions);
		}
		delete series.kdTree;

		if (series.options.kdSync) {  // For testing tooltips, don't build async
			startRecursive();
		} else {
			setTimeout(startRecursive);
		}
	},

	searchKDTree: function (point, compareX) {
		var series = this,
			kdX = this.kdAxisArray[0],
			kdY = this.kdAxisArray[1],
			kdComparer = compareX ? 'distX' : 'dist';

		// Set the one and two dimensional distance on the point object
		function setDistance(p1, p2) {
			var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
				y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
				r = (x || 0) + (y || 0);

			p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE;
			p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE;
		}
		function _search(search, tree, depth, dimensions) {
			var point = tree.point,
				axis = series.kdAxisArray[depth % dimensions],
				tdist,
				sideA,
				sideB,
				ret = point,
				nPoint1,
				nPoint2;

			setDistance(search, point);

			// Pick side based on distance to splitting point
			tdist = search[axis] - point[axis];
			sideA = tdist < 0 ? 'left' : 'right';
			sideB = tdist < 0 ? 'right' : 'left';

			// End of tree
			if (tree[sideA]) {
				nPoint1 =_search(search, tree[sideA], depth + 1, dimensions);

				ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point);
			}
			if (tree[sideB]) {
				// compare distance to current best to splitting point to decide wether to check side B or not
				if (Math.sqrt(tdist * tdist) < ret[kdComparer]) {
					nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
					ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret);
				}
			}

			return ret;
		}

		if (!this.kdTree) {
			this.buildKDTree();
		}

		if (this.kdTree) {
			return _search(point,
				this.kdTree, this.kdDimensions, this.kdDimensions);
		}
	}

}; // end Series prototype


text:
package org.smartdeveloperhub.harvesters.ci.backend.domain;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import java.net.URI;
import java.util.Date;
import java.util.List;

import org.smartdeveloperhub.harvesters.ci.backend.domain.command.CreateBuildCommand;
import org.smartdeveloperhub.harvesters.ci.backend.domain.command.CreateExecutionCommand;
import org.smartdeveloperhub.harvesters.ci.backend.domain.command.DeleteBuildCommand;
import org.smartdeveloperhub.harvesters.ci.backend.domain.command.DeleteExecutionCommand;
import org.smartdeveloperhub.harvesters.ci.backend.domain.command.FinishExecutionCommand;
import org.smartdeveloperhub.harvesters.ci.backend.domain.command.RegisterServiceCommand;
import org.smartdeveloperhub.harvesters.ci.backend.domain.command.UpdateBuildCommand;
import org.smartdeveloperhub.harvesters.ci.backend.domain.persistence.BuildRepository;
import org.smartdeveloperhub.harvesters.ci.backend.domain.persistence.ExecutionRepository;
import org.smartdeveloperhub.harvesters.ci.backend.domain.persistence.ServiceRepository;

public final class ContinuousIntegrationService {

	private final class BuildDeleter extends BuildVisitor {

		private void deleteBuild(Build aBuild) {
			buildRepository().remove(aBuild);
			for(URI executionId:aBuild.executions()) {
				Execution execution = executionRepository().executionOfId(executionId);
				if(execution!=null) {
					executionRepository().remove(execution);
				}
			}
			aBuild.executions().clear();
		}

		@Override
		public void visitSimpleBuild(SimpleBuild aBuild) {
			deleteBuild(aBuild);
		}

		@Override
		public void visitCompositeBuild(CompositeBuild aBuild) {
			deleteBuild(aBuild);
			for(URI childId:aBuild.subBuilds()) {
				Build subBuild = buildRepository().buildOfId(childId);
				if(subBuild!=null) {
					deleteBuild(subBuild);
				}
			}
			aBuild.subBuilds().clear();
		}

		@Override
		public void visitSubBuild(SubBuild aBuild) {
			deleteBuild(aBuild);
			CompositeBuild parent=
				buildRepository().
					buildOfId(aBuild.parentId(),CompositeBuild.class);
			if(parent!=null) {
				parent.removeSubBuild(aBuild);
			}
		}
	}

	private static final String EXECUTION_IS_NOT_REGISTERED = "Execution '%s' is not registered";
	private static final String BUILD_IS_NOT_REGISTERED     = "Build '%s' is not registered";
	private static final String COMMAND_CANNOT_BE_NULL      = "Command cannot be null";

	private ServiceRepository serviceRepository;
	private BuildRepository buildRepository;
	private ExecutionRepository executionRepository;

	public ContinuousIntegrationService(ServiceRepository serviceRepository, BuildRepository buildRepository, ExecutionRepository executionRepository) {
		setServiceRepository(serviceRepository);
		setBuildRepository(buildRepository);
		setExecutionRepository(executionRepository);
	}

	protected void setServiceRepository(ServiceRepository serviceRepository) {
		checkNotNull(serviceRepository,"Service repository cannot be null");
		this.serviceRepository = serviceRepository;
	}

	protected void setBuildRepository(BuildRepository buildRepository) {
		checkNotNull(buildRepository,"Build repository cannot be null");
		this.buildRepository = buildRepository;
	}

	protected void setExecutionRepository(ExecutionRepository executionRepository) {
		checkNotNull(executionRepository,"Execution repository cannot be null");
		this.executionRepository = executionRepository;
	}

	protected ServiceRepository serviceRepository() {
		return this.serviceRepository;
	}

	protected BuildRepository buildRepository() {
		return this.buildRepository;
	}

	protected ExecutionRepository executionRepository() {
		return this.executionRepository;
	}

	private Service findService(CreateBuildCommand aCommand) {
		URI serviceId=aCommand.serviceId();
		Service service = serviceRepository().serviceOfId(serviceId);
		checkArgument(service!=null,"Service '%s' is not registered",serviceId);
		return service;
	}

	public List<URI> getRegisteredServices() {
		return serviceRepository().serviceIds();
	}

	public Service getService(URI serviceId) {
		checkNotNull(serviceId,"Service identifier be null");
		return Service.newInstance(serviceRepository().serviceOfId(serviceId));
	}

	public Build getBuild(URI buildId) {
		checkNotNull(buildId,"Build identifier cannot be null");
		Build build = buildRepository().buildOfId(buildId);
		return Build.newInstance(build);
	}

	public Execution getExecution(URI executionId) {
		checkNotNull(executionId,"Execution identifier cannot be null");
		Execution execution = executionRepository().executionOfId(executionId);
		return Execution.newInstance(execution);
	}

	public void registerService(RegisterServiceCommand aCommand) {
		checkNotNull(aCommand,COMMAND_CANNOT_BE_NULL);
		URI serviceId=aCommand.serviceId();

		Service service = serviceRepository().serviceOfId(serviceId);
		checkArgument(service==null,"Service '%s' is already registered",serviceId);

		service=Service.newInstance(serviceId);
		serviceRepository().add(service);
	}

	public void createBuild(CreateBuildCommand aCommand) {
		checkNotNull(aCommand,COMMAND_CANNOT_BE_NULL);
		URI buildId=aCommand.buildId();
		Build build=null;
		if(aCommand.simple()) {
			Service service = findService(aCommand);
			build=service.addSimpleBuild(buildId,aCommand.title());
		} else if(aCommand.composite()) {
			Service service = findService(aCommand);
			build=service.addCompositeBuild(buildId,aCommand.title());
		} else {
			URI parentId = aCommand.subBuildOf();
			Build parent = buildRepository().buildOfId(parentId);
			checkArgument(parent instanceof CompositeBuild,"Parent build '%s' is not composite",parentId);
			CompositeBuild cb=(CompositeBuild)parent;
			build=cb.addSubBuild(buildId, aCommand.title());
		}
		build.setDescription(aCommand.description());
		build.setCreatedOn(aCommand.createdOn());
		buildRepository().add(build);
	}

	public void updateBuild(UpdateBuildCommand aCommand) {
		checkNotNull(aCommand,COMMAND_CANNOT_BE_NULL);
		URI buildId=aCommand.buildId();
		Build build = buildRepository().buildOfId(buildId);
		checkArgument(build!=null,BUILD_IS_NOT_REGISTERED,buildId);
		build.setTitle(aCommand.title());
		build.setCodebase(new Codebase(aCommand.codebase(),aCommand.branchName()));
		build.setDescription(aCommand.description());
		build.setCreatedOn(aCommand.createdOn());
	}

	public void deleteBuild(DeleteBuildCommand aCommand) {
		checkNotNull(aCommand,COMMAND_CANNOT_BE_NULL);
		URI buildId=aCommand.buildId();
		Build build = buildRepository().buildOfId(buildId);
		checkArgument(build!=null,BUILD_IS_NOT_REGISTERED,buildId);
		build.accept(new BuildDeleter());
	}

	public void createExecution(CreateExecutionCommand aCommand) {
		checkNotNull(aCommand,COMMAND_CANNOT_BE_NULL);
		URI buildId=aCommand.buildId();
		URI executionId=aCommand.executionId();
		Date createdOn=aCommand.createdOn();
		Build build = buildRepository().buildOfId(buildId);
		checkArgument(build!=null,BUILD_IS_NOT_REGISTERED,buildId);
		checkState(!build.executions().contains(executionId),"Execution '%s' is already registered in build '%s'",executionId,buildId);
		String commitId = aCommand.commitId();
		Codebase codebase = new Codebase(aCommand.codebase(),aCommand.branchName());
		Execution execution=build.addExecution(executionId, createdOn,codebase,commitId);
		if(aCommand.status()!=null && aCommand.finishedOn()!=null) {
			Result result=new Result(aCommand.status(),aCommand.finishedOn());
			execution.finish(result);
		}
		executionRepository().add(execution);
	}

	public void finishExecution(FinishExecutionCommand aCommand) {
		checkNotNull(aCommand,COMMAND_CANNOT_BE_NULL);
		URI executionId=aCommand.executionId();
		Execution execution = executionRepository().executionOfId(executionId);
		checkArgument(execution!=null,EXECUTION_IS_NOT_REGISTERED,executionId);
		checkState(!execution.isFinished(),"Execution '%s' is already finished",executionId);
		Result result=new Result(aCommand.status(),aCommand.finishedOn());
		execution.finish(result);
	}

	public void deleteExecution(DeleteExecutionCommand aCommand) {
		checkNotNull(aCommand,COMMAND_CANNOT_BE_NULL);
		URI executionId=aCommand.executionId();
		Execution execution = executionRepository().executionOfId(executionId);
		checkArgument(execution!=null,EXECUTION_IS_NOT_REGISTERED,executionId);
		Build build = buildRepository().buildOfId(execution.buildId());
		checkArgument(build!=null,BUILD_IS_NOT_REGISTERED,build.buildId());
		build.removeExecution(execution);
		executionRepository().remove(execution);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Shopsys\CodingStandards\CsFixer;

use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOption;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Shopsys\CodingStandards\Exception\NamespaceNotFoundException;
use SplFileInfo;

final class ForbiddenPrivateVisibilityFixer implements ConfigurableFixerInterface
{
    private const OPTION_ANALYZED_NAMESPACE = 'analyzed_namespaces';

    private array $analyzedNamespaces = [];

    /**
     * {@inheritdoc}
     */
    public function configure(?array $configuration = null): void
    {
        if ($configuration !== null) {
            $this->analyzedNamespaces = $this->extractNamespaces($configuration);
        }
    }

    /**
     * @return \PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface
     */
    public function getConfigurationDefinition(): FixerConfigurationResolverInterface
    {
        return new FixerConfigurationResolver(
            new FixerOption(
                self::OPTION_ANALYZED_NAMESPACE,
                'Define analyzed namespace.',
            )
        );
    }

    /**
     * @param array $configuration
     * @return array
     */
    private function extractNamespaces(array $configuration): array
    {
        if (!array_key_exists(self::OPTION_ANALYZED_NAMESPACE, $configuration)) {
            return [];
        }

        if (!is_array($configuration[self::OPTION_ANALYZED_NAMESPACE])) {
            throw new InvalidFixerConfigurationException(
                $this->getName(),
                'Namespace configuration has to be an array'
            );
        }

        return $configuration[self::OPTION_ANALYZED_NAMESPACE];
    }

    /**
     * {@inheritdoc}
     */
    public function getDefinition(): FixerDefinitionInterface
    {
        return new FixerDefinition(
            'Properties and methods should be public or protected in defined namespace',
            [
                new CodeSample(
                    '<?php
namespace Some\Namespace;
class SomeClass
{
private $property;
}'
                ),
                new CodeSample(
                    '<?php
namespace Some\Namespace;
class SomeClass
{
private function method()
{
    ...
}
}'
                ),
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens): bool
    {
        return $tokens->isAllTokenKindsFound([T_PRIVATE]) && $this->checkNamespace($tokens);
    }

    /**
     * @param \PhpCsFixer\Tokenizer\Tokens $tokens
     * @return bool
     */
    private function checkNamespace(Tokens $tokens): bool
    {
        try {
            $namespace = $this->getNamespace($tokens);
        } catch (NamespaceNotFoundException $e) {
            return false;
        }

        foreach ($this->analyzedNamespaces as $analyzedNamespace) {
            if ($this->namespaceStartsWith($namespace, $analyzedNamespace)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param \PhpCsFixer\Tokenizer\Tokens $tokens
     * @throws \Shopsys\CodingStandards\Exception\NamespaceNotFoundException
     * @return string
     */
    private function getNamespace(Tokens $tokens): string
    {
        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_NAMESPACE)) {
                continue;
            }

            $namespaceStartIndex = $tokens->getNextMeaningfulToken($index);
            $namespaceEndIndex = $tokens->getPrevMeaningfulToken($tokens->getNextTokenOfKind($index, [';']));

            return $tokens->generatePartialCode($namespaceStartIndex, $namespaceEndIndex);
        }

        throw new NamespaceNotFoundException('No namespace found');
    }

    /**
     * @param string $fullNamespace
     * @param string $namespacePrefix
     * @return bool
     */
    private function namespaceStartsWith(string $fullNamespace, string $namespacePrefix): bool
    {
        return strncmp($fullNamespace, $namespacePrefix, strlen($namespacePrefix)) === 0;
    }

    /**
     * {@inheritdoc}
     */
    public function fix(SplFileInfo $file, Tokens $tokens): void
    {
        foreach (array_keys($tokens->findGivenKind(T_PRIVATE)) as $index) {
            $tokens[$index] = new Token([T_PROTECTED, 'protected']);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isRisky(): bool
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'Shopsys/forbidden_private_visibility';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority(): int
    {
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(SplFileInfo $file): bool
    {
        return true;
    }
}


text:
package org.apache.ambari.server.controller;

import org.apache.ambari.server.state.Config;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class ConfigGroupRequest {
  private Long id;
  private String clusterName;
  private String groupName;
  private String tag;
  private String description;
  private String serviceConfigVersionNote;
  private Set<String> hosts;
  private Map<String, Config> configs;

  public ConfigGroupRequest(Long id, String clusterName, String groupName,
                            String tag, String description, Set<String> hosts,
                            Map<String, Config> configs) {
    this.id = id;
    this.clusterName = clusterName;
    this.groupName = groupName;
    this.tag = tag;
    this.description = description;
    this.hosts = hosts;
    this.configs = configs;
  }

  public String getClusterName() {
    return clusterName;
  }

  public void setClusterName(String clusterName) {
    this.clusterName = clusterName;
  }

  public String getGroupName() {
    return groupName;
  }

  public void setGroupName(String groupName) {
    this.groupName = groupName;
  }

  public String getTag() {
    return tag;
  }

  public void setTag(String tag) {
    this.tag = tag;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public Set<String> getHosts() {
    return hosts;
  }

  public void setHosts(Set<String> hosts) {
    this.hosts = hosts;
  }

  public Map<String, Config> getConfigs() {
    return configs;
  }

  public void setConfigs(Map<String, Config> configs) {
    this.configs = configs;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getServiceConfigVersionNote() {
    return serviceConfigVersionNote;
  }

  public void setServiceConfigVersionNote(String serviceConfigVersionNote) {
    this.serviceConfigVersionNote = serviceConfigVersionNote;
  }
}


text:
[![Stories in Ready](https://badge.waffle.io/david-meza/park-locator.png?label=ready&title=Ready)](https://waffle.io/david-meza/park-locator)
# Park Locator

Park Locator is a mapping tool for Raleigh parks that allows you to find the closest park to your home, search for parks by amenity, get directions to a park, and explore program offerings at the parks.

## Live Application

* Raleigh NC: [Open](https://maps.raleighnc.gov/parklocator)

## Demo

* V2 - Esri: [Open](https://park-locator-esri.surge.sh)
* Esri Experimental (API V4): [Open](https://park-locator-esri-test.surge.sh)

## Other Versions / Branches

* V1 (Deprecated): [Open](https://park-locator.surge.sh)
* V2 - Google Maps (Deprecated - No longer maintained): [Open](https://park-locator-gmaps.surge.sh)
* Backup Host - Heroku: [Open](https://park-locator.herokuapp.com)
* Backup Host 2 - AWS: [Open](http://goo.gl/qGCG4B)

## Build & development

To install dependencies run `npm install` and `bower install`.

The running of tasks for this application was automated using Grunt.

To produce a distributable/minified version of the app run `grunt build`.

To preview the application in development in a local live server run `grunt serve`.

## Testing

Running `grunt test` will run the unit tests with karma.


text:
package nl.tudelft.dnainator.javafx.widgets.animations;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.testfx.framework.junit.ApplicationTest;
import nl.tudelft.dnainator.javafx.widgets.animations.TransitionAnimation.Position;
import org.junit.Before;
import org.junit.Test;

/**
 * This class tests the implementation of the {@link DownSlideAnimation}.
 * This animation causes a {@link Pane} to slide in a downward direction.
 */
public class DownSlideAnimationTest extends ApplicationTest {

	private Pane pane;
	private DownSlideAnimation dsa;

	@Override
	public void start(Stage stage) throws Exception {
		pane = new Pane();
	}

	/**
	 * Set up common variables.
	 */
	@Before
	public void setup() {
		// CHECKSTYLE.OFF: MagicNumber
		dsa = new DownSlideAnimation(pane, 100.0, 1.0, Position.TOP);
		// CHECKSTYLE.ON: MagicNumber
	}

	/**
	 * Test setting the size of the pane.
	 */
	@Test
	public void testSetCurSize() {
		// CHECKSTYLE.OFF: MagicNumber
		dsa.setCurSize(0.2);
		assertEquals(dsa.newSize, dsa.size * 0.2, 0.001);

		dsa = new DownSlideAnimation(pane, 100.0, 1.0, Position.BOTTOM);
		dsa.setCurSize(0.2);
		assertEquals(dsa.newSize, dsa.size * (1.0 - 0.2), 0.001);

		dsa = new DownSlideAnimation(pane, 100.0, 1.0, Position.RIGHT);
		dsa.setCurSize(0.2);
		assertEquals(dsa.newSize, dsa.size, 0.001);
		// CHECKSTYLE.ON: MagicNumber
	}

	/**
	 * Test setting visibility of the pane.
	 */
	@Test
	public void testVisibility() {
		// CHECKSTYLE.OFF: MagicNumber
		pane.setVisible(true);
		dsa.setRate(-0.5);
		dsa.setVisibility(pane, Position.TOP);
		assertFalse(pane.isVisible());

		pane.setVisible(true);
		dsa.setRate(0.5);
		dsa.setVisibility(pane, Position.TOP);
		assertTrue(pane.isVisible());

		pane.setVisible(true);
		dsa.setRate(-0.5);
		dsa.setVisibility(pane, Position.BOTTOM);
		assertTrue(pane.isVisible());

		pane.setVisible(true);
		dsa.setRate(0.5);
		dsa.setVisibility(pane, Position.BOTTOM);
		assertFalse(pane.isVisible());
		// CHECKSTYLE.ON: MagicNumber
	}
}


text:
require 'spec_helper'
describe Bubbles::Monitorable do

  before(:each) do
    @name = "orly"
    @description = "yahrly"
    @initial_value = 1
    @monitorable = monitorable
    @observer = mock
    @observer.define_singleton_method(:update, lambda { |monitorable|  })
  end

  it "should return an initial value of nil" do
    monitorable(@name, @description, nil).value.should be nil
  end

  it "should return the initial value as provided" do
    @monitorable.value.should be @initial_value
  end

  it "should return the value set using block method" do
    new_value = 10
    @monitorable.change_monitored_value do |current_value|
      new_value
    end

    @monitorable.value.should be new_value
  end

  it "should return the value set using the operator method" do
    new_value = 4
    @monitorable.value=new_value

    @monitorable.value.should be new_value
  end

  it "should notify the observer when the value changes using the block method" do
    @monitorable.add_observer(@observer)
    @observer.should_receive(:update)
    @monitorable.change_monitored_value do |current_value|
      3
    end
  end

  it "should notify the observer when the value changes using the operator method" do
    @monitorable.add_observer(@observer)
    @observer.should_receive(:update)
    @monitorable.value=3
  end

  it "should pass the monitorable itself as the argument to the observers update method when using the operator method" do
    @monitorable.add_observer(@observer)
    @observer.should_receive(:update).with(@monitorable)
    @monitorable.value=3
  end

  it "should pass the monitorable itself as the argument to the observers update method when using the operator method" do
    @monitorable.add_observer(@observer)
    @observer.should_receive(:update).with(@monitorable)
    @monitorable.change_monitored_value do |current_value|
      3
    end
  end

  def monitorable name=@name, description=@description, initial_value=@initial_value
    Bubbles::MonitorableValue.new(name, description, initial_value)
  end

end


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Huxley</logradouro><bairro>Atuba</bairro><cidade>Colombo</cidade><uf>PR</uf><cep>83408180</cep></feed>


text:
package parts

import (
	"fmt"
	"runtime"

	"github.com/google/gxui"
	"github.com/google/gxui/mixins/outer"
)

const debugVerifyDetachOnGC = false

type DrawPaintOuter interface {
	outer.Attachable
	outer.Painter
	outer.Parenter
	outer.Sized
}

type DrawPaint struct {
	outer           DrawPaintOuter
	theme           gxui.Theme
	canvas          gxui.Canvas
	dirty           bool
	redrawRequested bool
}

func verifyDetach(o DrawPaintOuter) {
	if o.Attached() {
		panic(fmt.Errorf("%T garbage collected while still attached", o))
	}
}

func (d *DrawPaint) Init(outer DrawPaintOuter, theme gxui.Theme) {
	d.outer = outer
	d.theme = theme
	outer.OnDetach(func() {
		if d.canvas != nil {
			d.canvas.Release()
			d.canvas = nil
		}
	})

	if debugVerifyDetachOnGC {
		runtime.SetFinalizer(d.outer, verifyDetach)
	}
}

func (d *DrawPaint) Redraw() {
	if !d.redrawRequested {
		if p := d.outer.Parent(); p != nil {
			d.redrawRequested = true
			p.Redraw()
		}
	}
}

func (d *DrawPaint) Draw() gxui.Canvas {
	if !d.outer.Attached() {
		panic(fmt.Errorf("Attempting to draw a non-attached control %T", d.outer))
	}

	s := d.outer.Size()
	if s.Area() == 0 {
		return nil // No area to draw in
	}
	if d.canvas == nil || d.canvas.Size() != s || d.redrawRequested {
		if d.canvas != nil {
			d.canvas.Release()
		}
		d.canvas = d.theme.Driver().CreateCanvas(s)
		d.redrawRequested = false
		d.outer.Paint(d.canvas)
		d.canvas.Complete()
	}
	return d.canvas
}


text:
mindblow
========

Ghost theme


text:
namespace Microsoft.DocAsCode.Build.RestApi.Swagger.Internals
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    internal class SwaggerJsonBuilder
    {
        private IDictionary<string, SwaggerObject> _documentObjectCache;

        public SwaggerObjectBase Read(JsonReader reader)
        {
            _documentObjectCache = new Dictionary<string, SwaggerObject>();
            var token = JToken.ReadFrom(reader);
            var swagger = Build(token);
            return ResolveReferences(swagger);
        }

        private SwaggerObjectBase Build(JToken token)
        {
            var jObject = token as JObject;
            if (jObject != null)
            {
                JToken referenceToken;

                // Only one $ref is allowed inside a swagger JObject
                if (jObject.TryGetValue("$ref", out referenceToken))
                {
                    if (referenceToken.Type != JTokenType.String && referenceToken.Type != JTokenType.Null)
                    {
                        throw new JsonException($"JSON reference $ref property must have a string or null value, instead of {referenceToken.Type}, location: {referenceToken.Path}.");
                    }

                    SwaggerReferenceObject deferredObject = new SwaggerReferenceObject();
                    deferredObject.DeferredReference = (string)referenceToken;

                    // For swagger, other properties are still allowed besides $ref, e.g.
                    // "schema": {
                    //   "$ref": "#/defintions/foo"
                    //   "example": { }
                    // }
                    // Use Token property to keep other properties
                    // These properties cannot be referenced
                    jObject.Remove("$ref");
                    deferredObject.Token = jObject;
                    return deferredObject;
                }
                else
                {
                    string location = GetLocation(token);

                    SwaggerObject existingObject;
                    if (_documentObjectCache.TryGetValue(location, out existingObject))
                    {
                        return existingObject;
                    }

                    var swaggerObject = new SwaggerObject { Location = location };

                    foreach (KeyValuePair<string, JToken> property in jObject)
                    {
                        swaggerObject.Dictionary.Add(property.Key, Build(property.Value));
                    }

                    _documentObjectCache.Add(location, swaggerObject);
                    return swaggerObject;
                }
            }

            var jArray = token as JArray;
            if (jArray != null)
            {
                var swaggerArray = new SwaggerArray();
                foreach (var property in jArray)
                {
                    swaggerArray.Array.Add(Build(property));
                }

                return swaggerArray;
            }

            return new SwaggerValue
            {
                Token = token
            };
        }

        private SwaggerObjectBase ResolveReferences(SwaggerObjectBase swaggerBase)
        {
            if (swaggerBase.ReferencesResolved)
            {
                return swaggerBase;
            }

            swaggerBase.ReferencesResolved = true;
            switch (swaggerBase.ObjectType)
            {
                case SwaggerObjectType.ReferenceObject:
                    {
                        var swagger = (SwaggerReferenceObject)swaggerBase;
                        if (!string.IsNullOrEmpty(swagger.DeferredReference))
                        {
                            if (swagger.DeferredReference[0] != '#')
                            {
                                throw new JsonException($"reference \"{swagger.DeferredReference}\" is not supported. Reference must be inside current schema document starting with #");
                            }

                            SwaggerObject referencedObject;
                            if (!_documentObjectCache.TryGetValue(swagger.DeferredReference, out referencedObject))
                            {
                                throw new JsonException($"Could not resolve reference '{swagger.DeferredReference}' in the document.");
                            }

                            swagger.Reference = referencedObject;
                        }
                        return swagger;
                    }
                case SwaggerObjectType.Object:
                    {
                        var swagger = (SwaggerObject)swaggerBase;
                        foreach (var key in swagger.Dictionary.Keys.ToList())
                        {
                            swagger.Dictionary[key] = ResolveReferences(swagger.Dictionary[key]);
                        }
                        return swagger;
                    }
                case SwaggerObjectType.Array:
                    {
                        var swagger = (SwaggerArray)swaggerBase;
                        for (int i = 0; i < swagger.Array.Count; i++)
                        {
                            swagger.Array[i] = ResolveReferences(swagger.Array[i]);
                        }
                        return swagger;
                    }
                case SwaggerObjectType.ValueType:
                    return swaggerBase;
                default:
                    throw new NotSupportedException(swaggerBase.ObjectType.ToString());
            }
        }

        private static string GetLocation(JToken token)
        {
            if (token.Parent == null)
            {
                return "#";
            }

            IList<JToken> ancestors = token.AncestorsAndSelf().Reverse().ToList();

            var locations = new List<IJsonLocation>();
            for (int i = 0; i < ancestors.Count; i++)
            {
                JToken current = ancestors[i];
                switch (current.Type)
                {
                    case JTokenType.Property:
                        JProperty property = (JProperty)current;
                        locations.Add(new JsonObjectLocation(property.Name));
                        break;
                    case JTokenType.Array:
                    case JTokenType.Constructor:
                        if (i < ancestors.Count - 1)
                        {
                            var next = ancestors[i + 1];
                            int index = ((IList<JToken>)current).IndexOf(next);
                            locations.Add(new JsonIndexLocation(index));
                        }
                        break;
                }
            }

            StringBuilder sb = new StringBuilder();
            foreach (var state in locations)
            {
                state.WriteTo(sb);
            }

            return "#" + sb.ToString();
        }

        private class JsonIndexLocation : IJsonLocation
        {
            private readonly int _position;
            public JsonIndexLocation(int position)
            {
                _position = position;
            }

            public void WriteTo(StringBuilder sb)
            {
                sb.Append('/');
                sb.Append(_position);
            }
        }

        private class JsonObjectLocation : IJsonLocation
        {
            private readonly string _propertyName;
            public JsonObjectLocation(string propertyName)
            {
                _propertyName = propertyName;
            }

            public void WriteTo(StringBuilder sb)
            {
                sb.Append('/');
                sb.Append(EscapeReference(_propertyName));
            }

            /// <summary>
            /// Reverse to reference unescape described in http://tools.ietf.org/html/rfc6901#section-4
            /// </summary>
            /// <param name="reference"></param>
            /// <returns></returns>
            private static string EscapeReference(string reference)
            {
                return Uri.EscapeDataString(reference.Replace("~", "~0").Replace("/", "~1"));
            }
        }

        private interface IJsonLocation
        {
            void WriteTo(StringBuilder sb);
        }
    }
}


text:
(function(window) {
    'use strict';

    if (typeof window.epepite == "undefined") {
        window.epepite = {};
    }

    if (typeof epepite.DatePicker == "undefined") {
        epepite.DatePicker = {};
    }

    epepite.DatePicker.Translator = function(locale)
    {
        this.locale       = locale || 'en_EN';
        this.translations = {
            'en_EN' : {}
        };

        if (typeof epepite.DatePicker.Translations == "object") {
            for (var locale in epepite.DatePicker.Translations) {
                this.setTranslation(locale, epepite.DatePicker.Translations[locale]);
            }
        }
    };

    epepite.DatePicker.Translator.prototype.setCurrentLocale = function(locale)
    {
        this.locale = locale;

        return this;
    };

    epepite.DatePicker.Translator.prototype.getCurrentLocale = function()
    {
        return this.locale;
    };

    epepite.DatePicker.Translator.prototype.setTranslation = function(locale, translations)
    {
        this.translations[locale] = translations;

        return this;
    };

    epepite.DatePicker.Translator.prototype.trans = function(message, params, locale)
    {
        locale = locale || this.locale;

        if (typeof this.translations[locale] == "object") {
            var translate = '';

            if (typeof this.translations[locale][message] != "undefined") {
                translate = this.translations[locale][message];
            } else {
                var domain = this.translations[locale];
                var keys   = message.split('.');

                for (var i = 0; i < keys.length; i++) {
                    if (typeof domain[keys[i]] != "undefined") {
                        domain = domain[keys[i]];
                    } else {
                        return message;
                    }
                }

                translate = domain;
            }

            if (typeof translate == "string") {
                if (params) {
                    for (var key in params) {
                        if (params.hasOwnProperty(key)) {
                            translate = translate.replace(key, params[key]);
                        }
                    }
                }
            }

            return translate;
        }

        return message;
    };

    epepite.DatePicker.Translator.prototype.has = function(locale)
    {
        return (typeof this.translations[locale] != "undefined");
    };

})(window);


text:
<?php
namespace Sooh\Base\Form;
use Sooh\Base\Form\Error as form_err;
/**
 * 定义字段在不同情况下使用哪种表现形式, inputType可以是数组模式的回调函数
 * 已知缺陷:verifyPasswordCmp标记需要比较两次密码一致的时候,使用的是static变量保存的,估一个请求里只能有一次这种验证
 *
 * @author Simon Wang <hillstill_simon@163.com>
 */
class Item {
	const text = 'text';
	const datepicker = 'datepicker';
	const mulit= 'textarea';
	const passwd= 'password';
	const chkbox='checkbox';
	const radio = 'radio';
	const select= 'select';
	const hidden= 'hidden';
	const constval= 'const';
	const date = 'date';
	public $valForInput;
	public $capt;
	public $value;
	/**
	 *
	 * @var \Sooh\Base\Form\Options
	 */
	public $options;
	protected $inputDefault;
	protected $inputWhenUpdate=false;
	/**
	 * 构建input的工厂函数
	 *
	 * @param string $capt 标题
	 * @param mix $value 值
	 * @param string $inputDefault 默认的输入方式,可以是数组模式的回调函数
	 * @return \Sooh\Base\Form\Item
	 */
	public static function factory($capt,$value,$inputDefault) {
		$o = new Item();
		$o->capt=$capt;
		$o->value=$value;
		$o->inputDefault = $inputDefault;
		return $o;
	}
	/**
	 * 更多设置
	 * @param \Sooh\Base\Form\Options $options
	 * @param string $inputWhenUpdate 主要用于主键在更新时不可编辑,可以是数组模式的回调函数
	 * @return \Sooh\Base\Form\Item
	 */
	public function initMore($options=null,$inputWhenUpdate=null)
	{
		$this->options = $options;
		$this->inputWhenUpdate=$inputWhenUpdate;
		return $this;
	}
	/**
	 *
	 * @param string $crud
	 * @param array $record
	 * @return string
	 */
	public function input($crud=\Sooh\Base\Form\Broker::type_u)
	{
		if(!empty($this->inputWhenUpdate) && $crud===\Sooh\Base\Form\Broker::type_u){
			return $this->inputWhenUpdate;
		}else{
			return $this->inputDefault;
		}
	}
	public $verify=null;
	/**
	 *
	 * @param type $required
	 * @param type $min
	 * @param type $max
	 * @return \Sooh\Base\Form\Item
	 */
	public function verifyInteger($required=0,$min=0,$max=2000000000)
	{
		$this->verify=array('required'=>$required,'type'=>'int','min'=>$min,'max'=>$max);
		return $this;
	}
	/**
	 * 检查用户输入,返回错误描述(没问题返回空串),TODO: 日期类型
	 * @param string $inputVal 用户输入的值
	 * @param string $capt 输入项名称
	 * @param string $errClassName 指定错误类名称
	 * @return \Sooh\Base\Form\Error
	 */
	public function checkUserInput($inputVal,$capt,$errClassName=null)
	{
		if($errClassName==null){
			$errClassName = '\Sooh\Base\Form\Error';
		}
		$errClassName .= '::factory';
		if(!empty($this->verify)){
			if($this->verify['required'] && ($inputVal===null || $inputVal==='' )){
				return $errClassName($capt,form_err::REQUIRED);
			}else{
				switch ($this->verify['type']){
					case 'int':
						if($inputVal<$this->verify['min'] || $inputVal>$this->verify['max{']){
							return $errClassName($capt,form_err::INT_OVERFLOW,form_err::factoryParam($this->verify['min'], $this->verify['max']));
						}
						break;
					case 'str':
						$inputVal = strlen($inputVal);
						if($inputVal<$this->verify['min'] || $inputVal>$this->verify['max']){
							return $errClassName($capt,form_err::STR_LENGTH,form_err::factoryParam($this->verify['min'], $this->verify['max']));
						}
						break;
				}
			}
		}
		return null;
	}
	/**
	 * 英文标识串限制
	 * @param type $required
	 * @param type $min
	 * @param type $max
	 * @return \Sooh\Base\Form\Item
	 */
	public function verifyIdentifier($required=0,$min=0,$max=0)
	{
		$this->verify=array('required'=>$required,'type'=>'str','min'=>$min,'max'=>$max,'subcheck'=>'identifier');
		return $this;
	}
	/**
	 * 邮件地址串限制
	 * @param type $required
	 * @param type $min
	 * @param type $max
	 * @return \Sooh\Base\Form\Item
	 */
	public function verifyEmail($required=0,$min=0,$max=0)
	{
		$this->verify=array('required'=>$required,'type'=>'str','min'=>$min,'max'=>$max,'subcheck'=>'email');
		return $this;
	}
	/**
	 * 通用字符串限制
	 * @param type $required
	 * @param type $min
	 * @param type $max
	 * @return \Sooh\Base\Form\Item
	 */
	public function verifyString($required=0,$min=0,$max=0)
	{
		$this->verify=array('required'=>$required,'type'=>'str','min'=>$min,'max'=>$max,'subcheck'=>'default');
		return $this;
	}
	protected static $pwdCmp=null;
	/**
	 *
	 * @param type $min
	 * @param type $max
	 * @return \Sooh\Base\Form\Item
	 */
	public function verifyPasswordCmp($min=0,$max=0)
	{
		if(self::$pwdCmp==null){
			self::$pwdCmp= '__CSS_'.rand(10000,99999).'__';
			$this->verify=array('required'=>1,'type'=>'str','min'=>$min,'max'=>$max,'cssId'=>self::$pwdCmp);
		}else{
			$this->verify=array('required'=>1,'type'=>'str','min'=>$min,'max'=>$max,'cmpCssId'=>self::$pwdCmp);
		}
		return $this;
	}
}


text:
using namespace std;
using namespace IGCS;

DWORD WINAPI MainThread(LPVOID lpParam);
void DumpWindows();

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  reason, LPVOID lpReserved)
{
	DWORD threadID;

	DisableThreadLibraryCalls(hModule);

	switch (reason)
	{
		case DLL_PROCESS_ATTACH:
			CreateThread(
				NULL,
				0,
				MainThread,
				hModule,
				0,
				&threadID
			);
			break;
	}
	return TRUE;
}

// lpParam gets the hModule value of the DllMain process
DWORD WINAPI MainThread(LPVOID lpParam)
{
	Console::Init();
	Console::WriteHeader();
	DumpWindows();
	Console::Release();
	return 0;
}

void DumpWindows()
{
	IGCS::Utils::handle_data data;
	data.process_id = GetCurrentProcessId();
	EnumWindows(IGCS::Utils::enumWindowsCallback, (LPARAM)&data);
}


text:
package com.tvntd.service.api;

import java.util.ArrayList;

import com.tvntd.forms.UuidForm;

public class UuidResponse extends GenericResponse
{
    private UuidForm in;
    private ArrayList<String> failedUuids;

    public UuidResponse(UuidForm in)
    {
        super(GenericResponse.USER_HOME, "ok", null);
        this.in = in;
    }

    /**
     * @return the authorUuid
     */
    public String getAuthorUuid() {
        return in.getAuthorUuid();
    }

    /**
     * @return the uuidType
     */
    public String getUuidType() {
        return in.getUuidType();
    }

    /**
     * @return the uuids
     */
    public String[] getUuids() {
        return in.getUuids();
    }

    /**
     * @return the failedUuids
     */
    public ArrayList<String> getFailedUuids() {
        return failedUuids;
    }

    /**
     * @param failedUuids the failedUuids to set
     */
    public UuidResponse setFailedUuids(ArrayList<String> failedUuids) {
        this.failedUuids = failedUuids;
        return this;
    }
}


text:
This program identifies near-duplicates in a corpus using techniques described
by Professor William Arms of Cornell University in his lectures to the students
of INFO 4300, Information Retrieval, Fall 2012.

This program was written by Parker Moore (pjm336), Fall 2012.

It is hosten on GitHub at https://github.com/parkr/near-dup-detection

[![Build Status](https://travis-ci.org/parkr/near-dup-detection.svg?branch=master)](https://travis-ci.org/parkr/near-dup-detection?branch=master)

## Install

```
pip install git://github.com/parkr/near-dup-detection.git#egg=NearDuplicatesDetection
```

## Usage

    python ndd.py

## Explanation of Methodology

All of the logic for the program is built into the Detector class
(`detector.py`). This class contains the methods and instance variables needed
to detect near-duplicates, such as the `get_jaccard(file1, file2)` method, the
`calculate_sketches()` method and the fundamental `create_3grams()` method.

This program implements the standard procedure for detecting near-duplicates:

1. Generate n-grams (3-grams in this case) for each document. Assign these
    n-grams a unique ID based on a 64-bit hash.
2. Create 25 sketches for document based on 50 randomly selected
    numbers and some stuff we generated earlier:
    - `p` is the closest prime number to the # of n-grams
    - `a_s` random, in the range [1, p-1]
    - `b_s` random, in the range [0, p-1]
    - `x` is the n-gram ID (the hash generated in step 1)
    - using the equation: `f_s(x) = (a_s*x + b_s) % p`
    - note: this equation is calculated 25 times per document (one time per
            random pair `a_s` and `b_s`), but only the minimum result of
            `f_s(x)` for each of the 25 pairs is saved. Thus, at the end of
            the calculation, each document has 25 `f_min`'s, one for each
            pair of random numbers.
3. Go through each document and compare it to all the other documents using the
    Jaccard coefficient estimation equation : `J(d1, d2) = m/n`, where:
    - `m` = number of sketch values (must be at the same index in respective
        lists) which are the same between the two documents
    - `n` = number of samples (# of sketches)
4. Having defined an arbitrary Jaccard coefficient threshold of `0.5`, the
    program prints out the names of the documents whose Jaccard coefficient
    is greater than the threshold previously defined, as well as the corresponding
    Jaccard coefficient.

As an addendum to the project, the three "nearest neighbors" to the first ten
documents is calculated at the end using the same method (and the data from
before).

## License

Standard GPLv2 license applies. Copyright (2012) Parker Moore.


text:
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\User;

/**
 * Specific extension of the platform group menu renderer to select the default selected node
 *
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class SubscribedPlatformGroupMenuRenderer extends PlatformgroupMenuRenderer
{

    /**
     * Returns the default node id
     *
     * @return int
     */
    protected function getDefaultNodeId()
    {
        return 0;
    }
}