text:
console.warn("THREE.OrbitControls: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules.");
/**
 * @author qiao / https://github.com/qiao
 * @author mrdoob / http://mrdoob.com
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author erich666 / http://erichaines.com
 * @author ScieCode / http://github.com/sciecode
 */

// This set of controls performs orbiting, dollying (zooming), and panning.
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
//
//    Orbit - left mouse / touch: one-finger move
//    Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
//    Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move

THREE.OrbitControls = function (object, domElement) {
	if (domElement === undefined) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
	if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');

	this.object = object;
	this.domElement = domElement;

	// Set to false to disable this control
	this.enabled = true;

	// "target" sets the location of focus, where the object orbits around
	this.target = new THREE.Vector3();

	// How far you can dolly in and out ( PerspectiveCamera only )
	this.minDistance = 0;
	this.maxDistance = Infinity;

	// How far you can zoom in and out ( OrthographicCamera only )
	this.minZoom = 0;
	this.maxZoom = Infinity;

	// How far you can orbit vertically, upper and lower limits.
	// Range is 0 to Math.PI radians.
	this.minPolarAngle = 0; // radians
	this.maxPolarAngle = Math.PI; // radians

	// How far you can orbit horizontally, upper and lower limits.
	// If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
	this.minAzimuthAngle = -Infinity; // radians
	this.maxAzimuthAngle = Infinity; // radians

	// Set to true to enable damping (inertia)
	// If damping is enabled, you must call controls.update() in your animation loop
	this.enableDamping = false;
	this.dampingFactor = 0.05;

	// This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
	// Set to false to disable zooming
	this.enableZoom = true;
	this.zoomSpeed = 1.0;

	// Set to false to disable rotating
	this.enableRotate = true;
	this.rotateSpeed = 1.0;

	// Set to false to disable panning
	this.enablePan = true;
	this.panSpeed = 1.0;
	this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
	this.keyPanSpeed = 7.0; // pixels moved per arrow key push

	// Set to true to automatically rotate around the target
	// If auto-rotate is enabled, you must call controls.update() in your animation loop
	this.autoRotate = false;
	this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60

	// Set to false to disable use of the keys
	this.enableKeys = true;

	// The four arrow keys
	this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };

	// Mouse buttons
	this.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN };

	// Touch fingers
	this.touches = { ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN };

	// for reset
	this.target0 = this.target.clone();
	this.position0 = this.object.position.clone();
	this.zoom0 = this.object.zoom;

	//
	// public methods
	//

	this.getPolarAngle = function () {
		return spherical.phi;
	};

	this.getAzimuthalAngle = function () {
		return spherical.theta;
	};

	this.saveState = function () {
		scope.target0.copy(scope.target);
		scope.position0.copy(scope.object.position);
		scope.zoom0 = scope.object.zoom;
	};

	this.reset = function () {
		scope.target.copy(scope.target0);
		scope.object.position.copy(scope.position0);
		scope.object.zoom = scope.zoom0;

		scope.object.updateProjectionMatrix();
		scope.dispatchEvent(changeEvent);

		scope.update();

		state = STATE.NONE;
	};

	// this method is exposed, but perhaps it would be better if we can make it private...
	this.update = (function () {
		var offset = new THREE.Vector3();

		// so camera.up is the orbit axis
		var quat = new THREE.Quaternion().setFromUnitVectors(object.up, new THREE.Vector3(0, 1, 0));
		var quatInverse = quat.clone().inverse();

		var lastPosition = new THREE.Vector3();
		var lastQuaternion = new THREE.Quaternion();

		var twoPI = 2 * Math.PI;

		return function update() {
			var position = scope.object.position;

			offset.copy(position).sub(scope.target);

			// rotate offset to "y-axis-is-up" space
			offset.applyQuaternion(quat);

			// angle from z-axis around y-axis
			spherical.setFromVector3(offset);

			if (scope.autoRotate && state === STATE.NONE) {
				rotateLeft(getAutoRotationAngle());
			}

			if (scope.enableDamping) {
				spherical.theta += sphericalDelta.theta * scope.dampingFactor;
				spherical.phi += sphericalDelta.phi * scope.dampingFactor;
			} else {
				spherical.theta += sphericalDelta.theta;
				spherical.phi += sphericalDelta.phi;
			}

			// restrict theta to be between desired limits

			var min = scope.minAzimuthAngle;
			var max = scope.maxAzimuthAngle;

			if (isFinite(min) && isFinite(max)) {
				if (min < -Math.PI) min += twoPI;
				else if (min > Math.PI) min -= twoPI;

				if (max < -Math.PI) max += twoPI;
				else if (max > Math.PI) max -= twoPI;

				if (min < max) {
					spherical.theta = Math.max(min, Math.min(max, spherical.theta));
				} else {
					spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta);
				}
			}

			// restrict phi to be between desired limits
			spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));

			spherical.makeSafe();

			spherical.radius *= scale;

			// restrict radius to be between desired limits
			spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius));

			// move target to panned location

			if (scope.enableDamping === true) {
				scope.target.addScaledVector(panOffset, scope.dampingFactor);
			} else {
				scope.target.add(panOffset);
			}

			offset.setFromSpherical(spherical);

			// rotate offset back to "camera-up-vector-is-up" space
			offset.applyQuaternion(quatInverse);

			position.copy(scope.target).add(offset);

			scope.object.lookAt(scope.target);

			if (scope.enableDamping === true) {
				sphericalDelta.theta *= 1 - scope.dampingFactor;
				sphericalDelta.phi *= 1 - scope.dampingFactor;

				panOffset.multiplyScalar(1 - scope.dampingFactor);
			} else {
				sphericalDelta.set(0, 0, 0);

				panOffset.set(0, 0, 0);
			}

			scale = 1;

			// update condition is:
			// min(camera displacement, camera rotation in radians)^2 > EPS
			// using small-angle approximation cos(x/2) = 1 - x^2 / 8

			if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
				scope.dispatchEvent(changeEvent);

				lastPosition.copy(scope.object.position);
				lastQuaternion.copy(scope.object.quaternion);
				zoomChanged = false;

				return true;
			}

			return false;
		};
	})();

	this.dispose = function () {
		scope.domElement.removeEventListener("contextmenu", onContextMenu, false);
		scope.domElement.removeEventListener("mousedown", onMouseDown, false);
		scope.domElement.removeEventListener("wheel", onMouseWheel, false);

		scope.domElement.removeEventListener("touchstart", onTouchStart, false);
		scope.domElement.removeEventListener("touchend", onTouchEnd, false);
		scope.domElement.removeEventListener("touchmove", onTouchMove, false);

		scope.domElement.ownerDocument.removeEventListener("mousemove", onMouseMove, false);
		scope.domElement.ownerDocument.removeEventListener("mouseup", onMouseUp, false);

		scope.domElement.removeEventListener("keydown", onKeyDown, false);

		//scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
	};

	//
	// internals
	//

	var scope = this;

	var changeEvent = { type: "change" };
	var startEvent = { type: "start" };
	var endEvent = { type: "end" };

	var STATE = {
		NONE: -1,
		ROTATE: 0,
		DOLLY: 1,
		PAN: 2,
		TOUCH_ROTATE: 3,
		TOUCH_PAN: 4,
		TOUCH_DOLLY_PAN: 5,
		TOUCH_DOLLY_ROTATE: 6,
	};

	var state = STATE.NONE;

	var EPS = 0.000001;

	// current position in spherical coordinates
	var spherical = new THREE.Spherical();
	var sphericalDelta = new THREE.Spherical();

	var scale = 1;
	var panOffset = new THREE.Vector3();
	var zoomChanged = false;

	var rotateStart = new THREE.Vector2();
	var rotateEnd = new THREE.Vector2();
	var rotateDelta = new THREE.Vector2();

	var panStart = new THREE.Vector2();
	var panEnd = new THREE.Vector2();
	var panDelta = new THREE.Vector2();

	var dollyStart = new THREE.Vector2();
	var dollyEnd = new THREE.Vector2();
	var dollyDelta = new THREE.Vector2();

	function getAutoRotationAngle() {
		return ((2 * Math.PI) / 60 / 60) * scope.autoRotateSpeed;
	}

	function getZoomScale() {
		return Math.pow(0.95, scope.zoomSpeed);
	}

	function rotateLeft(angle) {
		sphericalDelta.theta -= angle;
	}

	function rotateUp(angle) {
		sphericalDelta.phi -= angle;
	}

	var panLeft = (function () {
		var v = new THREE.Vector3();

		return function panLeft(distance, objectMatrix) {
			v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
			v.multiplyScalar(-distance);

			panOffset.add(v);
		};
	})();

	var panUp = (function () {
		var v = new THREE.Vector3();

		return function panUp(distance, objectMatrix) {
			if (scope.screenSpacePanning === true) {
				v.setFromMatrixColumn(objectMatrix, 1);
			} else {
				v.setFromMatrixColumn(objectMatrix, 0);
				v.crossVectors(scope.object.up, v);
			}

			v.multiplyScalar(distance);

			panOffset.add(v);
		};
	})();

	// deltaX and deltaY are in pixels; right and down are positive
	var pan = (function () {
		var offset = new THREE.Vector3();

		return function pan(deltaX, deltaY) {
			var element = scope.domElement;

			if (scope.object.isPerspectiveCamera) {
				// perspective
				var position = scope.object.position;
				offset.copy(position).sub(scope.target);
				var targetDistance = offset.length();

				// half of the fov is center to top of screen
				targetDistance *= Math.tan(((scope.object.fov / 2) * Math.PI) / 180.0);

				// we use only clientHeight here so aspect ratio does not distort speed
				panLeft((2 * deltaX * targetDistance) / element.clientHeight, scope.object.matrix);
				panUp((2 * deltaY * targetDistance) / element.clientHeight, scope.object.matrix);
			} else if (scope.object.isOrthographicCamera) {
				// orthographic
				panLeft((deltaX * (scope.object.right - scope.object.left)) / scope.object.zoom / element.clientWidth, scope.object.matrix);
				panUp((deltaY * (scope.object.top - scope.object.bottom)) / scope.object.zoom / element.clientHeight, scope.object.matrix);
			} else {
				// camera neither orthographic nor perspective
				console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");
				scope.enablePan = false;
			}
		};
	})();

	function dollyOut(dollyScale) {
		if (scope.object.isPerspectiveCamera) {
			scale /= dollyScale;
		} else if (scope.object.isOrthographicCamera) {
			scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
			scope.object.updateProjectionMatrix();
			zoomChanged = true;
		} else {
			console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
			scope.enableZoom = false;
		}
	}

	function dollyIn(dollyScale) {
		if (scope.object.isPerspectiveCamera) {
			scale *= dollyScale;
		} else if (scope.object.isOrthographicCamera) {
			scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
			scope.object.updateProjectionMatrix();
			zoomChanged = true;
		} else {
			console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
			scope.enableZoom = false;
		}
	}

	//
	// event callbacks - update the object state
	//

	function handleMouseDownRotate(event) {
		rotateStart.set(event.clientX, event.clientY);
	}

	function handleMouseDownDolly(event) {
		dollyStart.set(event.clientX, event.clientY);
	}

	function handleMouseDownPan(event) {
		panStart.set(event.clientX, event.clientY);
	}

	function handleMouseMoveRotate(event) {
		rotateEnd.set(event.clientX, event.clientY);

		rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);

		var element = scope.domElement;

		rotateLeft((2 * Math.PI * rotateDelta.x) / element.clientHeight); // yes, height

		rotateUp((2 * Math.PI * rotateDelta.y) / element.clientHeight);

		rotateStart.copy(rotateEnd);

		scope.update();
	}

	function handleMouseMoveDolly(event) {
		dollyEnd.set(event.clientX, event.clientY);

		dollyDelta.subVectors(dollyEnd, dollyStart);

		if (dollyDelta.y > 0) {
			dollyOut(getZoomScale());
		} else if (dollyDelta.y < 0) {
			dollyIn(getZoomScale());
		}

		dollyStart.copy(dollyEnd);

		scope.update();
	}

	function handleMouseMovePan(event) {
		panEnd.set(event.clientX, event.clientY);

		panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);

		pan(panDelta.x, panDelta.y);

		panStart.copy(panEnd);

		scope.update();
	}

	function handleMouseUp(/*event*/) {
		// no-op
	}

	function handleMouseWheel(event) {
		if (event.deltaY < 0) {
			dollyIn(getZoomScale());
		} else if (event.deltaY > 0) {
			dollyOut(getZoomScale());
		}

		scope.update();
	}

	function handleKeyDown(event) {
		var needsUpdate = false;

		switch (event.keyCode) {
			case scope.keys.UP:
				pan(0, scope.keyPanSpeed);
				needsUpdate = true;
				break;

			case scope.keys.BOTTOM:
				pan(0, -scope.keyPanSpeed);
				needsUpdate = true;
				break;

			case scope.keys.LEFT:
				pan(scope.keyPanSpeed, 0);
				needsUpdate = true;
				break;

			case scope.keys.RIGHT:
				pan(-scope.keyPanSpeed, 0);
				needsUpdate = true;
				break;
		}

		if (needsUpdate) {
			// prevent the browser from scrolling on cursor keys
			event.preventDefault();

			scope.update();
		}
	}

	function handleTouchStartRotate(event) {
		if (event.touches.length == 1) {
			rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
		} else {
			var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
			var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);

			rotateStart.set(x, y);
		}
	}

	function handleTouchStartPan(event) {
		if (event.touches.length == 1) {
			panStart.set(event.touches[0].pageX, event.touches[0].pageY);
		} else {
			var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
			var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);

			panStart.set(x, y);
		}
	}

	function handleTouchStartDolly(event) {
		var dx = event.touches[0].pageX - event.touches[1].pageX;
		var dy = event.touches[0].pageY - event.touches[1].pageY;

		var distance = Math.sqrt(dx * dx + dy * dy);

		dollyStart.set(0, distance);
	}

	function handleTouchStartDollyPan(event) {
		if (scope.enableZoom) handleTouchStartDolly(event);

		if (scope.enablePan) handleTouchStartPan(event);
	}

	function handleTouchStartDollyRotate(event) {
		if (scope.enableZoom) handleTouchStartDolly(event);

		if (scope.enableRotate) handleTouchStartRotate(event);
	}

	function handleTouchMoveRotate(event) {
		if (event.touches.length == 1) {
			rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
		} else {
			var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
			var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);

			rotateEnd.set(x, y);
		}

		rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);

		var element = scope.domElement;

		rotateLeft((2 * Math.PI * rotateDelta.x) / element.clientHeight); // yes, height

		rotateUp((2 * Math.PI * rotateDelta.y) / element.clientHeight);

		rotateStart.copy(rotateEnd);
	}

	function handleTouchMovePan(event) {
		if (event.touches.length == 1) {
			panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
		} else {
			var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
			var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);

			panEnd.set(x, y);
		}

		panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);

		pan(panDelta.x, panDelta.y);

		panStart.copy(panEnd);
	}

	function handleTouchMoveDolly(event) {
		var dx = event.touches[0].pageX - event.touches[1].pageX;
		var dy = event.touches[0].pageY - event.touches[1].pageY;

		var distance = Math.sqrt(dx * dx + dy * dy);

		dollyEnd.set(0, distance);

		dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));

		dollyOut(dollyDelta.y);

		dollyStart.copy(dollyEnd);
	}

	function handleTouchMoveDollyPan(event) {
		if (scope.enableZoom) handleTouchMoveDolly(event);

		if (scope.enablePan) handleTouchMovePan(event);
	}

	function handleTouchMoveDollyRotate(event) {
		if (scope.enableZoom) handleTouchMoveDolly(event);

		if (scope.enableRotate) handleTouchMoveRotate(event);
	}

	function handleTouchEnd(/*event*/) {
		// no-op
	}

	//
	// event handlers - FSM: listen for events and reset state
	//

	function onMouseDown(event) {
		if (scope.enabled === false) return;

		// Prevent the browser from scrolling.
		event.preventDefault();

		// Manually set the focus since calling preventDefault above
		// prevents the browser from setting it automatically.

		scope.domElement.focus ? scope.domElement.focus() : window.focus();

		var mouseAction;

		switch (event.button) {
			case 0:
				mouseAction = scope.mouseButtons.LEFT;
				break;

			case 1:
				mouseAction = scope.mouseButtons.MIDDLE;
				break;

			case 2:
				mouseAction = scope.mouseButtons.RIGHT;
				break;

			default:
				mouseAction = -1;
		}

		switch (mouseAction) {
			case THREE.MOUSE.DOLLY:
				if (scope.enableZoom === false) return;

				handleMouseDownDolly(event);

				state = STATE.DOLLY;

				break;

			case THREE.MOUSE.ROTATE:
				if (event.ctrlKey || event.metaKey || event.shiftKey) {
					if (scope.enablePan === false) return;

					handleMouseDownPan(event);

					state = STATE.PAN;
				} else {
					if (scope.enableRotate === false) return;

					handleMouseDownRotate(event);

					state = STATE.ROTATE;
				}

				break;

			case THREE.MOUSE.PAN:
				if (event.ctrlKey || event.metaKey || event.shiftKey) {
					if (scope.enableRotate === false) return;

					handleMouseDownRotate(event);

					state = STATE.ROTATE;
				} else {
					if (scope.enablePan === false) return;

					handleMouseDownPan(event);

					state = STATE.PAN;
				}

				break;

			default:
				state = STATE.NONE;
		}

		if (state !== STATE.NONE) {
			scope.domElement.ownerDocument.addEventListener("mousemove", onMouseMove, false);
			scope.domElement.ownerDocument.addEventListener("mouseup", onMouseUp, false);

			scope.dispatchEvent(startEvent);
		}
	}

	function onMouseMove(event) {
		if (scope.enabled === false) return;

		event.preventDefault();

		switch (state) {
			case STATE.ROTATE:
				if (scope.enableRotate === false) return;

				handleMouseMoveRotate(event);

				break;

			case STATE.DOLLY:
				if (scope.enableZoom === false) return;

				handleMouseMoveDolly(event);

				break;

			case STATE.PAN:
				if (scope.enablePan === false) return;

				handleMouseMovePan(event);

				break;
		}
	}

	function onMouseUp(event) {
		if (scope.enabled === false) return;

		handleMouseUp(event);

		scope.domElement.ownerDocument.removeEventListener("mousemove", onMouseMove, false);
		scope.domElement.ownerDocument.removeEventListener("mouseup", onMouseUp, false);

		scope.dispatchEvent(endEvent);

		state = STATE.NONE;
	}

	function onMouseWheel(event) {
		if (scope.enabled === false || scope.enableZoom === false || (state !== STATE.NONE && state !== STATE.ROTATE)) return;

		event.preventDefault();
		event.stopPropagation();

		scope.dispatchEvent(startEvent);

		handleMouseWheel(event);

		scope.dispatchEvent(endEvent);
	}

	function onKeyDown(event) {
		if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;

		handleKeyDown(event);
	}

	function onTouchStart(event) {
		if (scope.enabled === false) return;

		event.preventDefault(); // prevent scrolling

		switch (event.touches.length) {
			case 1:
				switch (scope.touches.ONE) {
					case THREE.TOUCH.ROTATE:
						if (scope.enableRotate === false) return;

						handleTouchStartRotate(event);

						state = STATE.TOUCH_ROTATE;

						break;

					case THREE.TOUCH.PAN:
						if (scope.enablePan === false) return;

						handleTouchStartPan(event);

						state = STATE.TOUCH_PAN;

						break;

					default:
						state = STATE.NONE;
				}

				break;

			case 2:
				switch (scope.touches.TWO) {
					case THREE.TOUCH.DOLLY_PAN:
						if (scope.enableZoom === false && scope.enablePan === false) return;

						handleTouchStartDollyPan(event);

						state = STATE.TOUCH_DOLLY_PAN;

						break;

					case THREE.TOUCH.DOLLY_ROTATE:
						if (scope.enableZoom === false && scope.enableRotate === false) return;

						handleTouchStartDollyRotate(event);

						state = STATE.TOUCH_DOLLY_ROTATE;

						break;

					default:
						state = STATE.NONE;
				}

				break;

			default:
				state = STATE.NONE;
		}

		if (state !== STATE.NONE) {
			scope.dispatchEvent(startEvent);
		}
	}

	function onTouchMove(event) {
		if (scope.enabled === false) return;

		event.preventDefault(); // prevent scrolling
		event.stopPropagation();

		switch (state) {
			case STATE.TOUCH_ROTATE:
				if (scope.enableRotate === false) return;

				handleTouchMoveRotate(event);

				scope.update();

				break;

			case STATE.TOUCH_PAN:
				if (scope.enablePan === false) return;

				handleTouchMovePan(event);

				scope.update();

				break;

			case STATE.TOUCH_DOLLY_PAN:
				if (scope.enableZoom === false && scope.enablePan === false) return;

				handleTouchMoveDollyPan(event);

				scope.update();

				break;

			case STATE.TOUCH_DOLLY_ROTATE:
				if (scope.enableZoom === false && scope.enableRotate === false) return;

				handleTouchMoveDollyRotate(event);

				scope.update();

				break;

			default:
				state = STATE.NONE;
		}
	}

	function onTouchEnd(event) {
		if (scope.enabled === false) return;

		handleTouchEnd(event);

		scope.dispatchEvent(endEvent);

		state = STATE.NONE;
	}

	function onContextMenu(event) {
		if (scope.enabled === false) return;

		event.preventDefault();
	}

	//

	scope.domElement.addEventListener("contextmenu", onContextMenu, false);

	scope.domElement.addEventListener("mousedown", onMouseDown, false);
	scope.domElement.addEventListener("wheel", onMouseWheel, false);

	scope.domElement.addEventListener("touchstart", onTouchStart, false);
	scope.domElement.addEventListener("touchend", onTouchEnd, false);
	scope.domElement.addEventListener("touchmove", onTouchMove, false);

	scope.domElement.addEventListener("keydown", onKeyDown, false);

	// make sure element can receive keys.

	if (scope.domElement.tabIndex === -1) {
		scope.domElement.tabIndex = 0;
	}

	// force an update at start

	this.update();
};

THREE.OrbitControls.prototype = Object.create(THREE.EventDispatcher.prototype);
THREE.OrbitControls.prototype.constructor = THREE.OrbitControls;

// This set of controls performs orbiting, dollying (zooming), and panning.
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
// This is very similar to OrbitControls, another set of touch behavior
//
//    Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
//    Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
//    Pan - left mouse, or arrow keys / touch: one-finger move

THREE.MapControls = function (object, domElement) {
	THREE.OrbitControls.call(this, object, domElement);

	this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up

	this.mouseButtons.LEFT = THREE.MOUSE.PAN;
	this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE;

	this.touches.ONE = THREE.TOUCH.PAN;
	this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE;
};

THREE.MapControls.prototype = Object.create(THREE.EventDispatcher.prototype);
THREE.MapControls.prototype.constructor = THREE.MapControls;


text:
var fs = require("fs"),
	assert = require("assert");

var runCount = 0,
	testCount = 0;

function compare(expected, result){
	if(typeof expected !== typeof result){
		throw Error("types didn't match");
	}
	if(typeof expected !== "object" || expected === null){
		if(expected !== result){
			throw Error("result doesn't equal expected");
		}
		return;
	}

	for(var prop in expected){
		if(!(prop in result)) throw Error("result didn't contain property " + prop);
		compare(expected[prop], result[prop]);
	}
}

function runTests(test){
	//read files, load them, run them
	fs.readdirSync(__dirname + test.dir
	).map(function(file){
		if(file[0] === ".") return false;
		if(file.substr(-5) === ".json") return JSON.parse(
			fs.readFileSync(__dirname + test.dir + file)
		);
		return require(__dirname + test.dir + file);
	}).forEach(function(file){
		if(!file) return;
		var second = false;

		runCount++;

		console.log("Testing:", file.name);

		test.test(file, function(err, dom){
			assert.ifError(err);
			compare(file.expected, dom);

			if(second){
				runCount--;
				testCount++;
			}
			else second = true;
		});
	});
	console.log("->", test.dir.slice(1, -1), "started");
}

runTests(require("./01-dom.js"));

//log the results
(function check(){
	if(runCount !== 0) return process.nextTick(check);
	console.log("Total tests:", testCount);
}());

redpajama_set_name: RedPajamaGithub


text:
package cc.ycn.common.bean.message;

import cc.ycn.common.bean.WxArticle;
import cc.ycn.common.bean.WxError;
import cc.ycn.common.exception.WxErrorException;

import java.util.ArrayList;

/**
 * Created by andy on 12/15/15.
 */
public class NewsBuilder extends BaseBuilder<NewsBuilder> {

    public NewsBuilder() {
        message.news = message.new WxMsgNews();
        message.news.articles = new ArrayList<WxArticle>();
    }

    public NewsBuilder addArticle(WxArticle article) {
        if (article != null)
            message.news.articles.add(article);
        return this;
    }

    @Override
    protected WxMsgType getType() {
        return WxMsgType.NEWS;
    }

    @Override
    protected void isValid() {
        if (message.news.articles.isEmpty())
            throw new WxErrorException(new WxError(1004, "missing articles"));
    }
}


text:
package com.intellij.codeInspection.ui;

import com.intellij.ui.AnActionButton;
import com.intellij.ui.AnActionButtonRunnable;
import com.intellij.ui.TableUtil;
import com.intellij.ui.ToolbarDecorator;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.util.List;

public class ListEditForm {
  JPanel contentPanel;
  ListTable table;

  public ListEditForm(String title, List<String> stringList) {
    table = new ListTable(new ListWrappingTableModel(stringList, title));

    contentPanel = ToolbarDecorator.createDecorator(table)
      .setAddAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton button) {
          final ListWrappingTableModel tableModel = table.getModel();
          tableModel.addRow();
          EventQueue.invokeLater(() -> {
            final int lastRowIndex = tableModel.getRowCount() - 1;
            final Rectangle rectangle =
              table.getCellRect(lastRowIndex, 0, true);
            table.scrollRectToVisible(rectangle);
            table.editCellAt(lastRowIndex, 0);
            final ListSelectionModel selectionModel =
              table.getSelectionModel();
            selectionModel.setSelectionInterval(lastRowIndex, lastRowIndex);
            final TableCellEditor editor = table.getCellEditor();
            final Component component =
              editor.getTableCellEditorComponent(table,
                                                 null, true, lastRowIndex, 0);
            component.requestFocus();
          });
        }
      })
      .setRemoveAction(button -> TableUtil.removeSelectedItems(table))
      .disableUpDownActions().createPanel();
  }

  public JComponent getContentPanel() {
    return contentPanel;
  }
}


text:
Java implementation of an NHS Spine Message Handling System

Dependencies:

https://github.com/DamianJMurphy/DistributionEnvelopeTools-Java

Apache commons-coded-1.3.jar

Apache commons-io-2.4.jar

javax.json-1.0.jar

JDK 1.8


text:
/* @flow */

/**
 * Cross-platform code generation for component v-model
 */
export function genComponentModel (
  el: ASTElement,
  value: string,
  modifiers: ?ASTModifiers
): ?boolean {
  const { number, trim } = modifiers || {}

  const baseValueExpression = '$$v'
  let valueExpression = baseValueExpression
  if (trim) {
    valueExpression =
      `(typeof ${baseValueExpression} === 'string'` +
        `? ${baseValueExpression}.trim()` +
        `: ${baseValueExpression})`
  }
  if (number) {
    valueExpression = `_n(${valueExpression})`
  }
  const assignment = genAssignmentCode(value, valueExpression)

  el.model = {
    value: `(${value})`,
    expression: `"${value}"`,
    callback: `function (${baseValueExpression}) {${assignment}}`
  }
}

/**
 * Cross-platform codegen helper for generating v-model value assignment code.
 */
export function genAssignmentCode (
  value: string,
  assignment: string
): string {
  const res = parseModel(value)
  if (res.key === null) {
    return `${value}=${assignment}`
  } else {
    return `$set(${res.exp}, ${res.key}, ${assignment})`
  }
}

/**
 * Parse a v-model expression into a base path and a final key segment.
 * Handles both dot-path and possible square brackets.
 *
 * Possible cases:
 *
 * - test
 * - test[key]
 * - test[test1[key]]
 * - test["a"][key]
 * - xxx.test[a[a].test1[key]]
 * - test.xxx.a["asa"][test1[key]]
 *
 */

let len, str, chr, index, expressionPos, expressionEndPos

type ModelParseResult = {
  exp: string,
  key: string | null
}

export function parseModel (val: string): ModelParseResult {
  len = val.length

  if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
    index = val.lastIndexOf('.')
    if (index > -1) {
      return {
        exp: val.slice(0, index),
        key: '"' + val.slice(index + 1) + '"'
      }
    } else {
      return {
        exp: val,
        key: null
      }
    }
  }

  str = val
  index = expressionPos = expressionEndPos = 0

  while (!eof()) {
    chr = next()
    /* istanbul ignore if */
    if (isStringStart(chr)) {
      parseString(chr)
    } else if (chr === 0x5B) {
      parseBracket(chr)
    }
  }

  return {
    exp: val.slice(0, expressionPos),
    key: val.slice(expressionPos + 1, expressionEndPos)
  }
}

function next (): number {
  return str.charCodeAt(++index)
}

function eof (): boolean {
  return index >= len
}

function isStringStart (chr: number): boolean {
  return chr === 0x22 || chr === 0x27
}

function parseBracket (chr: number): void {
  let inBracket = 1
  expressionPos = index
  while (!eof()) {
    chr = next()
    if (isStringStart(chr)) {
      parseString(chr)
      continue
    }
    if (chr === 0x5B) inBracket++
    if (chr === 0x5D) inBracket--
    if (inBracket === 0) {
      expressionEndPos = index
      break
    }
  }
}

function parseString (chr: number): void {
  const stringQuote = chr
  while (!eof()) {
    chr = next()
    if (chr === stringQuote) {
      break
    }
  }
}


text:
/**
 *
 * @fileoverview Basic arithmetic operations for big numbers.
 * @author thaidn@google.com (Thai Duong).
 */

goog.provide('e2e.BigNum');

goog.require('e2e');
goog.require('e2e.error.InvalidArgumentsError');
goog.require('e2e.fixedtiming');
goog.require('goog.array');
goog.require('goog.asserts');

/**
 * Non-negative arbitrary-precision integers.
 * @param {(!e2e.ByteArray|!Uint8Array)=} opt_value The value of the BigNum in
 *     big endian.
 * @constructor
 */
e2e.BigNum = function(opt_value) {
  /**
   * The internal representation of this BigNum. It's an array of 24-bit numbers
   * in little endian.
   * @type {!Array.<number>}
   */
  this.n = [];
  if (goog.isDef(opt_value)) {
    if (!(
          goog.isFunction(goog.global.Uint8Array) &&
          opt_value instanceof Uint8Array
        ) && !e2e.isByteArray(/** @type {!e2e.ByteArray} */ (opt_value))) {
      throw new e2e.error.InvalidArgumentsError(
          'Input should be a byte array.');
    }
    this.n = e2e.BigNum.bigEndianToInternal_(opt_value);
  }

  /**
   * The length in bits of this BigNum. Calculate only when needed.
   * @private {number}
   */
  this.bitLength_ = 0;
};

/**
 * @const {number} The length in bits of radix.
 */
e2e.BigNum.BASE_LEN = 24;

/**
 * @const {number} Radix used to calculate multiplications.
 */
e2e.BigNum.BASE = 1 << e2e.BigNum.BASE_LEN;

/**
 * @const {number} Bit mask of the radix.
 */
e2e.BigNum.BASE_MASK = e2e.BigNum.BASE - 1;

/**
 * A factory method to create a BigNum of a predefined size.
 * @param {number} n The size of the BigNum. Must be larger than 0.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.createBigNumOfSize = function(n) {
  var bignum = new e2e.BigNum();
  bignum.n.length = n;
  return bignum;
};

/**
 * For internal use only.  Creates a BigNum from a little-endian array
 * of 24-bit numbers, which is the internal format of a BigNum.
 *
 * @param {Array.<number>} array An array of 24-bit integers
 * @return {!e2e.BigNum} a new bignum.
 */
e2e.BigNum.fromInternalArray = function(array) {
  var bignum = new e2e.BigNum();
  bignum.n = goog.array.clone(array);
  return bignum;
};

/**
 * A factory method to create a BigNum from a 32-bit non-negative integer
 * @param {number} value a non-negative 32-bit integer
 * @return {!e2e.BigNum}
 */
e2e.BigNum.fromInteger = function(value) {
  if (value < 0 || value > 0x1000000000000  /* 2^48 */) {
    throw new e2e.error.InvalidArgumentsError(
        'Argument must be a valid integer.');
  }
  var bignum = new e2e.BigNum();
  do {
    bignum.n.push(value & e2e.BigNum.BASE_MASK);
    value = Math.floor(value / e2e.BigNum.BASE);
  } while (value > 0);
  return bignum;
};

/**
 * Converts big endian byte array to internal format.
 * @param {(!e2e.ByteArray|!Uint8Array)} input The big endian number.
 * @return {!Array.<number>}
 * @private
 */
e2e.BigNum.bigEndianToInternal_ = function(input) {
  var i = input.length;
  var pw = new Array(((i + 2) / 3) | 0);
  var j = 0;
  for (; i >= 0; i -= 3) {
    pw[j++] = (input[i - 1] & 255) |
              ((input[i - 2] & 255) << 8) |
              ((input[i - 3] & 255) << 16);
  }
  return pw;
};

/**
 * Selects conditionally. Returns a if bit is 1, b if bit is 0.
 * @param {!e2e.BigNum} a
 * @param {!e2e.BigNum} b
 * @param {number} bit
 * @return {!e2e.BigNum}
 */
e2e.BigNum.select = function(a, b, bit) {
  var mask = (-bit) | 0;
  var maxLen = e2e.fixedtiming.max(a.n.length, b.n.length);
  var ret = e2e.BigNum.createBigNumOfSize(maxLen);
  for (var i = 0; i < maxLen; ++i) {
    ret.n[i] = mask & (a.n[i] ^ b.n[i]);
  }
  for (var i = 0; i < maxLen; ++i) {
    ret.n[i] = ret.n[i] ^ b.n[i];
  }
  return ret;
};

/**
 * Converts this to big endian byte array. Drop leading zeros.
 * @return {!e2e.ByteArray} The big endian representation.
 */
e2e.BigNum.prototype.toByteArray = function() {
  var i = this.n.length;
  var j = 0;
  var r = new Array(3 * i);

  for (; i > 0; --i) {
    r[j++] = (this.n[i - 1] >>> 16) & 255;
    r[j++] = (this.n[i - 1] >>> 8) & 255;
    r[j++] = (this.n[i - 1] & 255);
  }

  // Drops leading zeros.
  var n = 0;
  var z = 0;
  for (var m = 0; m < r.length; ++m) {
    z |= r[m]; // All zeros so far?
    n += !z & (!r[m]);
  }
  return r.slice(n - (1 & !z));
};

/**
 * Converts this to a base 16 little-endian representation in which "digit"
 * is in the range [-7, 8]. Needed to perform scalar multiplications in ECC.
 * @return {!Array.<number>} The little endian signed-nybble representation.
 */
e2e.BigNum.prototype.toSignedNybbleArray = function() {
  var result = [];
  var carry = 0;
  for (var word = 0; word < this.n.length; word++) {
    // We add 0x777777 to the word as a whole, then subtract 7 from each of
    // the resulting nybbles.
    var value = this.n[word] + carry + 0x777777;
    carry = value >> e2e.BigNum.BASE_LEN;
    for (var offset = 0; offset < e2e.BigNum.BASE_LEN; offset += 4) {
      result.push(((value >> offset) & 0xF) - 7);
    }
  }
  result.push(carry);
  return result;
};

/** @override */
e2e.BigNum.prototype.toString = function() {
  var result = [];
  var current = this;
  var divisor = e2e.BigNum.fromInteger(1000 * 1000);
  do {
    var qr = current.divmod(divisor);
    var remainder = qr.remainder;
    result.unshift(remainder.n[0]);
    current = qr.quotient;
    current.dropLeadingZeros();
  } while (!current.isEqual(e2e.BigNum.ZERO));
  return result.map(function(element, index) {
    // pad all but the first element to be six digits
    if (index == 0 || element > 1000 * 1000) {
      return '' + element;
    } else {
      return ('000000' + element).slice(-6);
    }

  }).join('');
};

/**
 * Drops leading zeros.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.dropLeadingZeros = function() {
  // Fixed-timing up to the length of this.
  var j = 0;
  var z = 0;
  for (var i = this.n.length - 1; i > 0; --i) {
    z |= this.n[i]; // All zeros so far?
    j += !z & (!this.n[i]);
  }
  this.n.length -= j;
  return this;
};

/**
 * Returns a copy of this object.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.clone = function() {
  return e2e.BigNum.fromInternalArray(this.n);
};

/**
 * Resets the size of this BigNum by removing or adding leading zeros.
 * @param {number} n The new size.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.cloneWithSize = function(n) {
  var r = e2e.BigNum.createBigNumOfSize(n);
  for (var i = 0; i < n; i++) {
    r.n[i] = this.n[i] | 0;
  }
  return r;
};

/**
 * Resets the size of this BigNum.
 * @param {number} n The new size. Must be smaller than current size.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.setSize = function(n) {
  goog.asserts.assert(n <= this.n.length, 'Wrong size.');
  this.n.length = n;
  return this;
};

/**
 * Gets the size of this BigNum.
 * @return {number}
 */
e2e.BigNum.prototype.getSize = function() {
  return this.n.length;
};

/**
 * Returns the bit length of this.
 * @return {number}
 */
e2e.BigNum.prototype.getBitLength = function() {
  if (this.bitLength_ == 0) {
    return this.getBitLength_();
  }
  return this.bitLength_;
};

/**
 * Calculates the bit length of this.
 * @return {number}
 * @private
 */
e2e.BigNum.prototype.getBitLength_ = function() {
  var j = 0;
  var z = 0;
  for (var i = this.n.length - 1; i > 0; --i) {
    z |= this.n[i]; // All zeros so far?
    j += !z & (!this.n[i]);
  }
  var len = this.n.length - j;
  var nbits = len * e2e.BigNum.BASE_LEN;
  var msw = this.n[len - 1];
  // change [0] to [1], as they have the same length.
  // msw = 1 if msw = 0; otherwise no change.
  msw = msw | (!msw);
  while ((msw & (e2e.BigNum.BASE >> 1)) == 0) {
    msw <<= 1;
    --nbits;
  }
  this.bitLength_ = nbits;
  return nbits;
};

/**
 * Calculates this + that.
 * @param {!e2e.BigNum} that The number to add.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.add = function(that) {
  var maxLen = e2e.fixedtiming.max(this.n.length, that.n.length);
  var sum = e2e.BigNum.createBigNumOfSize(maxLen + 1);
  var accu = 0;
  for (var i = 0; i < maxLen; ++i) {
    accu += (this.n[i] | 0) + (that.n[i] | 0);
    sum.n[i] = accu & e2e.BigNum.BASE_MASK;
    accu >>= e2e.BigNum.BASE_LEN;
  }
  sum.n[maxLen] = accu;
  return sum;
};

/**
 * Calculates this - that.
 * @param {!e2e.BigNum} that The number to subtract. It must
 *     be smaller than this.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.subtract = function(that) {
  if (!this.isGreaterOrEqual(that)) {
    throw new e2e.error.InvalidArgumentsError(
        'Cannot subtract to a larger BigNum.');
  }

  var result = this.clone();
  var n = result.n.length;
  var accu = 0;
  for (var i = 0; i < result.n.length; ++i) {
    accu += result.n[i] - (that.n[i] | 0);
    result.n[i] = accu & e2e.BigNum.BASE_MASK;
    accu >>= e2e.BigNum.BASE_LEN;
  }
  return result;
};

/**
 * Subtracts conditionally: return this - that if this >= that.
 * @param {!e2e.BigNum} that Number to subtract.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.subtractIfGreaterOrEqual = function(that) {
  var maxLen = e2e.fixedtiming.max(this.n.length, that.n.length);
  var result = e2e.BigNum.createBigNumOfSize(maxLen);
  var accu = 0;
  for (var i = 0; i < maxLen; ++i) {
    accu += (this.n[i] | 0) - (that.n[i] | 0);
    result.n[i] = accu & e2e.BigNum.BASE_MASK;
    accu >>= e2e.BigNum.BASE_LEN;
  }
  var mask = accu;
  accu = 0;
  for (var i = 0; i < maxLen; ++i) {
    accu += result.n[i] + (that.n[i] & mask);
    result.n[i] = (accu) & e2e.BigNum.BASE_MASK;
    accu >>= e2e.BigNum.BASE_LEN;
  }
  return result;
};

/**
 * Calculates this * that.
 * @param {!e2e.BigNum} that The number to multiply.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.multiply = function(that) {
  var thisLen = this.n.length;
  var thatLen = that.n.length;
  var productLen = thisLen + thatLen;
  var product = e2e.BigNum.createBigNumOfSize(productLen);
  for (var i = 0; i < productLen; i++) {
    product.n[i] = 0;
  }
  for (var i = 0; i < thisLen; i++) {
    var U = 0;
    for (var j = 0; j < thatLen; j++) {
      var accu = product.n[i + j] + this.n[i] * that.n[j] + U;
      U = (accu / e2e.BigNum.BASE) | 0;
      product.n[i + j] = accu & e2e.BigNum.BASE_MASK;
    }
    product.n[i + thatLen] = U;
  }
  return product;
};

/**
 * Calculates this * this.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.square = function() {
  var m = this.n.length;
  var product = e2e.BigNum.createBigNumOfSize(2 * m);
  for (var i = 0; i < 2 * m; i++) {
    product.n[i] = 0;
  }
  for (var i = 0; i < m; i++) {
    var accu = product.n[i + i] + this.n[i] * this.n[i];
    var U = (accu / e2e.BigNum.BASE) | 0;
    product.n[i + i] = accu & e2e.BigNum.BASE_MASK;
    for (var j = i + 1; j < m; j++) {
      accu = product.n[i + j] + 2 * this.n[i] * this.n[j] + U;
      U = (accu / e2e.BigNum.BASE) | 0;
      product.n[i + j] = accu & e2e.BigNum.BASE_MASK;
    }
    product.n[i + m] = U;
  }
  return product;
};

/**
 * Calculates this % that
 * @param {!e2e.BigNum} that
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.mod = function(that) {
  return this.divmod(that).remainder;
};

/**
 * Calculates this / that
 * @param {!e2e.BigNum} that
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.div = function(that) {
  return this.divmod(that).quotient;
};

/**
 * Calculates both quotient and remainder of this / that.
 * @param {!e2e.BigNum} that
 * @return {!{quotient:!e2e.BigNum, remainder:!e2e.BigNum}}
 */
e2e.BigNum.prototype.divmod = function(that) {
  var bitLength = that.getBitLength();
  // divisor length w/o padding
  var length = ((bitLength + e2e.BigNum.BASE_LEN - 1) /
      e2e.BigNum.BASE_LEN) | 0;
  var shift = length * e2e.BigNum.BASE_LEN - bitLength;
  // Shift the divisor that that its high bit is set.
  // Shift the dividend by the same amount.
  var divisor = that.shiftLeft(shift);
  var dividend = e2e.BigNum.select(
      this.clone(), this.shiftLeft(shift), (shift == 0) | 0);
  var quotient = e2e.BigNum.select(
      e2e.BigNum.ZERO,
      e2e.BigNum.createBigNumOfSize(dividend.n.length + 1),
      (dividend.n.length + 1 - length <= 0) | 0);
  dividend.n.push(0);

  for (var delta = dividend.n.length - length - 1; delta >= 0; delta--) {
    // ASSERT:  dividend / (divisor * b^(delta)) < b, where b = 2^24.
    // Our goal is to find q = floor(dividend / (divisor * b^delta)).
    // We can then subtract q * divisor * b^delta from the dividend and add
    // q * b ^ delta to the quotient.
    //
    // Get q, the tentative quotient digit.  This is either the right answer
    // or one too large.
    var q = this.calculateQuotient_(dividend, divisor, delta);
    // Subtract quotient * divisor
    var accu = 0;
    quotient.n[delta] = q;
    for (var i = 0; i <= length; i++) {
      accu += dividend.n[i + delta] - (divisor.n[i] | 0) * q;
      dividend.n[i + delta] = accu & e2e.BigNum.BASE_MASK;
      accu = Math.floor(accu / e2e.BigNum.BASE);
    }
    goog.asserts.assert(
        dividend.n[delta + length] == e2e.BigNum.BASE_MASK ||
        dividend.n[delta + length] == 0);
    goog.asserts.assert(accu == -1 || accu == 0);

    // If the result is negative, then q was 1 too large, and we add
    // b ^ delta * divisor back, and subtract b ^ delta from the quotient.
    var mask = accu;  //
    accu = 0;
    quotient.n[delta] += mask;
    for (var i = 0; i <= length; i++) {
      accu += dividend.n[i + delta] + (divisor.n[i] & mask);
      dividend.n[i + delta] = accu & e2e.BigNum.BASE_MASK;
      accu >>= e2e.BigNum.BASE_LEN;
    }
    goog.asserts.assert(dividend.n[delta + length] == 0);
  }
  dividend = dividend.shiftRight(shift).cloneWithSize(length);
  quotient.dropLeadingZeros();
  goog.asserts.assert(quotient.multiply(that).add(dividend).isEqual(this));
  return {quotient: quotient, remainder: dividend};
};

/**
 * Calculates the quotient digit for dividend / (divisor << (24 * delta)).
 * The resulting quotient digit is guaranteed to be either the right answer,
 * or one larger than the right answer.
 * @param {e2e.BigNum} dividend
 * @param {e2e.BigNum} divisor
 * @param {number} delta
 * @return {number}
 * @private
 */
e2e.BigNum.prototype.calculateQuotient_ = function(
    dividend, divisor, delta) {
  var length = divisor.n.length;
  goog.asserts.assert(dividend.n[length + delta] <=
      divisor.n[length - 1]);
  // Let the top three digits of the dividend be s2, s1, s0, and the top two
  // digits of the divisor be v1, v0.  Let the base be b.  Let the correct value
  // for the quotient be q.  Knuth shows that calculating
  //     qhat = floor((s2 * b + s1) / v1)
  // gives an amount such that the true quotient is qhat, qhat - 1, or qhat - 2.
  var numerator = dividend.n[length + delta] * e2e.BigNum.BASE +
      dividend.n[length + delta - 1];
  var denominator = divisor.n[length - 1];
  var qhat = Math.floor(numerator / denominator);
  var rhat = numerator - qhat * denominator;  // remainder
  // Let qtilde = floor((s2 * b^2 + s1 * b + s0) / (v1 * b + v0)
  // Knuth likewise shows that qtilde <= qhat, that the true quotient is qtilde
  // or qtilde - 1, and that the q = qtilde with very high probability.
  // But this code needs to be data-independent, so we bother to distinguish
  // only between the two cases qtilde == qhat and qtilde < qhat. From above:
  //     qhat * v1 + rhat = s2 * b + s1
  //     qhat * v1 * b  + rhat * b = s2 * b^2 + s1 * b
  //     qhat * (v1 + b + v0) + ((rhat * b + s0 - qhat * v0))
  //                   = s2 * b^2 + s1 * b + s0
  // The quantity marked by ((...)) looks like a remainder in calculating
  // qtilde.  So we have
  //             ((...)) >= 0  if  qtilde == qhat
  //             ((...)) < 0   if  qtilde < qhat.
  // NB: HAC points out that the algorithm works fine with non-zero 1-word
  // divisors, as long as negative indices are treated as 0.

  // If this is true, then it has to be the case that qhat is too large,
  // and the real quotient must be qhat - 1 or qhat - 2.
  var decrement1 = (qhat == e2e.BigNum.BASE);
  // If this is true, then per above, qtilde < qhat, so that the real
  // quotient must be qhat - 1 or qhat - 2.
  var decrement2 = qhat * (divisor.n[length - 2] | 0) >
      rhat * e2e.BigNum.BASE + (dividend.n[length + delta - 2] | 0);
  return qhat - (decrement1 | decrement2);
};

/**
 * Divides this by a small, one-word divisor.
 * @param  {number} divisor The one-word divisor.
 * @return {!{quotient:!e2e.BigNum, remainder:number}}
 */
e2e.BigNum.prototype.divmodInt = function(divisor) {
  goog.asserts.assert(0 <= divisor && divisor < e2e.BigNum.BASE);
  var dividend = this.clone();

  var tmp, remainder = 0;
  for (var i = dividend.n.length - 1; i >= 0; --i) {
    tmp = remainder * (e2e.BigNum.BASE) + dividend.n[i];
    dividend.n[i] = (tmp / divisor) | 0;
    remainder = tmp % divisor;
  }
  return {quotient: dividend, remainder: remainder};
};

/**
 * Return true if a < this < b.
 * @param {e2e.BigNum} a The lower bound.
 * @param {e2e.BigNum} b The upper bound.
 * @return {boolean}
 */
e2e.BigNum.prototype.isBetween = function(a, b) {
  return this.compare(a) > 0 && this.compare(b) < 0;
};

/**
 * Returns true if this = that.
 * @param {e2e.BigNum} that The number to compare.
 * @return {boolean}
 */
e2e.BigNum.prototype.isEqual = function(that) {
  return this.compare(that) == 0;
};

/**
 * Returns true if this < that.
 * @param {e2e.BigNum} that The number to compare.
 * @return {boolean}
 */
e2e.BigNum.prototype.isLess = function(that) {
  return this.compare(that) < 0;
};

/**
 * Returns true if this >= that.
 * @param {e2e.BigNum} that The number to compare.
 * @return {boolean}
 */
e2e.BigNum.prototype.isGreaterOrEqual = function(that) {
  return this.compare(that) >= 0;
};

/**
 * Compares this to another number. Return a negative, zero, and a positive
 * number when this is smaller than, equal to, or bigger than the other BigNum
 * respectively.
 * This is fixed-timing, thanks to quannguyen@.
 * @param {e2e.BigNum} that The number to compare.
 * @return {number}
 */
e2e.BigNum.prototype.compare = function(that) {
  var greater = 0;
  var previousLesser = 0;
  var previousGreater = 0;
  var lesser = 0;
  var maxLen = e2e.fixedtiming.max(this.n.length, that.n.length);
  for (var i = maxLen - 1; i >= 0; --i) {
    var x = this.n[i] | 0;
    var y = that.n[i] | 0;
    previousLesser |= (x < y);
    greater |= (x > y) & !previousLesser;
    previousGreater |= (x > y);
    lesser |= (x < y) & !previousGreater;
  }
  return greater - lesser;
};

/**
 * Performs a bitwise-AND of this and that.
 * @param {e2e.BigNum} that The number to AND with.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.and = function(that) {
  var maxLen = e2e.fixedtiming.max(this.n.length, that.n.length);
  var result = e2e.BigNum.createBigNumOfSize(maxLen);
  for (var i = maxLen; i >= 0; --i) {
    var x = this.n[i] | 0;
    var y = that.n[i] | 0;
    result.n[i] = x & y;
  }
  return result;
};

/**
 * Performs a bitwise-OR of this and that.
 * @param {e2e.BigNum} that The number to XOR with.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.or = function(that) {
  var maxLen = e2e.fixedtiming.max(this.n.length, that.n.length);
  var result = e2e.BigNum.createBigNumOfSize(maxLen);
  for (var i = maxLen; i >= 0; --i) {
    var x = this.n[i] | 0;
    var y = that.n[i] | 0;
    result.n[i] = x | y;
  }
  return result;
};

/**
 * Performs a bitwise-XOR of this and that.
 * @param {e2e.BigNum} that The number to XOR with.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.xor = function(that) {
  var maxLen = e2e.fixedtiming.max(this.n.length, that.n.length);
  var result = e2e.BigNum.createBigNumOfSize(maxLen);
  for (var i = maxLen; i >= 0; --i) {
    var x = this.n[i] | 0;
    var y = that.n[i] | 0;
    result.n[i] = x ^ y;
  }
  return result;
};

/**
 * Negates this value.
 *
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.negate = function() {
  var length = this.n.length;
  var result = e2e.BigNum.createBigNumOfSize(length);
  for (var i = length - 1; i >= 0; i--) {
    result.n[i] = (~ this.n[i]) & e2e.BigNum.BASE_MASK;
  }
  return result.add(e2e.BigNum.ONE);
};

/**
 * Calculates this << shift.  Shift must be in the range 0 <= shift <= 23.
 *
 * @param {number} shift  The amount by which to shift.  0 <= shift <= 23.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.shiftLeft = function(shift) {
  if (shift < 0 || shift > 23) {
    throw new e2e.error.InvalidArgumentsError(
        'Illegal shift value.');
  }
  var length = this.n.length;
  var result = e2e.BigNum.createBigNumOfSize(length + 1);
  var mask = (1 << shift) - 1;
  var xmask = (1 << (e2e.BigNum.BASE_LEN - shift)) - 1;
  var carry = 0;
  for (var i = 0; i < length; i++) {
    // We purposely mask before shifting to ensure the result stays 32 bits.
    result.n[i] = ((this.n[i] & xmask) << shift) + carry;
    carry = (this.n[i] >> (e2e.BigNum.BASE_LEN - shift)) & mask;
  }
  result.n[length] = carry;
  return result.dropLeadingZeros();
};

/**
 * Calculates this >> shift.  Shift must be in the range 0 <= shift <= 23.
 *
 * @param {number} shift  The amount by which to shift.  0 <= shift <= 23.
 * @return {!e2e.BigNum}
 */
e2e.BigNum.prototype.shiftRight = function(shift) {
  if (shift < 0 || shift > 23) {
    throw new e2e.error.InvalidArgumentsError(
        'Illegal shift value.');
  }
  var length = this.n.length;
  var result = e2e.BigNum.createBigNumOfSize(length);
  var mask = (1 << shift) - 1;
  var carry = 0;
  for (var i = length - 1; i >= 0; i--) {
    result.n[i] = carry + (this.n[i] >> shift);
    carry = (this.n[i] & mask) << (e2e.BigNum.BASE_LEN - shift);
  }
  return result;
};

/**
 * Returns true if bit nth in the little-endian representation of this is set.
 * @param {number} n The bit number to test.
 * @return {boolean}
 */
e2e.BigNum.prototype.isBitSet = function(n) {
  // The digit where the bit lives.
  var i = (n / e2e.BigNum.BASE_LEN) | 0;
  // The position in that digit.
  var j = n % e2e.BigNum.BASE_LEN;
  // When i >= n.length returns 0.
  return (this.n[i] & (1 << j)) != 0;
};

/**
 * Returns true if this is even
 * @return {boolean}
 */
e2e.BigNum.prototype.isEven = function() {
  return (this.n[0] & 1) == 0;
};

/**
 * Returns true if this is odd
 * @return {boolean}
 */
e2e.BigNum.prototype.isOdd = function() {
  return (this.n[0] & 1) != 0;
};

// Public constants.

/**
 * BigNum constant 0.
 */
e2e.BigNum.ZERO = e2e.BigNum.fromInteger(0);

/**
 * BigNum constant 1.
 */
e2e.BigNum.ONE = e2e.BigNum.fromInteger(1);

/**
 * BigNum constant 2.
 */
e2e.BigNum.TWO = e2e.BigNum.fromInteger(2);


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

    angular
        .module('app.users')
        .factory('UsersFactory', UsersFactory);

    function UsersFactory(SocketsFactory) {
        var factory = {
            getUsers: getUsers,
            addUnread: addUnread,
            resetUnread: resetUnread
        };

        var users = [];

        activate();

        function activate() {
            SocketsFactory.on('found users', function (data) {
                async.map(data.users, attachUnreadCounter, function (err, modifiedUsers) {
                    console.log('Finished adding counters');
                });
            });

            SocketsFactory.on('user connected', function (data) {
                toggleUserStatus(data.user);
            });

            SocketsFactory.on('user disconnected', function (data) {
                toggleUserStatus(data.user);
            });
        }

        function getUsers() {
            return users;
        }

        function toggleUserStatus(user) {
            var userToToggle = getUser(user.id);

            if (typeof(userToToggle.online) === 'undefined') {
                userToToggle.online = true;
            } else {
                userToToggle.online = user.online ? false : true;
            }
        }

        function addUnread(id) {
            var user = getUser(id);

            user.unread++;
        }

        function resetUnread(id) {
            var user = getUser(id);

            user.unread = 0;
        }

        function attachUnreadCounter(user, callback) {
            user.unread = 0;
            users.push(user);
            callback(null, user);
        }

        function getUser(id) {
            for (var i = 0; i < users.length; i++) {
                if (users[i].id === id) {
                    return users[i];
                }
            }
        }

        return factory;
    }
})();


text:
from core.models.request import Request
from core import deviceDB
import pickle
import logging

def sendRequest(request):
  logging.debug('send_request' + str(request))
  d = deviceDB.find_one({'id':request.deviceID})
  if d:
    if not request.forceRefresh:
      if request.all or request.multi:
        return d.get('status')
      else:
        return d.get('status').get(request.request)
    else:
      device = pickle.loads(d.get('ffObject'))
      data = device.requestData(request)
      return data
  return None


text:
#define DEBUG

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetroLog.Layouts;

namespace MetroLog.Targets
{
    public class DebugTarget : SyncTarget
    {
        public DebugTarget()
            : this(new SingleLineLayout())
        {
        }

        public DebugTarget(Layout layout)
            : base(layout)
        {
        }

        protected override void Write(LogWriteContext context, LogEventInfo entry)
        {
            var message = Layout.GetFormattedString(context, entry);

            Debug.WriteLine(message);
        }
    }
}


text: require 'generated/azure_mgmt_key_vault'


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

class Model_User extends Model_Auth_User
{
    /**
     * PDO must declare table columns
     */
    protected $_table_columns = array(
        'id' => array('type' => 'int'),
        'username' => array('type' => 'string'),
        'email' => array('type' => 'string'),
        'password' => array('type' => 'string'),
        'status' => array('type' => 'int'),
        'timezone' => array('type' => 'string'),
        'language' => array('type' => 'string'),
        'logins' => array('type' => 'int'),
        'last_login' => array('type' => 'int'),
        'ips' => array('type' => 'string'),
    );

    /**
     * explicit db group. Developers could rewrite or change the value
     */
    protected $_db_group = 'default';

} // End User Model


text:
#import <AppKit/NSResponder.h>
#import <AppKit/NSAlert.h>
#import <AppKit/NSEvent.h>
#import <AppKit/NSKeyboardBindingManager.h>
#import <AppKit/NSKeyboardBinding.h>
#import <AppKit/NSApplication.h>
#import <Foundation/NSKeyedArchiver.h>
#import <AppKit/NSGraphics.h>
#import <AppKit/NSRaise.h>

@implementation NSResponder

-(void)encodeWithCoder:(NSCoder *)encoder {
}

-initWithCoder:(NSCoder *)coder {
   if([coder allowsKeyedCoding]){
    // NSKeyedUnarchiver *keyed=(NSKeyedUnarchiver *)coder;

    //; _nextResponder=[keyed decodeObjectForKey:@"NSNextResponder"];
   }
   return self;
}

-(NSResponder *)nextResponder {
   return _nextResponder;
}

-(NSMenu *)menu {
   NSInvalidAbstractInvocation();
   return nil;
}

-(NSUndoManager *)undoManager {
    return [_nextResponder performSelector:_cmd];
}

-(void)setNextResponder:(NSResponder *)responder {
   _nextResponder=responder;
}

-(void)setMenu:(NSMenu *)menu {
   NSInvalidAbstractInvocation();
}

-validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType {
   return [_nextResponder validRequestorForSendType:sendType returnType:returnType];
}

-(void)doCommandBySelector:(SEL)selector {

    if([self respondsToSelector:selector]) {
        [self performSelector:selector withObject:nil];
    }
    else
        [_nextResponder doCommandBySelector:selector];
}

-(void)interpretKeyEvents:(NSArray *)events {
   int i,icount=[events count];

   for(i=0;i<icount;i++){
    NSEvent      *event=[events objectAtIndex:i];
    NSString     *string=[event charactersIgnoringModifiers];
    NSKeyboardBinding *keyBinding=[[NSKeyboardBindingManager defaultKeyBindingManager] keyBindingWithString:string modifierFlags:[event modifierFlags]];
    NSArray      *selectorNames=[keyBinding selectorNames];

    if(selectorNames!=nil){
     int j = 0, jcount = [selectorNames count];

     for (j = 0; j < jcount; ++j) {
      //  NSLog(@"doing %@ for %@", [selectorNames objectAtIndex:j], keyBinding);
      [self doCommandBySelector:NSSelectorFromString([selectorNames objectAtIndex:j])];
     }
    }
    else if([self respondsToSelector:@selector(insertText:)]){
     string=[event characters];

     if([string length]>0){ // FIX THIS IN APPKIT shouldnt get 0 length

      unsigned j,length=[string length];
      unichar  buffer[length];

      [string getCharacters:buffer];
      for(j=0;j<length;j++){
       unichar check=buffer[j];

       if(check>=NSUpArrowFunctionKey)
        check=' ';
       else if(check<' ')
        check=' ';

       buffer[j]=check;
      }
      string=[NSString stringWithCharacters:buffer length:length];
      [self insertText:string];
     }
    }
   }
}

-(BOOL)performKeyEquivalent:(NSEvent *)event {
   return NO;
}

-(BOOL)tryToPerform:(SEL)action with:object {
   if([self respondsToSelector:action]){
    [self performSelector:action withObject:object];
    return YES;
   }

   return [_nextResponder tryToPerform:action with:object];
}

-(void)noResponderFor:(SEL)action {
   if(action==@selector(keyDown:))
    NSBeep();
}

-(BOOL)acceptsFirstResponder {
   return NO;
}

-(BOOL)becomeFirstResponder {
   return YES;
}

-(BOOL)resignFirstResponder {
   return YES;
}

-(NSError *)willPresentError:(NSError *)error {
	// do nothing
	return error;
}

-(BOOL)presentError:(NSError *)error {
	BOOL result;
	if (self == NSApp) {
		result=NO;

		NSError *newError; //error after being modified by delegate
		id delegate = [NSApp delegate];
		if ([delegate respondsToSelector:@selector(application:willPresentError:)])
			newError = [delegate application:NSApp willPresentError:error];
		else
			newError = error;

		NSError *strippedError; //newError stripped of its recovery options if necessary
		BOOL needToRemoveOptions=NO;
		BOOL validRecoveryAttempter=NO;
		id recoveryAttempter = [newError recoveryAttempter];
		NSArray *recoveryOptions = [newError localizedRecoveryOptions];
		if ([recoveryOptions count]) {
			if (!recoveryAttempter) {
				NSLog(@"There are recovery options but no recovery attempter to interpret the user's choice of one of them. Ignoring the recovery options and suggestion.");
				needToRemoveOptions=YES;
			}
			else if (![recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:optionIndex:)]) {
				NSLog(@"The recovery attempter %@ doesn't respond to -attemptRecoveryFromError:optionIndex:. Ignoring the recovery attempter, options, and suggestion.",
					  recoveryAttempter);
				needToRemoveOptions=YES;
			}
			else
				validRecoveryAttempter=YES;
		}
		if (needToRemoveOptions) {
			NSMutableDictionary *newUserInfo = [NSMutableDictionary dictionaryWithDictionary:[newError userInfo]];
			[newUserInfo removeObjectForKey:NSLocalizedRecoveryOptionsErrorKey];
			strippedError = [NSError errorWithDomain:[newError domain] code:[newError code] userInfo:newUserInfo];
		}
		else
			strippedError = newError;
		NSInteger alertButton=[[NSAlert alertWithError:strippedError] runModal];
		if (validRecoveryAttempter)
			result = [recoveryAttempter attemptRecoveryFromError:strippedError optionIndex:alertButton];
	}
	else {
		//Forward message to nextResponder or to NSApp if there is no nextResponder
		result = [_nextResponder ? _nextResponder : NSApp presentError:[self willPresentError:error]];
	}
	return result;
}

-(void)presentError:(NSError *)error modalForWindow:(NSWindow *)window delegate:delegate didPresentSelector:(SEL)selector contextInfo:(void *)info {
	NSUnimplementedMethod();
}

-(void)flagsChanged:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)keyUp:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)keyDown:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)cursorUpdate:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)scrollWheel:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)mouseUp:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)mouseDown:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)mouseMoved:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)mouseEntered:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)mouseExited:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)mouseDragged:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)rightMouseUp:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)rightMouseDown:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)rightMouseDragged:(NSEvent *)event {
   [_nextResponder performSelector:_cmd withObject:event];
}

-(void)noop:sender {
}

@end


text:
class DropViews < ActiveRecord::Migration
  def up
    if respond_to?(:drop_view)
      drop_view :match_best_decks_with_results
      drop_view :match_decks_with_results
    end
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end


text:
import gulp from 'gulp';
import path from 'path';
import changedInPlace from 'gulp-changed-in-place';
import project from '../aurelia.json';

export default function copyFiles(done) {
  if (typeof project.build.copyFiles !== 'object') {
    done();
    return;
  }

  const instruction = getNormalizedInstruction();
  const files = Object.keys(instruction);

  return gulp.src(files)
    .pipe(changedInPlace({ firstPass: true }))
    .pipe(gulp.dest(x => {
      const filePath = prepareFilePath(x.path);
      const key = files.find(f => f === filePath);
      return instruction[key];
    }));
}

function getNormalizedInstruction() {
  const files = project.build.copyFiles;
  let normalizedInstruction = {};

  for (let key in files) {
    normalizedInstruction[path.posix.normalize(key)] = files[key];
  }

  return normalizedInstruction;
}

function prepareFilePath(filePath) {
  let preparedPath = filePath.replace(process.cwd(), '').substring(1);

  //if we are running on windows we have to fix the path
  if (/^win/.test(process.platform)) {
    preparedPath = preparedPath.replace(/\\/g, '/');
  }

  return preparedPath;
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;

namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
    internal static class DefaultExpressionSyntaxExtensions
    {
        private static readonly LiteralExpressionSyntax s_defaultLiteralExpression =
            SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression);

        public static bool CanReplaceWithDefaultLiteral(
            this DefaultExpressionSyntax defaultExpression,
            CSharpParseOptions parseOptions,
            OptionSet options,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            if (parseOptions.LanguageVersion < LanguageVersion.CSharp7_1 ||
                !options.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression).Value)
            {
                return false;
            }

            // Using the speculation analyzer can be slow.  Check for common cases first before
            // trying the expensive path.
            return CanReplaceWithDefaultLiteralFast(defaultExpression, semanticModel, cancellationToken) ??
                   CanReplaceWithDefaultLiteralSlow(defaultExpression, semanticModel, cancellationToken);
        }

        private static bool? CanReplaceWithDefaultLiteralFast(
            DefaultExpressionSyntax defaultExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            if (defaultExpression.IsParentKind(SyntaxKind.EqualsValueClause))
            {
                var equalsValueClause = (EqualsValueClauseSyntax)defaultExpression.Parent;
                var typeSyntax = GetTypeSyntax(equalsValueClause);

                if (typeSyntax != null)
                {
                    if (typeSyntax.IsVar)
                    {
                        // If we have:   var v = default(CancellationToken);    then we can't simplify this.
                        return false;
                    }

                    var entityType = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
                    var defaultType = semanticModel.GetTypeInfo(defaultExpression.Type, cancellationToken).Type;

                    if (entityType != null && entityType.Equals(defaultType))
                    {
                        // We have a simple case of "CancellationToken c = default(CancellationToken)".
                        // We can just simplify without having to do any additional analysis.
                        return true;
                    }
                }
            }

            return null;
        }

        private static TypeSyntax GetTypeSyntax(EqualsValueClauseSyntax equalsValueClause)
        {
            if (equalsValueClause.IsParentKind(SyntaxKind.VariableDeclarator) &&
                equalsValueClause.Parent.IsParentKind(SyntaxKind.VariableDeclaration))
            {
                var declaration = (VariableDeclarationSyntax)equalsValueClause.Parent.Parent;
                return declaration.Type;
            }
            else if (equalsValueClause.IsParentKind(SyntaxKind.Parameter))
            {
                var parameter = (ParameterSyntax)equalsValueClause.Parent;
                return parameter.Type;
            }

            return null;
        }

        private static bool CanReplaceWithDefaultLiteralSlow(
            DefaultExpressionSyntax defaultExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            var speculationAnalyzer = new SpeculationAnalyzer(
                defaultExpression, s_defaultLiteralExpression, semanticModel,
                cancellationToken,
                skipVerificationForReplacedNode: false,
                failOnOverloadResolutionFailuresInOriginalCode: true);

            return !speculationAnalyzer.ReplacementChangesSemantics();
        }
    }
}


text:
from __future__ import absolute_import

from copy import copy
from itertools import chain
import logging
import os
import re
import sys
import shlex
from tempfile import NamedTemporaryFile

from django.utils.encoding import smart_text

try:
    from urllib.request import pathname2url
    from urllib.parse import urljoin
except ImportError:  # Python2
    from urllib import pathname2url
    from urlparse import urljoin

import django
from django.conf import settings
from django.template.context import Context, RequestContext
from django.utils import six

from .subprocess import check_output

logger = logging.getLogger(__name__)

NO_ARGUMENT_OPTIONS = ['--collate', '--no-collate', '-H', '--extended-help', '-g',
                       '--grayscale', '-h', '--help', '--htmldoc', '--license', '-l',
                       '--lowquality', '--manpage', '--no-pdf-compression', '-q',
                       '--quiet', '--read-args-from-stdin', '--readme',
                       '--use-xserver', '-V', '--version', '--dump-default-toc-xsl',
                       '--outline', '--no-outline', '--background', '--no-background',
                       '--custom-header-propagation', '--no-custom-header-propagation',
                       '--debug-javascript', '--no-debug-javascript', '--default-header',
                       '--disable-external-links', '--enable-external-links',
                       '--disable-forms', '--enable-forms', '--images', '--no-images',
                       '--disable-internal-links', '--enable-internal-links', '-n',
                       '--disable-javascript', '--enable-javascript', '--keep-relative-links',
                       '--load-error-handling', '--load-media-error-handling',
                       '--disable-local-file-access', '--enable-local-file-access',
                       '--exclude-from-outline', '--include-in-outline', '--disable-plugins',
                       '--enable-plugins', '--print-media-type', '--no-print-media-type',
                       '--resolve-relative-links', '--disable-smart-shrinking',
                       '--enable-smart-shrinking', '--stop-slow-scripts',
                       '--no-stop-slow-scripts', '--disable-toc-back-links',
                       '--enable-toc-back-links', '--footer-line', '--no-footer-line',
                       '--header-line', '--no-header-line', '--disable-dotted-lines',
                       '--disable-toc-links', '--verbose']

def _options_to_args(**options):
    """
    Converts ``options`` into a list of command-line arguments.
    Skip arguments where no value is provided
    For flag-type (No argument) variables, pass only the name and only then if the value is True
    """
    flags = []
    for name in sorted(options):
        value = options[name]
        formatted_flag = '--%s' % name if len(name) > 1 else '-%s' % name
        formatted_flag = formatted_flag.replace('_', '-')
        accepts_no_arguments = formatted_flag in NO_ARGUMENT_OPTIONS
        if value is None or (value is False and accepts_no_arguments):
            continue
        flags.append(formatted_flag)
        if accepts_no_arguments:
            continue
        flags.append(six.text_type(value))
    return flags

def wkhtmltopdf(pages, output=None, **kwargs):
    """
    Converts html to PDF using http://wkhtmltopdf.org/.

    pages: List of file paths or URLs of the html to be converted.
    output: Optional output file path. If None, the output is returned.
    **kwargs: Passed to wkhtmltopdf via _extra_args() (See
              https://github.com/antialize/wkhtmltopdf/blob/master/README_WKHTMLTOPDF
              for acceptable args.)
              Kwargs is passed through as arguments. e.g.:
                  {'footer_html': 'http://example.com/foot.html'}
              becomes
                  '--footer-html http://example.com/foot.html'

              Where there is no value passed, use True. e.g.:
                  {'disable_javascript': True}
              becomes:
                  '--disable-javascript'

              To disable a default option, use None. e.g:
                  {'quiet': None'}
              becomes:
                  ''

    example usage:
        wkhtmltopdf(pages=['/tmp/example.html'],
                    dpi=300,
                    orientation='Landscape',
                    disable_javascript=True)
    """
    if isinstance(pages, six.string_types):
        # Support a single page.
        pages = [pages]

    if output is None:
        # Standard output.
        output = '-'
    has_cover = kwargs.pop('has_cover', False)

    # Default options:
    options = getattr(settings, 'WKHTMLTOPDF_CMD_OPTIONS', None)
    if options is None:
        options = {'quiet': True}
    else:
        options = copy(options)
    options.update(kwargs)

    page_list = list(pages)

    # handle Table of Contents
    use_toc = options.pop('toc', False)
    toc_xsl = options.pop('toc_xsl', '')
    if use_toc:
        insert_at = 1 if has_cover else 0
        if toc_xsl:
            page_list.insert(insert_at, 'toc --xsl-style-sheet %s' % toc_xsl)
        else:
            page_list.insert(insert_at, 'toc')

    # Force --encoding utf8 unless the user has explicitly overridden this.
    options.setdefault('encoding', 'utf8')

    env = getattr(settings, 'WKHTMLTOPDF_ENV', None)
    if env is not None:
        env = dict(os.environ, **env)

    cmd = 'WKHTMLTOPDF_CMD'
    cmd = getattr(settings, cmd, os.environ.get(cmd, 'wkhtmltopdf'))

    ck_args = list(chain(shlex.split(cmd),
                         _options_to_args(**options),
                         page_list,
                         [output]))
    ck_kwargs = {
        'env': env,
        'shell': True
    }
    # Handling of fileno() attr. based on https://github.com/GrahamDumpleton/mod_wsgi/issues/85
    try:
        i = sys.stderr.fileno()
        ck_kwargs['stderr'] = sys.stderr
    except (AttributeError, IOError):
        # can't call fileno() on mod_wsgi stderr object
        pass

    ck_args = ' '.join(ck_args)
    return check_output(ck_args, **ck_kwargs)

def convert_to_pdf(filename, header_filename=None, footer_filename=None, cmd_options=None, cover_filename=None):
    # Clobber header_html and footer_html only if filenames are
    # provided. These keys may be in self.cmd_options as hardcoded
    # static files.
    # The argument `filename` may be a string or a list. However, wkhtmltopdf
    # will coerce it into a list if a string is passed.
    cmd_options = cmd_options if cmd_options else {}

    if cover_filename:
        pages = [cover_filename, filename]
        cmd_options['has_cover'] = True
    else:
        pages = [filename]

    if header_filename is not None:
        cmd_options['header_html'] = header_filename
    if footer_filename is not None:
        cmd_options['footer_html'] = footer_filename
    return wkhtmltopdf(pages=pages, **cmd_options)

class RenderedFile(object):
    """
    Create a temporary file resource of the rendered template with context.
    The filename will be used for later conversion to PDF.
    """
    temporary_file = None
    filename = ''

    def __init__(self, template, context, request=None):
        debug = getattr(settings, 'WKHTMLTOPDF_DEBUG', settings.DEBUG)

        self.temporary_file = render_to_temporary_file(
            template=template,
            context=context,
            request=request,
            prefix='wkhtmltopdf', suffix='.html',
            delete=(not debug)
        )
        self.filename = self.temporary_file.name

    def __del__(self):
        # Always close the temporary_file on object destruction.
        if self.temporary_file is not None:
            self.temporary_file.close()

def render_pdf_from_template(input_template, header_template, footer_template, context, request=None, cmd_options=None,
                             cover_template=None):
    # For basic usage. Performs all the actions necessary to create a single
    # page PDF from a single template and context.
    cmd_options = cmd_options if cmd_options else {}

    header_filename = footer_filename = None

    # Main content.
    input_file = RenderedFile(
        template=input_template,
        context=context,
        request=request
    )

    # Optional. For header template argument.
    if header_template:
        header_file = RenderedFile(
            template=header_template,
            context=context,
            request=request
        )
        header_filename = header_file.filename

    # Optional. For footer template argument.
    if footer_template:
        footer_file = RenderedFile(
            template=footer_template,
            context=context,
            request=request
        )
        footer_filename = footer_file.filename

    cover = None
    if cover_template:
        cover = RenderedFile(
            template=cover_template,
            context=context,
            request=request
        )

    return convert_to_pdf(filename=input_file.filename,
                          header_filename=header_filename,
                          footer_filename=footer_filename,
                          cmd_options=cmd_options,
                          cover_filename=cover.filename if cover else None)

def content_disposition_filename(filename):
    """
    Sanitize a file name to be used in the Content-Disposition HTTP
    header.

    Even if the standard is quite permissive in terms of
    characters, there are a lot of edge cases that are not supported by
    different browsers.

    See http://greenbytes.de/tech/tc2231/#attmultinstances for more details.
    """
    filename = filename.replace(';', '').replace('"', '')
    return http_quote(filename)

def http_quote(string):
    """
    Given a unicode string, will do its dandiest to give you back a
    valid ascii charset string you can use in, say, http headers and the
    like.
    """
    if isinstance(string, six.text_type):
        try:
            import unidecode
        except ImportError:
            pass
        else:
            string = unidecode.unidecode(string)
        string = string.encode('ascii', 'replace')
    # Wrap in double-quotes for ; , and the like
    string = string.replace(b'\\', b'\\\\').replace(b'"', b'\\"')
    return '"{0!s}"'.format(string.decode())

def pathname2fileurl(pathname):
    """Returns a file:// URL for pathname. Handles OS-specific conversions."""
    return urljoin('file:', pathname2url(pathname))

def make_absolute_paths(content):
    """Convert all MEDIA files into a file://URL paths in order to
    correctly get it displayed in PDFs."""
    overrides = [
        {
            'root': settings.MEDIA_ROOT,
            'url': settings.MEDIA_URL,
        },
        {
            'root': settings.STATIC_ROOT,
            'url': settings.STATIC_URL,
        }
    ]
    has_scheme = re.compile(r'^[^:/]+://')

    for x in overrides:
        if not x['url'] or has_scheme.match(x['url']):
            continue

        if not x['root'].endswith('/'):
            x['root'] += '/'

        occur_pattern = '''["|']({0}.*?)["|']'''
        occurences = re.findall(occur_pattern.format(x['url']), content)
        occurences = list(set(occurences))  # Remove dups
        for occur in occurences:
            content = content.replace(occur,
                                      pathname2fileurl(x['root']) +
                                      occur[len(x['url']):])

    return content

def render_to_temporary_file(template, context, request=None, mode='w+b',
                             bufsize=-1, suffix='.html', prefix='tmp',
                             dir=None, delete=True):
    if django.VERSION < (1, 8):
        # If using a version of Django prior to 1.8, ensure ``context`` is an
        # instance of ``Context``
        if not isinstance(context, Context):
            if request:
                context = RequestContext(request, context)
            else:
                context = Context(context)
        content = template.render(context)
    else:
        content = template.render(context, request)

    content = smart_text(content)
    content = make_absolute_paths(content)

    try:
        # Python3 has 'buffering' arg instead of 'bufsize'
        tempfile = NamedTemporaryFile(mode=mode, buffering=bufsize,
                                      suffix=suffix, prefix=prefix,
                                      dir=dir, delete=delete)
    except TypeError:
        tempfile = NamedTemporaryFile(mode=mode, bufsize=bufsize,
                                      suffix=suffix, prefix=prefix,
                                      dir=dir, delete=delete)

    try:
        tempfile.write(content.encode('utf-8'))
        tempfile.flush()
        return tempfile
    except:
        # Clean-up tempfile if an Exception is raised.
        tempfile.close()
        raise


text:
class Browser;

namespace commander {

class CommanderBackend;

// Abstract interface for the commander UI.
class CommanderFrontend {
 public:
  CommanderFrontend() = default;
  virtual ~CommanderFrontend() = default;

  // If the UI is currently showing for |browser|, hides it.
  // If the UI is currently showing for a different browser,
  // hides it, then shows it for |browser|.
  // If the UI is not showing, shows it for |browser|.
  virtual void ToggleForBrowser(Browser* browser) = 0;
  // Show the UI, anchored to |browser|'s window.
  virtual void Show(Browser* browser) = 0;
  // Hide the UI, if showing.
  virtual void Hide() = 0;

  static std::unique_ptr<CommanderFrontend> Create(CommanderBackend* backend);

  // Disallow copy and assign
  CommanderFrontend(const CommanderFrontend& other) = delete;
  CommanderFrontend& operator=(const CommanderFrontend& other) = delete;
};

}  // namespace commander

#endif  // CHROME_BROWSER_UI_COMMANDER_COMMANDER_FRONTEND_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@color/default_indicator_color_selected"/>
</shape>


text:
function verifPassword() {
    var pass1 = document.getElementById("pwd").value;
    var pass2 = document.getElementById("pwdc").value;
    var ok = true;
    if (pass1 != pass2) {
        //alert("Passwords Do not match");
        document.getElementById("pwd").style.borderColor = "#E34234";
        document.getElementById("pwdc").style.borderColor = "#E34234";
        ok = false;
    }
    else {
        alert("Passwords Match!!!");
    }
    return ok;
}


text:
package org.appng.tools.poi;

public class ColumnDefinition {
	private String name;
	private String propertyName;

	public ColumnDefinition(String name, String propertyName) {
		this.name = name;
		this.propertyName = propertyName;
	}

	public String getName() {
		return name;
	}

	public String getPropertyName() {
		return propertyName;
	}

}


text:
'use strict';

/**
 * Check if a string is the same written forward and backwards.
 * This implementation is faster than doing standard convert to array, reverse, join pattern.
 * @returns {Boolean} True if value is same forward and backwards
 */
String.prototype.isPalindrome = String.prototype.isPalindrome || function () {
  let length = Math.floor(this.length / 2);
  for (let i = 0; i < length; i++) {
    if (this[i] !== this[this.length - i - 1]) {
      return false;
    }
  }
  return true;
};


text:
var http = require('http');

function onRequest(Request, Response) {
    Response.writeHead(200, {'Content-Type': 'text/plain'});
    Response.write('Hello Node JS');
    Response.end();
}

http.createServer(onRequest).listen(8000);