<commit_before>/**
 * util.js
 *
 * This sets up our util object, which defines a way to export Composer
 * components and also defines a number of helper functions the rest of the
 * system will use.
 * -----------------------------------------------------------------------------
 *
 * Composer.js is an MVC framework for creating and organizing javascript
 * applications. For documentation, please visit:
 *
 *     http://lyonbros.github.com/composer.js/
 *
 * -----------------------------------------------------------------------------
 *
 * Copyright (c) 2011, Lyon Bros Enterprises, LLC. (http://www.lyonbros.com)
 *
 * Licensed under The MIT License.
 * Redistributions of files must retain the above copyright notice.
 */
(function() {
	"use strict";

	if(!this.Composer) {
		var Composer = {
			version: 'GITHEAD',

			// note: this used to be "export" but IE is a whiny little bitch, so now
			// we're sup3r 1337 h4x0r5
			exp0rt: function(obj) {
				Object.keys(obj).forEach(function(key) {
					Composer[key] = obj[key];
				});
			}
		};
		this.Composer = Composer;
	}

	/**
	 * You must override this function in your app.
	 */
	var sync = function(method, model, options) { return options.success(); };

	// Used to override the default sync function.
	var set_sync = function(syncfn) { this.Composer.sync = syncfn; }.bind(this);

	// a closure that returns incrementing integers. these will be unique across
	// the entire app since only one counter is instantiated
	var cid = (function() {
		var counter = 1;
		return function(inc) { return 'c'+counter++; };
	})();

	// wraps error callbacks for syncing functions
	var wrap_error = function(callback, model, options) {
		return function(resp) {
			if(callback) {
				callback(model, resp, options);
			} else {
				this.fire_event('error', options, model, resp, options);
			}
		};
	};

	// Composer equality function. Does deep-inpection and is able to tell the
	// difference between {key: 3} and {key: 3, key2: 4} (_.eq had problems with
	// this back in the day).
	var eq = function(a, b) {
		if ( a === b ) return true;
		if(a instanceof Function) return false;
		if(typeof(a) != typeof(b)) return false;
		if((a && a.constructor) && !b || !b.constructor) return false;
		if((b && b.constructor) && !a || !a.constructor) return false;
		if(a && b && a.constructor != b.constructor) return false;
		if(a instanceof Array || Object.prototype.toString.call(a) === '[object Array]') {
			if(a.length != b.length) return false;
			// TODO: check if array indexes are always sequential
			for(var i = 0, n = a.length; i < n; i++) {
				if(!b.hasOwnProperty(i)) return false;
				if(!eq(a[i], b[i])) return false;
			}
		} else if(a instanceof Date && b instanceof Date) {
			return a.getTime() == b.getTime();
		} else if(a instanceof Object) {
			for( var p in b ) {
				if( b.hasOwnProperty(p) && ! a.hasOwnProperty(p) ) return false;
			}
			for( var p in a ) {
				if ( ! a.hasOwnProperty( p ) ) continue;
				if ( ! b.hasOwnProperty( p ) ) return false;
				if ( a[ p ] === b[ p ] ) continue;
				if ( typeof( a[ p ] ) !== "object" ) return false;
				if ( ! eq( a[ p ],  b[ p ] ) ) return false;
			}
		} else if(a != b) {
			return false;
		}
		return true;
	};

	// create an extension function that merges specific properties from
	// inherited objects
	var merge_extend = function(cls, properties) {
		var _extend = cls.extend;
		cls.extend = function(def, base) {
			base || (base = this);
			var attr = base.prototype;

			properties.forEach(function(prop) {
				def[prop] = Composer.object.merge({}, attr[prop], def[prop]);
			});

			var cls = _extend.call(base, def);
			Composer.merge_extend(cls, properties);
			return cls;
		}
	};

	// some Mootools-reminiscent object utilities Composer uses
	var array = {
		erase: function(arr, item) {
			for(var i = arr.length - 1; i >= 0; i--) {
				if(arr[i] === item) arr.splice(i, 1);
			}
		},

		is: (function() {
			return ('isArray' in Array) ?
				Array.isArray :
				function(obj) {
					return obj instanceof Array || Object.prototype.toString.call(obj) === '[object Array]'
				}
		})()
	};
	var object = {
		each: function(obj, fn, bind) {
			if(!obj) return;
			bind || (bind = this);
			Object.keys(obj).forEach(function(key) {
				(fn.bind(bind))(obj[key], key)
			});
		},
		clone: function(obj, options) {
			options || (options = {});
			if(options.deep) return JSON.parse(JSON.stringify(obj));

			var clone = {};
			Object.keys(obj).forEach(function(key) {
				clone[key] = obj[key];
			});
			return clone;
		},
		merge: function(to, _) {
			var args = Array.prototype.slice.call(arguments, 1);
			args.forEach(function(obj) {
				if(!obj) return;
				Object.keys(obj).forEach(function(key) {
					to[key] = obj[key];
				});
			});
			return to;
		},
		set: function(object, key, value) {
			object || (object = {});
			var paths = key.split('.');
			var obj = object;
			for(var i = 0, n = paths.length; i < n; i++) {
				var path = paths[i];
				if(i == n - 1) {
					obj[path] = value;
					break;
				}

				if(!obj[path]) {
					obj[path] = {};
				} else if(typeof(obj) != 'object' || Composer.array.is(obj)) {
					obj[path] = {};
				}
				obj = obj[path];
			}
			return object;
		},
		get: function(object, key) {
			object || (object = {});
			var paths = key.split('.');
			var obj = object;
			for(var i = 0, n = paths.length; i < n; i++) {
				var path = paths[i];
				var type = typeof(obj[path]);
				if(type == 'undefined') {
					return obj[path];
				}
				obj = obj[path];
			}
			return obj;
		}
	};

	var promisify = function(poptions) {
		poptions || (poptions = {});

		var convert = function(type, asyncs) {
			Object.keys(asyncs).forEach(function(key) {
				var spec = asyncs[key];
				var options_idx = spec.options_idx || 0;
				var names = spec.names || ['success', 'error'];
				var _old = Composer[type].prototype[key];
				Composer[type].prototype[key] = function() {
					var args = Array.prototype.slice.call(arguments, 0);
					if(args.length < options_idx) {
						var _tmp = new Array(options_idx);
						args.forEach(function(item, i) { _tmp[i] = item; });
						args = _tmp;
					}
					if(!args[options_idx]) args[options_idx] = {};
					var _self = this;
					var options = args[options_idx];
					if(options.promisified) return _old.apply(_self, args);
					if(poptions.warn && (options[names[0]] || options[names[1]])) {
						console.warn('Composer: promisify: attempting to pass callbacks to promisified function: ', type, key);
					}
					return new Promise(function(resolve, reject) {
						if(names[0]) options[names[0]] = resolve;
						if(names[1]) options[names[1]] = function(_, err) { reject(err); };
						options.promisified = true;
						_old.apply(_self, args);
					});
				};
			});
		};
		convert('Model', {
			fetch: {},
			save: {},
			destroy: {}
		});
		convert('Collection', {
			fetch: {},
			reset_async: {options_idx: 1, names: ['complete']}
		});
		convert('Controller', {
			html: {options_idx: 1, names: ['complete']}
		});
		// NOTE: you'd think that because ListController.html() calls the parent
		// Controller.html() (which is promisified) but because the
		// ListController is defined *before* we call promisify, it's html()
		// parent function is the un-promisified Controller.html(). we don't
		// have a way to "reach into" the parent chain and replace it, so we
		// hack it by promisifying ListController.html()
		convert('ListController', {
			html: {options_idx: 1, names: ['complete']}
		});
	};

	this.Composer.exp0rt({
		sync: sync,
		set_sync: set_sync,
		cid: cid,
		wrap_error: wrap_error,
		eq: eq,
		merge_extend: merge_extend,
		array: array,
		object: object,
		promisify: promisify
	});
}).apply((typeof exports != 'undefined') ? exports : this);

<commit_msg>binding issue<commit_after>/**
 * util.js
 *
 * This sets up our util object, which defines a way to export Composer
 * components and also defines a number of helper functions the rest of the
 * system will use.
 * -----------------------------------------------------------------------------
 *
 * Composer.js is an MVC framework for creating and organizing javascript
 * applications. For documentation, please visit:
 *
 *     http://lyonbros.github.com/composer.js/
 *
 * -----------------------------------------------------------------------------
 *
 * Copyright (c) 2011, Lyon Bros Enterprises, LLC. (http://www.lyonbros.com)
 *
 * Licensed under The MIT License.
 * Redistributions of files must retain the above copyright notice.
 */
(function() {
	"use strict";

	if(!this.Composer) {
		var Composer = {
			version: 'GITHEAD',

			// note: this used to be "export" but IE is a whiny little bitch, so now
			// we're sup3r 1337 h4x0r5
			exp0rt: function(obj) {
				Object.keys(obj).forEach(function(key) {
					Composer[key] = obj[key];
				});
			}
		};
		this.Composer = Composer;
	}
	var Composer = this.Composer;

	/**
	 * You must override this function in your app.
	 */
	var sync = function(method, model, options) { return options.success(); };

	// Used to override the default sync function.
	var set_sync = function(syncfn) { this.Composer.sync = syncfn; }.bind(this);

	// a closure that returns incrementing integers. these will be unique across
	// the entire app since only one counter is instantiated
	var cid = (function() {
		var counter = 1;
		return function(inc) { return 'c'+counter++; };
	})();

	// wraps error callbacks for syncing functions
	var wrap_error = function(callback, model, options) {
		return function(resp) {
			if(callback) {
				callback(model, resp, options);
			} else {
				this.fire_event('error', options, model, resp, options);
			}
		};
	};

	// Composer equality function. Does deep-inpection and is able to tell the
	// difference between {key: 3} and {key: 3, key2: 4} (_.eq had problems with
	// this back in the day).
	var eq = function(a, b) {
		if ( a === b ) return true;
		if(a instanceof Function) return false;
		if(typeof(a) != typeof(b)) return false;
		if((a && a.constructor) && !b || !b.constructor) return false;
		if((b && b.constructor) && !a || !a.constructor) return false;
		if(a && b && a.constructor != b.constructor) return false;
		if(a instanceof Array || Object.prototype.toString.call(a) === '[object Array]') {
			if(a.length != b.length) return false;
			// TODO: check if array indexes are always sequential
			for(var i = 0, n = a.length; i < n; i++) {
				if(!b.hasOwnProperty(i)) return false;
				if(!eq(a[i], b[i])) return false;
			}
		} else if(a instanceof Date && b instanceof Date) {
			return a.getTime() == b.getTime();
		} else if(a instanceof Object) {
			for( var p in b ) {
				if( b.hasOwnProperty(p) && ! a.hasOwnProperty(p) ) return false;
			}
			for( var p in a ) {
				if ( ! a.hasOwnProperty( p ) ) continue;
				if ( ! b.hasOwnProperty( p ) ) return false;
				if ( a[ p ] === b[ p ] ) continue;
				if ( typeof( a[ p ] ) !== "object" ) return false;
				if ( ! eq( a[ p ],  b[ p ] ) ) return false;
			}
		} else if(a != b) {
			return false;
		}
		return true;
	};

	// create an extension function that merges specific properties from
	// inherited objects
	var merge_extend = function(cls, properties) {
		var _extend = cls.extend;
		cls.extend = function(def, base) {
			base || (base = this);
			var attr = base.prototype;

			properties.forEach(function(prop) {
				def[prop] = Composer.object.merge({}, attr[prop], def[prop]);
			});

			var cls = _extend.call(base, def);
			Composer.merge_extend(cls, properties);
			return cls;
		}
	};

	// some Mootools-reminiscent object utilities Composer uses
	var array = {
		erase: function(arr, item) {
			for(var i = arr.length - 1; i >= 0; i--) {
				if(arr[i] === item) arr.splice(i, 1);
			}
		},

		is: (function() {
			return ('isArray' in Array) ?
				Array.isArray :
				function(obj) {
					return obj instanceof Array || Object.prototype.toString.call(obj) === '[object Array]'
				}
		})()
	};
	var object = {
		each: function(obj, fn, bind) {
			if(!obj) return;
			bind || (bind = this);
			Object.keys(obj).forEach(function(key) {
				(fn.bind(bind))(obj[key], key)
			});
		},
		clone: function(obj, options) {
			options || (options = {});
			if(options.deep) return JSON.parse(JSON.stringify(obj));

			var clone = {};
			Object.keys(obj).forEach(function(key) {
				clone[key] = obj[key];
			});
			return clone;
		},
		merge: function(to, _) {
			var args = Array.prototype.slice.call(arguments, 1);
			args.forEach(function(obj) {
				if(!obj) return;
				Object.keys(obj).forEach(function(key) {
					to[key] = obj[key];
				});
			});
			return to;
		},
		set: function(object, key, value) {
			object || (object = {});
			var paths = key.split('.');
			var obj = object;
			for(var i = 0, n = paths.length; i < n; i++) {
				var path = paths[i];
				if(i == n - 1) {
					obj[path] = value;
					break;
				}

				if(!obj[path]) {
					obj[path] = {};
				} else if(typeof(obj) != 'object' || Composer.array.is(obj)) {
					obj[path] = {};
				}
				obj = obj[path];
			}
			return object;
		},
		get: function(object, key) {
			object || (object = {});
			var paths = key.split('.');
			var obj = object;
			for(var i = 0, n = paths.length; i < n; i++) {
				var path = paths[i];
				var type = typeof(obj[path]);
				if(type == 'undefined') {
					return obj[path];
				}
				obj = obj[path];
			}
			return obj;
		}
	};

	var promisify = function(poptions) {
		poptions || (poptions = {});

		var convert = function(type, asyncs) {
			Object.keys(asyncs).forEach(function(key) {
				var spec = asyncs[key];
				var options_idx = spec.options_idx || 0;
				var names = spec.names || ['success', 'error'];
				var _old = Composer[type].prototype[key];
				Composer[type].prototype[key] = function() {
					var args = Array.prototype.slice.call(arguments, 0);
					if(args.length < options_idx) {
						var _tmp = new Array(options_idx);
						args.forEach(function(item, i) { _tmp[i] = item; });
						args = _tmp;
					}
					if(!args[options_idx]) args[options_idx] = {};
					var _self = this;
					var options = args[options_idx];
					if(options.promisified) return _old.apply(_self, args);
					if(poptions.warn && (options[names[0]] || options[names[1]])) {
						console.warn('Composer: promisify: attempting to pass callbacks to promisified function: ', type, key);
					}
					return new Promise(function(resolve, reject) {
						if(names[0]) options[names[0]] = resolve;
						if(names[1]) options[names[1]] = function(_, err) { reject(err); };
						options.promisified = true;
						_old.apply(_self, args);
					});
				};
			});
		};
		convert('Model', {
			fetch: {},
			save: {},
			destroy: {}
		});
		convert('Collection', {
			fetch: {},
			reset_async: {options_idx: 1, names: ['complete']}
		});
		convert('Controller', {
			html: {options_idx: 1, names: ['complete']}
		});
		// NOTE: you'd think that because ListController.html() calls the parent
		// Controller.html() (which is promisified) but because the
		// ListController is defined *before* we call promisify, it's html()
		// parent function is the un-promisified Controller.html(). we don't
		// have a way to "reach into" the parent chain and replace it, so we
		// hack it by promisifying ListController.html()
		convert('ListController', {
			html: {options_idx: 1, names: ['complete']}
		});
	};

	this.Composer.exp0rt({
		sync: sync,
		set_sync: set_sync,
		cid: cid,
		wrap_error: wrap_error,
		eq: eq,
		merge_extend: merge_extend,
		array: array,
		object: object,
		promisify: promisify
	});
}).apply((typeof exports != 'undefined') ? exports : this);

<|endoftext|>


<commit_before>_ = require('underscore');

var Stack = function(initialCapacity) {
	var _initialCapacity = initialCapacity || Infinity;
	var _elements = [];

	function push(element) {
		if (size() === _initialCapacity) {
			throw new Error('push(): Stack is full.');
		}
		return _elements.push(element);
	}

	function pop() {
		if (isEmpty()) {
			throw new Error('pop(): Stack is empty.');
		}
		return _elements.pop();
	}

	function peek() {
		if (isEmpty()) {
			throw new Error('peek(): Stack is empty.');
		}
		return _elements[_elements.length - 1];
	}

	function isEmpty() {
		return size() === 0;
	}

	function size() {
		return _elements.length;
	}

	function empty() {
		while (_elements.length) {
			_elements.pop();
		}
	}

	function Iterator() {
		var counter = 0;

		function hasNext() {
			return _elements.length !== counter;
		}

		function next() {
			if (!hasNext()) {
				throw new Error('next(): No such element.');
			}
			return _elements[_elements.length - 1 - counter++];
		}
		return {
			hasNext: hasNext,
			next: next
		};
	}

	return {
		push: push,
		pop: pop,
		peek: peek,
		isEmpty: isEmpty,
		size: size,
		empty: empty,
		iterator: new Iterator()
	};
};

function convert(literal) {
    var result = literal.substring(1, literal.length - 1);
    result = result.replace(/"/g, '');
    return result;
}

var trans = {
	uncomment: function(str) {
		// Add some padding so we can always look ahead and behind by two chars
		str = ('__' + str + '__').split('');
		var quote = false,
			quoteSign,
			// regularExpression = false,
			// characterClass = false,
			blockComment = false,
			lineComment = false;
			// preserveComment = false;

		for (var i = 0, l = str.length; i < l; i++) {

			// When checking for quote escaping, we also need to check that the
			// escape sign itself is not escaped, as otherwise '\\' would cause
			// the wrong impression of an unclosed string:
			var unescaped = str[i - 1] !== '\\' || str[i - 2] === '\\';

			if (quote) {
				if (str[i] === quoteSign && unescaped){
					quote = false;
				}

			} else if (blockComment) {
				// Is the block comment closing?
				if (str[i] === '*' && str[i + 1] === '/') {
					// if (!preserveComment)
						str[i] = str[i + 1] = '';
					blockComment /* = preserveComment*/ = false;
					// Increase by 1 to skip closing '/', as it would be mistaken
					// for a regexp otherwise
					i++;
				} else { //if (!preserveComment) {
					str[i] = '';
				}
			} else if (lineComment) {
				// One-line comments end with the line-break
				if (str[i + 1] === '\n' || str[i + 1] === '\r'){
					lineComment = false;
				}
				str[i] = '';
			} else {
				if (str[i] === '"' || str[i] === "'") {
					quote = true;
					quoteSign = str[i];
				} else if (str[i] === '[' && str[i-1] !== "@") {
					quote = true;
					quoteSign = ']';
				// } else if (str[i] === '-' &&  str[i + 1] === '-') {
				// 	str[i] = '';
				// 	lineComment = true;
				} else if (str[i] === '/' && str[i + 1] === '*') {
						// Do not filter out conditional comments /*@ ... */
						// and comments marked as protected /*! ... */

						str[i] = '';
						blockComment = true;

				}
			}
		}
		// Remove padding again.
		str = str.join('').slice(2, -2);

		return str;
	},
	value: function(value, type) {
		if (type == 'NUMBER') return +value;
		return convert(value);
	},
	esTermExpr: function(field, value) {
		var expr = {
			term: {
			}
		};
		expr.term[field] = value;
		return expr;
	},
	esTermsExpr: function(field, value) {
		var expr = {
			terms: {
			}
		};
		expr.terms[field] = value;
		return expr;
	},
	esNotTermExpr: function(field, value) {
		var expr = {
			must_not: {
				term: {
				}
			}
		};
		expr.must_not.term[field] = value;
		return {bool: expr};
	},

	esRangeExpr: function(field, value, op) {
		var expr = {
			range: {

			}
		};
		expr.range[field] = {};
		expr.range[field][op] = value;
		return expr;
	},

	esMustExpr: function(expr1, expr2) {
		var expr = {
			bool: {
				must: []
			}
		}
		expr.bool.must.push(expr1);
		expr.bool.must.push(expr2);
		return expr;
	},

	esShouldExpr: function(expr1, expr2) {
		var expr = {
			bool: {
				should: []
			}
		}
		expr.bool.should.push(expr1);
		expr.bool.should.push(expr2);
		return expr;
	},
	esQueryStringExpr: function(field, value) {
		var expr = {
			query_string: {
				default_field: field
			}
		}
		expr.query_string.query = convert(value);
		return expr;
	},
    esQueryStringInExpr: function(field, value) {
		var expr = {
			query_string: {
				default_field: field
			}
		}
        console.log(value);
		expr.query_string.query = _.map(value, function(o) { return convert(o); }).join(' OR ');
		return expr;
	}
}

module.exports.Stack = Stack;
module.exports.trans = trans;
<commit_msg>* Fix: remove console<commit_after>_ = require('underscore');

var Stack = function(initialCapacity) {
	var _initialCapacity = initialCapacity || Infinity;
	var _elements = [];

	function push(element) {
		if (size() === _initialCapacity) {
			throw new Error('push(): Stack is full.');
		}
		return _elements.push(element);
	}

	function pop() {
		if (isEmpty()) {
			throw new Error('pop(): Stack is empty.');
		}
		return _elements.pop();
	}

	function peek() {
		if (isEmpty()) {
			throw new Error('peek(): Stack is empty.');
		}
		return _elements[_elements.length - 1];
	}

	function isEmpty() {
		return size() === 0;
	}

	function size() {
		return _elements.length;
	}

	function empty() {
		while (_elements.length) {
			_elements.pop();
		}
	}

	function Iterator() {
		var counter = 0;

		function hasNext() {
			return _elements.length !== counter;
		}

		function next() {
			if (!hasNext()) {
				throw new Error('next(): No such element.');
			}
			return _elements[_elements.length - 1 - counter++];
		}
		return {
			hasNext: hasNext,
			next: next
		};
	}

	return {
		push: push,
		pop: pop,
		peek: peek,
		isEmpty: isEmpty,
		size: size,
		empty: empty,
		iterator: new Iterator()
	};
};

function convert(literal) {
    var result = literal.substring(1, literal.length - 1);
    result = result.replace(/"/g, '');
    return result;
}

var trans = {
	uncomment: function(str) {
		// Add some padding so we can always look ahead and behind by two chars
		str = ('__' + str + '__').split('');
		var quote = false,
			quoteSign,
			// regularExpression = false,
			// characterClass = false,
			blockComment = false,
			lineComment = false;
			// preserveComment = false;

		for (var i = 0, l = str.length; i < l; i++) {

			// When checking for quote escaping, we also need to check that the
			// escape sign itself is not escaped, as otherwise '\\' would cause
			// the wrong impression of an unclosed string:
			var unescaped = str[i - 1] !== '\\' || str[i - 2] === '\\';

			if (quote) {
				if (str[i] === quoteSign && unescaped){
					quote = false;
				}

			} else if (blockComment) {
				// Is the block comment closing?
				if (str[i] === '*' && str[i + 1] === '/') {
					// if (!preserveComment)
						str[i] = str[i + 1] = '';
					blockComment /* = preserveComment*/ = false;
					// Increase by 1 to skip closing '/', as it would be mistaken
					// for a regexp otherwise
					i++;
				} else { //if (!preserveComment) {
					str[i] = '';
				}
			} else if (lineComment) {
				// One-line comments end with the line-break
				if (str[i + 1] === '\n' || str[i + 1] === '\r'){
					lineComment = false;
				}
				str[i] = '';
			} else {
				if (str[i] === '"' || str[i] === "'") {
					quote = true;
					quoteSign = str[i];
				} else if (str[i] === '[' && str[i-1] !== "@") {
					quote = true;
					quoteSign = ']';
				// } else if (str[i] === '-' &&  str[i + 1] === '-') {
				// 	str[i] = '';
				// 	lineComment = true;
				} else if (str[i] === '/' && str[i + 1] === '*') {
						// Do not filter out conditional comments /*@ ... */
						// and comments marked as protected /*! ... */

						str[i] = '';
						blockComment = true;

				}
			}
		}
		// Remove padding again.
		str = str.join('').slice(2, -2);

		return str;
	},
	value: function(value, type) {
		if (type == 'NUMBER') return +value;
		return convert(value);
	},
	esTermExpr: function(field, value) {
		var expr = {
			term: {
			}
		};
		expr.term[field] = value;
		return expr;
	},
	esTermsExpr: function(field, value) {
		var expr = {
			terms: {
			}
		};
		expr.terms[field] = value;
		return expr;
	},
	esNotTermExpr: function(field, value) {
		var expr = {
			must_not: {
				term: {
				}
			}
		};
		expr.must_not.term[field] = value;
		return {bool: expr};
	},

	esRangeExpr: function(field, value, op) {
		var expr = {
			range: {

			}
		};
		expr.range[field] = {};
		expr.range[field][op] = value;
		return expr;
	},

	esMustExpr: function(expr1, expr2) {
		var expr = {
			bool: {
				must: []
			}
		}
		expr.bool.must.push(expr1);
		expr.bool.must.push(expr2);
		return expr;
	},

	esShouldExpr: function(expr1, expr2) {
		var expr = {
			bool: {
				should: []
			}
		}
		expr.bool.should.push(expr1);
		expr.bool.should.push(expr2);
		return expr;
	},
	esQueryStringExpr: function(field, value) {
		var expr = {
			query_string: {
				default_field: field
			}
		}
		expr.query_string.query = convert(value);
		return expr;
	},
    esQueryStringInExpr: function(field, value) {
		var expr = {
			query_string: {
				default_field: field
			}
		}
		expr.query_string.query = _.map(value, function(o) { return convert(o); }).join(' OR ');
		return expr;
	}
}

module.exports.Stack = Stack;
module.exports.trans = trans;
<|endoftext|>


<commit_before>module.exports = {
  compact: function (arr) {
    var compactedArr = [];

    for (var i = 0; i < arr.length; i++) {
      arr[i] && compactedArr.push(arr[i]);
    }

    return compactedArr;
  },
  shallowClone: function (obj) {
    var clone = {};

    for (var key in obj) {
      clone[key] = obj[key];
    }

    return clone;
  },
  extend: function (dest, source) {
    for (var key in source) {
      dest[key] = source[key];
    }

    return dest;
  },
  uniq: function (arr) {
    var n = {},
      r = [],
      i;

    for (i = 0; i < arr.length; i++) {
      if (!n[arr[i]]) {
        n[arr[i]] = true;
        r.push(arr[i]);
      }
    }

    return r;
  },
  objectEach: function (obj, iterator) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        iterator(obj[key], key);
      }
    }
  },
  isString: function (value) {
    return typeof value === 'string';
  },
  encode64: function (str) {
    var encodedUtf8Str = unescape(encodeURIComponent(str)),
      b64Str = btoa(encodedUtf8Str),
      urlSafeB64Str = b64Str.replace(/\+/g, '-');

    urlSafeB64Str = urlSafeB64Str
      .replace(/\//g, '_')
      .replace(/\//g, '_')
      .replace(/\=+$/, '');

    return urlSafeB64Str;
  },
  decode64: function (urlSafeB64Str) {
    var b64Str = urlSafeB64Str.replace(/-/g, '+').replace(/_/g, '/'),
      encodedUtf8Str = atob(b64Str),
      str = decodeURIComponent(escape(encodedUtf8Str));

    return str;
  },
  domReady: function (cb) {
    if (document.readyState === 'complete') {
      setTimeout(cb, 0);
    } else if (document.addEventListener) {
      document.addEventListener('DOMContentLoaded', cb, false);
    } else {
      document.attachEvent('onreadystatechange', function () {
        if (document.readyState === 'complete') {
          cb();
        }
      });
    }
  },
  getMetaTagValue: function (propertyName) {
    var metaTag = document.querySelector(
        'meta[property="ix:' + propertyName + '"]'
      ),
      metaTagContent;

    if (!metaTag) {
      return;
    }

    metaTagContent = metaTag.getAttribute('content');

    if (metaTagContent === 'true') {
      return true;
    } else if (metaTagContent === 'false') {
      return false;
    } else if (metaTagContent === '' || metaTagContent === 'null') {
      return null;
    } else {
      return metaTagContent;
    }
  },
  debounce: function (func, waitMs) {
    // based off: http://modernjavascript.blogspot.com/2013/08/building-better-debounce.html
    // we need to save these in the closure
    var timeout, args, context, timestamp;

    return function () {
      // save details of latest call
      context = this;
      args = [].slice.call(arguments, 0);
      timestamp = new Date();

      // this is where the magic happens
      var later = function () {
        // how long ago was the last call
        var timeSinceLastCallMs = new Date() - timestamp;

        // if the latest call was less that the wait period ago
        // then we reset the timeout to wait for the difference
        if (timeSinceLastCallMs < waitMs) {
          timeout = setTimeout(later, waitMs - timeSinceLastCallMs);

          // or if not we can null out the timer and run the latest
        } else {
          timeout = null;
          func.apply(context, args);
        }
      };

      // we only need to set the timer now if one isn't already running
      if (!timeout) {
        timeout = setTimeout(later, waitMs);
      }
    };
  },
  rICShim: function (_window) {
    // from: https://developers.google.com/web/updates/2015/08/using-requestidlecallback#checking_for_requestidlecallback
    return (
      _window.requestIdleCallback ||
      function (cb) {
        var start = Date.now();
        return setTimeout(function () {
          cb({
            didTimeout: false,
            timeRemaining: function () {
              return Math.max(0, 50 - (Date.now() - start));
            },
          });
        }, 1);
      }
    );
  },
};
<commit_msg>chore(debounce): use lodash debounce package<commit_after>const _debounce = require('lodash.debounce');

module.exports = {
  compact: function (arr) {
    var compactedArr = [];

    for (var i = 0; i < arr.length; i++) {
      arr[i] && compactedArr.push(arr[i]);
    }

    return compactedArr;
  },
  shallowClone: function (obj) {
    var clone = {};

    for (var key in obj) {
      clone[key] = obj[key];
    }

    return clone;
  },
  extend: function (dest, source) {
    for (var key in source) {
      dest[key] = source[key];
    }

    return dest;
  },
  uniq: function (arr) {
    var n = {},
      r = [],
      i;

    for (i = 0; i < arr.length; i++) {
      if (!n[arr[i]]) {
        n[arr[i]] = true;
        r.push(arr[i]);
      }
    }

    return r;
  },
  objectEach: function (obj, iterator) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        iterator(obj[key], key);
      }
    }
  },
  isString: function (value) {
    return typeof value === 'string';
  },
  encode64: function (str) {
    var encodedUtf8Str = unescape(encodeURIComponent(str)),
      b64Str = btoa(encodedUtf8Str),
      urlSafeB64Str = b64Str.replace(/\+/g, '-');

    urlSafeB64Str = urlSafeB64Str
      .replace(/\//g, '_')
      .replace(/\//g, '_')
      .replace(/\=+$/, '');

    return urlSafeB64Str;
  },
  decode64: function (urlSafeB64Str) {
    var b64Str = urlSafeB64Str.replace(/-/g, '+').replace(/_/g, '/'),
      encodedUtf8Str = atob(b64Str),
      str = decodeURIComponent(escape(encodedUtf8Str));

    return str;
  },
  domReady: function (cb) {
    if (document.readyState === 'complete') {
      setTimeout(cb, 0);
    } else if (document.addEventListener) {
      document.addEventListener('DOMContentLoaded', cb, false);
    } else {
      document.attachEvent('onreadystatechange', function () {
        if (document.readyState === 'complete') {
          cb();
        }
      });
    }
  },
  getMetaTagValue: function (propertyName) {
    var metaTag = document.querySelector(
        'meta[property="ix:' + propertyName + '"]'
      ),
      metaTagContent;

    if (!metaTag) {
      return;
    }

    metaTagContent = metaTag.getAttribute('content');

    if (metaTagContent === 'true') {
      return true;
    } else if (metaTagContent === 'false') {
      return false;
    } else if (metaTagContent === '' || metaTagContent === 'null') {
      return null;
    } else {
      return metaTagContent;
    }
  },
  debounce: _debounce,
  rICShim: function (_window) {
    // from: https://developers.google.com/web/updates/2015/08/using-requestidlecallback#checking_for_requestidlecallback
    return (
      _window.requestIdleCallback ||
      function (cb) {
        var start = Date.now();
        return setTimeout(function () {
          cb({
            didTimeout: false,
            timeRemaining: function () {
              return Math.max(0, 50 - (Date.now() - start));
            },
          });
        }, 1);
      }
    );
  },
};
<|endoftext|>


<commit_before>var SOSI = window.SOSI || {};

(function (ns, undefined) {
    "use strict";

    function getValues(line) {
        return _.rest(line.split(" ")).join(" ").trim();
    }

    function getNumDots(num) {
        return new Array(num + 1).join(".");
    }

    function getKeyFromLine(line) {
        if (line.indexOf(":") !== -1) {
            return _.first(line.split(":")).trim();
        }
        return _.first(line.split(" ")).trim();
    }

    function cleanupLine(line) {
        if (line.indexOf('!') !== -1) {
            line = line.substring(0, line.indexOf('!'));
        }
        return line.replace(/\s\s*$/, '');
    }

    function getKey(line, parentLevel) {
        return cleanupLine(
            getKeyFromLine(
                line.replace(getNumDots(parentLevel), "")
            )
        );
    }

    function pushOrCreate(dict, val) {
        if (!_.isArray(dict.objects[dict.key])) {
            dict.objects[dict.key] = [];
        }
        dict.objects[dict.key].push(val);
    }

    function c2(str) {
        var substr = str.substr(0, _.lastIndexOf(str, ".") + 1);
        if (_.every(substr, function (character) {return (character === "."); })) {
            return substr.length;
        }
        return 0;
    }

    function countStartingDots(str) {
        var differs = _.find(str, function (character) {return (character !== "."); });
        if (differs) {
            str = str.substr(0, _.indexOf(str, differs));
        }
        if (_.every(str, function (character) {  return (character === "."); })) {
            return str.length;
        }
        return 0;
    }

    function isParent(line, parentLevel) {
        return (countStartingDots(line) === parentLevel);
    }

    function isEmpty(line) {
        return line === "";
    }

    function parseTree(data, parentLevel) {
        return _.reduce(_.reject(data, isEmpty), function (res, line) {
            line = cleanupLine(line);
            if (isParent(line, parentLevel)) {
                res.key = getKey(line, parentLevel);
                line = getValues(line);
            }
            if (!isEmpty(line)) {
                pushOrCreate(res, line);
            }
            return res;
        }, {objects: {}}).objects;
    }

    function setDataType(key, value) {
      var type = _.isArray(key) ? key : window.SOSI.types[key];
      if (type) {
        if (typeof(type[0]) == 'Object') {
        } else {
          if (type[1]=="Integer") {
            return parseInt(value);
          } else if (type[1]=="Real") {
            return parseFloat(value);
          } else if (type[1]=="Date") {
            return new Date(parseInt(value.substring(0,4)), parseInt(value.substring(4,6))-1, parseInt(value.substring(6,8)));
          } else if (type[1]=="String") {
            if (value[0] == '"' || value[0]=="'") return value.substring(1,value.length-1);
            return value;
          }
        }
      }
      return value;
    }

    function parseSpecial(key, subfields) {
          return function (data) {
            if (!data) return null;
            if (_.isObject(data)) return data; // extended subfields

            if (_.isString(data)) {
              return _.reduce(data.match(/"[^"]*"|'[^']*'|\S+/g), function (res, chunk, i) {
                res[subfields[i][0]] = setDataType(subfields[i], chunk);
                return res;
              }, {});
            }
          }
    };

    function getLongname (key) { // not tested
          var type = window.SOSI.types[key];
          if (!type || _.isArray(type[0])) return key;
          return type[0];
    };

    ns.util = {

        parseTree: parseTree,
        cleanupLine: cleanupLine,

        parseFromLevel2: function (data) {
            return _.reduce(parseTree(data, 2), function (dict, lines, key) {
                if (lines.length && lines[0][0]==".") {
                  dict[key] = _.reduce(parseTree(lines, 3), function (subdict, value, key) {
                    subdict[getLongname(key)] = setDataType(key, value[0]);
                      return subdict;
                    }, {});
                } else if (lines.length > 1) {
                  dict[getLongname(key)] = _.map(lines, function(value){return setDataType(key, value);});
                } else if (lines.length) {
                  dict[getLongname(key)] = setDataType(key, lines[0]);
                }
                return dict;
            }, {});
        },

        specialAttributes: function() {
          var atts = {};
          _.each(SOSI.types, function(type,key) {
            if (_.isObject(type[0])) { // true for complex datatypes
              atts[key]={name:key, createFunction:parseSpecial(key, type)};
          }});
          return atts;
        }(),

        round: function (number, numDecimals) {
            var pow = Math.pow(10, numDecimals);
            return Math.round(number * pow) / pow;
        }

    };

    ns.geosysMap = {
        2: {"srid": "EPSG:4326", def: "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "}
    };

    ns.koordsysMap = {
        1: {"srid": "EPSG:27391", "def": "+proj=tmerc +lat_0=58 +lon_0=-4.666666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        2: {"srid": "EPSG:27392", "def": "+proj=tmerc +lat_0=58 +lon_0=-2.333333333333333 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        3: {"srid": "EPSG:27393", "def": "+proj=tmerc +lat_0=58 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        4: {"srid": "EPSG:27394", "def": "+proj=tmerc +lat_0=58 +lon_0=2.5 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        5: {"srid": "EPSG:27395", "def": "+proj=tmerc +lat_0=58 +lon_0=6.166666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        6: {"srid": "EPSG:27396", "def": "+proj=tmerc +lat_0=58 +lon_0=10.16666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        7: {"srid": "EPSG:27397", "def": "+proj=tmerc +lat_0=58 +lon_0=14.16666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        8: {"srid": "EPSG:27398", "def": "+proj=tmerc +lat_0=58 +lon_0=18.33333333333333 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        9: {"srid": "EPSG:4273", "def": "+proj=longlat +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +no_defs"},
        21: {"srid": "EPSG:32631", "def": "+proj=utm +zone=31 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        22: {"srid": "EPSG:32632", "def": "+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        23: {"srid": "EPSG:32633", "def": "+proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        24: {"srid": "EPSG:32634", "def": "+proj=utm +zone=34 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        25: {"srid": "EPSG:32635", "def": "+proj=utm +zone=35 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        26: {"srid": "EPSG:32636", "def": "+proj=utm +zone=35 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        31: {"srid": "EPSG:23031", def: "+proj=utm +zone=31 +ellps=intl +units=m +no_defs"},
        32: {"srid": "EPSG:23032", def: "+proj=utm +zone=32 +ellps=intl +units=m +no_defs"},
        33: {"srid": "EPSG:23033", def: "+proj=utm +zone=33 +ellps=intl +units=m +no_defs"},
        34: {"srid": "EPSG:23034", def: "+proj=utm +zone=34 +ellps=intl +units=m +no_defs"},
        35: {"srid": "EPSG:23035", def: "+proj=utm +zone=35 +ellps=intl +units=m +no_defs"},
        36: {"srid": "EPSG:23036", def: "+proj=utm +zone=36 +ellps=intl +units=m +no_defs"},
        50: {"srid": "EPSG:4230", def: "+proj=longlat +ellps=intl +no_defs"},
        72: {"srid": "EPSG:4322", def: "+proj=longlat +ellps=WGS72 +no_defs "},
        84: {"srid": "EPSG:4326", def: "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "},
        87: {"srid": "EPSG:4231", "def": "+proj=longlat +ellps=intl +no_defs "}

        //41 Lokalnett, uspes.
        //42 Lokalnett, uspes.
        //51 NGO-56A (Møre) NGO1948 Gauss-Krüger
        //52 NGO-56B (Møre) NGO1948 Gauss-Krüger
        //53 NGO-64A (Møre) NGO1948 Gauss-Krüger
        //54 NGO-64B (Møre) NGO1948 Gauss-Krüger
        //99 Egendefinert *
        //101 Lokalnett, Oslo
        //102 Lokalnett, Bærum
        //103 Lokalnett, Asker
        //104 Lokalnett, Lillehammer
        //105 Lokalnett,Drammen
        //106 Lokalnett, Bergen / Askøy
    };

    //add proj4 defs so that proj4js works
    _.each(ns.koordsysMap, function (koordsys) {
      if (proj4) { // newer proj4js (>=1.3.1)
        proj4.defs(koordsys.srid, koordsys.def);
      } else if (Proj4js) { //older proj4js (=< 1.1.0)
        Proj4js.defs[koordsys.srid] = koordsys.def;
      }
    });

}(SOSI));
<commit_msg>parse date *and* time<commit_after>var SOSI = window.SOSI || {};

(function (ns, undefined) {
    "use strict";

    function getValues(line) {
        return _.rest(line.split(" ")).join(" ").trim();
    }

    function getNumDots(num) {
        return new Array(num + 1).join(".");
    }

    function getKeyFromLine(line) {
        if (line.indexOf(":") !== -1) {
            return _.first(line.split(":")).trim();
        }
        return _.first(line.split(" ")).trim();
    }

    function cleanupLine(line) {
        if (line.indexOf('!') !== -1) {
            line = line.substring(0, line.indexOf('!'));
        }
        return line.replace(/\s\s*$/, '');
    }

    function getKey(line, parentLevel) {
        return cleanupLine(
            getKeyFromLine(
                line.replace(getNumDots(parentLevel), "")
            )
        );
    }

    function pushOrCreate(dict, val) {
        if (!_.isArray(dict.objects[dict.key])) {
            dict.objects[dict.key] = [];
        }
        dict.objects[dict.key].push(val);
    }

    function c2(str) {
        var substr = str.substr(0, _.lastIndexOf(str, ".") + 1);
        if (_.every(substr, function (character) {return (character === "."); })) {
            return substr.length;
        }
        return 0;
    }

    function countStartingDots(str) {
        var differs = _.find(str, function (character) {return (character !== "."); });
        if (differs) {
            str = str.substr(0, _.indexOf(str, differs));
        }
        if (_.every(str, function (character) {  return (character === "."); })) {
            return str.length;
        }
        return 0;
    }

    function isParent(line, parentLevel) {
        return (countStartingDots(line) === parentLevel);
    }

    function isEmpty(line) {
        return line === "";
    }

    function parseTree(data, parentLevel) {
        return _.reduce(_.reject(data, isEmpty), function (res, line) {
            line = cleanupLine(line);
            if (isParent(line, parentLevel)) {
                res.key = getKey(line, parentLevel);
                line = getValues(line);
            }
            if (!isEmpty(line)) {
                pushOrCreate(res, line);
            }
            return res;
        }, {objects: {}}).objects;
    }

    function setDataType(key, value) {
      var type = _.isArray(key) ? key : window.SOSI.types[key];
      if (type) {
        if (typeof(type[0]) == 'Object') {
        } else {
          if (type[1]=="Integer") {
            return parseInt(value);
          } else if (type[1]=="Real") {
            return parseFloat(value);
          } else if (type[1]=="Date") {
            if (value.length==8) {
              return new Date(parseInt(value.substring(0,4)), parseInt(value.substring(4,6))-1, parseInt(value.substring(6,8)));
            } else if (value.length==14) {
              return new Date(parseInt(value.substring(0,4)), parseInt(value.substring(4,6))-1, parseInt(value.substring(6,8)),
                              parseInt(value.substring(8,10)), parseInt(value.substring(10,12)), parseInt(value.substring(12,14)));
            }
          } else if (type[1]=="String") {
            if (value[0] == '"' || value[0]=="'") return value.substring(1,value.length-1);
            return value;
          }
        }
      }
      return value;
    }

    function parseSpecial(key, subfields) {
          return function (data) {
            if (!data) return null;
            if (_.isObject(data)) return data; // extended subfields

            if (_.isString(data)) {
              return _.reduce(data.match(/"[^"]*"|'[^']*'|\S+/g), function (res, chunk, i) {
                res[subfields[i][0]] = setDataType(subfields[i], chunk);
                return res;
              }, {});
            }
          }
    };

    function getLongname (key) { // not tested
          var type = window.SOSI.types[key];
          if (!type || _.isArray(type[0])) return key;
          return type[0];
    };

    ns.util = {

        parseTree: parseTree,
        cleanupLine: cleanupLine,

        parseFromLevel2: function (data) {
            return _.reduce(parseTree(data, 2), function (dict, lines, key) {
                if (lines.length && lines[0][0]==".") {
                  dict[key] = _.reduce(parseTree(lines, 3), function (subdict, value, key) {
                    subdict[getLongname(key)] = setDataType(key, value[0]);
                      return subdict;
                    }, {});
                } else if (lines.length > 1) {
                  dict[getLongname(key)] = _.map(lines, function(value){return setDataType(key, value);});
                } else if (lines.length) {
                  dict[getLongname(key)] = setDataType(key, lines[0]);
                }
                return dict;
            }, {});
        },

        specialAttributes: function() {
          var atts = {};
          _.each(SOSI.types, function(type,key) {
            if (_.isObject(type[0])) { // true for complex datatypes
              atts[key]={name:key, createFunction:parseSpecial(key, type)};
          }});
          return atts;
        }(),

        round: function (number, numDecimals) {
            var pow = Math.pow(10, numDecimals);
            return Math.round(number * pow) / pow;
        }

    };

    ns.geosysMap = {
        2: {"srid": "EPSG:4326", def: "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "}
    };

    ns.koordsysMap = {
        1: {"srid": "EPSG:27391", "def": "+proj=tmerc +lat_0=58 +lon_0=-4.666666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        2: {"srid": "EPSG:27392", "def": "+proj=tmerc +lat_0=58 +lon_0=-2.333333333333333 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        3: {"srid": "EPSG:27393", "def": "+proj=tmerc +lat_0=58 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        4: {"srid": "EPSG:27394", "def": "+proj=tmerc +lat_0=58 +lon_0=2.5 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        5: {"srid": "EPSG:27395", "def": "+proj=tmerc +lat_0=58 +lon_0=6.166666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        6: {"srid": "EPSG:27396", "def": "+proj=tmerc +lat_0=58 +lon_0=10.16666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        7: {"srid": "EPSG:27397", "def": "+proj=tmerc +lat_0=58 +lon_0=14.16666666666667 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        8: {"srid": "EPSG:27398", "def": "+proj=tmerc +lat_0=58 +lon_0=18.33333333333333 +k=1 +x_0=0 +y_0=0 +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +pm=oslo +units=m +no_defs"},
        9: {"srid": "EPSG:4273", "def": "+proj=longlat +a=6377492.018 +b=6356173.508712696 +towgs84=278.3,93,474.5,7.889,0.05,-6.61,6.21 +no_defs"},
        21: {"srid": "EPSG:32631", "def": "+proj=utm +zone=31 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        22: {"srid": "EPSG:32632", "def": "+proj=utm +zone=32 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        23: {"srid": "EPSG:32633", "def": "+proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        24: {"srid": "EPSG:32634", "def": "+proj=utm +zone=34 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        25: {"srid": "EPSG:32635", "def": "+proj=utm +zone=35 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        26: {"srid": "EPSG:32636", "def": "+proj=utm +zone=35 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"},
        31: {"srid": "EPSG:23031", def: "+proj=utm +zone=31 +ellps=intl +units=m +no_defs"},
        32: {"srid": "EPSG:23032", def: "+proj=utm +zone=32 +ellps=intl +units=m +no_defs"},
        33: {"srid": "EPSG:23033", def: "+proj=utm +zone=33 +ellps=intl +units=m +no_defs"},
        34: {"srid": "EPSG:23034", def: "+proj=utm +zone=34 +ellps=intl +units=m +no_defs"},
        35: {"srid": "EPSG:23035", def: "+proj=utm +zone=35 +ellps=intl +units=m +no_defs"},
        36: {"srid": "EPSG:23036", def: "+proj=utm +zone=36 +ellps=intl +units=m +no_defs"},
        50: {"srid": "EPSG:4230", def: "+proj=longlat +ellps=intl +no_defs"},
        72: {"srid": "EPSG:4322", def: "+proj=longlat +ellps=WGS72 +no_defs "},
        84: {"srid": "EPSG:4326", def: "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "},
        87: {"srid": "EPSG:4231", "def": "+proj=longlat +ellps=intl +no_defs "}

        //41 Lokalnett, uspes.
        //42 Lokalnett, uspes.
        //51 NGO-56A (Møre) NGO1948 Gauss-Krüger
        //52 NGO-56B (Møre) NGO1948 Gauss-Krüger
        //53 NGO-64A (Møre) NGO1948 Gauss-Krüger
        //54 NGO-64B (Møre) NGO1948 Gauss-Krüger
        //99 Egendefinert *
        //101 Lokalnett, Oslo
        //102 Lokalnett, Bærum
        //103 Lokalnett, Asker
        //104 Lokalnett, Lillehammer
        //105 Lokalnett,Drammen
        //106 Lokalnett, Bergen / Askøy
    };

    //add proj4 defs so that proj4js works
    _.each(ns.koordsysMap, function (koordsys) {
      if (proj4) { // newer proj4js (>=1.3.1)
        proj4.defs(koordsys.srid, koordsys.def);
      } else if (Proj4js) { //older proj4js (=< 1.1.0)
        Proj4js.defs[koordsys.srid] = koordsys.def;
      }
    });

}(SOSI));
<|endoftext|>


<commit_before>import { capitalize } from 'lodash'

// Add 'https://' prefix to a URL
// Must be 'https://' here because GitHub pages is loaded over HTTPS
// HTTP request will be blocked by default
export function completeUrl(url) {
  // No dot in URL, redirect to Bing search
  if (!url.includes('.')) {
    return `https://www.bing.com/search?q=${encodeURIComponent(url)}`
  }

  if (/^https:\/\//.test(url)) {
    return url
  }

  if (/^http:\/\/(.*)/.test(url)) {
    return url.replace(/^http/, 'https')
  }

  return `https://${url}`
}

// Guess favicon from url
export function getFavicon(url) {
  const a = document.createElement('a')
  a.href = completeUrl(url)

  return `${a.protocol}//${a.host}/favicon.ico`
}

// Fake title
export function getTitle(url) {
  const arr = url.replace(/^https:\/\//, '').split('.')
  switch (arr.length) {
    case 2: // twitter.com
      return capitalize(arr[0])
    case 3: // www.google.com
    case 4: // www.google.co.uk
      return capitalize(arr[1])
    default:
      return url
  }
}

// Github start widget
export function getGithubWidget() {
  return ''
}
<commit_msg>Fix IE11, replace `includes` with `indexOf`<commit_after>import { capitalize } from 'lodash'

// Add 'https://' prefix to a URL
// Must be 'https://' here because GitHub pages is loaded over HTTPS
// HTTP request will be blocked by default
export function completeUrl(url) {
  // No dot in URL, redirect to Bing search
  if (url.indexOf('.') === -1) {
    return `https://www.bing.com/search?q=${encodeURIComponent(url)}`
  }

  if (/^https:\/\//.test(url)) {
    return url
  }

  if (/^http:\/\/(.*)/.test(url)) {
    return url.replace(/^http/, 'https')
  }

  return `https://${url}`
}

// Guess favicon from url
export function getFavicon(url) {
  const a = document.createElement('a')
  a.href = completeUrl(url)

  return `${a.protocol}//${a.host}/favicon.ico`
}

// Fake title
export function getTitle(url) {
  const arr = url.replace(/^https:\/\//, '').split('.')
  switch (arr.length) {
    case 2: // twitter.com
      return capitalize(arr[0])
    case 3: // www.google.com
    case 4: // www.google.co.uk
      return capitalize(arr[1])
    default:
      return url
  }
}

// Github start widget
export function getGithubWidget() {
  return ''
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {

	// Project configuration.
	grunt.initConfig({
		//pkg: grunt.file.readJSON("package.json"),
		jsdoc : {
			src : {
				src: ["../Tone/**/*.js", "!../Tone/*/preset/*", "../README.md"],
				options: {
					destination: "../doc",
					template : "./doc_config/template",
					configure : "./doc_config/template/jsdoc.conf.json",
					private : false
				}
			},
		},
		requirejs : {
			compile: {
				options: {
					baseUrl: "../",
					name : "main",
					out: "./Tone.js.tmp",
					optimize : "none"
				}
			},
			min: {
				options: {
					baseUrl: "../",
					name : "main",
					out: "./Tone.min.js.tmp",
					optimize : "uglify2"
				}
			}
		},
		copy : {
			npm : {
				files : [{
					expand : true,
					src: ["../build/Tone.js", "../build/Tone.min.js", "../build/Tone.Preset.js"],
					dest: "./npm/Tone.js"
				}, {
					src : ["../Tone/**"],
					dest : "./npm/Tone/"
				}, {
					src : ["../README.md"],
					dest : "./npm/README.md"
				}]
			}
		},
		concat: {
			dist: {
				options: {
					banner: "require([",
					separator: ",",
					process: function(src, filepath) {
						return "\"" + filepath.substring(3,(filepath.length-3)) + "\"";
					},
					footer: "], function(){});",

				},
				files: {
					//exclude presets
					"../main.js" : ["../Tone/**/*.js", "!../Tone/*/preset/*"],
				}
			},
			presets : {
				files: {
					"../build/Tone.Preset.js" : ["../Tone/**/preset/*.js"],
				}
			},
			removeRequireString: {
				options: {
					process: function(src, filepath) {
						var withoutRequire = src.substr(0, src.indexOf("require([") - 1);
						return withoutRequire;
					},
				},
				files: {
					"../build/Tone.js": ["./Tone.js.tmp"],
				}
			},
			removeRequireStringMin: {
				options: {
					process: function(src, filepath) {
						var withoutRequire = src.substr(0, src.indexOf("require([") - 1);
						return withoutRequire;
					},
				},
				files: {
					"../build/Tone.min.js": ["./Tone.min.js.tmp"],
				}
			}
		},
		clean: {
			options: {
				force: true,
			},
			dist: ["../main.js","./Tone.js.tmp"],
			min: ["../main.js","./Tone.min.js.tmp"],
		}
	});

	// Load the plugin that provides the "uglify" task.
	grunt.loadNpmTasks("grunt-jsdoc");
	grunt.loadNpmTasks("grunt-contrib-requirejs");
	grunt.loadNpmTasks("grunt-contrib-concat");
	grunt.loadNpmTasks("grunt-contrib-clean");
	grunt.loadNpmTasks("grunt-contrib-copy");

	// Default task(s).
	grunt.registerTask("docs", ["jsdoc:src"]);
	grunt.registerTask("npm", ["copy:npm"]);
	grunt.registerTask("presets", ["concat:presets"]);
	grunt.registerTask("min", ["concat:dist", "requirejs:min", "concat:removeRequireStringMin", "clean:min"]);
	grunt.registerTask("build", ["concat:dist","requirejs:compile","concat:removeRequireString","clean:dist"]);
	grunt.registerTask("buildall", ["build", "min", "presets"]);
	grunt.registerTask("dist", ["buildall", "docs", "npm"]);

};<commit_msg>moved doc_config stuff into a vendors folder<commit_after>module.exports = function(grunt) {

	// Project configuration.
	grunt.initConfig({
		//pkg: grunt.file.readJSON("package.json"),
		jsdoc : {
			src : {
				src: ["../Tone/**/*.js", "!../Tone/*/preset/*", "../README.md"],
				options: {
					destination: "../doc",
					template : "./doc_config/vendors",
					configure : "./doc_config/vendors/jsdoc.conf.json",
					private : false
				}
			},
		},
		requirejs : {
			compile: {
				options: {
					baseUrl: "../",
					name : "main",
					out: "./Tone.js.tmp",
					optimize : "none"
				}
			},
			min: {
				options: {
					baseUrl: "../",
					name : "main",
					out: "./Tone.min.js.tmp",
					optimize : "uglify2"
				}
			}
		},
		copy : {
			npm : {
				files : [{
					expand : true,
					src: ["../build/Tone.js", "../build/Tone.min.js", "../build/Tone.Preset.js"],
					dest: "./npm/Tone.js"
				}, {
					src : ["../Tone/**"],
					dest : "./npm/Tone/"
				}, {
					src : ["../README.md"],
					dest : "./npm/README.md"
				}]
			}
		},
		concat: {
			dist: {
				options: {
					banner: "require([",
					separator: ",",
					process: function(src, filepath) {
						return "\"" + filepath.substring(3,(filepath.length-3)) + "\"";
					},
					footer: "], function(){});",

				},
				files: {
					//exclude presets
					"../main.js" : ["../Tone/**/*.js", "!../Tone/*/preset/*"],
				}
			},
			presets : {
				files: {
					"../build/Tone.Preset.js" : ["../Tone/**/preset/*.js"],
				}
			},
			removeRequireString: {
				options: {
					process: function(src, filepath) {
						var withoutRequire = src.substr(0, src.indexOf("require([") - 1);
						return withoutRequire;
					},
				},
				files: {
					"../build/Tone.js": ["./Tone.js.tmp"],
				}
			},
			removeRequireStringMin: {
				options: {
					process: function(src, filepath) {
						var withoutRequire = src.substr(0, src.indexOf("require([") - 1);
						return withoutRequire;
					},
				},
				files: {
					"../build/Tone.min.js": ["./Tone.min.js.tmp"],
				}
			}
		},
		clean: {
			options: {
				force: true,
			},
			dist: ["../main.js","./Tone.js.tmp"],
			min: ["../main.js","./Tone.min.js.tmp"],
		}
	});

	// Load the plugin that provides the "uglify" task.
	grunt.loadNpmTasks("grunt-jsdoc");
	grunt.loadNpmTasks("grunt-contrib-requirejs");
	grunt.loadNpmTasks("grunt-contrib-concat");
	grunt.loadNpmTasks("grunt-contrib-clean");
	grunt.loadNpmTasks("grunt-contrib-copy");

	// Default task(s).
	grunt.registerTask("docs", ["jsdoc:src"]);
	grunt.registerTask("npm", ["copy:npm"]);
	grunt.registerTask("presets", ["concat:presets"]);
	grunt.registerTask("min", ["concat:dist", "requirejs:min", "concat:removeRequireStringMin", "clean:min"]);
	grunt.registerTask("build", ["concat:dist","requirejs:compile","concat:removeRequireString","clean:dist"]);
	grunt.registerTask("buildall", ["build", "min", "presets"]);
	grunt.registerTask("dist", ["buildall", "docs", "npm"]);

};<|endoftext|>


<commit_before>var camelize = require('camelize'),
    config =  require('../config.js'),
    nano = require('nano')(config.couch_auth_db_url),
    newdb,
    olddb,
    relPouch =require('relational-pouch');

if (process.argv.length < 4) {
    console.log('Usage: node pouch-mig.js olddb newdb');
} else {
    olddb = nano.use(process.argv[2]);
    newdb = nano.use(process.argv[3]);
    relPouch.setSchema([]);
    migrateRecords();
}

function migrateRecords() {
  var newDocs = [];
  olddb.list({
    startkey: 'appointment',
    include_docs:true,
  }, function(err, results) {
    results.rows.forEach(function(result) {
      var parsedId = parseOldId(result.id);
      var newDocId = getNewId(parsedId);
      var newDoc = {
        _id: newDocId,
        data: result.doc
      };
      delete newDoc.data._rev;

      switch(parsedId.doctype) {
        case 'appointment': {
          updateChildId(newDoc.data, 'patient');
          break;
        }
        case 'billing-line-item': {
          updateChildId(newDoc.data, 'details');
          break;
        }
        case 'imaging': {
          updateChildId(newDoc.data, 'charges');
          updateChildId(newDoc.data, 'imagingType');
          updateChildId(newDoc.data, 'patient');
          updateChildId(newDoc.data, 'visit');
          break;
        }
        case 'inventory': {
          updateChildId(newDoc.data, 'locations');
          updateChildId(newDoc.data, 'purchases');
          newDoc.data.inventoryType = newDoc.data.type;
          delete newDoc.data.type;
          break;
        }
        case 'inv-purchase': {
          updateChildId(newDoc.data, 'inventoryItem');
          break;
        }
        case 'inv-request': {
          updateChildId(newDoc.data, 'inventoryItem');
          updateChildId(newDoc.data, 'patient');
          updateChildId(newDoc.data, 'visit');
          break;
        }
        case 'invoice': {
          updateChildId(newDoc.data, 'lineItems');
          updateChildId(newDoc.data, 'patient');
          updateChildId(newDoc.data, 'paymentProfile');
          updateChildId(newDoc.data, 'payments');
          updateChildId(newDoc.data, 'visit');
          break;
        }
        case 'lab': {
          updateChildId(newDoc.data, 'charges');
          updateChildId(newDoc.data, 'labType');
          updateChildId(newDoc.data, 'patient');
          updateChildId(newDoc.data, 'visit');
          break;
        }

        case 'line-item-detail': {
          updateChildId(newDoc.data, 'pricingItem');
          break;
        }

        case 'medication': {
          updateChildId(newDoc.data, 'inventoryItem');
          updateChildId(newDoc.data, 'patient');
          updateChildId(newDoc.data, 'visit');
          break;
        }

        case 'override-price': {
          updateChildId(newDoc.data, 'profile');
          break;
        }

        case 'patient': {
          updateChildId(newDoc.data, 'paymentProfile');
          updateChildId(newDoc.data, 'payments');
          break;
        }

        case 'payment': {
          updateChildId(newDoc.data, 'invoice');
          newDoc.data.paymentType = newDoc.data.type;
          delete newDoc.data.type;
          break;
        }

        case 'photo': {
          updateChildId(newDoc.data, 'patient');
          break;
        }

        case 'pricing': {
          updateChildId(newDoc.data, 'pricingOverrides');
          newDoc.data.pricingType = newDoc.data.type;
          delete newDoc.data.type;
          break;
        }

        case 'proc-charge': {
          updateChildId(newDoc.data, 'medication');
          updateChildId(newDoc.data, 'pricingItem');
          break;
        }

        case 'procedure': {
          updateChildId(newDoc.data, 'charges');
          updateChildId(newDoc.data, 'visit');
          break;
        }

        case 'visit': {
          updateChildId(newDoc.data, 'charges');
          updateChildId(newDoc.data, 'imaging');
          updateChildId(newDoc.data, 'labs');
          updateChildId(newDoc.data, 'medication');
          updateChildId(newDoc.data, 'patient');
          updateChildId(newDoc.data, 'procedures');
          updateChildId(newDoc.data, 'vitals');
          break;
        }
      }
      newDocs.push(newDoc);
    });
    newdb.bulk({docs:newDocs}, function(err, body) {
      if(err) {
        console.log("ERROR ON INSERT:",err,body);
      }
    });
  });
}

function getNewId(parsedId) {
  return relPouch.rel.makeDocID({
    id: parsedId.id,
    type: camelize(parsedId.doctype)
  });
}

function parseOldId(oldId) {
  var parsedId = {},
      uidx;
  if ((uidx = oldId.indexOf("_")) > 0) {
    parsedId.doctype = oldId.substring(0, uidx);
    parsedId.id = oldId.substring(uidx+1);
  }
  return parsedId;
}

function updateChildId(data, field) {
  if (data[field]) {
    if (Array.isArray(data[field])) {
      data[field] = data[field].map(function(key) {
        return transformId(key);
      });
    } else {
      data[field] = transformId(data[field]);
    }
  }
}

function transformId(oldValue) {
  var parsedId = parseOldId(oldValue);
  if (!parsedId.id) {
    console.log("ERROR PARSING ID:"+oldValue);
  } else {
    return parsedId.id;
  }
}<commit_msg>Added logic to delete orphan records.<commit_after>var camelize = require('camelize'),
    config =  require('../config.js'),
    nano = require('nano')(config.couch_auth_db_url),
    newdb,
    olddb,
    relPouch =require('relational-pouch');

if (process.argv.length < 4) {
    console.log('Usage: node pouch-mig.js olddb newdb');
} else {
    olddb = nano.use(process.argv[2]);
    newdb = nano.use(process.argv[3]);
    relPouch.setSchema([]);
    migrateRecords();
}

var existingKeys = {};
var childKeys = [];

function migrateRecords() {
  var newDocs = [];
  olddb.list({
    startkey: 'appointment',
    include_docs:true,
  }, function(err, results) {
    results.rows.forEach(function(result) {
      var parsedId = parseOldId(result.id);
      var newDocId = getNewId(parsedId);
      var newDoc = {
        _id: newDocId,
        data: result.doc
      };
      existingKeys[newDocId] = true;
      delete newDoc.data._rev;

      switch(parsedId.doctype) {
        case 'appointment': {
          updateChildId(newDoc, 'patient');
          break;
        }
        case 'billing-line-item': {
          updateChildId(newDoc, 'details');
          break;
        }
        case 'imaging': {
          updateChildId(newDoc, 'charges');
          updateChildId(newDoc, 'imagingType');
          updateChildId(newDoc, 'patient');
          updateChildId(newDoc, 'visit');
          break;
        }
        case 'inventory': {
          updateChildId(newDoc, 'locations');
          updateChildId(newDoc, 'purchases');
          newDoc.data.inventoryType = newDoc.data.type;
          delete newDoc.data.type;
          break;
        }
        case 'inv-purchase': {
          updateChildId(newDoc, 'inventoryItem');
          break;
        }
        case 'inv-request': {
          updateChildId(newDoc, 'inventoryItem');
          updateChildId(newDoc, 'patient');
          updateChildId(newDoc, 'visit');
          break;
        }
        case 'invoice': {
          updateChildId(newDoc, 'lineItems');
          updateChildId(newDoc, 'patient');
          updateChildId(newDoc, 'paymentProfile');
          updateChildId(newDoc, 'payments');
          updateChildId(newDoc, 'visit');
          break;
        }
        case 'lab': {
          updateChildId(newDoc, 'charges');
          updateChildId(newDoc, 'labType');
          updateChildId(newDoc, 'patient');
          updateChildId(newDoc, 'visit');
          break;
        }

        case 'line-item-detail': {
          updateChildId(newDoc, 'pricingItem');
          break;
        }

        case 'medication': {
          updateChildId(newDoc, 'inventoryItem');
          updateChildId(newDoc, 'patient');
          updateChildId(newDoc, 'visit');
          break;
        }

        case 'override-price': {
          updateChildId(newDoc, 'profile');
          break;
        }

        case 'patient': {
          updateChildId(newDoc, 'paymentProfile');
          updateChildId(newDoc, 'payments');
          break;
        }

        case 'payment': {
          updateChildId(newDoc, 'invoice');
          newDoc.data.paymentType = newDoc.data.type;
          delete newDoc.data.type;
          break;
        }

        case 'photo': {
          updateChildId(newDoc, 'patient');
          break;
        }

        case 'pricing': {
          updateChildId(newDoc, 'pricingOverrides');
          newDoc.data.pricingType = newDoc.data.type;
          delete newDoc.data.type;
          break;
        }

        case 'proc-charge': {
          updateChildId(newDoc, 'medication');
          updateChildId(newDoc, 'pricingItem');
          break;
        }

        case 'procedure': {
          updateChildId(newDoc, 'charges');
          updateChildId(newDoc, 'visit');
          break;
        }

        case 'visit': {
          updateChildId(newDoc, 'charges');
          updateChildId(newDoc, 'imaging');
          updateChildId(newDoc, 'labs');
          updateChildId(newDoc, 'medication');
          updateChildId(newDoc, 'patient');
          updateChildId(newDoc, 'procedures');
          updateChildId(newDoc, 'vitals');
          break;
        }
      }
      newDocs.push(newDoc);
    });
    newdb.bulk({docs:newDocs}, function(err, body) {
      if(err) {
        console.log("ERROR ON INSERT:",err,body);
      } else {
        console.log("Successfully migrated documents");
        deleteOrphanRecords();
      }
    });
  });
}

function deleteOrphanRecords() {
var recordsToDelete = {};
  childKeys.forEach(function(keyInfo) {
    keyInfo.keys.forEach(function(key) {
      if (!existingKeys[key]) {
        if (!recordsToDelete[keyInfo.id]) {
          recordsToDelete[keyInfo.id] = true;
        }
      }
    });
  });
  var deleteKeys = Object.keys(recordsToDelete);
  deleteKeys.forEach(function(deleteKey) {
    newdb.get(deleteKey, function (err, doc){
      if (err) {
        console.log("Err on get record to delete: ",err);
      } else {
        doc._deleted = true;
        newdb.insert(doc, function(err, result) {
          if (err) {
            console.log("Error deleting unneeded record:",err);
          } else {
            console.log("Deleted unneeded record:"+result.id);
          }
        });
      }
    });
  });
}

function getNewId(parsedId) {
  return relPouch.rel.makeDocID({
    id: parsedId.id,
    type: camelize(parsedId.doctype)
  });
}

function parseOldId(oldId) {
  var parsedId = {},
      uidx;
  if ((uidx = oldId.indexOf("_")) > 0) {
    parsedId.doctype = oldId.substring(0, uidx);
    parsedId.id = oldId.substring(uidx+1);
  }
  return parsedId;
}

function updateChildId(doc, field) {
  var data = doc.data,
      childKeyValues = {
        id: doc._id,
        keys: []
      };
  if (data[field]) {
    if (Array.isArray(data[field])) {
      data[field] = data[field].map(function(key) {
        childKeyValues.keys.push(getNewId(parseOldId(key)));
        return transformId(key);
      });
    } else {
      childKeyValues.keys.push(getNewId(parseOldId(data[field])));
      data[field] = transformId(data[field]);
    }
    childKeys.push(childKeyValues);
  }
}

function transformId(oldValue) {
  var parsedId = parseOldId(oldValue);
  if (!parsedId.id) {
    console.log("ERROR PARSING ID:"+oldValue);
  } else {
    return parsedId.id;
  }
}<|endoftext|>


<commit_before>// JavaScript Document

var _adrrsearchC = "./include/monitoring/status/TopCounter/xml/statusCounter.php";

function getXhrC(){
	if (window.XMLHttpRequest) {
		// Firefox and others
	   	var xhrC = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		// Internet Explorer
	   	try {
            	var xhrC = new ActiveXObject("Msxml2.XMLHTTP");
           	} catch (e) {
                var xhrC = new ActiveXObject("Microsoft.XMLHTTP");
           	}
	} else {
		// XMLHttpRequest non support2 par le navigateur
		alert("Your Browser doesn't support XMLHTTPRequest object...");
	   	var xhrC = false;
	}
	return xhrC;
}

function reloadStatusCounter(_reload_time, _sid) {

	var xhrC = getXhrC();
	// On defini ce qu'on va faire quand on aura la reponse
	xhrC.onreadystatechange = function() {
		// On ne fait quelque chose que si on a tout recu et que le serveur est ok
		if (xhrC && xhrC.readyState == 4 && xhrC.status == 200 && xhrC.responseXML) {
			reponseC = xhrC.responseXML.documentElement;

			// Get stats
			var stats = reponseC.getElementsByTagName("s");
			for (var i = 0 ; i < stats.length ; i++) {
				var stat = stats[i];
				var _statistic_total_service 	= stat.getElementsByTagName("ts")[0].firstChild.nodeValue;
				var _statistic_total_host 		= stat.getElementsByTagName("th")[0].firstChild.nodeValue;
				var _statistic_service_ok 		= stat.getElementsByTagName("o")[0].firstChild.nodeValue;
				var _statistic_service_warning 	= stat.getElementsByTagName("w")[0].firstChild.nodeValue;
				var _statistic_service_critical = stat.getElementsByTagName("c")[0].firstChild.nodeValue;
				var _statistic_service_unknown 	= stat.getElementsByTagName("un1")[0].firstChild.nodeValue;
				var _statistic_service_warningU	= stat.getElementsByTagName("wU")[0].firstChild.nodeValue;
				var _statistic_service_criticalU = stat.getElementsByTagName("cU")[0].firstChild.nodeValue;
				var _statistic_service_unknownU	= stat.getElementsByTagName("un1U")[0].firstChild.nodeValue;
				var _statistic_service_pending 	= stat.getElementsByTagName("p1")[0].firstChild.nodeValue;
				var _statistic_host_up 			= stat.getElementsByTagName("up")[0].firstChild.nodeValue;
				var _statistic_host_down 		= stat.getElementsByTagName("d")[0].firstChild.nodeValue;
				var _statistic_host_unreachable = stat.getElementsByTagName("un2")[0].firstChild.nodeValue;
				var _statistic_host_pending 	= stat.getElementsByTagName("p2")[0].firstChild.nodeValue;

				/*
				 * host
				 */
				document.getElementById('hosts').innerHTML = '';
				var _text_total_host = document.createTextNode(_statistic_total_host);
				var _linkHosttotal = document.createElement("a");
			  	_linkHosttotal.href = 'main.php?p=20202&o=h&search=';
				_linkHosttotal.appendChild(_text_total_host);
				document.getElementById('hosts').appendChild(_linkHosttotal);

				document.getElementById('host_up').innerHTML = '';
				var _text_host_up = document.createTextNode(_statistic_host_up);
				var _linkHostup = document.createElement("a");
			  	_linkHostup.href = 'main.php?p=20202&o=h_up&search=';
				_linkHostup.appendChild(_text_host_up);
				document.getElementById('host_up').appendChild(_linkHostup);

				document.getElementById('host_down').innerHTML = '';
				var _text_host_down = document.createTextNode(_statistic_host_down);
				var _linkHostProblem = document.createElement("a");
			  	_linkHostProblem.href = 'main.php?p=20202&o=h_down&search=';
				_linkHostProblem.appendChild(_text_host_down);
				document.getElementById('host_down').appendChild(_linkHostProblem);

				document.getElementById('host_unreachable').innerHTML = '';
				var _text_host_unreachable = document.createTextNode(_statistic_host_unreachable);
				var _linkHostunreachable = document.createElement("a");
			  	_linkHostunreachable.href = 'main.php?p=20202&o=h_unreachable&search=';
				_linkHostunreachable.appendChild(_text_host_unreachable);
				document.getElementById('host_unreachable').appendChild(_linkHostunreachable);

				document.getElementById('host_pending').innerHTML = '';
				var _text_host_pending = document.createTextNode(_statistic_host_pending);
				var _linkHostpending = document.createElement("a");
			  	_linkHostpending.href = 'main.php?p=20202&o=h_pending&search=';
				_linkHostpending.appendChild(_text_host_pending);
				document.getElementById('host_pending').appendChild(_linkHostpending);

				/*
				 * svc
				 */
				document.getElementById('service_total').innerHTML = '';
				var _text_total_service = document.createTextNode(_statistic_total_service);
				var _linkservice_total = document.createElement("a");
			  	_linkservice_total.href = 'main.php?p=20201&o=svc&search=';
				_linkservice_total.appendChild(_text_total_service);
				document.getElementById('service_total').appendChild(_linkservice_total);

				// Ok service Stats
				document.getElementById('service_ok').innerHTML = '';
				var _text_service_ok = document.createTextNode(_statistic_service_ok);
				var _linkservice_ok = document.createElement("a");
			  	_linkservice_ok.href = 'main.php?p=20201&o=svc_ok&search=';
				_linkservice_ok.appendChild(_text_service_ok);
				document.getElementById('service_ok').appendChild(_linkservice_ok);

				// Warning service stats
				document.getElementById('service_warning').innerHTML = '';
				var _text_service_warning = document.createTextNode(_statistic_service_warningU+"/"+_statistic_service_warning);
				var _linkservice_warning = document.createElement("a");
			  	_linkservice_warning.href = 'main.php?p=20201&o=svc_warning&search=';
				_linkservice_warning.appendChild(_text_service_warning);
				document.getElementById('service_warning').appendChild(_linkservice_warning);

				// Critcal Service Stats
				document.getElementById('service_critical').innerHTML = '';
				var _text_service_critical = document.createTextNode(_statistic_service_criticalU+"/"+_statistic_service_critical);
				var _linkservice_critical = document.createElement("a");
			  	_linkservice_critical.href = 'main.php?p=20201&o=svc_critical&search=';
				_linkservice_critical.appendChild(_text_service_critical);
				document.getElementById('service_critical').appendChild(_linkservice_critical);

				// Unknown Service Stats
				document.getElementById('service_unknown').innerHTML = '';
				var _text_service_unknown = document.createTextNode(_statistic_service_unknownU+"/"+_statistic_service_unknown);
				var _linkservice_unknown = document.createElement("a");
			  	_linkservice_unknown.href = 'main.php?p=20201&o=svc_unknown&search=';
				_linkservice_unknown.appendChild(_text_service_unknown);
				document.getElementById('service_unknown').appendChild(_linkservice_unknown);

				// Pending Services Stats
				document.getElementById('service_pending').innerHTML = '';
				var _text_service_pending = document.createTextNode(_statistic_service_pending);
				var _linkservice_pending = document.createElement("a");
			  	_linkservice_pending.href = 'main.php?p=20201&o=svc_pending&search=';
				_linkservice_pending.appendChild(_text_service_pending);
				document.getElementById('service_pending').appendChild(_linkservice_pending);
			}

			// Get Poller Statistics
			if (document.getElementById('img_pollingState')) {
				var statPoller = reponseC.getElementsByTagName("m");
				for (var i = 0 ; i < statPoller.length ; i++) {
					var statp = statPoller[i];
					var _statistic_pollingState = statp.getElementsByTagName("pstt")[0].firstChild.nodeValue;
					var _statistic_latency = statp.getElementsByTagName("ltc")[0].firstChild.nodeValue;
					var _statistic_activity = statp.getElementsByTagName("act")[0].firstChild.nodeValue;
					var _error_pollingState = statp.getElementsByTagName("errorPstt")[0].firstChild.nodeValue;
					var _error_latency = statp.getElementsByTagName("errorLtc")[0].firstChild.nodeValue;
					var _error_activity = statp.getElementsByTagName("errorAct")[0].firstChild.nodeValue;

					document.getElementById("img_pollingState").title = _error_pollingState;
					document.getElementById("img_latency").title = _error_latency;
					document.getElementById("img_activity").title = _error_activity;

					if (_statistic_latency == 0) {
						document.getElementById("latency").style.backgroundColor = "#88b917";
					} else if (_statistic_latency == 1) {
						document.getElementById("latency").style.backgroundColor = "#ff9a13";
					} else if (_statistic_latency == 2) {
						document.getElementById("latency").style.backgroundColor = "#e00b3d";
					}

					if (_statistic_activity == 0) {
						document.getElementById("activity").style.backgroundColor = "#818285";
					} else if (_statistic_activity == 1) {
						document.getElementById("activity").style.backgroundColor = "#ff9a13";
					} else if (_statistic_activity == 2) {
						document.getElementById("activity").style.backgroundColor = "#e00b3d";
					}

					if (_statistic_pollingState == 0) {
						document.getElementById("pollingState").style.backgroundColor = "#818285";
					} else if (_statistic_pollingState == 1) {
						document.getElementById("pollingState").style.backgroundColor = "#ff9a13";
					} else if (_statistic_pollingState == 2) {
						document.getElementById("pollingState").style.backgroundColor = "#e00b3d";
					}
				}
			}
		}
	}

	xhrC.open("POST",_adrrsearchC,true);
	xhrC.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhrC.send("&session_expire="+(_reload_time/1000));
	setTimeout('reloadStatusCounter("'+ _reload_time +'","'+ _sid +'")', _reload_time);
}
<commit_msg>    * Fix issue with poller and satabase color not green when "OK" in top counter<commit_after>// JavaScript Document

var _adrrsearchC = "./include/monitoring/status/TopCounter/xml/statusCounter.php";

function getXhrC(){
	if (window.XMLHttpRequest) {
		// Firefox and others
	   	var xhrC = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		// Internet Explorer
	   	try {
            	var xhrC = new ActiveXObject("Msxml2.XMLHTTP");
           	} catch (e) {
                var xhrC = new ActiveXObject("Microsoft.XMLHTTP");
           	}
	} else {
		// XMLHttpRequest non support2 par le navigateur
		alert("Your Browser doesn't support XMLHTTPRequest object...");
	   	var xhrC = false;
	}
	return xhrC;
}

function reloadStatusCounter(_reload_time, _sid) {

	var xhrC = getXhrC();
	// On defini ce qu'on va faire quand on aura la reponse
	xhrC.onreadystatechange = function() {
		// On ne fait quelque chose que si on a tout recu et que le serveur est ok
		if (xhrC && xhrC.readyState == 4 && xhrC.status == 200 && xhrC.responseXML) {
			reponseC = xhrC.responseXML.documentElement;

			// Get stats
			var stats = reponseC.getElementsByTagName("s");
			for (var i = 0 ; i < stats.length ; i++) {
				var stat = stats[i];
				var _statistic_total_service 	= stat.getElementsByTagName("ts")[0].firstChild.nodeValue;
				var _statistic_total_host 		= stat.getElementsByTagName("th")[0].firstChild.nodeValue;
				var _statistic_service_ok 		= stat.getElementsByTagName("o")[0].firstChild.nodeValue;
				var _statistic_service_warning 	= stat.getElementsByTagName("w")[0].firstChild.nodeValue;
				var _statistic_service_critical = stat.getElementsByTagName("c")[0].firstChild.nodeValue;
				var _statistic_service_unknown 	= stat.getElementsByTagName("un1")[0].firstChild.nodeValue;
				var _statistic_service_warningU	= stat.getElementsByTagName("wU")[0].firstChild.nodeValue;
				var _statistic_service_criticalU = stat.getElementsByTagName("cU")[0].firstChild.nodeValue;
				var _statistic_service_unknownU	= stat.getElementsByTagName("un1U")[0].firstChild.nodeValue;
				var _statistic_service_pending 	= stat.getElementsByTagName("p1")[0].firstChild.nodeValue;
				var _statistic_host_up 			= stat.getElementsByTagName("up")[0].firstChild.nodeValue;
				var _statistic_host_down 		= stat.getElementsByTagName("d")[0].firstChild.nodeValue;
				var _statistic_host_unreachable = stat.getElementsByTagName("un2")[0].firstChild.nodeValue;
				var _statistic_host_pending 	= stat.getElementsByTagName("p2")[0].firstChild.nodeValue;

				/*
				 * host
				 */
				document.getElementById('hosts').innerHTML = '';
				var _text_total_host = document.createTextNode(_statistic_total_host);
				var _linkHosttotal = document.createElement("a");
			  	_linkHosttotal.href = 'main.php?p=20202&o=h&search=';
				_linkHosttotal.appendChild(_text_total_host);
				document.getElementById('hosts').appendChild(_linkHosttotal);

				document.getElementById('host_up').innerHTML = '';
				var _text_host_up = document.createTextNode(_statistic_host_up);
				var _linkHostup = document.createElement("a");
			  	_linkHostup.href = 'main.php?p=20202&o=h_up&search=';
				_linkHostup.appendChild(_text_host_up);
				document.getElementById('host_up').appendChild(_linkHostup);

				document.getElementById('host_down').innerHTML = '';
				var _text_host_down = document.createTextNode(_statistic_host_down);
				var _linkHostProblem = document.createElement("a");
			  	_linkHostProblem.href = 'main.php?p=20202&o=h_down&search=';
				_linkHostProblem.appendChild(_text_host_down);
				document.getElementById('host_down').appendChild(_linkHostProblem);

				document.getElementById('host_unreachable').innerHTML = '';
				var _text_host_unreachable = document.createTextNode(_statistic_host_unreachable);
				var _linkHostunreachable = document.createElement("a");
			  	_linkHostunreachable.href = 'main.php?p=20202&o=h_unreachable&search=';
				_linkHostunreachable.appendChild(_text_host_unreachable);
				document.getElementById('host_unreachable').appendChild(_linkHostunreachable);

				document.getElementById('host_pending').innerHTML = '';
				var _text_host_pending = document.createTextNode(_statistic_host_pending);
				var _linkHostpending = document.createElement("a");
			  	_linkHostpending.href = 'main.php?p=20202&o=h_pending&search=';
				_linkHostpending.appendChild(_text_host_pending);
				document.getElementById('host_pending').appendChild(_linkHostpending);

				/*
				 * svc
				 */
				document.getElementById('service_total').innerHTML = '';
				var _text_total_service = document.createTextNode(_statistic_total_service);
				var _linkservice_total = document.createElement("a");
			  	_linkservice_total.href = 'main.php?p=20201&o=svc&search=';
				_linkservice_total.appendChild(_text_total_service);
				document.getElementById('service_total').appendChild(_linkservice_total);

				// Ok service Stats
				document.getElementById('service_ok').innerHTML = '';
				var _text_service_ok = document.createTextNode(_statistic_service_ok);
				var _linkservice_ok = document.createElement("a");
			  	_linkservice_ok.href = 'main.php?p=20201&o=svc_ok&search=';
				_linkservice_ok.appendChild(_text_service_ok);
				document.getElementById('service_ok').appendChild(_linkservice_ok);

				// Warning service stats
				document.getElementById('service_warning').innerHTML = '';
				var _text_service_warning = document.createTextNode(_statistic_service_warningU+"/"+_statistic_service_warning);
				var _linkservice_warning = document.createElement("a");
			  	_linkservice_warning.href = 'main.php?p=20201&o=svc_warning&search=';
				_linkservice_warning.appendChild(_text_service_warning);
				document.getElementById('service_warning').appendChild(_linkservice_warning);

				// Critcal Service Stats
				document.getElementById('service_critical').innerHTML = '';
				var _text_service_critical = document.createTextNode(_statistic_service_criticalU+"/"+_statistic_service_critical);
				var _linkservice_critical = document.createElement("a");
			  	_linkservice_critical.href = 'main.php?p=20201&o=svc_critical&search=';
				_linkservice_critical.appendChild(_text_service_critical);
				document.getElementById('service_critical').appendChild(_linkservice_critical);

				// Unknown Service Stats
				document.getElementById('service_unknown').innerHTML = '';
				var _text_service_unknown = document.createTextNode(_statistic_service_unknownU+"/"+_statistic_service_unknown);
				var _linkservice_unknown = document.createElement("a");
			  	_linkservice_unknown.href = 'main.php?p=20201&o=svc_unknown&search=';
				_linkservice_unknown.appendChild(_text_service_unknown);
				document.getElementById('service_unknown').appendChild(_linkservice_unknown);

				// Pending Services Stats
				document.getElementById('service_pending').innerHTML = '';
				var _text_service_pending = document.createTextNode(_statistic_service_pending);
				var _linkservice_pending = document.createElement("a");
			  	_linkservice_pending.href = 'main.php?p=20201&o=svc_pending&search=';
				_linkservice_pending.appendChild(_text_service_pending);
				document.getElementById('service_pending').appendChild(_linkservice_pending);
			}

			// Get Poller Statistics
			if (document.getElementById('img_pollingState')) {
				var statPoller = reponseC.getElementsByTagName("m");
				for (var i = 0 ; i < statPoller.length ; i++) {
					var statp = statPoller[i];
					var _statistic_pollingState = statp.getElementsByTagName("pstt")[0].firstChild.nodeValue;
					var _statistic_latency = statp.getElementsByTagName("ltc")[0].firstChild.nodeValue;
					var _statistic_activity = statp.getElementsByTagName("act")[0].firstChild.nodeValue;
					var _error_pollingState = statp.getElementsByTagName("errorPstt")[0].firstChild.nodeValue;
					var _error_latency = statp.getElementsByTagName("errorLtc")[0].firstChild.nodeValue;
					var _error_activity = statp.getElementsByTagName("errorAct")[0].firstChild.nodeValue;

					document.getElementById("img_pollingState").title = _error_pollingState;
					document.getElementById("img_latency").title = _error_latency;
					document.getElementById("img_activity").title = _error_activity;

					if (_statistic_latency === '0') {
                                            document.getElementById("latency").style.backgroundColor = "#88b917";
					} else if (_statistic_latency === '1') {
                                            document.getElementById("latency").style.backgroundColor = "#ff9a13";
					} else if (_statistic_latency === '2') {
                                            document.getElementById("latency").style.backgroundColor = "#e00b3d";
					}

					if (_statistic_activity === '0') {
                                            console.log(document.getElementById("activity"));
                                            document.getElementById("activity").style.backgroundColor = "#88b917";
					} else if (_statistic_activity === '1') {
                                            document.getElementById("activity").style.backgroundColor = "#ff9a13";
					} else if (_statistic_activity === '2') {
                                            document.getElementById("activity").style.backgroundColor = "#e00b3d";
					}

					if (_statistic_pollingState === '0') {
                                            console.log(document.getElementById("pollingState"));
                                            document.getElementById("pollingState").style.backgroundColor = "#88b917";
					} else if (_statistic_pollingState === '1') {
                                            document.getElementById("pollingState").style.backgroundColor = "#ff9a13";
					} else if (_statistic_pollingState === '2') {
                                            document.getElementById("pollingState").style.backgroundColor = "#e00b3d";
					}
				}
			}
		}
	}

	xhrC.open("POST",_adrrsearchC,true);
	xhrC.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhrC.send("&session_expire="+(_reload_time/1000));
	setTimeout('reloadStatusCounter("'+ _reload_time +'","'+ _sid +'")', _reload_time);
}
<|endoftext|>


<commit_before>import React from 'react';
import { Form } from 'semantic-ui-react';

const ListingBody = ({ body, onChange }) =>
  <Form.TextArea
    rows="5"
    className='ui center aligned grid'
    label="Job Description"
    placeholder="Tell us about the job..."
    name="body"
    value={body}
    onChange={e => onChange(e)}
  />;

ListingBody.propTypes = {
  body: React.PropTypes.string.isRequired,
  onChange: React.PropTypes.func.isRequired,
};

export default ListingBody;
<commit_msg>Add form class to textarea<commit_after>import React from 'react';
import { Form } from 'semantic-ui-react';

const ListingBody = ({ body, onChange, getFormClass }) =>
  <Form.TextArea
    rows="5"
    label="Job Description"
    placeholder="Tell us about the job..."
    name="body"
    value={body}
    onChange={e => onChange(e)}
    className={getFormClass('body')}
  />;

ListingBody.propTypes = {
  body: React.PropTypes.string.isRequired,
  onChange: React.PropTypes.func.isRequired,
  getFormClass: React.PropTypes.func.isRequired,
};

export default ListingBody;
<|endoftext|>