<commit_before>/**
 * Bootstrap JavaScript Library
 * (c) 2006 - 2011 Juerg Lehni, http://lehni.org/
 *
 * Bootstrap is released under the MIT license
 * http://bootstrapjs.org/
 *
 * Inspirations:
 * http://dean.edwards.name/weblog/2006/03/base/
 * http://dev.helma.org/Wiki/JavaScript+Inheritance+Sugar/
 * http://prototypejs.org/
 */

var Base = this.Base = new function() {
	// Fix __proto__ for browsers where it is not implemented (IE and Opera).
	var fix = !this.__proto__,
		hidden = /^(statics|generics|preserve|beans|enumerable|prototype|__proto__|toString|valueOf)$/,
		proto = Object.prototype,
		toString = proto.toString,
		/**
		 * Private function that checks if an object contains a given property.
		 * Naming it 'has' causes problems on Opera when defining
		 * Object.prototype.has, as the local version then seems to be overriden
		 * by that. Giving it a idfferent name fixes it.
		 */
		has = fix
			? function(name) {
				return name !== '__proto__' && this.hasOwnProperty(name);
			}
			: proto.hasOwnProperty,
		proto = Array.prototype,
		isArray = Array.isArray = Array.isArray || function(obj) {
			return toString.call(obj) === '[object Array]';
		},
		slice = proto.slice,
		forEach = proto.forEach = proto.forEach || function(iter, bind) {
			for (var i = 0, l = this.length; i < l; i++)
				iter.call(bind, this[i], i, this);
		},
		forIn = function(iter, bind) {
			for (var i in this)
				if (has.call(this, i))
					iter.call(bind, this[i], i, this);
		},
		_define = Object.defineProperty,
		_describe = Object.getOwnPropertyDescriptor;

	// Support a mixed environment of some ECMAScript 5 features present,
	// along with __defineGetter/Setter__ functions, as found in browsers today.
	function define(obj, name, desc) {
		// Unfortunately Safari seems to ignore configurable: true and
		// does not override existing properties, so we need to delete
		// first:
		if (_define) {
			try {
				delete obj[name];
				return _define(obj, name, desc);
			} catch (e) {}
		}
		if ((desc.get || desc.set) && obj.__defineGetter__) {
			desc.get && obj.__defineGetter__(name, desc.get);
			desc.set && obj.__defineSetter__(name, desc.set);
		} else {
			obj[name] = desc.value;
		}
		return obj;
	}

	function describe(obj, name) {
		if (_describe) {
			try {
				return _describe(obj, name);
			} catch (e) {}
		}
		var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);
		return get
			? { get: get, set: obj.__lookupSetter__(name), enumerable: true,
					configurable: true }
			: has.call(obj, name)
				? { value: obj[name], enumerable: true, configurable: true,
						writable: true }
				: null;
	}

	/**
	 * Private function that injects functions from src into dest, overriding
	 * (and inherinting from) base.
	 */
	function inject(dest, src, enumerable, base, preserve, generics) {
		var beans, bean;

		/**
		 * Private function that injects one field with given name and checks if
		 * the field is a function that needs to be wrapped for calls of base().
		 * This is only needed if the function in base is different from the one
		 * in src, and if the one in src is actually calling base through base.
		 * The string of the function is parsed for this.base to detect calls.
		 */
		function field(name, val, dontCheck, generics) {
			// This does even work for prop: 0, as it will just be looked up
			// again through describe.
			var val = val || (val = describe(src, name))
					&& (val.get ? val : val.value),
				func = typeof val === 'function',
				res = val,
				// Only lookup previous value if we preserve or define a
				// function that might need it for this.base(). If we're
				// defining a getter, don't lookup previous value, but look if
				// the property exists (name in dest) and store result in prev
				prev = preserve || func
					? (val && val.get ? name in dest : dest[name]) : null;
			if (generics && func && (!preserve || !generics[name])) {
				generics[name] = function(bind) {
					return bind && dest[name].apply(bind,
							slice.call(arguments, 1));
				}
			}
			if ((dontCheck || val !== undefined && has.call(src, name))
					&& (!preserve || !prev)) {
				if (func) {
					if (prev && /\bthis\.base\b/.test(val)) {
						var fromBase = base && base[name] == prev;
						res = function() {
							var tmp = describe(this, 'base');
							define(this, 'base', { value: fromBase
								? base[name] : prev, configurable: true });
							try {
								return val.apply(this, arguments);
							} finally {
								tmp ? define(this, 'base', tmp)
									: delete this.base;
							}
						};
						// Make wrapping closure pretend to be the original
						// function on inspection
						res.toString = function() {
							return val.toString();
						}
						res.valueOf = function() {
							return val.valueOf();
						}
					}
					// Produce bean properties if getters are specified. This
					// does not produce properties for setter-only properties.
					// Just collect beans for now, and look them up in dest at
					// the end of fields injection. This ensures this.base()
					// works in beans too, and inherits setters for redefined
					// getters in subclasses. Only add getter beans if they do
					// not expect arguments. Functions that should function both
					// with optional arguments and as beans should not declare
					// the parameters and use the arguments array internally
					// instead.
					if (beans && val.length == 0
							&& (bean = name.match(/^(get|is)(([A-Z])(.*))$/)))
						beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]);
				}
				if (!res || func || !res.get && !res.set)
					res = { value: res, writable: true };
				// Only set/change configurable and enumerable if this field is
				// configurable
				if ((describe(dest, name)
						|| { configurable: true }).configurable) {
					res.configurable = true;
					res.enumerable = enumerable;
				}
				define(dest, name, res);
			}
		}
		// Iterate through all definitions in src now and call field() for each.
		if (src) {
			beans = src.beans && [];
			for (var name in src)
				if (has.call(src, name) && !hidden.test(name))
					field(name, null, true, generics);
			// IE (and some other browsers?) never enumerate these, even  if
			// they are simply set on an object. Force their creation. Do not
			// create generics for these, and check them for not being defined
			// (by passing undefined for dontCheck).
			field('toString');
			field('valueOf');
			// Now finally define beans as well. Look up methods on dest, for
			// support of this.base() (See above).
			for (var i = 0, l = beans && beans.length; i < l; i++)
				try {
					var bean = beans[i], part = bean[1];
					field(bean[0], {
						get: dest['get' + part] || dest['is' + part],
						set: dest['set' + part]
					}, true);
				} catch (e) {}
		}
		return dest;
	}

	/**
	 * Private function that creates a constructor to extend the given object.
	 * When this constructor is called through new, a new object is craeted
	 * that inherits all from obj.
	 */
	function extend(obj) {
		// Create the constructor for the new prototype that calls initialize
		// if it is defined.
		var ctor = function(dont) {
			// Fix __proto__
			if (fix) define(this, '__proto__', { value: obj });
			// Call the constructor function, if defined and we are not
			// inheriting, in which case ctor.dont would be set, see bellow.
			if (this.initialize && dont !== ctor.dont)
				return this.initialize.apply(this, arguments);
		}
		ctor.prototype = obj;
		// Add a toString function that delegates to initialize if possible
		ctor.toString = function() {
			return (this.prototype.initialize || function() {}).toString();
		}
		return ctor;
	}

	/**
	 * Converts the argument to an iterator function. If none is specified, the
	 * identity function is returned.
	 * This supports normal functions, which are returned unmodified, and values
	 * to compare to. Wherever this function is used in the Enumerable
	 * functions, a value, a Function or null may be passed.
	 */
	function iterator(iter) {
		return !iter
			? function(val) { return val }
			: typeof iter !== 'function'
				? function(val) { return val == iter }
				: iter;
	}

	function each(obj, iter, bind, asArray) {
		try {
			(asArray || asArray === undefined && isArray(obj) ? forEach : forIn)
				.call(obj, iterator(iter), bind = bind || obj);
		} catch (e) {
			if (e !== Base.stop) throw e;
		}
		return bind;
	}

	function clone(obj) {
		return each(obj, function(val, i) {
			this[i] = val;
		}, new obj.constructor());
	}

	// Inject into new ctor object that's passed to inject(), and then returned
	return inject(function() {}, {
		inject: function(src/* , ... */) {
			if (src) {
				var proto = this.prototype,
					base = proto.__proto__ && proto.__proto__.constructor,
					// Allow the whole scope to just define statics by defining
					// statics: true.
					statics = src.statics == true ? src : src.statics;
				if (statics != src)
					inject(proto, src, src.enumerable, base && base.prototype,
							src.preserve, src.generics && this);
				// Define new static fields as enumerable, and inherit from
				// base. enumerable is necessary so they can be copied over from
				// base, and it does not disturb to be enumerable in the
				// constructor. Use the preserve setting in src.preserve for
				// statics too, not their own.
				inject(this, statics, true, base, src.preserve);
			}
			// If there are more than one argument, loop through them and call
			// inject again. Do not simple inline the above code in one loop,
			// since each of the passed objects might override this.inject.
			for (var i = 1, l = arguments.length; i < l; i++)
				this.inject(arguments[i]);
			return this;
		},

		extend: function(src/* , ... */) {
			// The new prototype extends the constructor on which extend is
			// called. Fix constructor.
			// TODO: Consider using Object.create instead of using this.dont if
			// available?
			var proto = new this(this.dont),
				ctor = extend(proto);
			define(proto, 'constructor',
					{ value: ctor, writable: true, configurable: true });
			// Define an object to be passed as the first parameter in
			// constructors when initialize should not be called.
			ctor.dont = {};
			// Copy over static fields, as prototype-like inheritance
			// is not possible for static fields. Mark them as enumerable
			// so they can be copied over again.
			inject(ctor, this, true);
			// Inject all the definitions in src. Use the new inject instead of
			// the one in ctor, in case it was overriden. this is needed when
			// overriding the static .inject(). But only inject if there's
			// something to actually inject.
			return arguments.length ? this.inject.apply(ctor, arguments) : ctor;
		}
		// Pass true for enumerable, so inject() and extend() can be passed on
		// to subclasses of Base through Base.inject() / extend().
	}, true).inject({
		/**
		 * Returns true if the object contains a property with the given name,
		 * false otherwise.
		 * Just like in .each, objects only contained in the prototype(s) are
		 * filtered.
		 */
		has: has,
		each: each,

		/**
		 * Injects the fields from the given object, adding this.base()
		 * functionality
		 */
		inject: function(/* src, ... */) {
			for (var i = 0, l = arguments.length; i < l; i++)
				inject(this, arguments[i]);
			return this;
		},

		/**
		 * Returns a new object that inherits all properties from "this",
		 * through proper JS inheritance, not copying.
		 * Optionally, src and hide parameters can be passed to fill in the
		 * newly created object just like in inject(), to copy the behavior
		 * of Function.prototype.extend.
		 */
		extend: function(/* src, ... */) {
			// Notice the "new" here: the private extend returns a constructor
			// as it's used for Function.prototype.extend as well. But when
			// extending objects, we want to return a new object that inherits
			// from "this". In that case, the constructor is never used again,
			// its just created to create a new object with the proper
			// inheritance set and is garbage collected right after.
			var res = new (extend(this));
			return res.inject.apply(res, arguments);
		},

		each: function(iter, bind) {
			return each(this, iter, bind);
		},

		/**
		 * Creates a new object of the same type and copies over all
		 * name / value pairs from this object.
		 */
		clone: function() {
			return clone(this);
		},

		statics: {
			// Expose some local privates as Base generics.
			each: each,
			clone: clone,
			define: define,
			describe: describe,
			iterator: iterator,

			has: function(obj, name) {
				return has.call(obj, name);
			},

			type: function(obj) {
				return (obj || obj === 0) && (obj._type || typeof obj) || null;
			},

			check: function(obj) {
				return !!(obj || obj === 0);
			},

			/**
			 * Returns the first argument that is defined.
			 * Null is counted as defined too, since !== undefined is used for
			 * comparisons. In this it differs from Mootools!
			 */
			pick: function() {
				for (var i = 0, l = arguments.length; i < l; i++)
					if (arguments[i] !== undefined)
						return arguments[i];
				return null;
			},

			/**
			 * A special constant, to be thrown by closures passed to each()
			 *
			 * $continue / Base.next is not implemented, as the same
			 * functionality can achieved by using return in the closure.
			 * In prototype, the implementation of $continue also leads to a
			 * huge speed decrease, as the closure is wrapped in another closure
			*  that does nothing else than handling $continue.
			 */
			stop: {}
		}
	});
}
<commit_msg>No need to call has(), since __proto__ is hidden using define().<commit_after>/**
 * Bootstrap JavaScript Library
 * (c) 2006 - 2011 Juerg Lehni, http://lehni.org/
 *
 * Bootstrap is released under the MIT license
 * http://bootstrapjs.org/
 *
 * Inspirations:
 * http://dean.edwards.name/weblog/2006/03/base/
 * http://dev.helma.org/Wiki/JavaScript+Inheritance+Sugar/
 * http://prototypejs.org/
 */

var Base = this.Base = new function() {
	// Fix __proto__ for browsers where it is not implemented (IE and Opera).
	var fix = !this.__proto__,
		hidden = /^(statics|generics|preserve|beans|enumerable|prototype|__proto__|toString|valueOf)$/,
		proto = Object.prototype,
		toString = proto.toString,
		/**
		 * Private function that checks if an object contains a given property.
		 * Naming it 'has' causes problems on Opera when defining
		 * Object.prototype.has, as the local version then seems to be overriden
		 * by that. Giving it a idfferent name fixes it.
		 */
		has = fix
			? function(name) {
				return name !== '__proto__' && this.hasOwnProperty(name);
			}
			: proto.hasOwnProperty,
		proto = Array.prototype,
		isArray = Array.isArray = Array.isArray || function(obj) {
			return toString.call(obj) === '[object Array]';
		},
		slice = proto.slice,
		forEach = proto.forEach = proto.forEach || function(iter, bind) {
			for (var i = 0, l = this.length; i < l; i++)
				iter.call(bind, this[i], i, this);
		},
		forIn = function(iter, bind) {
			for (var i in this)
				if (this.hasOwnProperty(i))
					iter.call(bind, this[i], i, this);
		},
		_define = Object.defineProperty,
		_describe = Object.getOwnPropertyDescriptor;

	// Support a mixed environment of some ECMAScript 5 features present,
	// along with __defineGetter/Setter__ functions, as found in browsers today.
	function define(obj, name, desc) {
		// Unfortunately Safari seems to ignore configurable: true and
		// does not override existing properties, so we need to delete
		// first:
		if (_define) {
			try {
				delete obj[name];
				return _define(obj, name, desc);
			} catch (e) {}
		}
		if ((desc.get || desc.set) && obj.__defineGetter__) {
			desc.get && obj.__defineGetter__(name, desc.get);
			desc.set && obj.__defineSetter__(name, desc.set);
		} else {
			obj[name] = desc.value;
		}
		return obj;
	}

	function describe(obj, name) {
		if (_describe) {
			try {
				return _describe(obj, name);
			} catch (e) {}
		}
		var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);
		return get
			? { get: get, set: obj.__lookupSetter__(name), enumerable: true,
					configurable: true }
			: has.call(obj, name)
				? { value: obj[name], enumerable: true, configurable: true,
						writable: true }
				: null;
	}

	/**
	 * Private function that injects functions from src into dest, overriding
	 * (and inherinting from) base.
	 */
	function inject(dest, src, enumerable, base, preserve, generics) {
		var beans, bean;

		/**
		 * Private function that injects one field with given name and checks if
		 * the field is a function that needs to be wrapped for calls of base().
		 * This is only needed if the function in base is different from the one
		 * in src, and if the one in src is actually calling base through base.
		 * The string of the function is parsed for this.base to detect calls.
		 */
		function field(name, val, dontCheck, generics) {
			// This does even work for prop: 0, as it will just be looked up
			// again through describe.
			var val = val || (val = describe(src, name))
					&& (val.get ? val : val.value),
				func = typeof val === 'function',
				res = val,
				// Only lookup previous value if we preserve or define a
				// function that might need it for this.base(). If we're
				// defining a getter, don't lookup previous value, but look if
				// the property exists (name in dest) and store result in prev
				prev = preserve || func
					? (val && val.get ? name in dest : dest[name]) : null;
			if (generics && func && (!preserve || !generics[name])) {
				generics[name] = function(bind) {
					return bind && dest[name].apply(bind,
							slice.call(arguments, 1));
				}
			}
			if ((dontCheck || val !== undefined && has.call(src, name))
					&& (!preserve || !prev)) {
				if (func) {
					if (prev && /\bthis\.base\b/.test(val)) {
						var fromBase = base && base[name] == prev;
						res = function() {
							var tmp = describe(this, 'base');
							define(this, 'base', { value: fromBase
								? base[name] : prev, configurable: true });
							try {
								return val.apply(this, arguments);
							} finally {
								tmp ? define(this, 'base', tmp)
									: delete this.base;
							}
						};
						// Make wrapping closure pretend to be the original
						// function on inspection
						res.toString = function() {
							return val.toString();
						}
						res.valueOf = function() {
							return val.valueOf();
						}
					}
					// Produce bean properties if getters are specified. This
					// does not produce properties for setter-only properties.
					// Just collect beans for now, and look them up in dest at
					// the end of fields injection. This ensures this.base()
					// works in beans too, and inherits setters for redefined
					// getters in subclasses. Only add getter beans if they do
					// not expect arguments. Functions that should function both
					// with optional arguments and as beans should not declare
					// the parameters and use the arguments array internally
					// instead.
					if (beans && val.length == 0
							&& (bean = name.match(/^(get|is)(([A-Z])(.*))$/)))
						beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]);
				}
				if (!res || func || !res.get && !res.set)
					res = { value: res, writable: true };
				// Only set/change configurable and enumerable if this field is
				// configurable
				if ((describe(dest, name)
						|| { configurable: true }).configurable) {
					res.configurable = true;
					res.enumerable = enumerable;
				}
				define(dest, name, res);
			}
		}
		// Iterate through all definitions in src now and call field() for each.
		if (src) {
			beans = src.beans && [];
			for (var name in src)
				if (has.call(src, name) && !hidden.test(name))
					field(name, null, true, generics);
			// IE (and some other browsers?) never enumerate these, even  if
			// they are simply set on an object. Force their creation. Do not
			// create generics for these, and check them for not being defined
			// (by passing undefined for dontCheck).
			field('toString');
			field('valueOf');
			// Now finally define beans as well. Look up methods on dest, for
			// support of this.base() (See above).
			for (var i = 0, l = beans && beans.length; i < l; i++)
				try {
					var bean = beans[i], part = bean[1];
					field(bean[0], {
						get: dest['get' + part] || dest['is' + part],
						set: dest['set' + part]
					}, true);
				} catch (e) {}
		}
		return dest;
	}

	/**
	 * Private function that creates a constructor to extend the given object.
	 * When this constructor is called through new, a new object is craeted
	 * that inherits all from obj.
	 */
	function extend(obj) {
		// Create the constructor for the new prototype that calls initialize
		// if it is defined.
		var ctor = function(dont) {
			// Fix __proto__
			if (fix) define(this, '__proto__', { value: obj });
			// Call the constructor function, if defined and we are not
			// inheriting, in which case ctor.dont would be set, see bellow.
			if (this.initialize && dont !== ctor.dont)
				return this.initialize.apply(this, arguments);
		}
		ctor.prototype = obj;
		// Add a toString function that delegates to initialize if possible
		ctor.toString = function() {
			return (this.prototype.initialize || function() {}).toString();
		}
		return ctor;
	}

	/**
	 * Converts the argument to an iterator function. If none is specified, the
	 * identity function is returned.
	 * This supports normal functions, which are returned unmodified, and values
	 * to compare to. Wherever this function is used in the Enumerable
	 * functions, a value, a Function or null may be passed.
	 */
	function iterator(iter) {
		return !iter
			? function(val) { return val }
			: typeof iter !== 'function'
				? function(val) { return val == iter }
				: iter;
	}

	function each(obj, iter, bind, asArray) {
		try {
			(asArray || asArray === undefined && isArray(obj) ? forEach : forIn)
				.call(obj, iterator(iter), bind = bind || obj);
		} catch (e) {
			if (e !== Base.stop) throw e;
		}
		return bind;
	}

	function clone(obj) {
		return each(obj, function(val, i) {
			this[i] = val;
		}, new obj.constructor());
	}

	// Inject into new ctor object that's passed to inject(), and then returned
	return inject(function() {}, {
		inject: function(src/* , ... */) {
			if (src) {
				var proto = this.prototype,
					base = proto.__proto__ && proto.__proto__.constructor,
					// Allow the whole scope to just define statics by defining
					// statics: true.
					statics = src.statics == true ? src : src.statics;
				if (statics != src)
					inject(proto, src, src.enumerable, base && base.prototype,
							src.preserve, src.generics && this);
				// Define new static fields as enumerable, and inherit from
				// base. enumerable is necessary so they can be copied over from
				// base, and it does not disturb to be enumerable in the
				// constructor. Use the preserve setting in src.preserve for
				// statics too, not their own.
				inject(this, statics, true, base, src.preserve);
			}
			// If there are more than one argument, loop through them and call
			// inject again. Do not simple inline the above code in one loop,
			// since each of the passed objects might override this.inject.
			for (var i = 1, l = arguments.length; i < l; i++)
				this.inject(arguments[i]);
			return this;
		},

		extend: function(src/* , ... */) {
			// The new prototype extends the constructor on which extend is
			// called. Fix constructor.
			// TODO: Consider using Object.create instead of using this.dont if
			// available?
			var proto = new this(this.dont),
				ctor = extend(proto);
			define(proto, 'constructor',
					{ value: ctor, writable: true, configurable: true });
			// Define an object to be passed as the first parameter in
			// constructors when initialize should not be called.
			ctor.dont = {};
			// Copy over static fields, as prototype-like inheritance
			// is not possible for static fields. Mark them as enumerable
			// so they can be copied over again.
			inject(ctor, this, true);
			// Inject all the definitions in src. Use the new inject instead of
			// the one in ctor, in case it was overriden. this is needed when
			// overriding the static .inject(). But only inject if there's
			// something to actually inject.
			return arguments.length ? this.inject.apply(ctor, arguments) : ctor;
		}
		// Pass true for enumerable, so inject() and extend() can be passed on
		// to subclasses of Base through Base.inject() / extend().
	}, true).inject({
		/**
		 * Returns true if the object contains a property with the given name,
		 * false otherwise.
		 * Just like in .each, objects only contained in the prototype(s) are
		 * filtered.
		 */
		has: has,
		each: each,

		/**
		 * Injects the fields from the given object, adding this.base()
		 * functionality
		 */
		inject: function(/* src, ... */) {
			for (var i = 0, l = arguments.length; i < l; i++)
				inject(this, arguments[i]);
			return this;
		},

		/**
		 * Returns a new object that inherits all properties from "this",
		 * through proper JS inheritance, not copying.
		 * Optionally, src and hide parameters can be passed to fill in the
		 * newly created object just like in inject(), to copy the behavior
		 * of Function.prototype.extend.
		 */
		extend: function(/* src, ... */) {
			// Notice the "new" here: the private extend returns a constructor
			// as it's used for Function.prototype.extend as well. But when
			// extending objects, we want to return a new object that inherits
			// from "this". In that case, the constructor is never used again,
			// its just created to create a new object with the proper
			// inheritance set and is garbage collected right after.
			var res = new (extend(this));
			return res.inject.apply(res, arguments);
		},

		each: function(iter, bind) {
			return each(this, iter, bind);
		},

		/**
		 * Creates a new object of the same type and copies over all
		 * name / value pairs from this object.
		 */
		clone: function() {
			return clone(this);
		},

		statics: {
			// Expose some local privates as Base generics.
			each: each,
			clone: clone,
			define: define,
			describe: describe,
			iterator: iterator,

			has: function(obj, name) {
				return has.call(obj, name);
			},

			type: function(obj) {
				return (obj || obj === 0) && (obj._type || typeof obj) || null;
			},

			check: function(obj) {
				return !!(obj || obj === 0);
			},

			/**
			 * Returns the first argument that is defined.
			 * Null is counted as defined too, since !== undefined is used for
			 * comparisons. In this it differs from Mootools!
			 */
			pick: function() {
				for (var i = 0, l = arguments.length; i < l; i++)
					if (arguments[i] !== undefined)
						return arguments[i];
				return null;
			},

			/**
			 * A special constant, to be thrown by closures passed to each()
			 *
			 * $continue / Base.next is not implemented, as the same
			 * functionality can achieved by using return in the closure.
			 * In prototype, the implementation of $continue also leads to a
			 * huge speed decrease, as the closure is wrapped in another closure
			*  that does nothing else than handling $continue.
			 */
			stop: {}
		}
	});
}
<|endoftext|>


<commit_before>/**
 * Bootstrap JavaScript Library
 * (c) 2006 - 2011 Juerg Lehni, http://lehni.org/
 *
 * Bootstrap is released under the MIT license
 * http://bootstrapjs.org/
 *
 * Inspirations:
 * http://dean.edwards.name/weblog/2006/03/base/
 * http://dev.helma.org/Wiki/JavaScript+Inheritance+Sugar/
 * http://prototypejs.org/
 * http://mootools.net/
 *
 * Some code in this file is based on Mootools.net and adapted to the
 * architecture of Bootstrap, with added changes in design and architecture
 * where deemeded necessary.
 * See http://www.bootstrap-js.net/wiki/MootoolsDifferences
 */
var Base = this.Base = new function() {
	var fix = !this.__proto__,
		has = fix
			? function(name) {
				return name != '__proto__' && this.hasOwnProperty(name);
			}
			: {}.hasOwnProperty,
		hidden = /^(statics|generics|preserve|beans|enumerable|prototype|__proto__|toString|valueOf)$/,
		isArray = Array.isArray = Array.isArray || function(obj) {
			return Object.prototype.toString.call(obj) === '[object Array]';
		},
		proto = Array.prototype,
		forEach = proto.forEach = proto.forEach || function(iter, bind) {
			for (var i = 0, l = this.length; i < l; i++)
				iter.call(bind, this[i], i, this);
		},
		slice = proto.slice,
		_define = Object.defineProperty,
		_describe = Object.getOwnPropertyDescriptor;

	function define(obj, name, desc) {
		if (_define) {
			try {
				delete obj[name];
				return _define(obj, name, desc);
			} catch (e) {}
		}
		if ((desc.get || desc.set) && obj.__defineGetter__) {
			desc.get && obj.__defineGetter__(name, desc.get);
			desc.set && obj.__defineSetter__(name, desc.set);
		} else {
			obj[name] = desc.value;
		}
		return obj;
	}

	function describe(obj, name) {
		if (_describe) {
			try {
				return _describe(obj, name);
			} catch (e) {}
		}
		var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);
		return get
			? { get: get, set: obj.__lookupSetter__(name), enumerable: true,
					configurable: true }
			: has.call(obj, name)
				? { value: obj[name], enumerable: true, configurable: true,
						writable: true }
				: null;
	}

	function inject(dest, src, enumerable, base, preserve, generics) {
		var beans, bean;

		function field(name, val, dontCheck, generics) {
			var val = val || (val = describe(src, name))
					&& (val.get ? val : val.value),
				func = typeof val == 'function', res = val,
				prev = preserve || func
					? (val && val.get ? name in dest : dest[name]) : null;
			if (generics && func && (!preserve || !generics[name])) {
				generics[name] = function(bind) {
					return bind && dest[name].apply(bind,
							slice.call(arguments, 1));
				}
			}
			if ((dontCheck || val !== undefined && has.call(src, name))
					&& (!preserve || !prev)) {
				if (func) {
					if (prev && /\bthis\.base\b/.test(val)) {
						var fromBase = base && base[name] == prev;
						res = function() {
							var tmp = describe(this, 'base');
							define(this, 'base', { value: fromBase
								? base[name] : prev, configurable: true });
							try {
								return val.apply(this, arguments);
							} finally {
								tmp ? define(this, 'base', tmp)
									: delete this.base;
							}
						};
						// Make wrapping closure pretend to be the original
						// function on inspection
						res.toString = function() {
							return val.toString();
						}
						res.valueOf = function() {
							return val.valueOf();
						}
					}
					if (beans && (bean = name.match(/^(get|is)(([A-Z])(.*))$/)))
						beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]);
				}
				if (!res || func || !res.get && !res.set)
					res = { value: res, writable: true };
				if ((describe(dest, name)
						|| { configurable: true }).configurable) {
					res.configurable = true;
					res.enumerable = enumerable;
				}
				define(dest, name, res);
			}
		}
		if (src) {
			beans = src.beans && [];
			for (var name in src)
				if (has.call(src, name) && !hidden.test(name))
					field(name, null, true, generics);
			field('toString');
			field('valueOf');
			for (var i = 0, l = beans && beans.length; i < l; i++)
				try {
					var bean = beans[i], part = bean[1];
					field(bean[0], {
						get: dest['get' + part] || dest['is' + part],
						set: dest['set' + part]
					}, true);
				} catch (e) {}
		}
		return dest;
	}

	function extend(obj) {
		function ctor(dont) {
			if (fix) define(this, '__proto__', { value: obj });
			if (this.initialize && dont !== ctor.dont)
				return this.initialize.apply(this, arguments);
		}
		ctor.prototype = obj;
		ctor.toString = function() {
			return (this.prototype.initialize || function() {}).toString();
		}
		return ctor;
	}

	function each(iter, bind) {
		var bind = bind || this, iter = iterator(iter);
		try {
			if (isArray(this)) {
				forEach.call(this, iter, bind);
			} else {
				for (var i in this)
					if (this.hasOwnProperty(i))
						iter.call(bind, this[i], i, this);
			}
		} catch (e) {
			if (e !== Base.stop) throw e;
		}
		return bind;
	}

	function iterator(iter) {
		return !iter
			? function(val) { return val }
			: typeof iter != 'function'
				? function(val) { return val == iter }
					: iter;
	}

	function clone(obj) {
		return each.call(obj, function(val, i) {
			this[i] = val;
		}, new obj.constructor());
	}

	// Inject into new ctor object that's passed to inject(), and then returned
	return inject(function() {}, {
		inject: function(src) {
			if (src) {
				var proto = this.prototype,
					base = proto.__proto__ && proto.__proto__.constructor,
					statics = src.statics == true ? src : src.statics;
				if (statics != src)
					inject(proto, src, src.enumerable, base && base.prototype,
							src.preserve, src.generics && this);
				inject(this, statics, true, base, src.preserve);
			}
			for (var i = 1, l = arguments.length; i < l; i++)
				this.inject(arguments[i]);
			return this;
		},

		extend: function(src) {
			var proto = new this(this.dont), ctor = extend(proto);
			define(proto, 'constructor',
					{ value: ctor, writable: true, configurable: true });
			ctor.dont = {};
			inject(ctor, this, true);
			return arguments.length ? this.inject.apply(ctor, arguments) : ctor;
		}
		// Pass true for enumerable, so inject() and extend() can be passed on
		// to subclasses of Base through Base.inject() / extend().
	}, true).inject({
		has: has,
		each: each,

		inject: function() {
			for (var i = 0, l = arguments.length; i < l; i++)
				inject(this, arguments[i]);
			return this;
		},

		extend: function() {
			var res = new (extend(this));
			return res.inject.apply(res, arguments);
		},

		clone: function() {
			return clone(this);
		},

		statics: {
			clone: clone,
			define: define,
			describe: describe,
			iterator: iterator,

			// TODO: Use generics?
			has: function(obj, name) {
				return has.call(obj, name);
			},

			each: function(obj, iter, bind) {
				return each.call(obj, iter, bind);
			},

			type: function(obj) {
				return (obj || obj === 0) && (obj._type || typeof obj) || null;
			},

			check: function(obj) {
				return !!(obj || obj === 0);
			},

			pick: function() {
				for (var i = 0, l = arguments.length; i < l; i++)
					if (arguments[i] !== undefined)
						return arguments[i];
				return null;
			},

			stop: {}
		}
	});
}
<commit_msg>Further optimise / clean-up Bootstrap core.<commit_after>/**
 * Bootstrap JavaScript Library
 * (c) 2006 - 2011 Juerg Lehni, http://lehni.org/
 *
 * Bootstrap is released under the MIT license
 * http://bootstrapjs.org/
 *
 * Inspirations:
 * http://dean.edwards.name/weblog/2006/03/base/
 * http://dev.helma.org/Wiki/JavaScript+Inheritance+Sugar/
 * http://prototypejs.org/
 * http://mootools.net/
 *
 * Some code in this file is based on Mootools.net and adapted to the
 * architecture of Bootstrap, with added changes in design and architecture
 * where deemeded necessary.
 * See http://www.bootstrap-js.net/wiki/MootoolsDifferences
 */
var Base = this.Base = new function() {
	var fix = !this.__proto__,
		hidden = /^(statics|generics|preserve|beans|enumerable|prototype|__proto__|toString|valueOf)$/,
		proto = Object.prototype,
		has = fix
			? function(name) {
				return name != '__proto__' && this.hasOwnProperty(name);
			}
			: proto.hasOwnProperty,
		toString = proto.toString,
		isArray = Array.isArray = Array.isArray || function(obj) {
			return toString.call(obj) === '[object Array]';
		},
		proto = Array.prototype,
		forEach = proto.forEach = proto.forEach || function(iter, bind) {
			for (var i = 0, l = this.length; i < l; i++)
				iter.call(bind, this[i], i, this);
		},
		slice = proto.slice,
		_define = Object.defineProperty,
		_describe = Object.getOwnPropertyDescriptor;

	function define(obj, name, desc) {
		if (_define) {
			try {
				delete obj[name];
				return _define(obj, name, desc);
			} catch (e) {}
		}
		if ((desc.get || desc.set) && obj.__defineGetter__) {
			desc.get && obj.__defineGetter__(name, desc.get);
			desc.set && obj.__defineSetter__(name, desc.set);
		} else {
			obj[name] = desc.value;
		}
		return obj;
	}

	function describe(obj, name) {
		if (_describe) {
			try {
				return _describe(obj, name);
			} catch (e) {}
		}
		var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);
		return get
			? { get: get, set: obj.__lookupSetter__(name), enumerable: true,
					configurable: true }
			: has.call(obj, name)
				? { value: obj[name], enumerable: true, configurable: true,
						writable: true }
				: null;
	}

	function inject(dest, src, enumerable, base, preserve, generics) {
		var beans, bean;

		function field(name, val, dontCheck, generics) {
			var val = val || (val = describe(src, name))
					&& (val.get ? val : val.value),
				func = typeof val == 'function', res = val,
				prev = preserve || func
					? (val && val.get ? name in dest : dest[name]) : null;
			if (generics && func && (!preserve || !generics[name])) {
				generics[name] = function(bind) {
					return bind && dest[name].apply(bind,
							slice.call(arguments, 1));
				}
			}
			if ((dontCheck || val !== undefined && has.call(src, name))
					&& (!preserve || !prev)) {
				if (func) {
					if (prev && /\bthis\.base\b/.test(val)) {
						var fromBase = base && base[name] == prev;
						res = function() {
							var tmp = describe(this, 'base');
							define(this, 'base', { value: fromBase
								? base[name] : prev, configurable: true });
							try {
								return val.apply(this, arguments);
							} finally {
								tmp ? define(this, 'base', tmp)
									: delete this.base;
							}
						};
						// Make wrapping closure pretend to be the original
						// function on inspection
						res.toString = function() {
							return val.toString();
						}
						res.valueOf = function() {
							return val.valueOf();
						}
					}
					if (beans && (bean = name.match(/^(get|is)(([A-Z])(.*))$/)))
						beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]);
				}
				if (!res || func || !res.get && !res.set)
					res = { value: res, writable: true };
				if ((describe(dest, name)
						|| { configurable: true }).configurable) {
					res.configurable = true;
					res.enumerable = enumerable;
				}
				define(dest, name, res);
			}
		}
		if (src) {
			beans = src.beans && [];
			for (var name in src)
				if (has.call(src, name) && !hidden.test(name))
					field(name, null, true, generics);
			field('toString');
			field('valueOf');
			for (var i = 0, l = beans && beans.length; i < l; i++)
				try {
					var bean = beans[i], part = bean[1];
					field(bean[0], {
						get: dest['get' + part] || dest['is' + part],
						set: dest['set' + part]
					}, true);
				} catch (e) {}
		}
		return dest;
	}

	function extend(obj) {
		function ctor(dont) {
			if (fix) define(this, '__proto__', { value: obj });
			if (this.initialize && dont !== ctor.dont)
				return this.initialize.apply(this, arguments);
		}
		ctor.prototype = obj;
		ctor.toString = function() {
			return (this.prototype.initialize || function() {}).toString();
		}
		return ctor;
	}

	function each(iter, bind) {
		var bind = bind || this, iter = iterator(iter);
		try {
			if (isArray(this)) {
				forEach.call(this, iter, bind);
			} else {
				for (var i in this)
					if (this.hasOwnProperty(i))
						iter.call(bind, this[i], i, this);
			}
		} catch (e) {
			if (e !== Base.stop) throw e;
		}
		return bind;
	}

	function iterator(iter) {
		return !iter
			? function(val) { return val }
			: typeof iter != 'function'
				? function(val) { return val == iter }
					: iter;
	}

	function clone(obj) {
		return each.call(obj, function(val, i) {
			this[i] = val;
		}, new obj.constructor());
	}

	// Inject into new ctor object that's passed to inject(), and then returned
	return inject(function() {}, {
		inject: function(src) {
			if (src) {
				var proto = this.prototype,
					base = proto.__proto__ && proto.__proto__.constructor,
					statics = src.statics == true ? src : src.statics;
				if (statics != src)
					inject(proto, src, src.enumerable, base && base.prototype,
							src.preserve, src.generics && this);
				inject(this, statics, true, base, src.preserve);
			}
			for (var i = 1, l = arguments.length; i < l; i++)
				this.inject(arguments[i]);
			return this;
		},

		extend: function(src) {
			var proto = new this(this.dont), ctor = extend(proto);
			define(proto, 'constructor',
					{ value: ctor, writable: true, configurable: true });
			ctor.dont = {};
			inject(ctor, this, true);
			return arguments.length ? this.inject.apply(ctor, arguments) : ctor;
		}
		// Pass true for enumerable, so inject() and extend() can be passed on
		// to subclasses of Base through Base.inject() / extend().
	}, true).inject({
		has: has,
		each: each,

		inject: function() {
			for (var i = 0, l = arguments.length; i < l; i++)
				inject(this, arguments[i]);
			return this;
		},

		extend: function() {
			var res = new (extend(this));
			return res.inject.apply(res, arguments);
		},

		clone: function() {
			return clone(this);
		},

		statics: {
			clone: clone,
			define: define,
			describe: describe,
			iterator: iterator,

			// TODO: Use generics?
			has: function(obj, name) {
				return has.call(obj, name);
			},

			each: function(obj, iter, bind) {
				return each.call(obj, iter, bind);
			},

			type: function(obj) {
				return (obj || obj === 0) && (obj._type || typeof obj) || null;
			},

			check: function(obj) {
				return !!(obj || obj === 0);
			},

			pick: function() {
				for (var i = 0, l = arguments.length; i < l; i++)
					if (arguments[i] !== undefined)
						return arguments[i];
				return null;
			},

			stop: {}
		}
	});
}
<|endoftext|>


<commit_before>const libraries = require('./libraries.json'),
      placeTypes = require('./placeTypes.json'),
      spaces = require('./spaces.json'),
      mustache = require('mustache'),
      fetch = require('node-fetch'),
      admin = require("firebase-admin");

const template = `
{{=<% %>=}}
{ "@context" : "http://schema.org",
  "@type" : "Organization",
  "url" : "https://library.virginia.edu",
  "location" : \{
<% #libraries %>
    "<% slug %>":{
      "@context": "http://schema.org",
      "@type": "Library",
      <% #image_url %>
      "image": [
        "<%{ image_url }%>"
       ],
      <% /image_url %>
      "@id": "https://www.library.virginia.edu/libraries/<% slug %>",
      "name": "<% title %>",
      <% #address %>
      "address": {
        "@type": "PostalAddress",
        "streetAddress": "291 McCormick Rd",
        "addressLocality": "Charlottesville",
        "addressRegion": "VA",
        "postalCode": "22903",
        "addressCountry": "US"
      },
      <% /address %>
      <% #geo %>
      "geo": {
        "@type": "GeoCoordinates",
        "latitude": <% geo.lat %>,
        "longitude": <% geo.lng %>
      },
      <% /geo %>
      "url": "https://www.library.virginia.edu/libraries/<% slug %>",
      <% #capacity %>
      "maximumAttendeeCapacity": <% capacity %>,
      <% /capacity %>
      <% #libcal %>
      "openingHoursSpecification": <% libcal %>,
      <% /libcal %>
      "telephone": "+1<% phone %>"
    }<% ^last %>,<% /last %>
<% /libraries %>
  }
}
`;

libraries[ libraries.length -1 ].last = true;
libraries.forEach(lib=>{
  lib.slug = lib.field_slug[0].value;
  lib.image_url = (lib.field_main_image && lib.field_main_image.length>0)? lib.field_main_image[0].url.replace('drupal.lib.virginia.edu/sites/default/files','library.virginia.edu/files'):null;
  lib.title = lib.title[0].value;
  if (lib.field_fm_location && lib.field_fm_location.length > 0) {
    lib.geo = {lat:lib.field_fm_location[0].lat,lng:lib.field_fm_location[0].lng}
  }
  if (lib.field_phone_number && lib.field_phone_number.length > 0) {
    lib.phone = lib.field_phone_number[0].value.replace(/[\-\(\)\s]/g,'');
  }
  if (lib.field_occupancy_capacity && lib.field_occupancy_capacity.length > 0) {
    lib.capacity = lib.field_occupancy_capacity[0].value;
  }
  if (lib.field_libcal_id && lib.field_libcal_id.length > 0) {
    lib.libcal = lib.field_libcal_id[0].value;
  }
});

result = mustache.render(template, { libraries:libraries, places:placeTypes } );

var plibs = JSON.parse(result);

async function fetchCalHours(){
  for (key in plibs.location) {
    var lib = plibs.location[key];
    if (lib.openingHoursSpecification) {
      const json = await fetch("https://api3.libcal.com/api_hours_grid.php?format=jsonld&iid=863&lid="+lib.openingHoursSpecification)
        .then(res => {
          if (res.ok) return res;
          else console.log("failed: "+res.statusText);
        })
        .then(res => res.json());
      if (json.openingHoursSpecification)
        plibs.location[key].openingHoursSpecification = json.openingHoursSpecification;
      else delete plibs.location[key].openingHoursSpecification;
    }
    if (spaces[key])
      plibs.location[key].containedInPlace = spaces[key];
  }
}

return fetchCalHours()
  .then(()=>{
    // Fetch the service account key JSON file contents
    var serviceAccount = require(process.env.firebasekey);

    // Initialize the app with a service account, granting admin privileges
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://uvalib-api.firebaseio.com"
    });
    var db = admin.database();
    var ref = db.ref("locations-schemaorg");
    //ref.update(plibs).then(() => process.exit(0));
    var promises = [];
    for (key in plibs.location) {
      promises.push(ref.child('location/'+key).update(plibs.location[key]));
    }
    Promise.all(promises).then(()=>process.exit(0));
  });
<commit_msg>count logging<commit_after>const libraries = require('./libraries.json'),
      placeTypes = require('./placeTypes.json'),
      spaces = require('./spaces.json'),
      mustache = require('mustache'),
      fetch = require('node-fetch'),
      admin = require("firebase-admin");

const template = `
{{=<% %>=}}
{ "@context" : "http://schema.org",
  "@type" : "Organization",
  "url" : "https://library.virginia.edu",
  "location" : \{
<% #libraries %>
    "<% slug %>":{
      "@context": "http://schema.org",
      "@type": "Library",
      <% #image_url %>
      "image": [
        "<%{ image_url }%>"
       ],
      <% /image_url %>
      "@id": "https://www.library.virginia.edu/libraries/<% slug %>",
      "name": "<% title %>",
      <% #address %>
      "address": {
        "@type": "PostalAddress",
        "streetAddress": "291 McCormick Rd",
        "addressLocality": "Charlottesville",
        "addressRegion": "VA",
        "postalCode": "22903",
        "addressCountry": "US"
      },
      <% /address %>
      <% #geo %>
      "geo": {
        "@type": "GeoCoordinates",
        "latitude": <% geo.lat %>,
        "longitude": <% geo.lng %>
      },
      <% /geo %>
      "url": "https://www.library.virginia.edu/libraries/<% slug %>",
      <% #capacity %>
      "maximumAttendeeCapacity": <% capacity %>,
      <% /capacity %>
      <% #libcal %>
      "openingHoursSpecification": <% libcal %>,
      <% /libcal %>
      "telephone": "+1<% phone %>"
    }<% ^last %>,<% /last %>
<% /libraries %>
  }
}
`;

libraries[ libraries.length -1 ].last = true;
libraries.forEach(lib=>{
  lib.slug = lib.field_slug[0].value;
  lib.image_url = (lib.field_main_image && lib.field_main_image.length>0)? lib.field_main_image[0].url.replace('drupal.lib.virginia.edu/sites/default/files','library.virginia.edu/files'):null;
  lib.title = lib.title[0].value;
  if (lib.field_fm_location && lib.field_fm_location.length > 0) {
    lib.geo = {lat:lib.field_fm_location[0].lat,lng:lib.field_fm_location[0].lng}
  }
  if (lib.field_phone_number && lib.field_phone_number.length > 0) {
    lib.phone = lib.field_phone_number[0].value.replace(/[\-\(\)\s]/g,'');
  }
  if (lib.field_occupancy_capacity && lib.field_occupancy_capacity.length > 0) {
    lib.capacity = lib.field_occupancy_capacity[0].value;
  }
  if (lib.field_libcal_id && lib.field_libcal_id.length > 0) {
    lib.libcal = lib.field_libcal_id[0].value;
  }
});

result = mustache.render(template, { libraries:libraries, places:placeTypes } );

var plibs = JSON.parse(result);

async function fetchCalHours(){
  for (key in plibs.location) {
    var lib = plibs.location[key];
    if (lib.openingHoursSpecification) {
      const json = await fetch("https://api3.libcal.com/api_hours_grid.php?format=jsonld&iid=863&lid="+lib.openingHoursSpecification)
        .then(res => {
          if (res.ok) return res;
          else console.log("failed: "+res.statusText);
        })
        .then(res => res.json());
      if (json.openingHoursSpecification)
        plibs.location[key].openingHoursSpecification = json.openingHoursSpecification;
      else delete plibs.location[key].openingHoursSpecification;
    }
    if (spaces[key])
      plibs.location[key].containedInPlace = spaces[key];
  }
}

return fetchCalHours()
  .then(()=>{
    // Fetch the service account key JSON file contents
    var serviceAccount = require(process.env.firebasekey);

    // Initialize the app with a service account, granting admin privileges
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://uvalib-api.firebaseio.com"
    });
    var db = admin.database();
    var ref = db.ref("locations-schemaorg");
    //ref.update(plibs).then(() => process.exit(0));
    var promises = [];
    for (key in plibs.location) {
      for (prop in plibs.location[key]) {
        if (prop == "containedInPlace") {
          for (place in plibs.location[key][prop][place]) {
            promises.push(ref.child('location/'+key+'/'+prop+'/'+place).update(plibs.location[key][prop][place]));
          }
        } else {
          promises.push(ref.child('location/'+key+'/'+prop).update(plibs.location[key][prop]));
        }
      }
    }
    Promise.all(promises).then(()=>process.exit(0));
  });
<|endoftext|>


<commit_before>import Rx from 'rx'

import {fetchUriParams,getUriQuery,setWindowPathAndTitle}  from '../utils/urlUtils'
import {setSetting$} from '../actions/appActions'
import {newDesign$, setDesignData$} from '../actions/designActions'

let mainUri    = window.location.href
let uriQuery   = getUriQuery(mainUri)
let designUri = fetchUriParams(mainUri, "designUrl").pop()
let meshUri   = fetchUriParams(mainUri, "modelUrl").pop()
let appMode    = fetchUriParams(mainUri, "appMode").pop()

//let designUri$ = new Rx.Observable()
//let meshUri$   = new Rx.Observable()

import {exists} from '../utils/obsUtils'

//mesh sources : drag & drop
//mesh URI source: drag & drop OR query param

//design sources: drag & drop OR remote
//design URI source: localstorage OR query param OR drag & drop

//only allow if appMode is actually set
Rx.Observable
  .just(appMode)
  .filter(exists)
  .subscribe( setSetting$({path:"mode",value:appMode}) )

//load from localstorage in case all else failed

//last but not least, try to load if anything is in the query (shorthand for design uuids)
/*if(!designUri && ! meshUri && uriQuery)
{
  //FIXME: this does not seem right ...
  let apiDesignsUri = "https://jamapi.youmagine.com/api/v1/designs/"
  designUri = apiDesignsUri+uriQuery
}

setDesignData$({uri:designUri})*/
//loadDesign$(designUri)

//only load meshes if no designs need to be loaded
//meshUri$(meshUrls) //self.loadMesh(meshUrl) })

function getShortDesignUri (uriQuery){
  if(!uriQuery) return Rx.Observable.just(undefined)
  let apiDesignsUri = "https://jamapi.youmagine.com/api/v1/designs/"
  let designUri = apiDesignsUri+uriQuery
  return Rx.Observable.just( designUri )
}

let urDesignUri$ = Rx.Observable
  .just( designUri )
  .filter(exists)

let lsDesignUri$  = Rx.Observable
  .just(  localStorage.getItem("jam!-lastDesignUri") )
  .filter(exists)

let stDesignUri$ = Rx.Observable.merge(
  urDesignUri$,
  getShortDesignUri(uriQuery)
)
  .shareReplay(1)
  //.filter(exists)

let foo$ = Rx.Observable.merge(
  urDesignUri$,//ORDER MATTERS !!!
  lsDesignUri$,
  stDesignUri$
  )
  .take(1)
  .subscribe(
  function(data){
    console.log("HI THERE : mixed data source",data)
  })

<commit_msg>- refined/ updated urlSources  * added handling for meshUrls  * added exporting of data streams  * still wip<commit_after>import Rx from 'rx'

import {fetchUriParams,getUriQuery,setWindowPathAndTitle}  from '../utils/urlUtils'
import {setSetting$} from '../actions/appActions'
import {newDesign$, setDesignData$} from '../actions/designActions'

let mainUri    = window.location.href
let uriQuery   = getUriQuery(mainUri)
let designUri = fetchUriParams(mainUri, "designUrl").pop()
let meshUris   = fetchUriParams(mainUri, "modelUrl")
let appMode    = fetchUriParams(mainUri, "appMode").pop()

//let designUri$ = new Rx.Observable()
//let meshUri$   = new Rx.Observable()

import {exists} from '../utils/obsUtils'

//mesh sources : drag & drop
//mesh URI source: drag & drop OR query param

//design sources: drag & drop OR remote
//design URI source: localstorage OR query param OR drag & drop

//only allow if appMode is actually set
Rx.Observable
  .just(appMode)
  .filter(exists)
  .subscribe( setSetting$({path:"mode",value:appMode}) )

//load from localstorage in case all else failed

//utility to run multiple ones in parallel, see here :
//https://github.com/Reactive-Extensions/RxJS/blob/master/doc/mapping/async/comparing.md#asyncparallel
function wrapArrayParallel (items) {
  //let __items = Rx.Observable.from()
  return Rx.Observable.forkJoin.apply(null, items);
}
//on second thought, that does not fit, as it merges the results back together
function inParallel (items){
  return Rx.Observable
    .for(items, function (item) {
        return Rx.Observable.just(item)
    })
}

function getShortDesignUri (uriQuery){
  if(!uriQuery) return Rx.Observable.just(undefined)
  let apiDesignsUri = "https://jamapi.youmagine.com/api/v1/designs/"
  let designUri = apiDesignsUri+uriQuery
  return Rx.Observable.just( designUri )
}

let urDesignUri$ = Rx.Observable
  .just( designUri )
  .filter(exists)
  .shareReplay(1)

let lsDesignUri$  = Rx.Observable
  .just(  localStorage.getItem("jam!-lastDesignUri") )
  .filter(exists)
  .shareReplay(1)

//only load meshes if no designs need to be loaded

let meshUris$ = Rx.Observable.just(meshUris.pop()) //inParallel(meshUris)
  .takeUntil(urDesignUri$.merge(lsDesignUri$))
  .filter(exists)

//only attempt to load from short uid as last resort
//last but not least, try to load if anything is in the query (shorthand for design uuids)
let stDesignUri$ = Rx.Observable.merge(
  urDesignUri$,
  getShortDesignUri(uriQuery)
)
  .takeUntil(meshUris$)
  .shareReplay(1)
  .filter(exists)

let designUri$ = Rx.Observable.merge(
  urDesignUri$,//ORDER MATTERS !!!
  lsDesignUri$
  //stDesignUri$
  )
  .take(1)

export {designUri$,meshUris$}
<|endoftext|>


<commit_before>const fs = require('fs');

const PDFDocument = require('pdfkit');

var schedule = JSON.parse(fs.readFileSync('contents/wanneer.json'));

var doc = new PDFDocument();
doc.pipe(fs.createWriteStream('templates/resources/pdf/schedule.pdf'));

const font = 'Times-Bold';
const font_size = 8;

doc.font(font);
doc.fontSize(font_size);

const cell_width = 95;
const header_height = 10;
const cell_height = 39;
const padding_width = 5;
const padding_height = 3;

["Tijd", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag"]
    .forEach(function(header, index){
        var x = padding_width + index * (cell_width + padding_width);
        var y = padding_height;
        doc.rect(x, y, cell_width, header_height);
        var text_y = y + header_height/2 - font_size/3;
        doc.text(header, x, text_y, { align: 'center', width: cell_width });
    });

const timetable = schedule.timetable;
timetable
    .forEach(function(row, row_index){
        var y = 2*padding_height + header_height + row_index * (padding_height + cell_height);
        var x = padding_width;
        doc.rect(x, y, cell_width, cell_height);
        var text_y = y + cell_height/2 - font_size/3;
        var time_text = row.time.start + "-" + row.time.end;
        doc.text(time_text, x, text_y, { align: 'center', width: cell_width });
        ["monday", "tuesday", "wednesday", "thursday", "friday"].forEach(function(day, column_index){
            var x = padding_width + (column_index + 1) * (padding_width + cell_width);
            doc.rect(x, y, cell_width, cell_height);
            var data = row.columns[day];
            if (data.hasOwnProperty('class')) {
                var text_y = y + font_size/2;
                doc.text(data.class + " (" + data.teacher + ")", x, text_y, { align: 'center', width: cell_width });
                doc.moveDown(0.25).text(data.description, { align: 'center', width: cell_width });
            }
        });
    });

doc.rect(0, 0,
         6 * (padding_width + cell_width) + padding_width,
         timetable.length * (padding_height + cell_height) + 2*padding_height + header_height);
doc.stroke();

doc.end();
<commit_msg>Make titles bold<commit_after>const fs = require('fs');

const PDFDocument = require('pdfkit');

var schedule = JSON.parse(fs.readFileSync('contents/wanneer.json'));

var doc = new PDFDocument();
doc.pipe(fs.createWriteStream('templates/resources/pdf/schedule.pdf'));

const font = 'Times-Bold';
const font_size = 8;

doc.font(font);
doc.fontSize(font_size);

const cell_width = 95;
const header_height = 10;
const cell_height = 39;
const padding_width = 5;
const padding_height = 3;

["Tijd", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag"]
    .forEach(function(header, index){
        var x = padding_width + index * (cell_width + padding_width);
        var y = padding_height;
        doc.rect(x, y, cell_width, header_height);
        var text_y = y + header_height/2 - font_size/3;
        doc.font('Times-Bold').text(header, x, text_y, { align: 'center', width: cell_width });
    });

const timetable = schedule.timetable;
timetable
    .forEach(function(row, row_index){
        var y = 2*padding_height + header_height + row_index * (padding_height + cell_height);
        var x = padding_width;
        doc.rect(x, y, cell_width, cell_height);
        var text_y = y + cell_height/2 - font_size/3;
        var time_text = row.time.start + "-" + row.time.end;
        doc.font('Times-Roman').text(time_text, x, text_y, { align: 'center', width: cell_width });
        ["monday", "tuesday", "wednesday", "thursday", "friday"].forEach(function(day, column_index){
            var x = padding_width + (column_index + 1) * (padding_width + cell_width);
            doc.rect(x, y, cell_width, cell_height);
            var data = row.columns[day];
            if (data.hasOwnProperty('class')) {
                var text_y = y + font_size/2;
                doc.font('Times-Bold').text(data.class + " (" + data.teacher + ")", x, text_y, { align: 'center', width: cell_width });
                doc.moveDown(0.25).font('Times-Roman').text(data.description, { align: 'center', width: cell_width });
            }
        });
    });

doc.rect(0, 0,
         6 * (padding_width + cell_width) + padding_width,
         timetable.length * (padding_height + cell_height) + 2*padding_height + header_height);
doc.stroke();

doc.end();
<|endoftext|>


<commit_before>/// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/node-lzma/node-lzma.d.ts" />
var Endian = require('./endian');
var CompressionAlgorith = require('./compression-algorithm');
var zlib = require('zlib');
var lzmalib = require('node-lzma');
var Amf = require('./amf');
var ByteArray = (function () {
    function ByteArray(buffer) {
        if (buffer instanceof ByteArray) {
            this.buffer = buffer.buffer;
        }
        else if (buffer instanceof Buffer) {
            this.buffer = buffer;
        }
        else {
            console.log(typeof (buffer), typeof (buffer) === 'number');
            this.buffer = new Buffer(typeof (buffer) === 'number' ? Number(buffer) : ByteArray.BUFFER_SIZE);
        }
        this.shareable = false;
        this.endian = Endian.Big;
        this.objectEncoding = -1;
        this.position = 0;
    }
    Object.defineProperty(ByteArray.prototype, "bytesAvailable", {
        get: function () {
            return this.length - this.position;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ByteArray.prototype, "length", {
        get: function () {
            return this.buffer.length;
        },
        set: function (value) {
            this.buffer.length = length;
        },
        enumerable: true,
        configurable: true
    });
    ByteArray.prototype.atomicCompareAndSwapIntAt = function (byteIndex, expectedValue, newValue) {
        var byte = this.buffer[byteIndex];
        if (byte === expectedValue) {
            this.buffer[byteIndex] = newValue;
        }
        return byte;
    };
    ByteArray.prototype.atomicCompareAndSwapLength = function (expectedLength, newLength) {
        var prevLength = this.length;
        if (prevLength !== expectedLength) {
            return prevLength;
        }
        if (prevLength < newLength) {
            this.buffer = Buffer.concat([this.buffer, new Buffer(newLength - prevLength)], newLength);
        }
        if (prevLength > newLength) {
            this.buffer = this.buffer.slice(newLength - 1, prevLength - 1);
        }
        this.buffer.length = newLength;
        return prevLength;
    };
    ByteArray.prototype.clear = function () {
        this.buffer = new Buffer(this.buffer.length);
    };
    ByteArray.prototype.compress = function (algorithm) {
        if (algorithm === void 0) { algorithm = CompressionAlgorith.Zlib; }
        switch (algorithm) {
            case CompressionAlgorith.Deflate:
                this.buffer = zlib.deflateRawSync(this.buffer);
                break;
            case CompressionAlgorith.Zlib:
                this.buffer = zlib.deflateSync(this.buffer);
                break;
            case CompressionAlgorith.Lzma:
                this.buffer = lzmalib.lzma.compress(this.buffer);
                break;
        }
    };
    ByteArray.prototype.deflate = function () {
        this.compress(CompressionAlgorith.Deflate);
    };
    ByteArray.prototype.inflate = function () {
        this.uncompress(CompressionAlgorith.Deflate);
    };
    ByteArray.prototype.readBoolean = function () {
        return Boolean(this.buffer.readInt8(this.updatePosition(1)));
    };
    ByteArray.prototype.readByte = function () {
        return this.buffer.readInt8(this.updatePosition(1));
    };
    ByteArray.prototype.readBytes = function (bytes, offset, length) {
        if (offset === void 0) { offset = 0; }
        length = length || 0;
        for (var i = offset; i < length && bytes.bytesAvailable > 0; i++) {
            bytes.writeByte(this.readByte());
        }
    };
    ByteArray.prototype.readDouble = function () {
        var position = this.updatePosition(8);
        return this.endian === Endian.Big
            ? this.buffer.readDoubleBE(position)
            : this.buffer.readDoubleBE(position);
    };
    ByteArray.prototype.readFloat = function () {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.readFloatBE(position)
            : this.buffer.readFloatBE(position);
    };
    ByteArray.prototype.readInt = function () {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.readInt32BE(position)
            : this.buffer.readInt32LE(position);
    };
    ByteArray.prototype.readMultiByte = function (length, charSet) {
        var position = this.updatePosition(length);
        return this.buffer.toString(charSet || 'utf8', position, position + length);
    };
    ByteArray.prototype.readObject = function () {
        return Amf.read(this.buffer, this.updatePosition(this.readInt()));
    };
    ByteArray.prototype.readShort = function () {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.readInt16BE(position)
            : this.buffer.readInt16LE(position);
    };
    ByteArray.prototype.readUnsignedByte = function () {
        return this.buffer.readUInt8(this.updatePosition(1));
    };
    ByteArray.prototype.readUnsignedInt = function () {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.readUInt32BE(position)
            : this.buffer.readUInt32LE(position);
    };
    ByteArray.prototype.readUnsignedShort = function () {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.readUInt16BE(position)
            : this.buffer.readUInt16LE(position);
    };
    ByteArray.prototype.readUTF = function () {
        var len = this.readShort();
        var position = this.updatePosition(len);
        return this.buffer.toString('utf8', position, position + len);
    };
    ByteArray.prototype.readUTFBytes = function (length) {
        return this.readMultiByte(length);
    };
    ByteArray.prototype.toJSON = function (k) {
        return this.buffer.toJSON();
    };
    ByteArray.prototype.toString = function (encoding, offset, length) {
        return this.buffer.toString(encoding || 'utf8', offset || 0, length || this.length);
    };
    ByteArray.prototype.uncompress = function (algorithm) {
        if (algorithm === void 0) { algorithm = CompressionAlgorith.Zlib; }
        switch (algorithm) {
            case CompressionAlgorith.Deflate:
                this.buffer = zlib.inflateRawSync(this.buffer);
                break;
            case CompressionAlgorith.Zlib:
                this.buffer = zlib.inflateSync(this.buffer);
                break;
            case CompressionAlgorith.Lzma:
                this.buffer = lzmalib.lzma.decompress(this.buffer);
                break;
        }
    };
    ByteArray.prototype.writeBoolean = function (value) {
        return this.buffer.writeInt8(Number(value), this.updatePosition(1));
    };
    ByteArray.prototype.writeByte = function (value) {
        return this.buffer.writeInt8(value, this.updatePosition(1));
    };
    ByteArray.prototype.writeBytes = function (bytes, offset, length) {
        if (offset === void 0) { offset = 0; }
        length = length || bytes.position;
        bytes.position = 0;
        for (var i = offset; i < length && this.bytesAvailable > 0; i++) {
            this.writeByte(bytes.readByte());
        }
    };
    ByteArray.prototype.writeDouble = function (value) {
        var position = this.updatePosition(8);
        return this.endian === Endian.Big
            ? this.buffer.writeDoubleBE(value, position)
            : this.buffer.writeDoubleBE(value, position);
    };
    ByteArray.prototype.writeFloat = function (value) {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.writeFloatBE(value, position)
            : this.buffer.writeFloatBE(value, position);
    };
    ByteArray.prototype.writeInt = function (value) {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.writeInt32BE(value, position)
            : this.buffer.writeInt32LE(value, position);
    };
    ByteArray.prototype.writeMultiByte = function (value, charSet) {
        var len = Buffer.byteLength(value);
        return this.buffer.write(value, this.updatePosition(len), len, charSet || 'utf8');
    };
    ByteArray.prototype.writeObject = function (object) {
        var len = Buffer.byteLength(object);
        this.writeInt(len);
        Amf.write(this.buffer, object, this.updatePosition(len));
    };
    ByteArray.prototype.writeShort = function (value) {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.writeInt16BE(value, position)
            : this.buffer.writeInt16LE(value, position);
    };
    ByteArray.prototype.writeUnsignedInt = function (value) {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.writeUInt32BE(value, position)
            : this.buffer.writeUInt32LE(value, position);
    };
    ByteArray.prototype.writeUnsignedShort = function (value) {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.writeUInt16BE(value, position)
            : this.buffer.writeUInt16LE(value, position);
    };
    ByteArray.prototype.writeUnsignedByte = function (value) {
        return this.buffer.writeUInt8(Number(value), this.updatePosition(1));
    };
    ByteArray.prototype.writeUTF = function (value) {
        var len = Buffer.byteLength(value);
        this.writeShort(len);
        return this.buffer.write(value, this.updatePosition(len), len);
    };
    ByteArray.prototype.writeUTFBytes = function (value) {
        return this.writeMultiByte(value);
    };
    ByteArray.prototype.updatePosition = function (n) {
        var a = this.position;
        this.position += n;
        return a;
    };
    ByteArray.BUFFER_SIZE = 1024;
    return ByteArray;
})();
module.exports = ByteArray;
<commit_msg>build<commit_after>/// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/node-lzma/node-lzma.d.ts" />
var Endian = require('./endian');
var CompressionAlgorith = require('./compression-algorithm');
var zlib = require('zlib');
var lzmalib = require('node-lzma');
var Amf = require('./amf');
var ByteArray = (function () {
    function ByteArray(buffer) {
        if (buffer instanceof ByteArray) {
            this.buffer = buffer.buffer;
        }
        else if (buffer instanceof Buffer) {
            this.buffer = buffer;
        }
        else {
            this.buffer = new Buffer(typeof (buffer) === 'number' ? Number(buffer) : ByteArray.BUFFER_SIZE);
        }
        this.shareable = false;
        this.endian = Endian.Big;
        this.objectEncoding = -1;
        this.position = 0;
    }
    Object.defineProperty(ByteArray.prototype, "bytesAvailable", {
        get: function () {
            return this.length - this.position;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ByteArray.prototype, "length", {
        get: function () {
            return this.buffer.length;
        },
        set: function (value) {
            this.buffer.length = length;
        },
        enumerable: true,
        configurable: true
    });
    ByteArray.prototype.atomicCompareAndSwapIntAt = function (byteIndex, expectedValue, newValue) {
        var byte = this.buffer[byteIndex];
        if (byte === expectedValue) {
            this.buffer[byteIndex] = newValue;
        }
        return byte;
    };
    ByteArray.prototype.atomicCompareAndSwapLength = function (expectedLength, newLength) {
        var prevLength = this.length;
        if (prevLength !== expectedLength) {
            return prevLength;
        }
        if (prevLength < newLength) {
            this.buffer = Buffer.concat([this.buffer, new Buffer(newLength - prevLength)], newLength);
        }
        if (prevLength > newLength) {
            this.buffer = this.buffer.slice(newLength - 1, prevLength - 1);
        }
        this.buffer.length = newLength;
        return prevLength;
    };
    ByteArray.prototype.clear = function () {
        this.buffer = new Buffer(this.buffer.length);
    };
    ByteArray.prototype.compress = function (algorithm) {
        if (algorithm === void 0) { algorithm = CompressionAlgorith.Zlib; }
        switch (algorithm) {
            case CompressionAlgorith.Deflate:
                this.buffer = zlib.deflateRawSync(this.buffer);
                break;
            case CompressionAlgorith.Zlib:
                this.buffer = zlib.deflateSync(this.buffer);
                break;
            case CompressionAlgorith.Lzma:
                this.buffer = lzmalib.lzma.compress(this.buffer);
                break;
        }
    };
    ByteArray.prototype.deflate = function () {
        this.compress(CompressionAlgorith.Deflate);
    };
    ByteArray.prototype.inflate = function () {
        this.uncompress(CompressionAlgorith.Deflate);
    };
    ByteArray.prototype.readBoolean = function () {
        return Boolean(this.buffer.readInt8(this.updatePosition(1)));
    };
    ByteArray.prototype.readByte = function () {
        return this.buffer.readInt8(this.updatePosition(1));
    };
    ByteArray.prototype.readBytes = function (bytes, offset, length) {
        if (offset === void 0) { offset = 0; }
        length = length || 0;
        for (var i = offset; i < length && bytes.bytesAvailable > 0; i++) {
            bytes.writeByte(this.readByte());
        }
    };
    ByteArray.prototype.readDouble = function () {
        var position = this.updatePosition(8);
        return this.endian === Endian.Big
            ? this.buffer.readDoubleBE(position)
            : this.buffer.readDoubleBE(position);
    };
    ByteArray.prototype.readFloat = function () {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.readFloatBE(position)
            : this.buffer.readFloatBE(position);
    };
    ByteArray.prototype.readInt = function () {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.readInt32BE(position)
            : this.buffer.readInt32LE(position);
    };
    ByteArray.prototype.readMultiByte = function (length, charSet) {
        var position = this.updatePosition(length);
        return this.buffer.toString(charSet || 'utf8', position, position + length);
    };
    ByteArray.prototype.readObject = function () {
        return Amf.read(this.buffer, this.updatePosition(this.readInt()));
    };
    ByteArray.prototype.readShort = function () {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.readInt16BE(position)
            : this.buffer.readInt16LE(position);
    };
    ByteArray.prototype.readUnsignedByte = function () {
        return this.buffer.readUInt8(this.updatePosition(1));
    };
    ByteArray.prototype.readUnsignedInt = function () {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.readUInt32BE(position)
            : this.buffer.readUInt32LE(position);
    };
    ByteArray.prototype.readUnsignedShort = function () {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.readUInt16BE(position)
            : this.buffer.readUInt16LE(position);
    };
    ByteArray.prototype.readUTF = function () {
        var len = this.readShort();
        var position = this.updatePosition(len);
        return this.buffer.toString('utf8', position, position + len);
    };
    ByteArray.prototype.readUTFBytes = function (length) {
        return this.readMultiByte(length);
    };
    ByteArray.prototype.toJSON = function (k) {
        return this.buffer.toJSON();
    };
    ByteArray.prototype.toString = function (encoding, offset, length) {
        return this.buffer.toString(encoding || 'utf8', offset || 0, length || this.length);
    };
    ByteArray.prototype.uncompress = function (algorithm) {
        if (algorithm === void 0) { algorithm = CompressionAlgorith.Zlib; }
        switch (algorithm) {
            case CompressionAlgorith.Deflate:
                this.buffer = zlib.inflateRawSync(this.buffer);
                break;
            case CompressionAlgorith.Zlib:
                this.buffer = zlib.inflateSync(this.buffer);
                break;
            case CompressionAlgorith.Lzma:
                this.buffer = lzmalib.lzma.decompress(this.buffer);
                break;
        }
    };
    ByteArray.prototype.writeBoolean = function (value) {
        return this.buffer.writeInt8(Number(value), this.updatePosition(1));
    };
    ByteArray.prototype.writeByte = function (value) {
        return this.buffer.writeInt8(value, this.updatePosition(1));
    };
    ByteArray.prototype.writeBytes = function (bytes, offset, length) {
        if (offset === void 0) { offset = 0; }
        length = length || bytes.position;
        bytes.position = 0;
        for (var i = offset; i < length && this.bytesAvailable > 0; i++) {
            this.writeByte(bytes.readByte());
        }
    };
    ByteArray.prototype.writeDouble = function (value) {
        var position = this.updatePosition(8);
        return this.endian === Endian.Big
            ? this.buffer.writeDoubleBE(value, position)
            : this.buffer.writeDoubleBE(value, position);
    };
    ByteArray.prototype.writeFloat = function (value) {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.writeFloatBE(value, position)
            : this.buffer.writeFloatBE(value, position);
    };
    ByteArray.prototype.writeInt = function (value) {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.writeInt32BE(value, position)
            : this.buffer.writeInt32LE(value, position);
    };
    ByteArray.prototype.writeMultiByte = function (value, charSet) {
        var len = Buffer.byteLength(value);
        return this.buffer.write(value, this.updatePosition(len), len, charSet || 'utf8');
    };
    ByteArray.prototype.writeObject = function (object) {
        var len = Buffer.byteLength(object);
        this.writeInt(len);
        Amf.write(this.buffer, object, this.updatePosition(len));
    };
    ByteArray.prototype.writeShort = function (value) {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.writeInt16BE(value, position)
            : this.buffer.writeInt16LE(value, position);
    };
    ByteArray.prototype.writeUnsignedInt = function (value) {
        var position = this.updatePosition(4);
        return this.endian === Endian.Big
            ? this.buffer.writeUInt32BE(value, position)
            : this.buffer.writeUInt32LE(value, position);
    };
    ByteArray.prototype.writeUnsignedShort = function (value) {
        var position = this.updatePosition(2);
        return this.endian === Endian.Big
            ? this.buffer.writeUInt16BE(value, position)
            : this.buffer.writeUInt16LE(value, position);
    };
    ByteArray.prototype.writeUnsignedByte = function (value) {
        return this.buffer.writeUInt8(Number(value), this.updatePosition(1));
    };
    ByteArray.prototype.writeUTF = function (value) {
        var len = Buffer.byteLength(value);
        this.writeShort(len);
        return this.buffer.write(value, this.updatePosition(len), len);
    };
    ByteArray.prototype.writeUTFBytes = function (value) {
        return this.writeMultiByte(value);
    };
    ByteArray.prototype.updatePosition = function (n) {
        var a = this.position;
        this.position += n;
        return a;
    };
    ByteArray.BUFFER_SIZE = 1024;
    return ByteArray;
})();
module.exports = ByteArray;
<|endoftext|>


<commit_before>$(document).ready(function () {
    if ($.isPlainObject($.uniform)) {
        $('input:file').uniform();
    }

    /* dinamic height for central column */
   /* function changeHeight() {
        var _chWindowHeight = $(window).height();
        var _chMyHeight = _chWindowHeight - $("header").outerHeight() - $("footer").outerHeight() - 3;
        $('div.layout-content').innerHeight(_chMyHeight);
    };
     changeHeight();
    $(window).resize(function() {
        changeHeight();
    });            */

    /* side bar functionality */
    $('div.side-nav').each(function () {
        var myParent = $(this);
        var myParentHolder = $(myParent).parent().height() -18;
        $(myParent).height(myParentHolder);
        /* open close bar */
        $(this).find("span.maximaze-bar").click(function () {
            if (($(myParent).hasClass("side-nav-open")) || ($(myParent).hasClass("side-nav-locked"))) {
                $(myParent).removeClass("side-nav-locked side-nav-open");
                if( $(myParent).hasClass('left-panel')){
                    $(myParent).parent('div.page-container').removeClass('left-locked');
                }else{
                    $(myParent).parent('div.page-container').removeClass('right-locked');
                }
                $(myParent).find('.bar-tools').css({
                    "height": "auto",
                    "overflow" : "visible"
                })
            } else {
                $(myParent).addClass("side-nav-open");
                var openBarHeight = $("div.page-container").height() - 20;
                /* minus top-padding and bottom-padding */
                $(myParent).height(openBarHeight);
                var testBarScroll = $(myParent).find('.bar-tools').height();
                if(openBarHeight < testBarScroll ){
                    $(myParent).find('.bar-tools').height((openBarHeight - 20)).css({
                        "overflow" : "auto"
                    })
                }
            }
        });

        /* lock&unlock bar */
        $(this).find("span.lock-bar").click(function () {
            if ($(this).hasClass("lock-bar-locked")) {
                $(myParent).addClass("side-nav-open")
                    .removeClass("side-nav-locked");
                if( $(myParent).hasClass('left-panel')){
                    $(myParent).parent('div.page-container').removeClass('left-locked');
                }else{
                    $(myParent).parent('div.page-container').removeClass('right-locked');
                }
            } else {
                $(myParent).addClass("side-nav-locked")
                    .removeClass("side-nav-open");
                if( $(myParent).hasClass('left-panel')){
                    $(myParent).parent('div.page-container').addClass('left-locked');
                }else{
                    $(myParent).parent('div.page-container').addClass('right-locked');
                }

            }
            $(this).toggleClass('lock-bar-locked');
        });

        /* open&close popup for bar items when bar is minimized. */
        $(this).find('.bar-tools li').each(function () {
            var myItem = $(this);
            $(myItem).find('.sn-opener').click(function () {
                $(myItem).find("div.nav-box").fadeToggle("slow");
                var overlayHeight = $('#page').height();
                var overlayWidth = $('#page > .wrapper').width();
                $('#bar-drop-overlay').width(overlayWidth).height(overlayHeight);
                $('#bar-drop-overlay').toggleClass('bar-open-overlay');
            });
            $(myItem).find("span.close").click(function () {
                $(myItem).find("div.nav-box").fadeToggle("slow");
                $('#bar-drop-overlay').toggleClass('bar-open-overlay');
            });
            $('#bar-drop-overlay').on({
                click:function () {
                    $(myItem).find("div.nav-box").animate({
                        opacity:0,
                        display:'none'
                    }, function () {
                        $(this).css({
                            opacity:1,
                            display:'none'
                        })
                    });
                    $('#bar-drop-overlay').removeClass('bar-open-overlay');
                }
            });
        });
        /* open content for open bar */
        $(myParent).find('ul.bar-tools > li').each(function(){
            var _barLi = $(this);
            $(_barLi).find('span.open-bar-item').click(function(){
                $(_barLi).find('div.nav-content').slideToggle();
                $(_barLi).toggleClass('open-item');
            });
        });
    })

/* ============================================================
 *Oro Dropdown close prevent
 * ============================================================ */
    var dropdownToggles = $('.oro-dropdown-toggle');
    dropdownToggles.click(function(e) {
        $(this).parent().toggleClass('open')
    });

    $('html').click(function(e) {
        var $target = $(e.target);
        var clickingTarget = null;
        if ($target.hasClass('dropdown') || $target.hasClass('oro-drop')) {
            clickingTarget = $target;
        } else {
            clickingTarget = $target.closest('.dropdown, .oro-drop');
        }
        clickingTarget.addClass('_currently_clicked');
        $('.open:not(._currently_clicked)').removeClass('open')
        clickingTarget.removeClass('_currently_clicked');
    });
 });
<commit_msg>Added centralized initialization of datepicker widgets<commit_after>$(document).ready(function () {
    if ($.isPlainObject($.uniform)) {
        $('input:file').uniform();
    }

    if (typeof($.datepicker) != 'undefined') {
        $('input.datepicker').each(function (index, el) {
            el = $(el);

            el.datepicker({
                dateFormat: el.attr('data-format') ? el.attr('data-format') : ''
            });
        });
    }

    /* dinamic height for central column */
   /* function changeHeight() {
        var _chWindowHeight = $(window).height();
        var _chMyHeight = _chWindowHeight - $("header").outerHeight() - $("footer").outerHeight() - 3;
        $('div.layout-content').innerHeight(_chMyHeight);
    };
     changeHeight();
    $(window).resize(function() {
        changeHeight();
    });            */

    /* side bar functionality */
    $('div.side-nav').each(function () {
        var myParent = $(this);
        var myParentHolder = $(myParent).parent().height() -18;
        $(myParent).height(myParentHolder);
        /* open close bar */
        $(this).find("span.maximaze-bar").click(function () {
            if (($(myParent).hasClass("side-nav-open")) || ($(myParent).hasClass("side-nav-locked"))) {
                $(myParent).removeClass("side-nav-locked side-nav-open");
                if( $(myParent).hasClass('left-panel')){
                    $(myParent).parent('div.page-container').removeClass('left-locked');
                }else{
                    $(myParent).parent('div.page-container').removeClass('right-locked');
                }
                $(myParent).find('.bar-tools').css({
                    "height": "auto",
                    "overflow" : "visible"
                })
            } else {
                $(myParent).addClass("side-nav-open");
                var openBarHeight = $("div.page-container").height() - 20;
                /* minus top-padding and bottom-padding */
                $(myParent).height(openBarHeight);
                var testBarScroll = $(myParent).find('.bar-tools').height();
                if(openBarHeight < testBarScroll ){
                    $(myParent).find('.bar-tools').height((openBarHeight - 20)).css({
                        "overflow" : "auto"
                    })
                }
            }
        });

        /* lock&unlock bar */
        $(this).find("span.lock-bar").click(function () {
            if ($(this).hasClass("lock-bar-locked")) {
                $(myParent).addClass("side-nav-open")
                    .removeClass("side-nav-locked");
                if( $(myParent).hasClass('left-panel')){
                    $(myParent).parent('div.page-container').removeClass('left-locked');
                }else{
                    $(myParent).parent('div.page-container').removeClass('right-locked');
                }
            } else {
                $(myParent).addClass("side-nav-locked")
                    .removeClass("side-nav-open");
                if( $(myParent).hasClass('left-panel')){
                    $(myParent).parent('div.page-container').addClass('left-locked');
                }else{
                    $(myParent).parent('div.page-container').addClass('right-locked');
                }

            }
            $(this).toggleClass('lock-bar-locked');
        });

        /* open&close popup for bar items when bar is minimized. */
        $(this).find('.bar-tools li').each(function () {
            var myItem = $(this);
            $(myItem).find('.sn-opener').click(function () {
                $(myItem).find("div.nav-box").fadeToggle("slow");
                var overlayHeight = $('#page').height();
                var overlayWidth = $('#page > .wrapper').width();
                $('#bar-drop-overlay').width(overlayWidth).height(overlayHeight);
                $('#bar-drop-overlay').toggleClass('bar-open-overlay');
            });
            $(myItem).find("span.close").click(function () {
                $(myItem).find("div.nav-box").fadeToggle("slow");
                $('#bar-drop-overlay').toggleClass('bar-open-overlay');
            });
            $('#bar-drop-overlay').on({
                click:function () {
                    $(myItem).find("div.nav-box").animate({
                        opacity:0,
                        display:'none'
                    }, function () {
                        $(this).css({
                            opacity:1,
                            display:'none'
                        })
                    });
                    $('#bar-drop-overlay').removeClass('bar-open-overlay');
                }
            });
        });
        /* open content for open bar */
        $(myParent).find('ul.bar-tools > li').each(function(){
            var _barLi = $(this);
            $(_barLi).find('span.open-bar-item').click(function(){
                $(_barLi).find('div.nav-content').slideToggle();
                $(_barLi).toggleClass('open-item');
            });
        });
    })

/* ============================================================
 *Oro Dropdown close prevent
 * ============================================================ */
    var dropdownToggles = $('.oro-dropdown-toggle');
    dropdownToggles.click(function(e) {
        $(this).parent().toggleClass('open')
    });

    $('html').click(function(e) {
        var $target = $(e.target);
        var clickingTarget = null;
        if ($target.hasClass('dropdown') || $target.hasClass('oro-drop')) {
            clickingTarget = $target;
        } else {
            clickingTarget = $target.closest('.dropdown, .oro-drop');
        }
        clickingTarget.addClass('_currently_clicked');
        $('.open:not(._currently_clicked)').removeClass('open')
        clickingTarget.removeClass('_currently_clicked');
    });
 });
<|endoftext|>