<commit_before>/*
 * jQuery UI @VERSION
 *
 * Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 *
 * $Id: ui.core.js 5587 2008-05-13 19:56:42Z scott.gonzalez $
 */
;(function($) {

$.ui = {
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},
	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('
').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');

		//if (!$.browser.safari)
			//tmp.appendTo('body');

		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},
	disableSelection: function(e) {
		e.unselectable = "on";
		e.onselectstart = function() { return false; };
		if (e.style) { e.style.MozUserSelect = "none"; }
	},
	enableSelection: function(e) {
		e.unselectable = "off";
		e.onselectstart = function() { return true; };
		if (e.style) { e.style.MozUserSelect = ""; }
	},
	hasScroll: function(e, a) {
		var scroll = /top/.test(a||"top") ? 'scrollTop' : 'scrollLeft', has = false;
		if (e[scroll] > 0) return true; e[scroll] = 1;
		has = e[scroll] > 0 ? true : false; e[scroll] = 0;
		return has;
	}
};

/** jQuery core modifications and additions **/

var _remove = $.fn.remove;
$.fn.remove = function() {
	$("*", this).add(this).trigger("remove");
	return _remove.apply(this, arguments );
};

// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott Gonz�lez and J�rn Zaefferer
function getter(namespace, plugin, method) {
	var methods = $[namespace][plugin].getter || [];
	methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods);
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		if (isMethodCall && getter(namespace, name, options)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		return this.each(function() {
			var instance = $.data(this, name);
			if (isMethodCall && instance) {
				instance[options].apply(instance, args);
			} else if (!isMethodCall) {
				$.data(this, name, new $[namespace][name](this, options));
			}
		});
	};

	// create widget constructor
	$[namespace][name] = function(element, options) {
		var self = this;

		this.widgetName = name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({}, $[namespace][name].defaults, options);
		this.element = $(element)
			.bind('setData.' + name, function(e, key, value) {
				return self.setData(key, value);
			})
			.bind('getData.' + name, function(e, key) {
				return self.getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});
		this.init();
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
};

$.widget.prototype = {
	init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},

	getData: function(key) {
		return this.options[key];
	},
	setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
		}
	},

	enable: function() {
		this.setData('disabled', false);
	},
	disable: function() {
		this.setData('disabled', true);
	}
};

/** Mouse Interaction Plugin **/

$.ui.mouse = {
	mouseInit: function() {
		var self = this;

		this.element.bind('mousedown.'+this.widgetName, function(e) {
			return self.mouseDown(e);
		});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	mouseDown: function(e) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this.mouseUp(e));

		this._mouseDownEvent = e;

		var self = this,
			btnIsLeft = (e.which == 1),
			elIsCancel = ($(e.target).is(this.options.cancel));
		if (!btnIsLeft || elIsCancel) {
			return true;
		}

		this._mouseDelayMet = !this.options.delay;
		if (!this._mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self._mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted = (this.mouseStart(e) !== false);
			if (!this._mouseStarted) { return false; }
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(e) {
			return self.mouseMove(e);
		};
		this._mouseUpDelegate = function(e) {
			return self.mouseUp(e);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		return false;
	},

	mouseMove: function(e) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !e.button) {
			return this.mouseUp(e);
		}

		if (this._mouseStarted) {
			this.mouseDrag(e);
			return false;
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted =
				(this.mouseStart(this._mouseDownEvent, e) !== false);
			(this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e));
		}

		return !this._mouseStarted;
	},

	mouseUp: function(e) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this.mouseStop(e);
		}

		return false;
	},

	mouseDistanceMet: function(e) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - e.pageX),
				Math.abs(this._mouseDownEvent.pageY - e.pageY)
			) >= this.options.distance
		);
	},

	mouseDelayMet: function(e) {
		return this._mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	mouseStart: function(e) {},
	mouseDrag: function(e) {},
	mouseStop: function(e) {}
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);<commit_msg>Core: fixed broken UTF-8 characters.<commit_after>/*
 * jQuery UI @VERSION
 *
 * Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 *
 * $Id: ui.core.js 5587 2008-05-13 19:56:42Z scott.gonzalez $
 */
;(function($) {

$.ui = {
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},
	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('
').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');

		//if (!$.browser.safari)
			//tmp.appendTo('body');

		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},
	disableSelection: function(e) {
		e.unselectable = "on";
		e.onselectstart = function() { return false; };
		if (e.style) { e.style.MozUserSelect = "none"; }
	},
	enableSelection: function(e) {
		e.unselectable = "off";
		e.onselectstart = function() { return true; };
		if (e.style) { e.style.MozUserSelect = ""; }
	},
	hasScroll: function(e, a) {
		var scroll = /top/.test(a||"top") ? 'scrollTop' : 'scrollLeft', has = false;
		if (e[scroll] > 0) return true; e[scroll] = 1;
		has = e[scroll] > 0 ? true : false; e[scroll] = 0;
		return has;
	}
};

/** jQuery core modifications and additions **/

var _remove = $.fn.remove;
$.fn.remove = function() {
	$("*", this).add(this).trigger("remove");
	return _remove.apply(this, arguments );
};

// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott González and Jörn Zaefferer
function getter(namespace, plugin, method) {
	var methods = $[namespace][plugin].getter || [];
	methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods);
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		if (isMethodCall && getter(namespace, name, options)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		return this.each(function() {
			var instance = $.data(this, name);
			if (isMethodCall && instance) {
				instance[options].apply(instance, args);
			} else if (!isMethodCall) {
				$.data(this, name, new $[namespace][name](this, options));
			}
		});
	};

	// create widget constructor
	$[namespace][name] = function(element, options) {
		var self = this;

		this.widgetName = name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({}, $[namespace][name].defaults, options);
		this.element = $(element)
			.bind('setData.' + name, function(e, key, value) {
				return self.setData(key, value);
			})
			.bind('getData.' + name, function(e, key) {
				return self.getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});
		this.init();
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
};

$.widget.prototype = {
	init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},

	getData: function(key) {
		return this.options[key];
	},
	setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
		}
	},

	enable: function() {
		this.setData('disabled', false);
	},
	disable: function() {
		this.setData('disabled', true);
	}
};

/** Mouse Interaction Plugin **/

$.ui.mouse = {
	mouseInit: function() {
		var self = this;

		this.element.bind('mousedown.'+this.widgetName, function(e) {
			return self.mouseDown(e);
		});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	mouseDown: function(e) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this.mouseUp(e));

		this._mouseDownEvent = e;

		var self = this,
			btnIsLeft = (e.which == 1),
			elIsCancel = ($(e.target).is(this.options.cancel));
		if (!btnIsLeft || elIsCancel) {
			return true;
		}

		this._mouseDelayMet = !this.options.delay;
		if (!this._mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self._mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted = (this.mouseStart(e) !== false);
			if (!this._mouseStarted) { return false; }
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(e) {
			return self.mouseMove(e);
		};
		this._mouseUpDelegate = function(e) {
			return self.mouseUp(e);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		return false;
	},

	mouseMove: function(e) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !e.button) {
			return this.mouseUp(e);
		}

		if (this._mouseStarted) {
			this.mouseDrag(e);
			return false;
		}

		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted =
				(this.mouseStart(this._mouseDownEvent, e) !== false);
			(this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e));
		}

		return !this._mouseStarted;
	},

	mouseUp: function(e) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this.mouseStop(e);
		}

		return false;
	},

	mouseDistanceMet: function(e) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - e.pageX),
				Math.abs(this._mouseDownEvent.pageY - e.pageY)
			) >= this.options.distance
		);
	},

	mouseDelayMet: function(e) {
		return this._mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	mouseStart: function(e) {},
	mouseDrag: function(e) {},
	mouseStop: function(e) {}
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);<|endoftext|>


<commit_before>/*
 * jQuery UI Progressbar @VERSION
 *
 * Copyright (c) 2008 Eduardo Lundgren
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Progressbar
 *
 * Depends:
 *   ui.core.js
 */
(function($) {

$.widget("ui.progressbar", {
	_init: function() {

		this._interval = this.options.interval;

		var self = this,
			options = this.options,
			identifier = 'progressbar' + (++$.ui.progressbar.uuid),
			text = options.text || '0%';

		this.element
			.addClass("ui-progressbar")
			.width(options.width)
			.attr({
				role: "progressbar",
				"aria-valuemin": 0,
				"aria-valuemax": 100,
				"aria-valuenow": 0
			});

		$.extend(this, {
			active: false,
			pixelState: 0,
			percentState: 0,
			identifier: identifier
		});

		this.wrapper = $('

')
			.appendTo(this.element);

		this.bar = $('

')
			.css({
				width: 0,
				overflow: 'hidden',
				zIndex: 100
			})
			.appendTo(this.wrapper);

		this.textElement = $('

')
			.html(text)
			.css({
				width: 0,
				overflow: 'hidden'
			})
			.appendTo(this.bar);

		this.textBg = $('

')
			.html(text)
			.css({
				width: this.element.width()
			})
			.appendTo(this.bar);
	},

	_animate: function() {
		var self = this,
			options = this.options,
			interval = options.interval;

		this.bar.animate(
			{
				width: options.width
			},
			{
				duration: interval,
				easing: options.equation || this.identifier,
				step: function(step, b) {
					var timestamp = new Date().getTime(), elapsedTime  = (timestamp - b.startTime);
					self.progress( (step/options.width) * 100 );
					options.interval = interval - elapsedTime;
				},
				complete: function() {
					if (self.active) {
						options.interval = self._interval;
						self.bar.width(0);
						self.textElement.width(0);
						self._animate();
					}
					else {
						delete $.easing[self.identifier];
					}
				}
			}
		);
	},

	destroy: function() {
		this.stop();

		this.element
			.removeClass("ui-progressbar ui-progressbar-disabled")
			.removeData("progressbar").unbind(".progressbar")
			.find('.ui-progressbar-wrap').remove();

		delete $.easing[this.identifier];
	},

	disable: function() {
		this.element.addClass("ui-progressbar-disabled");
		this.disabled = true;
		this.element.attr("aria-disabled", true);
	},

	enable: function() {
		this.element.removeClass("ui-progressbar-disabled");
		this.disabled = false;
		this.element.attr("aria-disabled", false);
	},

	pause: function() {
		if (this.disabled) return;
		this.bar.stop();
		this._trigger('pause', null, this.ui());
	},

	progress: function(percentState) {
		this.bar.removeClass('ui-hidden');

		this.percentState = percentState > 100 ? 100 : percentState;
		this.pixelState = (this.percentState/100) * this.options.width;
		this.bar.width(this.pixelState);
		this.textElement.width(this.pixelState);

		var percent = Math.round(this.percentState);
		if (this.options.range && !this.options.text) {
			this.text(percent + '%');
		}
		this.element.attr("aria-valuenow", percent);
		this._trigger('progress', null, this.ui());
	},

	start: function() {
		var self = this, options = this.options;

		if (this.disabled) {
			return;
		}

		$.easing[this.identifier] = function (x, t, b, c, d) {
			var inc = options.increment,
				width = options.width,
				step = ((inc > width ? width : inc)/width),
				state = Math.round(x/step)*step;
			return state > 1 ? 1 : state;
		};

		self.active = true;

		if (options.duration < options.interval) {
			options.duration = options.interval;
		}

		setTimeout(
			function() {
				self.active = false;
			},
			options.duration
		);

		this._animate();

		this._trigger('start', null, this.ui());
		return false;
	},

	stop: function() {
		this.bar.stop();
		this.bar.width(0);
		this.textElement.width(0);
		this.bar.addClass('ui-hidden');
		this.options.interval = this._interval;
		this._trigger('stop', null, this.ui());
	},

	text: function(text){
		this.textElement.add(this.textBg).html(text);
	},

	ui: function() {
		return {
			options: this.options,
			pixelState: this.pixelState,
			percentState: this.percentState
		};
	}
});

$.extend($.ui.progressbar, {
	version: "@VERSION",
	defaults: {
		width: 300,
		duration: 1000,
		interval: 1000,
		increment: 1,
		range: true,
		text: ''
	},

	uuid: 0
});

})(jQuery);
<commit_msg>Progressbar: Removed text method.<commit_after>/*
 * jQuery UI Progressbar @VERSION
 *
 * Copyright (c) 2008 Eduardo Lundgren
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Progressbar
 *
 * Depends:
 *   ui.core.js
 */
(function($) {

$.widget("ui.progressbar", {
	_init: function() {

		this._interval = this.options.interval;

		var self = this,
			options = this.options,
			identifier = 'progressbar' + (++$.ui.progressbar.uuid),
			text = options.text || '0%';

		this.element
			.addClass("ui-progressbar")
			.width(options.width)
			.attr({
				role: "progressbar",
				"aria-valuemin": 0,
				"aria-valuemax": 100,
				"aria-valuenow": 0
			});

		$.extend(this, {
			active: false,
			pixelState: 0,
			percentState: 0,
			identifier: identifier
		});

		this.wrapper = $('

')
			.appendTo(this.element);

		this.bar = $('

')
			.css({
				width: 0,
				overflow: 'hidden',
				zIndex: 100
			})
			.appendTo(this.wrapper);

		this.textElement = $('

')
			.html(text)
			.css({
				width: 0,
				overflow: 'hidden'
			})
			.appendTo(this.bar);

		this.textBg = $('

')
			.html(text)
			.css({
				width: this.element.width()
			})
			.appendTo(this.bar);
	},

	_animate: function() {
		var self = this,
			options = this.options,
			interval = options.interval;

		this.bar.animate(
			{
				width: options.width
			},
			{
				duration: interval,
				easing: options.equation || this.identifier,
				step: function(step, b) {
					var timestamp = new Date().getTime(), elapsedTime  = (timestamp - b.startTime);
					self.progress( (step/options.width) * 100 );
					options.interval = interval - elapsedTime;
				},
				complete: function() {
					if (self.active) {
						options.interval = self._interval;
						self.bar.width(0);
						self.textElement.width(0);
						self._animate();
					}
					else {
						delete $.easing[self.identifier];
					}
				}
			}
		);
	},

	destroy: function() {
		this.stop();

		this.element
			.removeClass("ui-progressbar ui-progressbar-disabled")
			.removeData("progressbar").unbind(".progressbar")
			.find('.ui-progressbar-wrap').remove();

		delete $.easing[this.identifier];
	},

	disable: function() {
		this.element.addClass("ui-progressbar-disabled");
		this.disabled = true;
		this.element.attr("aria-disabled", true);
	},

	enable: function() {
		this.element.removeClass("ui-progressbar-disabled");
		this.disabled = false;
		this.element.attr("aria-disabled", false);
	},

	pause: function() {
		if (this.disabled) return;
		this.bar.stop();
		this._trigger('pause', null, this.ui());
	},

	progress: function(percentState) {
		this.bar.removeClass('ui-hidden');

		this.percentState = percentState > 100 ? 100 : percentState;
		this.pixelState = (this.percentState/100) * this.options.width;
		this.bar.width(this.pixelState);
		this.textElement.width(this.pixelState);

		var percent = Math.round(this.percentState);
		if (this.options.range && !this.options.text) {
			this._setText(percent + '%');
		}
		this.element.attr("aria-valuenow", percent);
		this._trigger('progress', null, this.ui());
	},

	start: function() {
		var self = this, options = this.options;

		if (this.disabled) {
			return;
		}

		$.easing[this.identifier] = function (x, t, b, c, d) {
			var inc = options.increment,
				width = options.width,
				step = ((inc > width ? width : inc)/width),
				state = Math.round(x/step)*step;
			return state > 1 ? 1 : state;
		};

		self.active = true;

		if (options.duration < options.interval) {
			options.duration = options.interval;
		}

		setTimeout(
			function() {
				self.active = false;
			},
			options.duration
		);

		this._animate();

		this._trigger('start', null, this.ui());
		return false;
	},

	stop: function() {
		this.bar.stop();
		this.bar.width(0);
		this.textElement.width(0);
		this.bar.addClass('ui-hidden');
		this.options.interval = this._interval;
		this._trigger('stop', null, this.ui());
	},

	ui: function() {
		return {
			options: this.options,
			pixelState: this.pixelState,
			percentState: this.percentState
		};
	},

	_setData: function(key, value){
		switch (key) {
			case 'text':
				this._setText(value);
				break;
		}

		$.widget.prototype._setData.apply(this, arguments);
	},

	_setText: function(text){
		this.textElement.add(this.textBg).html(text);
	}
});

$.extend($.ui.progressbar, {
	version: "@VERSION",
	defaults: {
		width: 300,
		duration: 1000,
		interval: 1000,
		increment: 1,
		range: true,
		text: ''
	},

	uuid: 0
});

})(jQuery);
<|endoftext|>


<commit_before>//////////////////////////////////////////////////
// Package docs at http://docs.meteor.com/#deps //
//////////////////////////////////////////////////

Deps = {};

// http://docs.meteor.com/#deps_active
Deps.active = false;

// http://docs.meteor.com/#deps_currentcomputation
Deps.currentComputation = null;

var setCurrentComputation = function (c) {
  Deps.currentComputation = c;
  Deps.active = !! c;
};

var _debugFunc = function () {
  // lazy evaluation because `Meteor` does not exist right away
  return (typeof Meteor !== "undefined" ? Meteor._debug :
          ((typeof console !== "undefined") && console.log ? console.log :
           function () {}));
};

var _throwOrLog = function (from, e) {
  if (throwFirstError) {
    throw e;
  } else {
    _debugFunc()("Exception from Deps " + from + " function:",
                 e.stack || e.message);
  }
};

var nextId = 1;
// computations whose callbacks we should call at flush time
var pendingComputations = [];
// `true` if a Deps.flush is scheduled, or if we are in Deps.flush now
var willFlush = false;
// `true` if we are in Deps.flush now
var inFlush = false;
// `true` if we are computing a computation now, either first time
// or recompute.  This matches Deps.active unless we are inside
// Deps.nonreactive, which nullfies currentComputation even though
// an enclosing computation may still be running.
var inCompute = false;
// `true` if the `_throwFirstError` option was passed in to the call
// to Deps.flush that we are in. When set, throw rather than log the
// first error encountered while flushing. Before throwing the error,
// finish flushing (from a catch block), logging any subsequent
// errors.
var throwFirstError = false;

var afterFlushCallbacks = [];

var requireFlush = function () {
  if (! willFlush) {
    setTimeout(Deps.flush, 0);
    willFlush = true;
  }
};

// Deps.Computation constructor is visible but private
// (throws an error if you try to call it)
var constructingComputation = false;

//
// http://docs.meteor.com/#deps_computation
//
Deps.Computation = function (f, parent) {
  if (! constructingComputation)
    throw new Error(
      "Deps.Computation constructor is private; use Deps.autorun");
  constructingComputation = false;

  var self = this;

  // http://docs.meteor.com/#computation_stopped
  self.stopped = false;

  // http://docs.meteor.com/#computation_invalidated
  self.invalidated = false;

  // http://docs.meteor.com/#computation_firstrun
  self.firstRun = true;

  self._id = nextId++;
  self._onInvalidateCallbacks = [];
  // the plan is at some point to use the parent relation
  // to constrain the order that computations are processed
  self._parent = parent;
  self._func = f;
  self._recomputing = false;

  var errored = true;
  try {
    self._compute();
    errored = false;
  } finally {
    self.firstRun = false;
    if (errored)
      self.stop();
  }
};

_.extend(Deps.Computation.prototype, {

  // http://docs.meteor.com/#computation_oninvalidate
  onInvalidate: function (f) {
    var self = this;

    if (typeof f !== 'function')
      throw new Error("onInvalidate requires a function");

    var g = function () {
      Deps.nonreactive(function () {
        return Meteor._noYieldsAllowed(function () {
          f(self);
        });
      });
    };

    if (self.invalidated)
      g();
    else
      self._onInvalidateCallbacks.push(g);
  },

  // http://docs.meteor.com/#computation_invalidate
  invalidate: function () {
    var self = this;
    if (! self.invalidated) {
      // if we're currently in _recompute(), don't enqueue
      // ourselves, since we'll rerun immediately anyway.
      if (! self._recomputing && ! self.stopped) {
        requireFlush();
        pendingComputations.push(this);
      }

      self.invalidated = true;

      // callbacks can't add callbacks, because
      // self.invalidated === true.
      for(var i = 0, f; f = self._onInvalidateCallbacks[i]; i++)
        f(); // already bound with self as argument
      self._onInvalidateCallbacks = [];
    }
  },

  // http://docs.meteor.com/#computation_stop
  stop: function () {
    if (! this.stopped) {
      this.stopped = true;
      this.invalidate();
    }
  },

  _compute: function () {
    var self = this;
    self.invalidated = false;

    var previous = Deps.currentComputation;
    setCurrentComputation(self);
    var previousInCompute = inCompute;
    inCompute = true;
    try {
      self._func(self);
    } finally {
      setCurrentComputation(previous);
      inCompute = false;
    }
  },

  _recompute: function () {
    var self = this;

    self._recomputing = true;
    try {
      while (self.invalidated && ! self.stopped) {
        try {
          self._compute();
        } catch (e) {
          _throwOrLog("recompute", e);
        }
        // If _compute() invalidated us, we run again immediately.
        // A computation that invalidates itself indefinitely is an
        // infinite loop, of course.
        //
        // We could put an iteration counter here and catch run-away
        // loops.
      }
    } finally {
      self._recomputing = false;
    }
  }
});

//
// http://docs.meteor.com/#deps_dependency
//
Deps.Dependency = function () {
  this._dependentsById = {};
};

_.extend(Deps.Dependency.prototype, {
  // http://docs.meteor.com/#dependency_depend
  //
  // Adds `computation` to this set if it is not already
  // present.  Returns true if `computation` is a new member of the set.
  // If no argument, defaults to currentComputation, or does nothing
  // if there is no currentComputation.
  depend: function (computation) {
    if (! computation) {
      if (! Deps.active)
        return false;

      computation = Deps.currentComputation;
    }
    var self = this;
    var id = computation._id;
    if (! (id in self._dependentsById)) {
      self._dependentsById[id] = computation;
      computation.onInvalidate(function () {
        delete self._dependentsById[id];
      });
      return true;
    }
    return false;
  },

  // http://docs.meteor.com/#dependency_changed
  changed: function () {
    var self = this;
    for (var id in self._dependentsById)
      self._dependentsById[id].invalidate();
  },

  // http://docs.meteor.com/#dependency_hasdependents
  hasDependents: function () {
    var self = this;
    for(var id in self._dependentsById)
      return true;
    return false;
  }
});

_.extend(Deps, {
  // http://docs.meteor.com/#deps_flush
  flush: function (_opts) {
    // Nested flush could plausibly happen if, say, a flush causes
    // DOM mutation, which causes a "blur" event, which runs an
    // app event handler that calls Deps.flush.  At the moment
    // Spark blocks event handlers during DOM mutation anyway,
    // because the LiveRange tree isn't valid.  And we don't have
    // any useful notion of a nested flush.
    //
    // https://app.asana.com/0/159908330244/385138233856
    if (inFlush)
      throw new Error("Can't call Deps.flush while flushing");

    if (inCompute)
      throw new Error("Can't flush inside Deps.autorun");

    inFlush = true;
    willFlush = true;
    throwFirstError = !! (_opts && _opts._throwFirstError);

    try {
      while (pendingComputations.length ||
             afterFlushCallbacks.length) {

        // recompute all pending computations
        while (pendingComputations.length) {
          var comp = pendingComputations.shift();
          comp._recompute();
        }

        if (afterFlushCallbacks.length) {
          // call one afterFlush callback, which may
          // invalidate more computations
          var func = afterFlushCallbacks.shift();
          try {
            func();
          } catch (e) {
            _throwOrLog("afterFlush function", e);
          }
        }
      }
    } catch (e) {
      inFlush = false; // needed before calling `Deps.flush()` again
      Deps.flush({_throwFirstError: false}); // finish flushing
      throw e;
    } finally {
      willFlush = false;
      inFlush = false;
    }
  },

  // http://docs.meteor.com/#deps_autorun
  //
  // Run f(). Record its dependencies. Rerun it whenever the
  // dependencies change.
  //
  // Returns a new Computation, which is also passed to f.
  //
  // Links the computation to the current computation
  // so that it is stopped if the current computation is invalidated.
  autorun: function (f) {
    if (typeof f !== 'function')
      throw new Error('Deps.autorun requires a function argument');

    constructingComputation = true;
    var c = new Deps.Computation(function (c) {
      Meteor._noYieldsAllowed(function () { f(c); });
    }, Deps.currentComputation);

    if (Deps.active)
      Deps.onInvalidate(function () {
        c.stop();
      });

    return c;
  },

  // http://docs.meteor.com/#deps_nonreactive
  //
  // Run `f` with no current computation, returning the return value
  // of `f`.  Used to turn off reactivity for the duration of `f`,
  // so that reactive data sources accessed by `f` will not result in any
  // computations being invalidated.
  nonreactive: function (f) {
    var previous = Deps.currentComputation;
    setCurrentComputation(null);
    try {
      return f();
    } finally {
      setCurrentComputation(previous);
    }
  },

  // Wrap `f` so that it is always run nonreactively.
  _makeNonreactive: function (f) {
    if (f.$isNonreactive) // avoid multiple layers of wrapping.
      return f;
    var nonreactiveVersion = function (/*arguments*/) {
      var self = this;
      var args = _.toArray(arguments);
      var ret;
      Deps.nonreactive(function () {
        ret = f.apply(self, args);
      });
      return ret;
    };
    nonreactiveVersion.$isNonreactive = true;
    return nonreactiveVersion;
  },

  // http://docs.meteor.com/#deps_oninvalidate
  onInvalidate: function (f) {
    if (! Deps.active)
      throw new Error("Deps.onInvalidate requires a currentComputation");

    Deps.currentComputation.onInvalidate(f);
  },

  // http://docs.meteor.com/#deps_afterflush
  afterFlush: function (f) {
    afterFlushCallbacks.push(f);
    requireFlush();
  }
});
<commit_msg>Remove unused Deps._makeNonreactive<commit_after>//////////////////////////////////////////////////
// Package docs at http://docs.meteor.com/#deps //
//////////////////////////////////////////////////

Deps = {};

// http://docs.meteor.com/#deps_active
Deps.active = false;

// http://docs.meteor.com/#deps_currentcomputation
Deps.currentComputation = null;

var setCurrentComputation = function (c) {
  Deps.currentComputation = c;
  Deps.active = !! c;
};

var _debugFunc = function () {
  // lazy evaluation because `Meteor` does not exist right away
  return (typeof Meteor !== "undefined" ? Meteor._debug :
          ((typeof console !== "undefined") && console.log ? console.log :
           function () {}));
};

var _throwOrLog = function (from, e) {
  if (throwFirstError) {
    throw e;
  } else {
    _debugFunc()("Exception from Deps " + from + " function:",
                 e.stack || e.message);
  }
};

var nextId = 1;
// computations whose callbacks we should call at flush time
var pendingComputations = [];
// `true` if a Deps.flush is scheduled, or if we are in Deps.flush now
var willFlush = false;
// `true` if we are in Deps.flush now
var inFlush = false;
// `true` if we are computing a computation now, either first time
// or recompute.  This matches Deps.active unless we are inside
// Deps.nonreactive, which nullfies currentComputation even though
// an enclosing computation may still be running.
var inCompute = false;
// `true` if the `_throwFirstError` option was passed in to the call
// to Deps.flush that we are in. When set, throw rather than log the
// first error encountered while flushing. Before throwing the error,
// finish flushing (from a catch block), logging any subsequent
// errors.
var throwFirstError = false;

var afterFlushCallbacks = [];

var requireFlush = function () {
  if (! willFlush) {
    setTimeout(Deps.flush, 0);
    willFlush = true;
  }
};

// Deps.Computation constructor is visible but private
// (throws an error if you try to call it)
var constructingComputation = false;

//
// http://docs.meteor.com/#deps_computation
//
Deps.Computation = function (f, parent) {
  if (! constructingComputation)
    throw new Error(
      "Deps.Computation constructor is private; use Deps.autorun");
  constructingComputation = false;

  var self = this;

  // http://docs.meteor.com/#computation_stopped
  self.stopped = false;

  // http://docs.meteor.com/#computation_invalidated
  self.invalidated = false;

  // http://docs.meteor.com/#computation_firstrun
  self.firstRun = true;

  self._id = nextId++;
  self._onInvalidateCallbacks = [];
  // the plan is at some point to use the parent relation
  // to constrain the order that computations are processed
  self._parent = parent;
  self._func = f;
  self._recomputing = false;

  var errored = true;
  try {
    self._compute();
    errored = false;
  } finally {
    self.firstRun = false;
    if (errored)
      self.stop();
  }
};

_.extend(Deps.Computation.prototype, {

  // http://docs.meteor.com/#computation_oninvalidate
  onInvalidate: function (f) {
    var self = this;

    if (typeof f !== 'function')
      throw new Error("onInvalidate requires a function");

    var g = function () {
      Deps.nonreactive(function () {
        return Meteor._noYieldsAllowed(function () {
          f(self);
        });
      });
    };

    if (self.invalidated)
      g();
    else
      self._onInvalidateCallbacks.push(g);
  },

  // http://docs.meteor.com/#computation_invalidate
  invalidate: function () {
    var self = this;
    if (! self.invalidated) {
      // if we're currently in _recompute(), don't enqueue
      // ourselves, since we'll rerun immediately anyway.
      if (! self._recomputing && ! self.stopped) {
        requireFlush();
        pendingComputations.push(this);
      }

      self.invalidated = true;

      // callbacks can't add callbacks, because
      // self.invalidated === true.
      for(var i = 0, f; f = self._onInvalidateCallbacks[i]; i++)
        f(); // already bound with self as argument
      self._onInvalidateCallbacks = [];
    }
  },

  // http://docs.meteor.com/#computation_stop
  stop: function () {
    if (! this.stopped) {
      this.stopped = true;
      this.invalidate();
    }
  },

  _compute: function () {
    var self = this;
    self.invalidated = false;

    var previous = Deps.currentComputation;
    setCurrentComputation(self);
    var previousInCompute = inCompute;
    inCompute = true;
    try {
      self._func(self);
    } finally {
      setCurrentComputation(previous);
      inCompute = false;
    }
  },

  _recompute: function () {
    var self = this;

    self._recomputing = true;
    try {
      while (self.invalidated && ! self.stopped) {
        try {
          self._compute();
        } catch (e) {
          _throwOrLog("recompute", e);
        }
        // If _compute() invalidated us, we run again immediately.
        // A computation that invalidates itself indefinitely is an
        // infinite loop, of course.
        //
        // We could put an iteration counter here and catch run-away
        // loops.
      }
    } finally {
      self._recomputing = false;
    }
  }
});

//
// http://docs.meteor.com/#deps_dependency
//
Deps.Dependency = function () {
  this._dependentsById = {};
};

_.extend(Deps.Dependency.prototype, {
  // http://docs.meteor.com/#dependency_depend
  //
  // Adds `computation` to this set if it is not already
  // present.  Returns true if `computation` is a new member of the set.
  // If no argument, defaults to currentComputation, or does nothing
  // if there is no currentComputation.
  depend: function (computation) {
    if (! computation) {
      if (! Deps.active)
        return false;

      computation = Deps.currentComputation;
    }
    var self = this;
    var id = computation._id;
    if (! (id in self._dependentsById)) {
      self._dependentsById[id] = computation;
      computation.onInvalidate(function () {
        delete self._dependentsById[id];
      });
      return true;
    }
    return false;
  },

  // http://docs.meteor.com/#dependency_changed
  changed: function () {
    var self = this;
    for (var id in self._dependentsById)
      self._dependentsById[id].invalidate();
  },

  // http://docs.meteor.com/#dependency_hasdependents
  hasDependents: function () {
    var self = this;
    for(var id in self._dependentsById)
      return true;
    return false;
  }
});

_.extend(Deps, {
  // http://docs.meteor.com/#deps_flush
  flush: function (_opts) {
    // Nested flush could plausibly happen if, say, a flush causes
    // DOM mutation, which causes a "blur" event, which runs an
    // app event handler that calls Deps.flush.  At the moment
    // Spark blocks event handlers during DOM mutation anyway,
    // because the LiveRange tree isn't valid.  And we don't have
    // any useful notion of a nested flush.
    //
    // https://app.asana.com/0/159908330244/385138233856
    if (inFlush)
      throw new Error("Can't call Deps.flush while flushing");

    if (inCompute)
      throw new Error("Can't flush inside Deps.autorun");

    inFlush = true;
    willFlush = true;
    throwFirstError = !! (_opts && _opts._throwFirstError);

    try {
      while (pendingComputations.length ||
             afterFlushCallbacks.length) {

        // recompute all pending computations
        while (pendingComputations.length) {
          var comp = pendingComputations.shift();
          comp._recompute();
        }

        if (afterFlushCallbacks.length) {
          // call one afterFlush callback, which may
          // invalidate more computations
          var func = afterFlushCallbacks.shift();
          try {
            func();
          } catch (e) {
            _throwOrLog("afterFlush function", e);
          }
        }
      }
    } catch (e) {
      inFlush = false; // needed before calling `Deps.flush()` again
      Deps.flush({_throwFirstError: false}); // finish flushing
      throw e;
    } finally {
      willFlush = false;
      inFlush = false;
    }
  },

  // http://docs.meteor.com/#deps_autorun
  //
  // Run f(). Record its dependencies. Rerun it whenever the
  // dependencies change.
  //
  // Returns a new Computation, which is also passed to f.
  //
  // Links the computation to the current computation
  // so that it is stopped if the current computation is invalidated.
  autorun: function (f) {
    if (typeof f !== 'function')
      throw new Error('Deps.autorun requires a function argument');

    constructingComputation = true;
    var c = new Deps.Computation(function (c) {
      Meteor._noYieldsAllowed(function () { f(c); });
    }, Deps.currentComputation);

    if (Deps.active)
      Deps.onInvalidate(function () {
        c.stop();
      });

    return c;
  },

  // http://docs.meteor.com/#deps_nonreactive
  //
  // Run `f` with no current computation, returning the return value
  // of `f`.  Used to turn off reactivity for the duration of `f`,
  // so that reactive data sources accessed by `f` will not result in any
  // computations being invalidated.
  nonreactive: function (f) {
    var previous = Deps.currentComputation;
    setCurrentComputation(null);
    try {
      return f();
    } finally {
      setCurrentComputation(previous);
    }
  },

  // http://docs.meteor.com/#deps_oninvalidate
  onInvalidate: function (f) {
    if (! Deps.active)
      throw new Error("Deps.onInvalidate requires a currentComputation");

    Deps.currentComputation.onInvalidate(f);
  },

  // http://docs.meteor.com/#deps_afterflush
  afterFlush: function (f) {
    afterFlushCallbacks.push(f);
    requireFlush();
  }
});
<|endoftext|>


<commit_before>"use import";

import std.uri as URI;

var doc;
exports.getDoc = function() {
	if (doc) { return doc; }
	try {
		doc = window.ActiveXObject && new ActiveXObject('htmlfile');
		if (doc) {
			doc.open().write('');
			doc.close();
			window.attachEvent('onunload', function() {
				try { doc.body.innerHTML = ''; } catch(e) {}
				doc = null;
			});
		}
	} catch(e) {}

	if (!doc) { doc = document; }
	return doc;
};

var ctor = function() {
	var win = window,
		doc = exports.getDoc();
	//if (doc.parentWindow) { win = doc.parentWindow; }

	return new (ctor = win.XMLHttpRequest ? win.XMLHttpRequest
		: function() { return win.ActiveXObject && new win.ActiveXObject('Msxml2.XMLHTTP') || null; });
};

exports.createXHR = function() { return new ctor(); }

exports.post = function(opts, cb) {
	return exports.get(merge({method: 'POST'}, opts), cb);
}

exports.get = function(opts, cb) {
	if (typeof opts == 'string') { opts = {url: opts}; }
	var method = (opts.method || 'GET').toUpperCase();
	var url = opts.url;
	var isObject = opts.data && typeof opts.data == 'object';
	if (!opts.url) { logger.error('no url provided'); return; }

	var data = method == 'POST' ? isObject ? JSON.stringify(opts.data) : opts.data : null;
	if (method == 'GET' && opts.data) {
		url = new URI(url).addQuery(isObject ? opts.data : URI.parseQuery(opts.data)).toString();
	}

	var xhr = exports.createXHR();
	xhr.open(method, url, !(opts.async == false));
	xhr.setRequestHeader('Content-Type', 'text/plain');
	if (opts.headers) {
		for (var key in opts.headers) if (opts.headers.hasOwnProperty(key)) {
			xhr.setRequestHeader(key, opts.headers[key]);
		}
	}
	if (cb) {
		xhr.onreadystatechange = bind(this, onReadyStateChange, url, xhr, opts.type, cb);
	}

	if (opts.timeout) {
		setTimeout(bind(this, cancel, xhr, cb), opts.timeout);
	}

	xhr.send(data || null);
}

function cancel(xhr, cb) {
	xhr.onreadystatechange = null;
	cb({timeout: true}, null);
}

function onReadyStateChange(url, xhr, type, cb) {
	if (xhr.readyState != 4) { return; }
	// .status will be 0 when requests are filled via app cache on at least iOS 4.x
	if (xhr.status != 200 && xhr.status != 0) {
		cb({status: xhr.status, response: xhr.response}, null);
	} else {
		var data = xhr.responseText;
		if (type == 'json') {
			data = JSON.parse(data);
		}
		cb(null, data);
	}
}
<commit_msg>add restrictions on number of simultaneous connections<commit_after>"use import";

import std.uri as URI;

var SIMULTANEOUS = 4;
var _inflight = 0;

var doc;
exports.getDoc = function() {
	if (doc) { return doc; }
	try {
		doc = window.ActiveXObject && new ActiveXObject('htmlfile');
		if (doc) {
			doc.open().write('');
			doc.close();
			window.attachEvent('onunload', function() {
				try { doc.body.innerHTML = ''; } catch(e) {}
				doc = null;
			});
		}
	} catch(e) {}

	if (!doc) { doc = document; }
	return doc;
};

var ctor = function() {
	var win = window,
		doc = exports.getDoc();
	//if (doc.parentWindow) { win = doc.parentWindow; }

	return new (ctor = win.XMLHttpRequest ? win.XMLHttpRequest
		: function() { return win.ActiveXObject && new win.ActiveXObject('Msxml2.XMLHTTP') || null; });
};

exports.createXHR = function() { return new ctor(); }

exports.post = function(opts, cb) {
	return exports.get(merge({method: 'POST'}, opts), cb);
}

var Request = Class(function() {
	var _UID = 0;

	this.init = function(opts, cb) {
		if (!opts || !opts.url) { logger.error('no url provided'); return; }

		this.method = (opts.method || 'GET').toUpperCase();
		this.url = opts.url;
		this.type = opts.type;
		this.async = opts.async;
		this.timeout = opts.timeout;
		this.id = ++_UID;
		this.headers = {};
		this.cb = cb;

		if (opts.headers) {
			for (var key in opts.headers) if (opts.headers.hasOwnProperty(key)) {
				var value = opts.headers[key];
				this.headers[key] = value;
			}
		}

		var isObject = opts.data && typeof opts.data == 'object';

		if (this.method == 'GET' && opts.data) {
			this.url = new URI(this.url).addQuery(isObject ? opts.data : URI.parseQuery(opts.data)).toString();
		}

		try {
			this.data = (this.method == 'POST' ? (isObject ? JSON.stringify(opts.data) : opts.data) : null);
		} catch(e) {
			cb && cb({invalidData: true});
			return;
		}
	}
});

var _pending = [];

exports.get = function(opts, cb) {
	var request = new Request(opts, cb);

	if (_inflight >= SIMULTANEOUS) {
		_pending.push(request);
	} else {
		_send(request);
	}
}

function _sendNext() {
	//logger.log('====INFLIGHT', _inflight, SIMULTANEOUS, 'might send next?');
	if (_inflight < SIMULTANEOUS) {
		var request = _pending.shift();
		if (request) {
			_send(request);
		}
	}
}

function _send(request) {
	++_inflight;
	//logger.log('====INFLIGHT', _inflight, 'sending request', request.id);

	var xhr = exports.createXHR();
	xhr.open(request.method, request.url, !(request.async == false));
	xhr.setRequestHeader('Content-Type', 'text/plain');
	for (var key in request.headers) {
		xhr.setRequestHeader(key, request.headers[key]);
	}

	xhr.onreadystatechange = bind(this, onReadyStateChange, request, xhr);
	if (request.timeout) {
		request.timeoutRef = setTimeout(bind(this, cancel, xhr, request), request.timeout);
		//logger.log('==== setting timeout for', request.timeout, request.timeoutRef, '<<');
	}

	request.ts = +new Date();
	xhr.send(request.data || null);
}

function cancel(xhr, request) {
	--_inflight;
	// logger.log('====INFLIGHT', _inflight, 'timeout (cancelled)', request.id);
	if (request.timedOut) {
		logger.log('already timed out?!');
	}

	xhr.onreadystatechange = null;
	request.timedOut = true;
	request.cb && request.cb({timeout: true}, null);
}

function onReadyStateChange(request, xhr) {
	if (xhr.readyState != 4) { return; }

	if (request.timedOut) { throw 'Unexpected?!'; }

	--_inflight;

	// logger.log('====INFLIGHT', _inflight, 'received response', request.ts, request.id, (+new Date() - request.ts) / 1000);
	setTimeout(_sendNext, 0);

	var cb = request.cb;
	if ('timeoutRef' in request) {
		// logger.log('==== AJAX CLEARING TIMEOUT', request.id);
		clearTimeout(request.timeoutRef);
		request.timeoutRef = null;
	}

	if (!cb) { return; }

	// .status will be 0 when requests are filled via app cache on at least iOS 4.x
	if (xhr.status != 200 && xhr.status != 0) {
		cb({status: xhr.status, response: xhr.response}, null);
	} else {
		var data = xhr.responseText;
		if (request.type == 'json') {
			if (!data) {
				cb({status: xhr.status, response: xhr.response});
				return;
			} else {
				try {
					data = JSON.parse(data);
				} catch(e) {
					cb({status: xhr.status, response: xhr.response, parseError: true});
					return;
				}
			}
		}
		cb(null, data);
	}
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { fetchContents } from './actions'

const mapStateToProps = ({ ranking }) => {
  ranking.sort(({profit: p1}, {profit: p2}) => p2 - p1) // Desc
  return { ranking }
}

const Result = ({ranking}) => (

順位	利得

        {
          ranking.map(({ profit, own }, i) => (

              {i+1}	{profit}

          ))
        }

)

export default connect(mapStateToProps)(Result)
<commit_msg>Limit the number of participants to display in the ranking<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { fetchContents } from './actions'

const mapStateToProps = ({ ranking }) => {
  ranking.sort(({profit: p1}, {profit: p2}) => p2 - p1) // Desc
  const filtered = ranking.filter(({ own }, index) => {
    return own || index < 10
  })
  return { ranking: filtered }
}

const Result = ({ranking}) => (

順位	利得

        {
          ranking.map(({ profit, own }, i) => (

              {i+1}	{profit}

          ))
        }

)

export default connect(mapStateToProps)(Result)
<|endoftext|>


<commit_before>/**
* Undo buffer web worker
* This module acts like a circular buffer - pushing and poping complex objects from a stack
*
* It is intended to be invoked as a web worker object
*
* @author Matt Carter <m@ttcarter.com>
*/

/**
* Main undo buffer
* Each buffer item is an object of the form:
* {
	id: String, // Unique ID for this history element
* 	compressed: Boolean|String, // Either true, false, 'compressing' or 'fullObject'
* 	contents: Object, // The actual object itself
* }
* @var {array}
*/
var buffer = [];

/**
* The maxmim size of the circular undo buffer
* Set to 0 for infinite (not recommended as this will slowly eat all system memory)
* @var {number}
*/
var maxBufferSize = 10;

/**
* How often the compression worker should perform its cleanup
* Set to 0 to disable
* @var {number}
*/
var compressionWorkerInterval = 1000;

/**
* How many items the compression worker should work on per cycle
* Set to 0 to compress all
* @var {number}
*/
var compressionWorkerPerCycle = 1;

/**
* Tracker for the next ID
* @var {number}
*/
var nextId = 0;

/**
* ID prefix
* @var {string}
*/
var idPrefix = 'hist-';

/**
* Debugging level
* @var {number}
*/
var debug = 0;

// Imports
self.importScripts('/js/deep-diff.js');

// Utility functions {{{
/**
* Retrieve a full history object by its ID
* @param {string} The ID of the history item to retrieve
* @param {boolean} [clone=false] Whether to return a cloned version of the full object if one already exists
* @return {Object} The complex, fully resolved object
*/
function getFullObjectAt(id, clone) {
	// find histOffset {{{
	var histOffset = buffer.findIndex(function(h) { return h.id == id });
	if (histOffset < 0) throw new Error('Cannot get full history for non-existant history ID: ' + id);
	// }}}

	// find lastFullObjOffset {{{
	// Walk backwards until we hit a full or non-compressed object
	var lastFullObjOffset = -1;
	for (var x = histOffset; x > -1; x--) {
		if (buffer[x].compressed == 'fullObject' || buffer[x].compressed === false) {
			lastFullObjOffset = x;
			break;
		}
	}
	if (lastFullObjOffset < 0) {
		console.log('BUFFER DUMP', buffer.map(function(b) { return b.id + ' (compressed:' + b.compressed + ')'}));
		throw new Error('Cannot reconstruct history ID: ' + id + ' as no fullObjects before it in the stack exist!');
	}
	// }}}

	// Walk between lastFullObjOffset -> histOffset and patch as we go {{{
	var output = JSON.parse(JSON.stringify(buffer[lastFullObjOffset].contents));
	for (var x = lastFullObjOffset + 1; x < histOffset + 1; x++) {
		console.log('PATCH', x, buffer[x].id, buffer[x].contents, 'AGAINST FULL', output);
		for (var i = buffer[x].contents.length - 1; i >= 0; i--) {
			DeepDiff.applyChange(output, true, buffer[x].contents[i]);
		}
	}
	// }}}
	return output;
}

/**
* Output a debug message based on the desired debugging level
* @param {number} The level at which this message should be output
* @param {msg,...} The components of the message
*/
function debugLog(level, msg) {
	var args = Array.prototype.slice.call(arguments, 0);
	args[0] = 'Angular-UndoBuffer #' + level; // Replace the level argument with a prefix instead
	if (debug < level) return; // Don't bother at this level
	console.log.apply(console, args);
}
// }}}

self.addEventListener('message', function(e) {
	debugLog(3, 'Recieved message', e.data.cmd);
	switch (e.data.cmd) {
		case 'start':
			self.postMessage({id: e.data.id, cmd: 'message', payload: 'UndoBuffer started'});
			break;
		case 'end':
			self.close();
			self.postMessage({id: e.data.id, cmd: 'message', payload: 'UndoBuffer closed'});
			break;
		case 'ping':
			self.postMessage({id: e.data.id, cmd: 'message', payload: 'PONG!'});
			break;
		case 'clear':
			buffer = [];
			debugLog(1, 'undo buffer cleared');
			self.postMessage({id: e.data.id, cmd: 'clear'});
			break;
		case 'push':
			debugLog(1, 'Added item to undo buffer');
			buffer.push({
				id: idPrefix + nextId++,
				compressed: buffer.length == 0 ? 'fullObject' : false,
				contents: e.data.payload,
			});
			if (maxBufferSize && buffer.length > maxBufferSize) { // Shift off start of buffer if we are limiting the buffer size
				if (buffer.length > 1 && buffer[1].compressed === true) {
					buffer[1].contents = getFullObjectAt(buffer[1].id, true);
					buffer[1].compressed = 'fullObject';
				}
				buffer.shift();
			}
			break;
		case 'pop':
			debugLog(1, 'popping undo buffer (as full object)');
			var contents = getFullObjectAt(buffer[buffer.length-1].id);
			buffer.pop(e.data.payload);
			self.postMessage({id: e.data.id, cmd: 'pop', payload: contents});
			break;
		case 'popPatch':
			debugLog(1, 'popping undo buffer (as patch)');
			var contents = buffer.pop(e.data.payload);
			self.postMessage({id: e.data.id, cmd: 'popPatch', payload: contents.contents});
			break;
		case 'getHistory':
			if (e.data.resolve) {
				self.postMessage({
					id: e.data.id,
					cmd: 'getHistory',
					payload: buffer.map(function(b) {
						return {
							id: b.id,
							compressed: b.compressed,
							contents: getFullObjectAt(b.id), // Resolve the full history object
						};
					}),
				});
			} else { // Return patch based history
				self.postMessage({id: e.data.id, cmd: 'getHistory', payload: buffer});
			}
			break;
		case 'setMaxBufferSize':
			maxBufferSize = e.data.payload;
			if (buffer.length > maxBufferSize) buffer = buffer.slice(buffer.length - maxBufferSize);
			self.postMessage({id: e.data.id, cmd: 'setMaxBufferSize', payload: maxBufferSize});
			debugLog(1, 'Maximum buffer size set to', maxBufferSize);
			break;
		case 'setDebug':
			debug = e.data.payload;
			self.postMessage({id: e.data.id, cmd: 'setDebug', payload: debug});
			debugLog(1, 'Setting debug level to', debug);
			break;
		default:
			self.postMessage({id: e.data.id, cmd: 'error', payload: 'Unknown UndoBuffer command: ' + e.data.cmd});
	}
}, false);

var compressionWorkerHandle;
if (compressionWorkerInterval) {
	var compressionWorkerFunc = function() {
		// Work out the candidate buffers to compress {{{
		var candidates = buffer.filter(function(buf) { return buf.compressed === false });
		candidates.reverse();
		if (compressionWorkerPerCycle > 0) candidates = candidates.slice(0, compressionWorkerPerCycle);
		// }}}

		if (candidates && candidates.length) {
			candidates.forEach(function(candidateBuffer) {
				debugLog(1, 'Compressing', candidateBuffer.id);
				candidateBuffer.compressed = 'compressing';
				var bufferIndex = buffer.findIndex(function(b) { return b.id == candidateBuffer.id });
				if (bufferIndex < 0) throw new Error('Trying to compress non-existant buffer ID: ' + candidateBuffer.id);
				var fullObject = getFullObjectAt(buffer[bufferIndex-1].id);

				debugLog(3, 'Compress', candidateBuffer.id, 'Last full object', fullObject);
				debugLog(3, 'Compress', candidateBuffer.id, 'Against', candidateBuffer.contents);

				var patch = DeepDiff.diff(fullObject, candidateBuffer.contents);

				if (patch === undefined) { // Empty buffer - slice from buffer stack
					debugLog(1, 'Removing duplicate buffer', candidateBuffer.id);
					buffer = buffer.filter(function(b) { return b.id != candidateBuffer.id });
				} else {
					candidateBuffer.contents = patch;
					candidateBuffer.compressed = true;
				}
				debugLog(1, 'Finished compressing', candidateBuffer.id);
				debugLog(3, candidateBuffer.id, 'is now compressed as', candidateBuffer.contents);
			});
		}

		compressionWorkerHandle = setTimeout(compressionWorkerFunc, compressionWorkerInterval);
	};

	compressionWorkerHandle = setTimeout(compressionWorkerFunc, compressionWorkerInterval);
}
<commit_msg>Popping when the buffer is empty now returns undefined rather than throwing an error<commit_after>/**
* Undo buffer web worker
* This module acts like a circular buffer - pushing and poping complex objects from a stack
*
* It is intended to be invoked as a web worker object
*
* @author Matt Carter <m@ttcarter.com>
*/

/**
* Main undo buffer
* Each buffer item is an object of the form:
* {
	id: String, // Unique ID for this history element
* 	compressed: Boolean|String, // Either true, false, 'compressing' or 'fullObject'
* 	contents: Object, // The actual object itself
* }
* @var {array}
*/
var buffer = [];

/**
* The maxmim size of the circular undo buffer
* Set to 0 for infinite (not recommended as this will slowly eat all system memory)
* @var {number}
*/
var maxBufferSize = 10;

/**
* How often the compression worker should perform its cleanup
* Set to 0 to disable
* @var {number}
*/
var compressionWorkerInterval = 1000;

/**
* How many items the compression worker should work on per cycle
* Set to 0 to compress all
* @var {number}
*/
var compressionWorkerPerCycle = 1;

/**
* Tracker for the next ID
* @var {number}
*/
var nextId = 0;

/**
* ID prefix
* @var {string}
*/
var idPrefix = 'hist-';

/**
* Debugging level
* @var {number}
*/
var debug = 0;

// Imports
self.importScripts('/js/deep-diff.js');

// Utility functions {{{
/**
* Retrieve a full history object by its ID
* @param {string} The ID of the history item to retrieve
* @param {boolean} [clone=false] Whether to return a cloned version of the full object if one already exists
* @return {Object} The complex, fully resolved object
*/
function getFullObjectAt(id, clone) {
	// find histOffset {{{
	var histOffset = buffer.findIndex(function(h) { return h.id == id });
	if (histOffset < 0) throw new Error('Cannot get full history for non-existant history ID: ' + id);
	// }}}

	// find lastFullObjOffset {{{
	// Walk backwards until we hit a full or non-compressed object
	var lastFullObjOffset = -1;
	for (var x = histOffset; x > -1; x--) {
		if (buffer[x].compressed == 'fullObject' || buffer[x].compressed === false) {
			lastFullObjOffset = x;
			break;
		}
	}
	if (lastFullObjOffset < 0) {
		console.log('BUFFER DUMP', buffer.map(function(b) { return b.id + ' (compressed:' + b.compressed + ')'}));
		throw new Error('Cannot reconstruct history ID: ' + id + ' as no fullObjects before it in the stack exist!');
	}
	// }}}

	// Walk between lastFullObjOffset -> histOffset and patch as we go {{{
	var output = JSON.parse(JSON.stringify(buffer[lastFullObjOffset].contents));
	for (var x = lastFullObjOffset + 1; x < histOffset + 1; x++) {
		console.log('PATCH', x, buffer[x].id, buffer[x].contents, 'AGAINST FULL', output);
		for (var i = buffer[x].contents.length - 1; i >= 0; i--) {
			DeepDiff.applyChange(output, true, buffer[x].contents[i]);
		}
	}
	// }}}
	return output;
}

/**
* Output a debug message based on the desired debugging level
* @param {number} The level at which this message should be output
* @param {msg,...} The components of the message
*/
function debugLog(level, msg) {
	var args = Array.prototype.slice.call(arguments, 0);
	args[0] = 'Angular-UndoBuffer #' + level; // Replace the level argument with a prefix instead
	if (debug < level) return; // Don't bother at this level
	console.log.apply(console, args);
}
// }}}

self.addEventListener('message', function(e) {
	debugLog(3, 'Recieved message', e.data.cmd);
	switch (e.data.cmd) {
		case 'start':
			self.postMessage({id: e.data.id, cmd: 'message', payload: 'UndoBuffer started'});
			break;
		case 'end':
			self.close();
			self.postMessage({id: e.data.id, cmd: 'message', payload: 'UndoBuffer closed'});
			break;
		case 'ping':
			self.postMessage({id: e.data.id, cmd: 'message', payload: 'PONG!'});
			break;
		case 'clear':
			buffer = [];
			debugLog(1, 'undo buffer cleared');
			self.postMessage({id: e.data.id, cmd: 'clear'});
			break;
		case 'push':
			debugLog(1, 'Added item to undo buffer');
			buffer.push({
				id: idPrefix + nextId++,
				compressed: buffer.length == 0 ? 'fullObject' : false,
				contents: e.data.payload,
			});
			if (maxBufferSize && buffer.length > maxBufferSize) { // Shift off start of buffer if we are limiting the buffer size
				if (buffer.length > 1 && buffer[1].compressed === true) {
					buffer[1].contents = getFullObjectAt(buffer[1].id, true);
					buffer[1].compressed = 'fullObject';
				}
				buffer.shift();
			}
			break;
		case 'pop':
			debugLog(1, 'popping undo buffer (as full object)');
			if (!buffer.length) return self.postMessage({id: e.data.id, cmd: 'cmd', payload: undefined});
			var contents = getFullObjectAt(buffer[buffer.length-1].id);
			buffer.pop(e.data.payload);
			self.postMessage({id: e.data.id, cmd: 'pop', payload: contents});
			break;
		case 'popPatch':
			debugLog(1, 'popping undo buffer (as patch)');
			var contents = buffer.pop(e.data.payload);
			self.postMessage({id: e.data.id, cmd: 'popPatch', payload: contents.contents});
			break;
		case 'getHistory':
			if (e.data.resolve) {
				self.postMessage({
					id: e.data.id,
					cmd: 'getHistory',
					payload: buffer.map(function(b) {
						return {
							id: b.id,
							compressed: b.compressed,
							contents: getFullObjectAt(b.id), // Resolve the full history object
						};
					}),
				});
			} else { // Return patch based history
				self.postMessage({id: e.data.id, cmd: 'getHistory', payload: buffer});
			}
			break;
		case 'setMaxBufferSize':
			maxBufferSize = e.data.payload;
			if (buffer.length > maxBufferSize) buffer = buffer.slice(buffer.length - maxBufferSize);
			self.postMessage({id: e.data.id, cmd: 'setMaxBufferSize', payload: maxBufferSize});
			debugLog(1, 'Maximum buffer size set to', maxBufferSize);
			break;
		case 'setDebug':
			debug = e.data.payload;
			self.postMessage({id: e.data.id, cmd: 'setDebug', payload: debug});
			debugLog(1, 'Setting debug level to', debug);
			break;
		default:
			self.postMessage({id: e.data.id, cmd: 'error', payload: 'Unknown UndoBuffer command: ' + e.data.cmd});
	}
}, false);

var compressionWorkerHandle;
if (compressionWorkerInterval) {
	var compressionWorkerFunc = function() {
		// Work out the candidate buffers to compress {{{
		var candidates = buffer.filter(function(buf) { return buf.compressed === false });
		candidates.reverse();
		if (compressionWorkerPerCycle > 0) candidates = candidates.slice(0, compressionWorkerPerCycle);
		// }}}

		if (candidates && candidates.length) {
			candidates.forEach(function(candidateBuffer) {
				debugLog(1, 'Compressing', candidateBuffer.id);
				candidateBuffer.compressed = 'compressing';
				var bufferIndex = buffer.findIndex(function(b) { return b.id == candidateBuffer.id });
				if (bufferIndex < 0) throw new Error('Trying to compress non-existant buffer ID: ' + candidateBuffer.id);
				var fullObject = getFullObjectAt(buffer[bufferIndex-1].id);

				debugLog(3, 'Compress', candidateBuffer.id, 'Last full object', fullObject);
				debugLog(3, 'Compress', candidateBuffer.id, 'Against', candidateBuffer.contents);

				var patch = DeepDiff.diff(fullObject, candidateBuffer.contents);

				if (patch === undefined) { // Empty buffer - slice from buffer stack
					debugLog(1, 'Removing duplicate buffer', candidateBuffer.id);
					buffer = buffer.filter(function(b) { return b.id != candidateBuffer.id });
				} else {
					candidateBuffer.contents = patch;
					candidateBuffer.compressed = true;
				}
				debugLog(1, 'Finished compressing', candidateBuffer.id);
				debugLog(3, candidateBuffer.id, 'is now compressed as', candidateBuffer.contents);
			});
		}

		compressionWorkerHandle = setTimeout(compressionWorkerFunc, compressionWorkerInterval);
	};

	compressionWorkerHandle = setTimeout(compressionWorkerFunc, compressionWorkerInterval);
}
<|endoftext|>