<commit_before>
var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
		"(?:[\\w*_-]|\\\\.)" :
		"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
	quickChild = new RegExp("^>\\s*(" + chars + "+)"),
	quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
	quickClass = new RegExp("^([#.]?)(" + chars + "*)");

jQuery.extend({
	expr: {
		"": "m[2]=='*'||jQuery.nodeName(a,m[2])",
		"#": "a.getAttribute('id')==m[2]",
		":": {
			// Position Checks
			lt: "i<m[3]-0",
			gt: "i>m[3]-0",
			nth: "m[3]-0==i",
			eq: "m[3]-0==i",
			first: "i==0",
			last: "i==r.length-1",
			even: "i%2==0",
			odd: "i%2",

			// Child Checks
			"first-child": "a.parentNode.getElementsByTagName('*')[0]==a",
			"last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
			"only-child": "!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",

			// Parent Checks
			parent: "a.firstChild",
			empty: "!a.firstChild",

			// Text Check
			contains: "(a.textContent||a.innerText||jQuery(a).text()||'').indexOf(m[3])>=0",

			// Visibility
			visible: '"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
			hidden: '"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',

			// Form attributes
			enabled: "!a.disabled",
			disabled: "a.disabled",
			checked: "a.checked",
			selected: "a.selected||jQuery.attr(a,'selected')",

			// Form elements
			text: "'text'==a.type",
			radio: "'radio'==a.type",
			checkbox: "'checkbox'==a.type",
			file: "'file'==a.type",
			password: "'password'==a.type",
			submit: "'submit'==a.type",
			image: "'image'==a.type",
			reset: "'reset'==a.type",
			button: '"button"==a.type||jQuery.nodeName(a,"button")',
			input: "/input|select|textarea|button/i.test(a.nodeName)",

			// :has()
			has: "jQuery.find(m[3],a).length",

			// :header
			header: "/h\\d/i.test(a.nodeName)",

			// :animated
			animated: "jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length"
		}
	},

	// The regular expressions that power the parsing engine
	parse: [
		// Match: [@value='test'], [@foo]
		/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,

		// Match: :contains('foo')
		/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,

		// Match: :even, :last-chlid, #id, .class
		new RegExp("^([:.#]*)(" + chars + "+)")
	],

	multiFilter: function( expr, elems, not ) {
		var old, cur = [];

		while ( expr && expr != old ) {
			old = expr;
			var f = jQuery.filter( expr, elems, not );
			expr = f.t.replace(/^\s*,\s*/, "" );
			cur = not ? elems = f.r : jQuery.merge( cur, f.r );
		}

		return cur;
	},

	find: function( t, context ) {
		// Quickly handle non-string expressions
		if ( typeof t != "string" )
			return [ t ];

		// check to make sure context is a DOM element or a document
		if ( context && context.nodeType != 1 && context.nodeType != 9)
			return [ ];

		// Set the correct context (if none is provided)
		context = context || document;

		// Initialize the search
		var ret = [context], done = [], last, nodeName;

		// Continue while a selector expression exists, and while
		// we're no longer looping upon ourselves
		while ( t && last != t ) {
			var r = [];
			last = t;

			t = jQuery.trim(t);

			var foundToken = false;

			// An attempt at speeding up child selectors that
			// point to a specific element tag
			var re = quickChild;
			var m = re.exec(t);

			if ( m ) {
				nodeName = m[1].toUpperCase();

				// Perform our own iteration and filter
				for ( var i = 0; ret[i]; i++ )
					for ( var c = ret[i].firstChild; c; c = c.nextSibling )
						if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
							r.push( c );

				ret = r;
				t = t.replace( re, "" );
				if ( t.indexOf(" ") == 0 ) continue;
				foundToken = true;
			} else {
				re = /^([>+~])\s*(\w*)/i;

				if ( (m = re.exec(t)) != null ) {
					r = [];

					nodeName = m[2].toUpperCase(), merge = {};
					m = m[1];

					for ( var j = 0, rl = ret.length; j < rl; j++ ) {
						var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
						for ( ; n; n = n.nextSibling )
							if ( n.nodeType == 1 ) {
								var id = jQuery.data(n);

								if ( m == "~" && merge[id] ) break;

								if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
									if ( m == "~" ) merge[id] = true;
									r.push( n );
								}

								if ( m == "+" ) break;
							}
					}

					ret = r;

					// And remove the token
					t = jQuery.trim( t.replace( re, "" ) );
					foundToken = true;
				}
			}

			// See if there's still an expression, and that we haven't already
			// matched a token
			if ( t && !foundToken ) {
				// Handle multiple expressions
				if ( !t.indexOf(",") ) {
					// Clean the result set
					if ( context == ret[0] ) ret.shift();

					// Merge the result sets
					done = jQuery.merge( done, ret );

					// Reset the context
					r = ret = [context];

					// Touch up the selector string
					t = " " + t.substr(1,t.length);

				} else {
					// Optimize for the case nodeName#idName
					var re2 = quickID;
					var m = re2.exec(t);

					// Re-organize the results, so that they're consistent
					if ( m ) {
						m = [ 0, m[2], m[3], m[1] ];

					} else {
						// Otherwise, do a traditional filter check for
						// ID, class, and element selectors
						re2 = quickClass;
						m = re2.exec(t);
					}

					m[2] = m[2].replace(/\\/g, "");

					var elem = ret[ret.length-1];

					// Try to do a global search by ID, where we can
					if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
						// Optimization for HTML document case
						var oid = elem.getElementById(m[2]);

						// Do a quick check for the existence of the actual ID attribute
						// to avoid selecting by the name attribute in IE
						// also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
						if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
							oid = jQuery('[@id="'+m[2]+'"]', elem)[0];

						// Do a quick check for node name (where applicable) so
						// that div#foo searches will be really fast
						ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
					} else {
						// We need to find all descendant elements
						for ( var i = 0; ret[i]; i++ ) {
							// Grab the tag name being searched for
							var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];

							// Handle IE7 being really dumb about <object>s
							if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
								tag = "param";

							r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
						}

						// It's faster to filter by class and be done with it
						if ( m[1] == "." )
							r = jQuery.classFilter( r, m[2] );

						// Same with ID filtering
						if ( m[1] == "#" ) {
							var tmp = [];

							// Try to find the element with the ID
							for ( var i = 0; r[i]; i++ )
								if ( r[i].getAttribute("id") == m[2] ) {
									tmp = [ r[i] ];
									break;
								}

							r = tmp;
						}

						ret = r;
					}

					t = t.replace( re2, "" );
				}

			}

			// If a selector string still exists
			if ( t ) {
				// Attempt to filter it
				var val = jQuery.filter(t,r);
				ret = r = val.r;
				t = jQuery.trim(val.t);
			}
		}

		// An error occurred with the selector;
		// just return an empty set instead
		if ( t )
			ret = [];

		// Remove the root context
		if ( ret && context == ret[0] )
			ret.shift();

		// And combine the results
		done = jQuery.merge( done, ret );

		return done;
	},

	classFilter: function(r,m,not){
		m = " " + m + " ";
		var tmp = [];
		for ( var i = 0; r[i]; i++ ) {
			var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
			if ( !not && pass || not && !pass )
				tmp.push( r[i] );
		}
		return tmp;
	},

	filter: function(t,r,not) {
		var last;

		// Look for common filter expressions
		while ( t && t != last ) {
			last = t;

			var p = jQuery.parse, m;

			for ( var i = 0; p[i]; i++ ) {
				m = p[i].exec( t );

				if ( m ) {
					// Remove what we just matched
					t = t.substring( m[0].length );

					m[2] = m[2].replace(/\\/g, "");
					break;
				}
			}

			if ( !m )
				break;

			// :not() is a special case that can be optimized by
			// keeping it out of the expression list
			if ( m[1] == ":" && m[2] == "not" )
				// optimize if only one selector found (most common case)
				r = isSimple.test( m[3] ) ?
					jQuery.filter(m[3], r, true).r :
					jQuery( r ).not( m[3] );

			// We can get a big speed boost by filtering by class here
			else if ( m[1] == "." )
				r = jQuery.classFilter(r, m[2], not);

			else if ( m[1] == "[" ) {
				var tmp = [], type = m[3];

				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];

					if ( z == null || /href|src|selected/.test(m[2]) )
						z = jQuery.attr(a,m[2]) || '';

					if ( (type == "" && !!z ||
						 type == "=" && z == m[5] ||
						 type == "!=" && z != m[5] ||
						 type == "^=" && z && !z.indexOf(m[5]) ||
						 type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
						 (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
							tmp.push( a );
				}

				r = tmp;

			// We can get a speed boost by handling nth-child here
			} else if ( m[1] == ":" && m[2] == "nth-child" ) {
				var merge = {}, tmp = [],
					// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
					test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
						m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
						!/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
					// calculate the numbers (first)n+(last) including if they are negative
					first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;

				// loop through all the elements left in the jQuery object
				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);

					if ( !merge[id] ) {
						var c = 1;

						for ( var n = parentNode.firstChild; n; n = n.nextSibling )
							if ( n.nodeType == 1 )
								n.nodeIndex = c++;

						merge[id] = true;
					}

					var add = false;

					if ( first == 0 ) {
						if ( node.nodeIndex == last )
							add = true;
					} else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
						add = true;

					if ( add ^ not )
						tmp.push( node );
				}

				r = tmp;

			// Otherwise, find the expression to execute
			} else {
				var f = jQuery.expr[m[1]];
				if ( typeof f != "string" )
					f = jQuery.expr[m[1]][m[2]];

				// Build a custom macro to enclose it
				f = eval("false||function(a,i){return " + f + "}");

				// Execute it against the current filter
				r = jQuery.grep( r, f, not );
			}
		}

		// Return an array of filtered elements (r)
		// and the modified expression string (t)
		return { r: r, t: t };
	},

	dir: function( elem, dir ){
		var matched = [];
		var cur = elem[dir];
		while ( cur && cur != document ) {
			if ( cur.nodeType == 1 )
				matched.push( cur );
			cur = cur[dir];
		}
		return matched;
	},

	nth: function(cur,result,dir,elem){
		result = result || 1;
		var num = 0;

		for ( ; cur; cur = cur[dir] )
			if ( cur.nodeType == 1 && ++num == result )
				break;

		return cur;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType == 1 && (!elem || n != elem) )
				r.push( n );
		}

		return r;
	}
});

<commit_msg>Fixed #2077 by adding a var to make it a local variable instead of initializing a global one.<commit_after>
var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
		"(?:[\\w*_-]|\\\\.)" :
		"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
	quickChild = new RegExp("^>\\s*(" + chars + "+)"),
	quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
	quickClass = new RegExp("^([#.]?)(" + chars + "*)");

jQuery.extend({
	expr: {
		"": "m[2]=='*'||jQuery.nodeName(a,m[2])",
		"#": "a.getAttribute('id')==m[2]",
		":": {
			// Position Checks
			lt: "i<m[3]-0",
			gt: "i>m[3]-0",
			nth: "m[3]-0==i",
			eq: "m[3]-0==i",
			first: "i==0",
			last: "i==r.length-1",
			even: "i%2==0",
			odd: "i%2",

			// Child Checks
			"first-child": "a.parentNode.getElementsByTagName('*')[0]==a",
			"last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
			"only-child": "!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",

			// Parent Checks
			parent: "a.firstChild",
			empty: "!a.firstChild",

			// Text Check
			contains: "(a.textContent||a.innerText||jQuery(a).text()||'').indexOf(m[3])>=0",

			// Visibility
			visible: '"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
			hidden: '"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',

			// Form attributes
			enabled: "!a.disabled",
			disabled: "a.disabled",
			checked: "a.checked",
			selected: "a.selected||jQuery.attr(a,'selected')",

			// Form elements
			text: "'text'==a.type",
			radio: "'radio'==a.type",
			checkbox: "'checkbox'==a.type",
			file: "'file'==a.type",
			password: "'password'==a.type",
			submit: "'submit'==a.type",
			image: "'image'==a.type",
			reset: "'reset'==a.type",
			button: '"button"==a.type||jQuery.nodeName(a,"button")',
			input: "/input|select|textarea|button/i.test(a.nodeName)",

			// :has()
			has: "jQuery.find(m[3],a).length",

			// :header
			header: "/h\\d/i.test(a.nodeName)",

			// :animated
			animated: "jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length"
		}
	},

	// The regular expressions that power the parsing engine
	parse: [
		// Match: [@value='test'], [@foo]
		/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,

		// Match: :contains('foo')
		/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,

		// Match: :even, :last-chlid, #id, .class
		new RegExp("^([:.#]*)(" + chars + "+)")
	],

	multiFilter: function( expr, elems, not ) {
		var old, cur = [];

		while ( expr && expr != old ) {
			old = expr;
			var f = jQuery.filter( expr, elems, not );
			expr = f.t.replace(/^\s*,\s*/, "" );
			cur = not ? elems = f.r : jQuery.merge( cur, f.r );
		}

		return cur;
	},

	find: function( t, context ) {
		// Quickly handle non-string expressions
		if ( typeof t != "string" )
			return [ t ];

		// check to make sure context is a DOM element or a document
		if ( context && context.nodeType != 1 && context.nodeType != 9)
			return [ ];

		// Set the correct context (if none is provided)
		context = context || document;

		// Initialize the search
		var ret = [context], done = [], last, nodeName;

		// Continue while a selector expression exists, and while
		// we're no longer looping upon ourselves
		while ( t && last != t ) {
			var r = [];
			last = t;

			t = jQuery.trim(t);

			var foundToken = false;

			// An attempt at speeding up child selectors that
			// point to a specific element tag
			var re = quickChild;
			var m = re.exec(t);

			if ( m ) {
				nodeName = m[1].toUpperCase();

				// Perform our own iteration and filter
				for ( var i = 0; ret[i]; i++ )
					for ( var c = ret[i].firstChild; c; c = c.nextSibling )
						if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
							r.push( c );

				ret = r;
				t = t.replace( re, "" );
				if ( t.indexOf(" ") == 0 ) continue;
				foundToken = true;
			} else {
				re = /^([>+~])\s*(\w*)/i;

				if ( (m = re.exec(t)) != null ) {
					r = [];

					var merge = {};
					nodeName = m[2].toUpperCase();
					m = m[1];

					for ( var j = 0, rl = ret.length; j < rl; j++ ) {
						var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
						for ( ; n; n = n.nextSibling )
							if ( n.nodeType == 1 ) {
								var id = jQuery.data(n);

								if ( m == "~" && merge[id] ) break;

								if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
									if ( m == "~" ) merge[id] = true;
									r.push( n );
								}

								if ( m == "+" ) break;
							}
					}

					ret = r;

					// And remove the token
					t = jQuery.trim( t.replace( re, "" ) );
					foundToken = true;
				}
			}

			// See if there's still an expression, and that we haven't already
			// matched a token
			if ( t && !foundToken ) {
				// Handle multiple expressions
				if ( !t.indexOf(",") ) {
					// Clean the result set
					if ( context == ret[0] ) ret.shift();

					// Merge the result sets
					done = jQuery.merge( done, ret );

					// Reset the context
					r = ret = [context];

					// Touch up the selector string
					t = " " + t.substr(1,t.length);

				} else {
					// Optimize for the case nodeName#idName
					var re2 = quickID;
					var m = re2.exec(t);

					// Re-organize the results, so that they're consistent
					if ( m ) {
						m = [ 0, m[2], m[3], m[1] ];

					} else {
						// Otherwise, do a traditional filter check for
						// ID, class, and element selectors
						re2 = quickClass;
						m = re2.exec(t);
					}

					m[2] = m[2].replace(/\\/g, "");

					var elem = ret[ret.length-1];

					// Try to do a global search by ID, where we can
					if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
						// Optimization for HTML document case
						var oid = elem.getElementById(m[2]);

						// Do a quick check for the existence of the actual ID attribute
						// to avoid selecting by the name attribute in IE
						// also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
						if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
							oid = jQuery('[@id="'+m[2]+'"]', elem)[0];

						// Do a quick check for node name (where applicable) so
						// that div#foo searches will be really fast
						ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
					} else {
						// We need to find all descendant elements
						for ( var i = 0; ret[i]; i++ ) {
							// Grab the tag name being searched for
							var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];

							// Handle IE7 being really dumb about <object>s
							if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
								tag = "param";

							r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
						}

						// It's faster to filter by class and be done with it
						if ( m[1] == "." )
							r = jQuery.classFilter( r, m[2] );

						// Same with ID filtering
						if ( m[1] == "#" ) {
							var tmp = [];

							// Try to find the element with the ID
							for ( var i = 0; r[i]; i++ )
								if ( r[i].getAttribute("id") == m[2] ) {
									tmp = [ r[i] ];
									break;
								}

							r = tmp;
						}

						ret = r;
					}

					t = t.replace( re2, "" );
				}

			}

			// If a selector string still exists
			if ( t ) {
				// Attempt to filter it
				var val = jQuery.filter(t,r);
				ret = r = val.r;
				t = jQuery.trim(val.t);
			}
		}

		// An error occurred with the selector;
		// just return an empty set instead
		if ( t )
			ret = [];

		// Remove the root context
		if ( ret && context == ret[0] )
			ret.shift();

		// And combine the results
		done = jQuery.merge( done, ret );

		return done;
	},

	classFilter: function(r,m,not){
		m = " " + m + " ";
		var tmp = [];
		for ( var i = 0; r[i]; i++ ) {
			var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
			if ( !not && pass || not && !pass )
				tmp.push( r[i] );
		}
		return tmp;
	},

	filter: function(t,r,not) {
		var last;

		// Look for common filter expressions
		while ( t && t != last ) {
			last = t;

			var p = jQuery.parse, m;

			for ( var i = 0; p[i]; i++ ) {
				m = p[i].exec( t );

				if ( m ) {
					// Remove what we just matched
					t = t.substring( m[0].length );

					m[2] = m[2].replace(/\\/g, "");
					break;
				}
			}

			if ( !m )
				break;

			// :not() is a special case that can be optimized by
			// keeping it out of the expression list
			if ( m[1] == ":" && m[2] == "not" )
				// optimize if only one selector found (most common case)
				r = isSimple.test( m[3] ) ?
					jQuery.filter(m[3], r, true).r :
					jQuery( r ).not( m[3] );

			// We can get a big speed boost by filtering by class here
			else if ( m[1] == "." )
				r = jQuery.classFilter(r, m[2], not);

			else if ( m[1] == "[" ) {
				var tmp = [], type = m[3];

				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];

					if ( z == null || /href|src|selected/.test(m[2]) )
						z = jQuery.attr(a,m[2]) || '';

					if ( (type == "" && !!z ||
						 type == "=" && z == m[5] ||
						 type == "!=" && z != m[5] ||
						 type == "^=" && z && !z.indexOf(m[5]) ||
						 type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
						 (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
							tmp.push( a );
				}

				r = tmp;

			// We can get a speed boost by handling nth-child here
			} else if ( m[1] == ":" && m[2] == "nth-child" ) {
				var merge = {}, tmp = [],
					// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
					test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
						m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
						!/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
					// calculate the numbers (first)n+(last) including if they are negative
					first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;

				// loop through all the elements left in the jQuery object
				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);

					if ( !merge[id] ) {
						var c = 1;

						for ( var n = parentNode.firstChild; n; n = n.nextSibling )
							if ( n.nodeType == 1 )
								n.nodeIndex = c++;

						merge[id] = true;
					}

					var add = false;

					if ( first == 0 ) {
						if ( node.nodeIndex == last )
							add = true;
					} else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
						add = true;

					if ( add ^ not )
						tmp.push( node );
				}

				r = tmp;

			// Otherwise, find the expression to execute
			} else {
				var f = jQuery.expr[m[1]];
				if ( typeof f != "string" )
					f = jQuery.expr[m[1]][m[2]];

				// Build a custom macro to enclose it
				f = eval("false||function(a,i){return " + f + "}");

				// Execute it against the current filter
				r = jQuery.grep( r, f, not );
			}
		}

		// Return an array of filtered elements (r)
		// and the modified expression string (t)
		return { r: r, t: t };
	},

	dir: function( elem, dir ){
		var matched = [];
		var cur = elem[dir];
		while ( cur && cur != document ) {
			if ( cur.nodeType == 1 )
				matched.push( cur );
			cur = cur[dir];
		}
		return matched;
	},

	nth: function(cur,result,dir,elem){
		result = result || 1;
		var num = 0;

		for ( ; cur; cur = cur[dir] )
			if ( cur.nodeType == 1 && ++num == result )
				break;

		return cur;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType == 1 && (!elem || n != elem) )
				r.push( n );
		}

		return r;
	}
});

<|endoftext|>


<commit_before>var auth = require('../../lib/auth');
var db = require('../../db');
var user = require('../../lib/user');

module.exports = function(server) {
    // Sample usage:
    // % curl -X POST 'http://localhost:5000/user/acl' -d 'id=1&dev=1&reviewer=1&admin=1'
    // TODO: Make sure only admins can do this
    server.post({
        url: '/user/acl',
        validation: {
            _user: {
                description: "A user's SSA token",
                isRequired: true
            },
            id: {
                description: 'User ID to change permissions for',
                isRequired: true
            },
            dev: {
                description: 'Whether or not user should have developer permissions',
                isRequired: true,
                isIn: ['0', '1']
            },
            reviewer: {
                description: 'Whether or not user should have reviewer permissions',
                isRequired: true,
                isIn: ['0', '1']
            },
            admin: {
                description: 'Whether or not user should have admin permissions',
                isRequired: false,
                isIn: ['0', '1']
            }
        },
        swagger: {
            nickname: 'acl',
            notes: 'Update User Permissions',
            summary: 'ACL'
        }
    }, db.redisView(function(client, done, req, res) {
        var POST = req.params;

        var userID = POST.id;
        // Convert from string to bool
        var isDev = !!+POST.dev;
        var isRev = !!+POST.reviewer;
        var isAdmin = !!+POST.admin;
        var _user = POST._user;

        var email = auth.verifySSA(_user);
        if (!email) {
            res.json(403, {error: 'bad_user'});
            done();
            return;
        }

        // Get user who is sending request and make sure it is an admin
        user.getUserFromEmail(client, email, function(err, authenticator) {
            if (err || !authenticator) {
                res.json(500, {error: 'db_error'});
                done();
                return;
            }

            // make sure it is admin
            if (!authenticator.permissions.admin) {
                res.json(403, {error: 'authenticator does not have admin permissions'});
                done();
                return;
            }

            // update permissions of target user
            user.getUserFromID(client, userID, function(err, resp) {
                if (err || !resp) {
                    res.json(500, {error: 'db_error'});
                    done();
                    return;
                }

                user.updateUser(client, resp, {
                    permissions: {
                      developer: isDev,
                      reviewer: isRev,
                      admin: isAdmin
                    }
                }, function(err, newData) {
                    if (err) {
                        res.json(500, {error: err});
                    } else {
                        res.json(200, {permissions: newData.permissions});
                    }
                    done();
                });

            });
        });
<<<<<<< HEAD
    })
    );
=======
    }));
>>>>>>> small fix to acl
};
<commit_msg>Update acl.js<commit_after>var auth = require('../../lib/auth');
var db = require('../../db');
var user = require('../../lib/user');

module.exports = function(server) {
    // Sample usage:
    // % curl -X POST 'http://localhost:5000/user/acl' -d 'id=1&dev=1&reviewer=1&admin=1'
    // TODO: Make sure only admins can do this
    server.post({
        url: '/user/acl',
        validation: {
            _user: {
                description: "A user's SSA token",
                isRequired: true
            },
            id: {
                description: 'User ID to change permissions for',
                isRequired: true
            },
            dev: {
                description: 'Whether or not user should have developer permissions',
                isRequired: true,
                isIn: ['0', '1']
            },
            reviewer: {
                description: 'Whether or not user should have reviewer permissions',
                isRequired: true,
                isIn: ['0', '1']
            },
            admin: {
                description: 'Whether or not user should have admin permissions',
                isRequired: false,
                isIn: ['0', '1']
            }
        },
        swagger: {
            nickname: 'acl',
            notes: 'Update User Permissions',
            summary: 'ACL'
        }
    }, db.redisView(function(client, done, req, res) {
        var POST = req.params;

        var userID = POST.id;
        // Convert from string to bool
        var isDev = !!+POST.dev;
        var isRev = !!+POST.reviewer;
        var isAdmin = !!+POST.admin;
        var _user = POST._user;

        var email = auth.verifySSA(_user);
        if (!email) {
            res.json(403, {error: 'bad_user'});
            done();
            return;
        }

        // Get user who is sending request and make sure it is an admin
        user.getUserFromEmail(client, email, function(err, authenticator) {
            if (err || !authenticator) {
                res.json(500, {error: 'db_error'});
                done();
                return;
            }

            // make sure it is admin
            if (!authenticator.permissions.admin) {
                res.json(403, {error: 'bad_permission'});
                done();
                return;
            }

            // update permissions of target user
            user.getUserFromID(client, userID, function(err, resp) {
                if (err || !resp) {
                    res.json(500, {error: 'db_error'});
                    done();
                    return;
                }

                user.updateUser(client, resp, {
                    permissions: {
                      developer: isDev,
                      reviewer: isRev,
                      admin: isAdmin
                    }
                }, function(err, newData) {
                    if (err) {
                        res.json(500, {error: err});
                    } else {
                        res.json(200, {permissions: newData.permissions});
                    }
                    done();
                });

            });
        });
    }));
};
<|endoftext|>


<commit_before>var utility = require('../utility');
var classMapping = require('./mapping')['classes'];

let semesterAccount = 'nus-cs2103-AY1617S2';

module.exports = (accuser, repoName) => {
  let warnInvalidTitle = (repository, issue) => {
    if (hasFormatCheckRequestedLabel(issue)) {
      return;
    }

    console.log("Adding warning for format fail to PR #" + issue.number);
    accuser.addLabels(repo, issue, ["FormatCheckRequested"]);
    var comment = "Hi @" + issue.user.login + ", your pull request title is invalid."
      + " It should be in the format of `[Activity ID][Team ID] Your name`,"
      + " where `[Activity Id]` has no dashes or spaces (e.g. `[T2A3]` stands"
      + " for Tutorial 2 Activity 3) and `[Team ID]` has one dash only and no"
      + " spaces (e.g. `[W14-A2]` means Wednesday 2pm (14 hrs), Phase A, Team 2)."
      + " Please follow the instructions given strictly and edit your title for reprocessing."
      + "\n\nSubmit only one activity per pull request (unless otherwise stated in instructions) and"
      + " do remember to create your branches from the commit where the `master` branch is pointing at so that each "
      + " PR you submit only consist of commits meant for the activity."
      + "\n\nNote: this comment is posted by a bot. If you believe this is done in error, please"
      + " create an issue at [cs2103-pr-bot](https://github.com/mauris/cs2103-pr-bot/issues) and add a link to this PR."
    accuser.comment(repository, issue, comment);
  };

  var hasFormatCheckRequestedLabel = (issue) => {
    var result = false;
    issue.labels.forEach(function(label){
      if (label.name.toLowerCase() == FormatCheckLabel.toLowerCase()) {
        result = true;
      }
    });
    return result;
  };

  let assignTutor = (repository, issue, tutor) => {
    if (!tutor) {
      console.log('no tutor found for PR #' + issue.number);
      return;
    }

    console.log("Assigning tutors to PR #" + issue.number);
    accuser.accuse(repository, issue, tutor);
  };

  let repo = accuser.addRepository(semesterAccount, repoName);
  let FormatCheckLabel = "FormatCheckRequested";

  repo.newWorker()
    .filter((repository, issue) => {
      // ensure that we only work with PRs that do not have an assignee
      return issue.pull_request;
    })
    .do((repository, issue) => {
      console.log("Looking at PR #" + issue.number);
      var result = utility._titleRegex.exec(issue.title);

      if (result === null) {
        console.log('Cannot parse title of PR #' + issue.number);
        // we ignore the PR if we cannot parse the title into our issuee-defined regex
        warnInvalidTitle(repository, issue);
        return;
      }

      var activityId = result[1];
      var classId = result[2];
      var teamId = result[4];

      if (!classMapping[classId] || !teamId) {
        // the class ID fetched is invalid.
        console.log('wrong class or team ID for PR #' + issue.number);
        warnInvalidTitle(repository, issue);
        return;
      }

      //var tutor = classMapping[classId][teamId];
      //assignTutor(repository, issue, tutor);

      if (hasFormatCheckRequestedLabel(issue)) {
        console.log("Removing format check label from PR #" + issue.number);
        accuser.removeLabel(repository, issue, FormatCheckLabel);
      }
    });
};
<commit_msg>activated tutor assignment<commit_after>var utility = require('../utility');
var classMapping = require('./mapping')['classes'];

let semesterAccount = 'nus-cs2103-AY1617S2';

module.exports = (accuser, repoName) => {
  let warnInvalidTitle = (repository, issue) => {
    if (hasFormatCheckRequestedLabel(issue)) {
      return;
    }

    console.log("Adding warning for format fail to PR #" + issue.number);
    accuser.addLabels(repo, issue, ["FormatCheckRequested"]);
    var comment = "Hi @" + issue.user.login + ", your pull request title is invalid."
      + " It should be in the format of `[Activity ID][Team ID] Your name`,"
      + " where `[Activity Id]` has no dashes or spaces (e.g. `[T2A3]` stands"
      + " for Tutorial 2 Activity 3) and `[Team ID]` has one dash only and no"
      + " spaces (e.g. `[W14-A2]` means Wednesday 2pm (14 hrs), Phase A, Team 2)."
      + " Please follow the instructions given strictly and edit your title for reprocessing."
      + "\n\nSubmit only one activity per pull request (unless otherwise stated in instructions) and"
      + " do remember to create your branches from the commit where the `master` branch is pointing at so that each "
      + " PR you submit only consist of commits meant for the activity."
      + "\n\nNote: this comment is posted by a bot. If you believe this is done in error, please"
      + " create an issue at [cs2103-pr-bot](https://github.com/mauris/cs2103-pr-bot/issues) and add a link to this PR."
    accuser.comment(repository, issue, comment);
  };

  var hasFormatCheckRequestedLabel = (issue) => {
    var result = false;
    issue.labels.forEach(function(label){
      if (label.name.toLowerCase() == FormatCheckLabel.toLowerCase()) {
        result = true;
      }
    });
    return result;
  };

  let assignTutor = (repository, issue, tutor) => {
    if (!tutor) {
      console.log('no tutor found for PR #' + issue.number);
      return;
    }

    console.log("Assigning tutors to PR #" + issue.number);
    accuser.accuse(repository, issue, tutor);
  };

  let repo = accuser.addRepository(semesterAccount, repoName);
  let FormatCheckLabel = "FormatCheckRequested";

  repo.newWorker()
    .filter((repository, issue) => {
      // ensure that we only work with PRs that do not have an assignee
      return issue.pull_request;
    })
    .do((repository, issue) => {
      console.log("Looking at PR #" + issue.number);
      var result = utility._titleRegex.exec(issue.title);

      if (result === null) {
        console.log('Cannot parse title of PR #' + issue.number);
        // we ignore the PR if we cannot parse the title into our issuee-defined regex
        warnInvalidTitle(repository, issue);
        return;
      }

      var activityId = result[1];
      var classId = result[2];
      var teamId = result[4];

      if (!classMapping[classId] || !teamId) {
        // the class ID fetched is invalid.
        console.log('wrong class or team ID for PR #' + issue.number);
        warnInvalidTitle(repository, issue);
        return;
      }

      var tutor = classMapping[classId][teamId];
      assignTutor(repository, issue, tutor);

      if (hasFormatCheckRequestedLabel(issue)) {
        console.log("Removing format check label from PR #" + issue.number);
        accuser.removeLabel(repository, issue, FormatCheckLabel);
      }
    });
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const util = require('util');

const intel = require('intel');

const SYSLOG_LEVELS = {};

SYSLOG_LEVELS[intel.TRACE] = 7;
SYSLOG_LEVELS[intel.VERBOSE] = 7;
SYSLOG_LEVELS[intel.DEBUG] = 7;
SYSLOG_LEVELS[intel.INFO] = 6;
SYSLOG_LEVELS[intel.WARN] = 4;
SYSLOG_LEVELS[intel.ERROR] = 2;
SYSLOG_LEVELS[intel.CRITICAL] = 0;

function json(obj) {
  var seen = [];
  return JSON.stringify(obj, function filter(key, val) {
    if (seen.indexOf(val) !== -1) {
      return '[Circular]';
    }
    seen.push(val);
    return val;
  }, 0);
}

function serialize(val) {
  var t = typeof val;
  if (t === 'number' || t === 'string' || t === 'boolean') {
    // val is fine
  } else if (Buffer.isBuffer(val)) {
    val = val.toString('hex');
  } else {
    val = json(val);
  }
  return val;
}

function HekaFormatter(options) {
  options = options || {};
  options.format = '%O';
  options.colorize = false;
  intel.Formatter.call(this, options);
}
util.inherits(HekaFormatter, intel.Formatter);

HekaFormatter.prototype.format = function hekaFormat(record) {
  var nameParts = record.name.split('.');
  var logger = nameParts.shift();
  var args = record.args;
  nameParts.push(args[0]);

  var rec = {
    Timestamp: record.timestamp * 1000000,
    Logger: logger,
    Type: nameParts.join('.'),
    Hostname: record.hostname,
    Severity: SYSLOG_LEVELS[record.level],
    Pid: record.pid,
  };

  var payload = args[1];
  var fields = {};
  if (typeof payload === 'object') {
    for (var key in payload) {
      fields[key] = serialize(payload[key]);
    }
    rec.Fields = fields;
  } else if (payload) {
    fields.msg = payload;
    rec.Fields = fields;
  }

  return intel.Formatter.prototype.format.call(this, rec);
};

module.exports = HekaFormatter;
<commit_msg>specify envelope version<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const util = require('util');

const intel = require('intel');

const ENV_VERSION = "2.0";

const SYSLOG_LEVELS = {};

SYSLOG_LEVELS[intel.TRACE] = 7;
SYSLOG_LEVELS[intel.VERBOSE] = 7;
SYSLOG_LEVELS[intel.DEBUG] = 7;
SYSLOG_LEVELS[intel.INFO] = 6;
SYSLOG_LEVELS[intel.WARN] = 4;
SYSLOG_LEVELS[intel.ERROR] = 2;
SYSLOG_LEVELS[intel.CRITICAL] = 0;

function json(obj) {
  var seen = [];
  return JSON.stringify(obj, function filter(key, val) {
    if (seen.indexOf(val) !== -1) {
      return '[Circular]';
    }
    seen.push(val);
    return val;
  }, 0);
}

function serialize(val) {
  var t = typeof val;
  if (t === 'number' || t === 'string' || t === 'boolean') {
    // val is fine
  } else if (Buffer.isBuffer(val)) {
    val = val.toString('hex');
  } else {
    val = json(val);
  }
  return val;
}

function HekaFormatter(options) {
  options = options || {};
  options.format = '%O';
  options.colorize = false;
  intel.Formatter.call(this, options);
}
util.inherits(HekaFormatter, intel.Formatter);

HekaFormatter.prototype.format = function hekaFormat(record) {
  var nameParts = record.name.split('.');
  var logger = nameParts.shift();
  var args = record.args;
  nameParts.push(args[0]);

  var rec = {
    Timestamp: record.timestamp * 1000000,
    Logger: logger,
    Type: nameParts.join('.'),
    Hostname: record.hostname,
    Severity: SYSLOG_LEVELS[record.level],
    Pid: record.pid,
    EnvVersion: ENV_VERSION,
  };

  var payload = args[1];
  var fields = {};
  if (typeof payload === 'object') {
    for (var key in payload) {
      fields[key] = serialize(payload[key]);
    }
    rec.Fields = fields;
  } else if (payload) {
    fields.msg = payload;
    rec.Fields = fields;
  }

  return intel.Formatter.prototype.format.call(this, rec);
};

module.exports = HekaFormatter;
<|endoftext|>


<commit_before>var takeUntil = Redash.takeUntil

describe('(Function) takeUntil', function () {
  var _spies

  beforeEach(function () {
    _spies = {}
    _spies.not5 = sinon.stub()
    _spies.not5.returns(false)
    _spies.not5.withArgs(5).returns(true)
  })

  it('Should be a function.', function () {
    expect(takeUntil).to.be.a('function')
  })

  it('Should be curried.', function () {
    expect(takeUntil()).to.be.a('function')
  })

  it('Should return all items until the predicate matches (exclusive).', function () {
    expect(takeUntil(_spies.not5)([1,2,3,4,5,6,7,8])).to.deep.equal([1,2,3,4])
  })

  it('Should return a new array even if it\'s identical to the input.', function () {
    var arr = [1,2,3,4]
    var res = takeUntil(_spies.not5, [1,2,3,4])

    expect(res).to.deep.equal([1,2,3,4])
    expect(res).to.not.equal(arr)
  })
})
<commit_msg>chore(takeUntil): cleanup tests<commit_after>var takeUntil = Redash.takeUntil

describe('(Function) takeUntil', function () {
  it('Should be a binary function that reports its arity', function () {
    takeUntil
      .should.have.length(2)
  })

  it('Should be curried', function () {
    takeUntil(function () {})
      .should.be.a('function')
  })

  it('Should return all items until the predicate matches (exclusive)', function () {
    var is5 = function (x) { return x === 5 }

    takeUntil(is5, [1,2,3,4,5,6,7,8])
      .should.deep.equal([1,2,3,4])
  })

  it('Should short circuit', function () {
    var is5 = sinon.spy(function (x) { return x === 5 })

    takeUntil(is5, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    is5.callCount.should.equal(5)
  })

  it('Should return a new array even if it\'s identical to the input', function () {
    var arr = [1,2,3,4]
    var res = takeUntil(function () { return false }, [1,2,3,4])

    res.should.deep.equal([1,2,3,4])
    res.should.not.equal(arr)
  })
})
<|endoftext|>


<commit_before>'use strict'

const ivp="initial value problem"

module.exports=(nt)=>({
	sn: {
		parents: {},
		name: "system of n first-order",
		htmlName: "system of n first-order",
		importance: 3,
		equation:
			`\\left\\{ \\begin{array}{c}`+
				`${nt.dd(`${nt.x}_1`)} = f_1(t,${nt.x}_1,\\dotsc,${nt.x}_n) \\\\`+
				`\\vdots \\\\`+
				`${nt.dd(`${nt.x}_n`)} = f_n(t,${nt.x}_1,\\dotsc,${nt.x}_n)`+
			`\\end{array} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{F}(t,${nt.X})`,
		traits: {
			testSolutionMethod: {
				content: [
					`Can test if \\( ${nt.X}_p \\) is a solution by substituting \\( ${nt.X} = ${nt.X}_p \\) into the equation.`,
				],
			},
		},
	},
	s2: {
		parents: {
			sn: true,
		},
		name: "system of 2 first-order",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= f(t,${nt.x},${nt.y}) \\\\`+
				`${nt.dd(nt.y)} &= g(t,${nt.x},${nt.y})`+
			`\\end{aligned} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{F}(t,${nt.X})`,
		traits: {},
	},
	s2_partlyDecoupled: {
		parents: {
			s2: true,
		},
		name: "partly decoupled system of 2 first-order",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= f(t,${nt.x},${nt.y}) \\\\`+
				`${nt.dd(nt.y)} &= g(t,${nt.y})`+
			`\\end{aligned} \\right.`,
		traits: {
			generalSolutionMethod: {
				form: true,
				content: [
					`Solve \\(${nt.dd(nt.y)} = g(t,${nt.y}) \\).`,
					`Substitute \\( ${nt.y} \\) into \\( ${nt.dd(nt.x)} = f(t,${nt.x},${nt.y}) \\).`,
				],
			},
		},
	},
	s2_autonomous: {
		parents: {
			s2: true,
		},
		name: "system of 2 first-order autonomous",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= f(${nt.x},${nt.y}) \\\\`+
				`${nt.dd(nt.y)} &= g(${nt.x},${nt.y})`+
			`\\end{aligned} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{F}(${nt.X})`,
		traits: {},
	},
	s2_linearHomogeneousConstant: {
		parents: {
			s2_autonomous: true,
		},
		name: "system of 2 first-order linear homogeneous equations with constant coefficients",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= a_{${nt.x}${nt.x}} ${nt.x} + a_{${nt.x}${nt.y}} ${nt.y} \\\\`+
				`${nt.dd(nt.y)} &= a_{${nt.y}${nt.x}} ${nt.x} + a_{${nt.y}${nt.y}} ${nt.y}`+
			`\\end{aligned} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{A} ${nt.X}`,
		traits: {
			characteristicEquation: {
				form: true,
				content: [
					`\\[ \\det(\\mathbf{A} - \\lambda \\mathbf{I}) = 0 \\]`,
					{type:'note',content:[
						`\\( \\lambda \\) is an eigenvalue of \\( \\mathbf{A} \\)`,
					]},
				],
			},
			generalSolutionMethod: {
				form: true,
				content: [
					`includes ${ivp} solution with initial conditions: \\( ${nt.x}_0 = ${nt.x}(0) \\), \\( ${nt.y}_0 = ${nt.y}(0) \\)`,
					{type:'cases',content:[
						{type:'case',title:`\\( a_{${nt.x}${nt.y}} = a_{${nt.y}${nt.x}} = 0 \\)`,content:[
							`the equation has the form:`,
							`\\[ ${nt.ddt} ${nt.vec2(nt.x,nt.y)} = ${nt.mat2('\\lambda_1',0,0,'\\lambda_2')} ${nt.vec2(nt.x,nt.y)} \\]`,
							`general solution (with arbitrary constants \\( ${nt.x}_0 \\), \\( ${nt.y}_0 \\)) and ${ivp} solution:`,
							`\\[ ${nt.X} = ${nt.x}_0 e^{\\lambda_1 t} ${nt.vec2(1,0)} + ${nt.y}_0 e^{\\lambda_2 t} ${nt.vec2(0,1)} \\]`,
						]},
						{type:'case',title:`\\( a_{${nt.x}${nt.y}} \\neq 0 \\) or \\( a_{${nt.y}${nt.x}} \\neq 0 \\)`,content:[
							`get eigenvalues by solving the characteristic equation for \\( \\lambda \\):`,
							`\\[ \\det(\\mathbf{A} - \\lambda \\mathbf{I}) = 0 \\]`,
							{type:'cases',content:[
								{type:'case',title:`repeated \\( \\lambda \\)`,content:[
									`general solution (with arbitrary constants \\( ${nt.x}_0 \\), \\( ${nt.y}_0 \\)) and ${ivp} solution:`,
									`\\[ ${nt.X} = e^{\\lambda t} ${nt.vec2(nt.x+'_0',nt.y+'_0')} + t e^{\\lambda t} (\\mathbf{A} - \\lambda \\mathbf{I}) ${nt.vec2(nt.x+'_0',nt.y+'_0')} \\]`,
								]},
								{type:'case',title:`real distinct \\( \\lambda_1 \\), \\( \\lambda_2 \\)`,content:[
									`find eigenvector \\( ${nt.svec2(`${nt.x}_1`,`${nt.y}_1`)} \\) by solving:`,
									`\\[ (\\mathbf{A} - \\lambda_1 \\mathbf{I}) ${nt.vec2(`${nt.x}_1`,`${nt.y}_1`)} = 0 \\]`,
									`find eigenvector \\( ${nt.svec2(`${nt.x}_2`,`${nt.y}_2`)} \\) by solving:`,
									`\\[ (\\mathbf{A} - \\lambda_2 \\mathbf{I}) ${nt.vec2(`${nt.x}_2`,`${nt.y}_2`)} = 0 \\]`,
									`general solution (with arbitrary constants \\( k_1 \\), \\( k_2 \\)):`,
									`\\[ ${nt.X} = k_1 e^{\\lambda_1 t} ${nt.vec2(`${nt.x}_1`,`${nt.y}_1`)} + k_2 e^{\\lambda_2 t} ${nt.vec2(`${nt.x}_2`,`${nt.y}_2`)} \\]`,
									`get constants \\( k_1 \\), \\( k_2 \\) for ${ivp} solution by solving:`,
									`\\[ ${nt.mat2(`${nt.x}_1`,`${nt.x}_2`,`${nt.y}_1`,`${nt.y}_2`)} ${nt.vec2('k_1','k_2')} = ${nt.vec2(`${nt.x}_0`,`${nt.y}_0`)} \\]`,
								]},
								{type:'case',title:`complex conjugate pair \\( \\lambda = \\alpha \\pm i \\beta \\)`,content:[
									`select either \\( \\alpha + i \\beta \\) or \\( \\alpha - i \\beta \\) as \\( \\lambda_1 \\)`,
									`find complex-valued eigenvector \\( ${nt.svec2(`${nt.x}_1 + i ${nt.x}_2`,`${nt.y}_1 + i ${nt.y}_2`)} \\) by solving:`,
									`\\[ (\\mathbf{A} - \\lambda_1 \\mathbf{I}) ${nt.vec2(`${nt.x}_1 + i ${nt.x}_2`,`${nt.y}_1 + i ${nt.y}_2`)} = 0 \\]`,
									`one of complex-valued solutions:`,
									`\\[ ${nt.X}_c = e^{\\alpha t} (\\cos \\beta t + i \\sin \\beta t) ${nt.svec2(`${nt.x}_1 + i ${nt.x}_2`,`${nt.y}_1 + i ${nt.y}_2`)} \\]`,
									`general solution (with arbitrary constants \\( k_1 \\), \\( k_2 \\)):`,
									`\\[ ${nt.X} = k_1 \\Re ${nt.X}_c + k_2 \\Im ${nt.X}_c \\]`,
									`\\[ \\begin{aligned} `+
										`${nt.X} = \\: & k_1 ${nt.vec2(`${nt.x}_1 \\cos \\beta t - ${nt.x}_2 \\sin \\beta t`,`${nt.y}_1 \\cos \\beta t - ${nt.y}_2 \\sin \\beta t`)} \\\\`+
										        `+ \\: & k_2 ${nt.vec2(`${nt.x}_1 \\sin \\beta t + ${nt.x}_2 \\cos \\beta t`,`${nt.y}_1 \\sin \\beta t + ${nt.y}_2 \\cos \\beta t`)} `+
									`\\end{aligned} \\]`,
									`get constants \\( k_1 \\), \\( k_2 \\) for ${ivp} solution by solving:`,
									`\\[ ${nt.mat2(`${nt.x}_1`,`${nt.x}_2`,`${nt.y}_1`,`${nt.y}_2`)} ${nt.vec2('k_1','k_2')} = ${nt.vec2(`${nt.x}_0`,`${nt.y}_0`)} \\]`,
								]},
							]},
						]},
					]},
				],
			}
		},
	},
	sn_sir: {
		parents: {
			sn: true,
		},
		name: "SIR model",
		htmlName: "SIR model",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd('S')} &= -\\alpha S I \\\\`+
				`${nt.dd('I')} &= \\alpha S I - \\beta I \\\\ `+
				`${nt.dd('R')} &= \\beta I`+
			`\\end{aligned} \\right.`,
		equationNotes: [
			`\\( S = \\) number susceptible`,
			`\\( I = \\) number infectious`,
			`\\( R = \\) number recovered (immune)`,
			`\\( \\alpha = \\) contact rate`,
			`\\( \\beta = \\) recovery rate`,
			`all quantities are nonnegative`,
		],
		traits: {
			phaseSolutionMethod: {
				form: true,
				content: [
					`threshold value \\( \\rho = \\frac\\beta\\alpha \\):`,
					`\\( I \\) increases when \\( S > \\rho \\)`,
					`\\( S \\) decreases`,
					`\\( I \\) attains its maximum when \\( S = \\rho \\)`,
					{type:'derivation',content:[
						`\\[ ${nt.dd('S')} + ${nt.dd('I')} + ${nt.dd('R')} = 0 \\]`,
						`total population \\( N \\) is constant`,
						`\\[ S + I + R = N \\]`,
						`eliminate \\( R \\)`,
						`\\[ \\left\\{ \\begin{aligned} `+
							`${nt.dd('S')} &= -\\alpha S I \\\\ `+
							`${nt.dd('I')} &= \\alpha S I - \\beta I \\\\ `+
						`\\end{aligned} \\right. \\]`,
						`\\[ ${nt.dd('I','S')} = \\frac{\\alpha S I - \\beta I}{-\\alpha S I} = -1 + \\frac{\\rho}{S} \\]`,
						`integrate by \\( S \\)`,
						`\\[ I = -S + \\rho \\ln S + C \\]`,
					]},
					`conserved quantities:`,
					`\\[ \\begin{multline}`+
						`S(t) + I(t) + R(t) = \\\\ `+
						`= S(0) + I(0) + R(0) `+
					`\\end{multline} \\]`,
					`\\[ \\begin{multline}`+
						`I(t) + S(t) - \\rho \\ln S(t) = \\\\ `+
						`= I(0) + S(0) - \\rho \\ln S(0) `+
					`\\end{multline} \\]`,
					`maximum of \\( I \\):`,
					`\\[ \\begin{multline}`+
						`I_{max} + \\rho - \\rho \\ln \\rho = \\\\ `+
						`= I(0) + S(0) - \\rho \\ln S(0) `+
					`\\end{multline} \\]`,
				],
			},
			equilibriumSolutionMethod: {
				form: true,
				content: [
					`\\[ I = 0 \\]`,
				],
			},
		},
	},
})
<commit_msg>fix: 2d linear const coef solution<commit_after>'use strict'

const ivp="initial value problem"

module.exports=(nt)=>({
	sn: {
		parents: {},
		name: "system of n first-order",
		htmlName: "system of n first-order",
		importance: 3,
		equation:
			`\\left\\{ \\begin{array}{c}`+
				`${nt.dd(`${nt.x}_1`)} = f_1(t,${nt.x}_1,\\dotsc,${nt.x}_n) \\\\`+
				`\\vdots \\\\`+
				`${nt.dd(`${nt.x}_n`)} = f_n(t,${nt.x}_1,\\dotsc,${nt.x}_n)`+
			`\\end{array} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{F}(t,${nt.X})`,
		traits: {
			testSolutionMethod: {
				content: [
					`Can test if \\( ${nt.X}_p \\) is a solution by substituting \\( ${nt.X} = ${nt.X}_p \\) into the equation.`,
				],
			},
		},
	},
	s2: {
		parents: {
			sn: true,
		},
		name: "system of 2 first-order",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= f(t,${nt.x},${nt.y}) \\\\`+
				`${nt.dd(nt.y)} &= g(t,${nt.x},${nt.y})`+
			`\\end{aligned} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{F}(t,${nt.X})`,
		traits: {},
	},
	s2_partlyDecoupled: {
		parents: {
			s2: true,
		},
		name: "partly decoupled system of 2 first-order",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= f(t,${nt.x},${nt.y}) \\\\`+
				`${nt.dd(nt.y)} &= g(t,${nt.y})`+
			`\\end{aligned} \\right.`,
		traits: {
			generalSolutionMethod: {
				form: true,
				content: [
					`Solve \\(${nt.dd(nt.y)} = g(t,${nt.y}) \\).`,
					`Substitute \\( ${nt.y} \\) into \\( ${nt.dd(nt.x)} = f(t,${nt.x},${nt.y}) \\).`,
				],
			},
		},
	},
	s2_autonomous: {
		parents: {
			s2: true,
		},
		name: "system of 2 first-order autonomous",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= f(${nt.x},${nt.y}) \\\\`+
				`${nt.dd(nt.y)} &= g(${nt.x},${nt.y})`+
			`\\end{aligned} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{F}(${nt.X})`,
		traits: {},
	},
	s2_linearHomogeneousConstant: {
		parents: {
			s2_autonomous: true,
		},
		name: "system of 2 first-order linear homogeneous equations with constant coefficients",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd(nt.x)} &= a_{${nt.x}${nt.x}} ${nt.x} + a_{${nt.x}${nt.y}} ${nt.y} \\\\`+
				`${nt.dd(nt.y)} &= a_{${nt.y}${nt.x}} ${nt.x} + a_{${nt.y}${nt.y}} ${nt.y}`+
			`\\end{aligned} \\right.`,
		vectorEquation: `${nt.dd(nt.X)} = \\mathbf{A} ${nt.X}`,
		traits: {
			characteristicEquation: {
				form: true,
				content: [
					`\\[ \\det(\\mathbf{A} - \\lambda \\mathbf{I}) = 0 \\]`,
					{type:'note',content:[
						`\\( \\lambda \\) is an eigenvalue of \\( \\mathbf{A} \\)`,
					]},
				],
			},
			generalSolutionMethod: {
				form: true,
				content: [
					`includes ${ivp} solution with initial conditions: \\( ${nt.x}_0 = ${nt.x}(0) \\), \\( ${nt.y}_0 = ${nt.y}(0) \\)`,
					{type:'cases',content:[
						{type:'case',title:`\\( a_{${nt.x}${nt.y}} = a_{${nt.y}${nt.x}} = 0 \\)`,content:[
							`the equation has the form:`,
							`\\[ ${nt.ddt} ${nt.vec2(nt.x,nt.y)} = ${nt.mat2('\\lambda_1',0,0,'\\lambda_2')} ${nt.vec2(nt.x,nt.y)} \\]`,
							`general solution (with arbitrary constants \\( ${nt.x}_0 \\), \\( ${nt.y}_0 \\)) and ${ivp} solution:`,
							`\\[ ${nt.X} = ${nt.x}_0 e^{\\lambda_1 t} ${nt.vec2(1,0)} + ${nt.y}_0 e^{\\lambda_2 t} ${nt.vec2(0,1)} \\]`,
						]},
						{type:'case',title:`\\( a_{${nt.x}${nt.y}} \\neq 0 \\) or \\( a_{${nt.y}${nt.x}} \\neq 0 \\)`,content:[
							`get eigenvalues by solving the characteristic equation for \\( \\lambda \\):`,
							`\\[ \\det(\\mathbf{A} - \\lambda \\mathbf{I}) = 0 \\]`,
							{type:'cases',content:[
								{type:'case',title:`repeated \\( \\lambda \\)`,content:[
									`general solution (with arbitrary constants \\( ${nt.x}_0 \\), \\( ${nt.y}_0 \\)) and ${ivp} solution:`,
									`\\[ ${nt.X} = e^{\\lambda t} ${nt.vec2(nt.x+'_0',nt.y+'_0')} + t e^{\\lambda t} (\\mathbf{A} - \\lambda \\mathbf{I}) ${nt.vec2(nt.x+'_0',nt.y+'_0')} \\]`,
								]},
								{type:'case',title:`real distinct \\( \\lambda_1 \\), \\( \\lambda_2 \\)`,content:[
									`find eigenvector \\( ${nt.svec2(`${nt.x}_1`,`${nt.y}_1`)} \\) by solving:`,
									`\\[ (\\mathbf{A} - \\lambda_1 \\mathbf{I}) ${nt.vec2(`${nt.x}_1`,`${nt.y}_1`)} = 0 \\]`,
									`find eigenvector \\( ${nt.svec2(`${nt.x}_2`,`${nt.y}_2`)} \\) by solving:`,
									`\\[ (\\mathbf{A} - \\lambda_2 \\mathbf{I}) ${nt.vec2(`${nt.x}_2`,`${nt.y}_2`)} = 0 \\]`,
									`general solution (with arbitrary constants \\( k_1 \\), \\( k_2 \\)):`,
									`\\[ ${nt.X} = k_1 e^{\\lambda_1 t} ${nt.vec2(`${nt.x}_1`,`${nt.y}_1`)} + k_2 e^{\\lambda_2 t} ${nt.vec2(`${nt.x}_2`,`${nt.y}_2`)} \\]`,
									`get constants \\( k_1 \\), \\( k_2 \\) for ${ivp} solution by solving:`,
									`\\[ ${nt.mat2(`${nt.x}_1`,`${nt.x}_2`,`${nt.y}_1`,`${nt.y}_2`)} ${nt.vec2('k_1','k_2')} = ${nt.vec2(`${nt.x}_0`,`${nt.y}_0`)} \\]`,
								]},
								{type:'case',title:`complex conjugate pair \\( \\lambda = \\alpha \\pm i \\beta \\)`,content:[
									`select one of eigenvalues \\( \\lambda_1 = \\alpha + i \\beta \\)`,
									`find complex-valued eigenvector \\( ${nt.svec2(`${nt.x}_1 + i ${nt.x}_2`,`${nt.y}_1 + i ${nt.y}_2`)} \\) by solving:`,
									`\\[ (\\mathbf{A} - \\lambda_1 \\mathbf{I}) ${nt.vec2(`${nt.x}_1 + i ${nt.x}_2`,`${nt.y}_1 + i ${nt.y}_2`)} = 0 \\]`,
									{type:'derivation',content:[
										`one of complex-valued solutions:`,
										`\\[ ${nt.X}_c = e^{\\alpha t} (\\cos \\beta t + i \\sin \\beta t) ${nt.svec2(`${nt.x}_1 + i ${nt.x}_2`,`${nt.y}_1 + i ${nt.y}_2`)} \\]`,
										`find general solution by taking real and imaginary parts of a complex-valued solution:`,
										`\\[ ${nt.X} = k_1 \\operatorname{Re}(${nt.X}_c) + k_2 \\operatorname{Im}(${nt.X}_c) \\]`,
									]},
									`general solution (with arbitrary constants \\( k_1 \\), \\( k_2 \\)):`,
									`\\[ \\begin{aligned} `+
										`${nt.X} = \\: & k_1 e^{\\alpha t} ${nt.vec2(`${nt.x}_1 \\cos \\beta t - ${nt.x}_2 \\sin \\beta t`,`${nt.y}_1 \\cos \\beta t - ${nt.y}_2 \\sin \\beta t`)} \\\\`+
										        `+ \\: & k_2 e^{\\alpha t} ${nt.vec2(`${nt.x}_1 \\sin \\beta t + ${nt.x}_2 \\cos \\beta t`,`${nt.y}_1 \\sin \\beta t + ${nt.y}_2 \\cos \\beta t`)} `+
									`\\end{aligned} \\]`,
									`get constants \\( k_1 \\), \\( k_2 \\) for ${ivp} solution by solving:`,
									`\\[ ${nt.mat2(`${nt.x}_1`,`${nt.x}_2`,`${nt.y}_1`,`${nt.y}_2`)} ${nt.vec2('k_1','k_2')} = ${nt.vec2(`${nt.x}_0`,`${nt.y}_0`)} \\]`,
								]},
							]},
						]},
					]},
				],
			}
		},
	},
	sn_sir: {
		parents: {
			sn: true,
		},
		name: "SIR model",
		htmlName: "SIR model",
		importance: 3,
		equation:
			`\\left\\{ \\begin{aligned}`+
				`${nt.dd('S')} &= -\\alpha S I \\\\`+
				`${nt.dd('I')} &= \\alpha S I - \\beta I \\\\ `+
				`${nt.dd('R')} &= \\beta I`+
			`\\end{aligned} \\right.`,
		equationNotes: [
			`\\( S = \\) number susceptible`,
			`\\( I = \\) number infectious`,
			`\\( R = \\) number recovered (immune)`,
			`\\( \\alpha = \\) contact rate`,
			`\\( \\beta = \\) recovery rate`,
			`all quantities are nonnegative`,
		],
		traits: {
			phaseSolutionMethod: {
				form: true,
				content: [
					`threshold value \\( \\rho = \\frac\\beta\\alpha \\):`,
					`\\( I \\) increases when \\( S > \\rho \\)`,
					`\\( S \\) decreases`,
					`\\( I \\) attains its maximum when \\( S = \\rho \\)`,
					{type:'derivation',content:[
						`\\[ ${nt.dd('S')} + ${nt.dd('I')} + ${nt.dd('R')} = 0 \\]`,
						`total population \\( N \\) is constant`,
						`\\[ S + I + R = N \\]`,
						`eliminate \\( R \\)`,
						`\\[ \\left\\{ \\begin{aligned} `+
							`${nt.dd('S')} &= -\\alpha S I \\\\ `+
							`${nt.dd('I')} &= \\alpha S I - \\beta I \\\\ `+
						`\\end{aligned} \\right. \\]`,
						`\\[ ${nt.dd('I','S')} = \\frac{\\alpha S I - \\beta I}{-\\alpha S I} = -1 + \\frac{\\rho}{S} \\]`,
						`integrate by \\( S \\)`,
						`\\[ I = -S + \\rho \\ln S + C \\]`,
					]},
					`conserved quantities:`,
					`\\[ \\begin{multline}`+
						`S(t) + I(t) + R(t) = \\\\ `+
						`= S(0) + I(0) + R(0) `+
					`\\end{multline} \\]`,
					`\\[ \\begin{multline}`+
						`I(t) + S(t) - \\rho \\ln S(t) = \\\\ `+
						`= I(0) + S(0) - \\rho \\ln S(0) `+
					`\\end{multline} \\]`,
					`maximum of \\( I \\):`,
					`\\[ \\begin{multline}`+
						`I_{max} + \\rho - \\rho \\ln \\rho = \\\\ `+
						`= I(0) + S(0) - \\rho \\ln S(0) `+
					`\\end{multline} \\]`,
				],
			},
			equilibriumSolutionMethod: {
				form: true,
				content: [
					`\\[ I = 0 \\]`,
				],
			},
		},
	},
})
<|endoftext|>


<commit_before>'use strict';

var _         = require('lodash');
var d3        = require('d3');

var areaChart = require('./renderer/area');
var data      = require('util/data');

module.exports = {
	replace : true,
	template: require('./chart.html'),

	mixins: [
		require('./line')
	],

	computed: {
		labels: function () {
			if (this.empty) {
				return [];
			}

			var x      = this.xScale;
			var y      = this.yScale;
			var series = this.series;
			var fmt    = this.yFmt;

			var labels = _(series)
				.map(function (d) {
					// lodash.max uses the accessor to find the comparison value, but
					// returns the entire object; d3.max returns the value returned
					// by the accessor
					var last = _.max(d.values, function (v) { return v.campaign.start_date; });

					return {
						text   : d.name + ' ' + fmt(last.value),
						x      : x(last.campaign.start_date),
						y      : y(last.y0 + last.y),
						defined: data.defined(last.y0) && data.defined(last.y)
					};
				})
				.filter('defined')
				.value();

			return labels;
		},

		renderer: function () {
			var x     = this.xScale;
			var y     = this.yScale;
			var color = this.colorScale;

			var renderer = areaChart()
				.x(function (d) {
					return x(d.campaign.start_date);
				})
				.y0(function (d) {
					return y(d.y0);
				})
				.y1(function (d) {
					return y(d.y0 + d.y);
				})
				.values(function (d) { return d.values; })
				.color(function (d, i) {
					return color(i);
				});

			return renderer;
		},

		series: function () {
			if (this.empty) {
				return [];
			}

			var stack = d3.layout.stack()
				.offset('zero')
				.x(function (d) {
					return d.campaign.start_date;
				})
				.y(function (d) {
					return d.value;
				})
				.values(function (d) {
					return d.values;
				});

			var indicators = _.indexBy(this.indicators, 'id');

			// Facet by indicator
			var series = _(this.datapoints)
				.sortBy(function (d) {
					return d.campaign.start_date;
				})
				.groupBy('indicator')
				.map(function (d, indicator) {
					return {
						name  : indicators[indicator].short_name,
						values: d
					};
				})
				.value();

			return stack(series);
		},

		yScale: function () {
			function y(d) {
				return d.y0 + d.y;
			}

			var scale = d3.scale.linear()
				.range([this.contentHeight, 0]);

			if (!this.empty) {
				var flat = _(this.series)
					.pluck('values')
					.flatten(true)
					.value();

				scale.domain([
					Math.min(0, d3.min(flat, y)),
					d3.max(flat, y)
				]);
			}

			return scale;
		}

	},

	methods: {
		getY: function (d) {
			return d.y0 + d.y;
		}
	}

};
<commit_msg>Fix the sort order on stacked area chart labels<commit_after>'use strict';

var _         = require('lodash');
var d3        = require('d3');

var areaChart = require('./renderer/area');
var data      = require('util/data');

module.exports = {
	replace : true,
	template: require('./chart.html'),

	mixins: [
		require('./line')
	],

	computed: {
		labels: function () {
			if (this.empty) {
				return [];
			}

			var x      = this.xScale;
			var y      = this.yScale;
			var series = this.series;
			var fmt    = this.yFmt;

			var labels = _(series)
				.map(function (d) {
					// lodash.max uses the accessor to find the comparison value, but
					// returns the entire object; d3.max returns the value returned
					// by the accessor
					var last = _.max(d.values, function (v) { return v.campaign.start_date; });

					return {
						text   : d.name + ' ' + fmt(last.value),
						x      : x(last.campaign.start_date),
						y      : y(last.y0 + last.y),
						defined: data.defined(last.y0) && data.defined(last.y)
					};
				})
				.filter('defined')
				.reverse()
				.value();

			return labels;
		},

		renderer: function () {
			var x     = this.xScale;
			var y     = this.yScale;
			var color = this.colorScale;

			var renderer = areaChart()
				.x(function (d) {
					return x(d.campaign.start_date);
				})
				.y0(function (d) {
					return y(d.y0);
				})
				.y1(function (d) {
					return y(d.y0 + d.y);
				})
				.values(function (d) { return d.values; })
				.color(function (d, i) {
					return color(i);
				});

			return renderer;
		},

		series: function () {
			if (this.empty) {
				return [];
			}

			var stack = d3.layout.stack()
				.offset('zero')
				.x(function (d) {
					return d.campaign.start_date;
				})
				.y(function (d) {
					return d.value;
				})
				.values(function (d) {
					return d.values;
				});

			var indicators = _.indexBy(this.indicators, 'id');

			// Facet by indicator
			var series = _(this.datapoints)
				.sortBy(function (d) {
					return d.campaign.start_date;
				})
				.groupBy('indicator')
				.map(function (d, indicator) {
					return {
						name  : indicators[indicator].short_name,
						values: d
					};
				})
				.value();

			return stack(series);
		},

		yScale: function () {
			function y(d) {
				return d.y0 + d.y;
			}

			var scale = d3.scale.linear()
				.range([this.contentHeight, 0]);

			if (!this.empty) {
				var flat = _(this.series)
					.pluck('values')
					.flatten(true)
					.value();

				scale.domain([
					Math.min(0, d3.min(flat, y)),
					d3.max(flat, y)
				]);
			}

			return scale;
		}

	},

	methods: {
		getY: function (d) {
			return d.y0 + d.y;
		}
	}

};
<|endoftext|>


<commit_before>import { parse } from "babel-core";
import _ from "lodash";

import { deepAssign } from "../util/object";

import transformAst from "./transform";

function template (strTemplate, modifier) {
  const templateAst = parse(strTemplate);

  return (replacements = {}) => {
    const bodyActions = Object.keys(replacements.body || {})
      .map(placeholder => tuple => {
        const { node } = tuple;

        if (node.body &&
            node.body.length &&
            node.body[0].type === "ExpressionStatement" &&
            node.body[0].expression.type === "Identifier" &&
            node.body[0].expression.name === placeholder) {
          return deepAssign(node, "body", replacements.body[placeholder]);
        }

        return node;
      });

    const identifierActions = Object.keys(replacements.identifier || {})
      .map(placeholder => tuple => {
        const { node } = tuple;
        if (node.type === "Identifier" && node.name === placeholder) {
          // Replacements should be cloned properly before being passed to the template,
          // if that is a concern.  We cannot deep-clone here, due to cycles in some of
          // the AST structures that Babel produces.
          return replacements.identifier[placeholder];
        }
        return node;
      });

    // TODO: `statementsActions`
    //  - inserts multiple nodes in array, replacing placeholder
    //  - parent should flatten arrays after chidren are processed

    const actions = [].concat(bodyActions, identifierActions);
    const programAst = transformAst(templateAst, tuple => {
      for (const action of actions) {
        const result = action(tuple);
        if (result !== tuple.node) { return result; }
      }
      return tuple.node;
    });

    return modifier(programAst);
  };
}

export function programTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst);
}

export function bodyTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst.body);
}

export function expressionStmtTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst.body[0]);
}

export function expressionTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst.body[0].expression);
}
<commit_msg>Remove unused import.<commit_after>import { parse } from "babel-core";

import { deepAssign } from "../util/object";

import transformAst from "./transform";

function template (strTemplate, modifier) {
  const templateAst = parse(strTemplate);

  return (replacements = {}) => {
    const bodyActions = Object.keys(replacements.body || {})
      .map(placeholder => tuple => {
        const { node } = tuple;

        if (node.body &&
            node.body.length &&
            node.body[0].type === "ExpressionStatement" &&
            node.body[0].expression.type === "Identifier" &&
            node.body[0].expression.name === placeholder) {
          return deepAssign(node, "body", replacements.body[placeholder]);
        }

        return node;
      });

    const identifierActions = Object.keys(replacements.identifier || {})
      .map(placeholder => tuple => {
        const { node } = tuple;
        if (node.type === "Identifier" && node.name === placeholder) {
          // Replacements should be cloned properly before being passed to the template,
          // if that is a concern.  We cannot deep-clone here, due to cycles in some of
          // the AST structures that Babel produces.
          return replacements.identifier[placeholder];
        }
        return node;
      });

    // TODO: `statementsActions`
    //  - inserts multiple nodes in array, replacing placeholder
    //  - parent should flatten arrays after chidren are processed

    const actions = [].concat(bodyActions, identifierActions);
    const programAst = transformAst(templateAst, tuple => {
      for (const action of actions) {
        const result = action(tuple);
        if (result !== tuple.node) { return result; }
      }
      return tuple.node;
    });

    return modifier(programAst);
  };
}

export function programTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst);
}

export function bodyTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst.body);
}

export function expressionStmtTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst.body[0]);
}

export function expressionTmpl (strTemplate) {
  return template(strTemplate, programAst => programAst.body[0].expression);
}
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'

import FieldListItem from 'src/data_explorer/components/FieldListItem'
import GroupByTimeDropdown from 'src/data_explorer/components/GroupByTimeDropdown'
import FillQuery from 'shared/components/FillQuery'
import FancyScrollbar from 'shared/components/FancyScrollbar'

import {showFieldKeys} from 'shared/apis/metaQuery'
import showFieldKeysParser from 'shared/parsing/showFieldKeys'

const {bool, func, shape, string} = PropTypes

const FieldList = React.createClass({
  propTypes: {
    query: shape({
      database: string,
      retentionPolicy: string,
      measurement: string,
    }).isRequired,
    onToggleField: func.isRequired,
    onGroupByTime: func.isRequired,
    onFill: func.isRequired,
    applyFuncsToField: func.isRequired,
    isKapacitorRule: bool,
    isInDataExplorer: bool,
  },

  getDefaultProps() {
    return {
      isKapacitorRule: false,
    }
  },

  contextTypes: {
    source: shape({
      links: shape({
        proxy: string.isRequired,
      }).isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {
      fields: [],
    }
  },

  componentDidMount() {
    const {database, measurement} = this.props.query
    if (!database || !measurement) {
      return
    }

    this._getFields()
  },

  componentDidUpdate(prevProps) {
    const {database, measurement, retentionPolicy} = this.props.query
    const {
      database: prevDB,
      measurement: prevMeas,
      retentionPolicy: prevRP,
    } = prevProps.query
    if (!database || !measurement) {
      return
    }

    if (
      database === prevDB &&
      measurement === prevMeas &&
      retentionPolicy === prevRP
    ) {
      return
    }

    this._getFields()
  },

  handleFill(value) {
    this.props.onFill(value)
  },

  handleGroupByTime(groupBy) {
    this.props.onGroupByTime(groupBy.menuOption)
  },

  render() {
    const {query, isKapacitorRule, isInDataExplorer} = this.props
    const hasAggregates = query.fields.some(f => f.funcs && f.funcs.length)
    const hasGroupByTime = query.groupBy.time

    return (

          Fields
          {hasAggregates
            ?

                {isKapacitorRule
                  ? null
                  : <FillQuery
                      value={query.fill}
                      onSelection={this.handleFill}
                    />}
                <GroupByTimeDropdown
                  isOpen={!hasGroupByTime}
                  selected={query.groupBy.time}
                  onChooseGroupByTime={this.handleGroupByTime}
                  isInRuleBuilder={isKapacitorRule}
                  isInDataExplorer={isInDataExplorer}
                />

            : null}

        {this.renderList()}

    )
  },

  renderList() {
    const {database, measurement} = this.props.query
    if (!database || !measurement) {
      return (

            No Measurement selected

      )
    }

    return (

        <FancyScrollbar>
          {this.state.fields.map(fieldFunc => {
            const selectedField = this.props.query.fields.find(
              f => f.field === fieldFunc.field
            )
            return (
              <FieldListItem
                key={fieldFunc.field}
                onToggleField={this.props.onToggleField}
                onApplyFuncsToField={this.props.applyFuncsToField}
                isSelected={!!selectedField}
                fieldFunc={selectedField || fieldFunc}
                isKapacitorRule={this.props.isKapacitorRule}
              />
            )
          })}
        </FancyScrollbar>

    )
  },

  _getFields() {
    const {database, measurement, retentionPolicy} = this.props.query
    const {source} = this.context
    const proxySource = source.links.proxy

    showFieldKeys(
      proxySource,
      database,
      measurement,
      retentionPolicy
    ).then(resp => {
      const {errors, fieldSets} = showFieldKeysParser(resp.data)
      if (errors.length) {
        // TODO: do something
      }

      this.setState({
        fields: fieldSets[measurement].map(f => {
          return {field: f, funcs: []}
        }),
      })
    })
  },
})

export default FieldList
<commit_msg>Switch order of group by and fill dropdowns<commit_after>import React, {PropTypes} from 'react'

import FieldListItem from 'src/data_explorer/components/FieldListItem'
import GroupByTimeDropdown from 'src/data_explorer/components/GroupByTimeDropdown'
import FillQuery from 'shared/components/FillQuery'
import FancyScrollbar from 'shared/components/FancyScrollbar'

import {showFieldKeys} from 'shared/apis/metaQuery'
import showFieldKeysParser from 'shared/parsing/showFieldKeys'

const {bool, func, shape, string} = PropTypes

const FieldList = React.createClass({
  propTypes: {
    query: shape({
      database: string,
      retentionPolicy: string,
      measurement: string,
    }).isRequired,
    onToggleField: func.isRequired,
    onGroupByTime: func.isRequired,
    onFill: func.isRequired,
    applyFuncsToField: func.isRequired,
    isKapacitorRule: bool,
    isInDataExplorer: bool,
  },

  getDefaultProps() {
    return {
      isKapacitorRule: false,
    }
  },

  contextTypes: {
    source: shape({
      links: shape({
        proxy: string.isRequired,
      }).isRequired,
    }).isRequired,
  },

  getInitialState() {
    return {
      fields: [],
    }
  },

  componentDidMount() {
    const {database, measurement} = this.props.query
    if (!database || !measurement) {
      return
    }

    this._getFields()
  },

  componentDidUpdate(prevProps) {
    const {database, measurement, retentionPolicy} = this.props.query
    const {
      database: prevDB,
      measurement: prevMeas,
      retentionPolicy: prevRP,
    } = prevProps.query
    if (!database || !measurement) {
      return
    }

    if (
      database === prevDB &&
      measurement === prevMeas &&
      retentionPolicy === prevRP
    ) {
      return
    }

    this._getFields()
  },

  handleFill(value) {
    this.props.onFill(value)
  },

  handleGroupByTime(groupBy) {
    this.props.onGroupByTime(groupBy.menuOption)
  },

  render() {
    const {query, isKapacitorRule, isInDataExplorer} = this.props
    const hasAggregates = query.fields.some(f => f.funcs && f.funcs.length)
    const hasGroupByTime = query.groupBy.time

    return (

          Fields
          {hasAggregates
            ?

                <GroupByTimeDropdown
                  isOpen={!hasGroupByTime}
                  selected={query.groupBy.time}
                  onChooseGroupByTime={this.handleGroupByTime}
                  isInRuleBuilder={isKapacitorRule}
                  isInDataExplorer={isInDataExplorer}
                />
                {isKapacitorRule
                  ? null
                  : <FillQuery
                      value={query.fill}
                      onSelection={this.handleFill}
                    />}

            : null}

        {this.renderList()}

    )
  },

  renderList() {
    const {database, measurement} = this.props.query
    if (!database || !measurement) {
      return (

            No Measurement selected

      )
    }

    return (

        <FancyScrollbar>
          {this.state.fields.map(fieldFunc => {
            const selectedField = this.props.query.fields.find(
              f => f.field === fieldFunc.field
            )
            return (
              <FieldListItem
                key={fieldFunc.field}
                onToggleField={this.props.onToggleField}
                onApplyFuncsToField={this.props.applyFuncsToField}
                isSelected={!!selectedField}
                fieldFunc={selectedField || fieldFunc}
                isKapacitorRule={this.props.isKapacitorRule}
              />
            )
          })}
        </FancyScrollbar>

    )
  },

  _getFields() {
    const {database, measurement, retentionPolicy} = this.props.query
    const {source} = this.context
    const proxySource = source.links.proxy

    showFieldKeys(
      proxySource,
      database,
      measurement,
      retentionPolicy
    ).then(resp => {
      const {errors, fieldSets} = showFieldKeysParser(resp.data)
      if (errors.length) {
        // TODO: do something
      }

      this.setState({
        fields: fieldSets[measurement].map(f => {
          return {field: f, funcs: []}
        }),
      })
    })
  },
})

export default FieldList
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import {NavBar, NavBlock, NavHeader, NavListItem} from 'src/side_nav/components/NavItems';

const {string, shape} = PropTypes;
const SideNav = React.createClass({
  propTypes: {
    location: string.isRequired,
    sourceID: string.isRequired,
    explorationID: string,
    me: shape({
      email: string,
    }),
  },

  render() {
    const {me, location, sourceID, explorationID} = this.props;
    const sourcePrefix = `/sources/${sourceID}`;
    const explorationSuffix = explorationID ? `/${explorationID}` : '';
    const dataExplorerLink = `${sourcePrefix}/chronograf/data-explorer${explorationSuffix}`;

    const loggedIn = !!(me && me.email);

    return (
      <NavBar location={location}>

        <NavBlock icon="cpu" link={`${sourcePrefix}/hosts`}>
          <NavHeader link={`${sourcePrefix}/hosts`} title="Infrastructure" />
          <NavListItem link={`${sourcePrefix}/hosts`}>Host List</NavListItem>
          <NavListItem link={`${sourcePrefix}/kubernetes`}>Kubernetes Dashboard</NavListItem>
        </NavBlock>
        <NavBlock icon="graphline" link={dataExplorerLink}>
          <NavHeader link={dataExplorerLink} title={'Data'} />
          <NavListItem link={dataExplorerLink}>Explorer</NavListItem>
        </NavBlock>
        <NavBlock matcher="alerts" icon="pulse-b" link={`${sourcePrefix}/alerts`}>
          <NavHeader link={`${sourcePrefix}/alerts`} title="Alerting" />
          <NavListItem link={`${sourcePrefix}/alerts`}>Alert History</NavListItem>
          <NavListItem link={`${sourcePrefix}/alert-rules`}>Kapacitor Rules</NavListItem>
        </NavBlock>
        <NavBlock icon="access-key" link={`${sourcePrefix}/manage-sources`}>
          <NavHeader link={`${sourcePrefix}/manage-sources`} title="Sources" />
          <NavListItem link={`${sourcePrefix}/manage-sources`}>InfluxDB</NavListItem>
          <NavListItem link={`${sourcePrefix}/kapacitor-config`}>Kapacitor</NavListItem>
        </NavBlock>
        {loggedIn ? (
        <NavBlock icon="user-outline" className="sidebar__square-last">
          Logout
        </NavBlock>
        ) : null}
      </NavBar>
    );
  },
});

export default SideNav;
<commit_msg>Rename sources to configuration in SideNav<commit_after>import React, {PropTypes} from 'react';
import {NavBar, NavBlock, NavHeader, NavListItem} from 'src/side_nav/components/NavItems';

const {string, shape} = PropTypes;
const SideNav = React.createClass({
  propTypes: {
    location: string.isRequired,
    sourceID: string.isRequired,
    explorationID: string,
    me: shape({
      email: string,
    }),
  },

  render() {
    const {me, location, sourceID, explorationID} = this.props;
    const sourcePrefix = `/sources/${sourceID}`;
    const explorationSuffix = explorationID ? `/${explorationID}` : '';
    const dataExplorerLink = `${sourcePrefix}/chronograf/data-explorer${explorationSuffix}`;

    const loggedIn = !!(me && me.email);

    return (
      <NavBar location={location}>

        <NavBlock icon="cpu" link={`${sourcePrefix}/hosts`}>
          <NavHeader link={`${sourcePrefix}/hosts`} title="Infrastructure" />
          <NavListItem link={`${sourcePrefix}/hosts`}>Host List</NavListItem>
          <NavListItem link={`${sourcePrefix}/kubernetes`}>Kubernetes Dashboard</NavListItem>
        </NavBlock>
        <NavBlock icon="graphline" link={dataExplorerLink}>
          <NavHeader link={dataExplorerLink} title={'Data'} />
          <NavListItem link={dataExplorerLink}>Explorer</NavListItem>
        </NavBlock>
        <NavBlock matcher="alerts" icon="pulse-b" link={`${sourcePrefix}/alerts`}>
          <NavHeader link={`${sourcePrefix}/alerts`} title="Alerting" />
          <NavListItem link={`${sourcePrefix}/alerts`}>Alert History</NavListItem>
          <NavListItem link={`${sourcePrefix}/alert-rules`}>Kapacitor Rules</NavListItem>
        </NavBlock>
        <NavBlock icon="access-key" link={`${sourcePrefix}/manage-sources`}>
          <NavHeader link={`${sourcePrefix}/manage-sources`} title="Configuration" />
          <NavListItem link={`${sourcePrefix}/manage-sources`}>InfluxDB</NavListItem>
          <NavListItem link={`${sourcePrefix}/kapacitor-config`}>Kapacitor</NavListItem>
        </NavBlock>
        {loggedIn ? (
        <NavBlock icon="user-outline" className="sidebar__square-last">
          Logout
        </NavBlock>
        ) : null}
      </NavBar>
    );
  },
});

export default SideNav;
<|endoftext|>


<commit_before>import FS from "fs";
import Path from "path";
import _ from "lodash-fp";
import { reverse } from "../helpers";

export const title = "Day 16: Aunt Sue";

export function parse(input) {
    return _.map((line) => {
        const sentence = line.replace("Sue", "index");
        const properties = sentence.match(/[a-z]+/g);
        const values = sentence.match(/\d+/g);

        return _.reduce((attributes, property, index) => _.assign(attributes, {
            [property]: parseInt(values[index], 10)
        }), {}, properties);
    }, input);
}

export function getMatchPercentage(subject, sample) {
    const matches = _.map((key) => {
        const a = subject[key];
        const b = sample[key];

        if (_.isUndefined(b))
            return false;

        if (_.isEqual(a, b))
            return true;
        else
            return null;
    }, _.keys(subject));

    if (_.includes(null, matches))
        return null;

    if (!matches.length)
        return 0;

    return (_.filter(_.isEqual(true), matches).length / matches.length) * 100;
}

export function analysisMachine(input, subject) {
    const isNull = _.compose(_.isEqual(null), _.get("score"));
    const matches = _.map((sample) => ({
        index: sample.index,
        score: getMatchPercentage(subject, sample)
    }), parse(input));

    return reverse(_.sortBy("score", _.filter(_.negate(isNull), matches)));
}

export function run() {
    const inputPath = Path.join(__dirname, "input.txt");
    const input = FS.readFileSync(inputPath, "utf-8").trim().split("\n");

    console.log("What is the number of the Sue that got you the gift?");
}
<commit_msg>Completed part 1. - Spoiler alert: the answer is 103.<commit_after>import FS from "fs";
import Path from "path";
import _ from "lodash-fp";
import { reverse } from "../helpers";

export const title = "Day 16: Aunt Sue";

export function parse(input) {
    return _.map((line) => {
        const sentence = line.replace("Sue", "index");
        const properties = sentence.match(/[a-z]+/g);
        const values = sentence.match(/\d+/g);

        return _.reduce((attributes, property, index) => _.assign(attributes, {
            [property]: parseInt(values[index], 10)
        }), {}, properties);
    }, input);
}

export function getMatchPercentage(subject, sample) {
    const matches = _.map((key) => {
        const a = subject[key];
        const b = sample[key];

        if (_.isUndefined(b))
            return false;

        if (_.isEqual(a, b))
            return true;
        else
            return null;
    }, _.keys(subject));

    if (_.includes(null, matches))
        return null;

    if (!matches.length)
        return 0;

    return (_.filter(_.isEqual(true), matches).length / matches.length) * 100;
}

export function analysisMachine(input, subject) {
    const isNull = _.compose(_.isEqual(null), _.get("score"));
    const matches = _.map((sample) => ({
        index: sample.index,
        score: getMatchPercentage(subject, sample)
    }), parse(input));

    return reverse(_.sortBy("score", _.filter(_.negate(isNull), matches)));
}

export function run() {
    const inputPath = Path.join(__dirname, "input.txt");
    const input = FS.readFileSync(inputPath, "utf-8").trim().split("\n");
    const matches = analysisMachine(input, {
        children: 3,
        cats: 7,
        samoyeds: 2,
        pomeranians: 3,
        akitas: 0,
        vizslas: 0,
        goldfish: 5,
        trees: 3,
        cars: 2,
        perfumes: 1
    });

    console.log("What is the number of the Sue that got you the gift?", _.get("index", _.first(matches)));
}
<|endoftext|>