<commit_before>var elementslib = new function(){

  var domNode = null;
  //keep track of the locators we cant get via the domNode
  var locators = {};

  //element constructor
  this.Element = function(node){
    if (node){ domNode = node;}
    if (node.id){ id = node.id;}
    if (node.name){ name = node.name;}
    return domNode;
  };
  //getters
  this.Element.exists = function(){
    if (domNode){ return true; }
    else{ return false; }
  };
  this.Element.getNode = function(){
    return domNode;
  };
  //setters
  this.Element.ID = function(s){
    locators.id = s;
    domNode = nodeSearch(nodeById, s);
    return returnOrThrow(s);
  };
  this.Element.NAME = function(s){
     locators.name = s;
     domNode = nodeSearch(nodeByName, s);
     return returnOrThrow(s);
  };
  this.Element.LINK = function(s){
    locators.link = s;
    domNode = nodeSearch(nodeByLink, s);
    return returnOrThrow(s);
  };
  this.Element.CLASSNAME = function(s){
    locators.classname = s;
    domNode = nodeSearch(nodeByClassname, s);
    return returnOrThrow(s);
  };
  this.Element.TAGNAME = function(s){
    locators.tagname = s;
    domNode = nodeSearch(nodeByTagname, s);
    return returnOrThrow(s);
  };
  this.Element.VALUE = function(s){
    locators.value = s;
    domNode = nodeSearch(nodeByValue, s);
    return returnOrThrow(s);
  };
  this.Element.LABEL = function(s){
    locators.labelname = s;
    domNode = nodeSearch(nodeByLabel, s);
    return returnOrThrow(s);
  };
  this.Element.XPATH = function(s){
    locators.xpath = s;
    domNode = nodeSearch(nodeByXPath, s, document);
    //do the lookup, then set the domNode to the result
    return returnOrThrow(s);
  };

  //either returns the element, or throws an exception
  var returnOrThrow = function(s){
    if (!domNode){
      //var e = {};
      //e.message = "Element "+s+" could not be found";
      //throw e;
      return null;
    }
    else{
      return domNode;
    }
  }

  //do the recursive search
  //takes the function for resolving nodes and the string
  var nodeSearch = function(func, s, doc){
    var e = null;

    //inline function to recursively find the element in the DOM, cross frame.
    var recurse = function(w, func, s, doc){
     //do the lookup in the current window
     try{ element = func.call(w, s, doc);}
     catch(err){ element = null; }

      if (!element){
        var fc = w.frames.length;
        var fa = w.frames;
        for (var i=0;i<fc;i++){
          recurse(fa[i], func, s, doc);
        }
     }
     else { e = element; }
    };

    //IE cross window problems require you to talk directly to opener
     try{ element = func.call(windmill.testWin(), s, doc);}
     catch(err){ element = null; }
     if (!element){
       for (var i=0;i<windmill.testWin().frames.length;i++){
         try { element = func.call(windmill.testWin().frames[i], s, doc); }
         catch(err){ element = null; }
       }
     }

    if (element){ return element; }
    recurse(windmill.testWin(), func, s, doc);
    recurse(windmill.baseTestWindow, func, s, doc);

    return e;
  }

  //Lookup by ID
  var nodeById = function (s){
    return this.document.getElementById(s);
  }

  //DOM element lookup functions, private to elementslib
  var nodeByName = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    try{
      var els = this.document.getElementsByName(s);
      if (els.length > 0) {
        return els[0];
      }
    }
    catch(err){};
    return null;
  };

  //Lookup by link
  var nodeByLink = function (s) {//search nodes by link text
    var getText = function(el){
      var text = "";
      if (el.nodeType == 3){ //textNode
        if (el.data != undefined){
          text = el.data;
        }
        else{ text = el.innerHTML; }
        text = text.replace(/\n|\r|\t/g, " ");
      }
      if (el.nodeType == 1){ //elementNode
          for (var i = 0; i < el.childNodes.length; i++) {
              var child = el.childNodes.item(i);
              text += getText(child);
          }
          if (el.tagName == "P" || el.tagName == "BR" ||
            el.tagName == "HR" || el.tagName == "DIV") {
            text += "\n";
          }
      }
      return text;
    }
    //sometimes the windows won't have this function
    try {
      var links = this.document.getElementsByTagName('a');
    }
    catch(err){}
    for (var i = 0; i < links.length; i++) {
      var el = links[i];
      var linkText = getText(el);
      if (linkText.trim() == s.trim()) {
        return el;
      }
    }
    return null;
  };

  //DOM element lookup functions, private to elementslib
  var nodeByTagname = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    if (s.indexOf(',') != -1){
      var cn = s.split(',');
      var idx = cn[1];
      var cn = cn[0];
    }
    else{
      var cn = s;
      var idx = 0;
    }
    return this.document.getElementsByTagName(cn)[idx];
  };

  //DOM element lookup functions, private to elementslib
  var nodeByClassname = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    if (s.indexOf(',') != -1){
      var cn = s.split(',');
      var idx = cn[1];
      var cn = cn[0];
    }
    else{
      var cn = s;
      var idx = 0;
    }
    return this.document.getElementsByClassName(cn)[idx];
  };

  //Lookup DOM node by value attribute
  var nodeByValue = function (s) {
    var getElementsByAttribute = function(oElm, strTagName, strAttributeName, strAttributeValue){
        var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
        var arrReturnElements = new Array();
        var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
        var oCurrent;
        var oAttribute;
        for(var i=0; i<arrElements.length; i++){
            oCurrent = arrElements[i];
            oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
            if(typeof oAttribute == "string" && oAttribute.length > 0){
                if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                    arrReturnElements.push(oCurrent);
                }
            }
        }
        return arrReturnElements;
    }
    var node = getElementsByAttribute(this.document, "*", "value", s);
    if (node.length == 0){
      return null;
    }
    return node[0];
  };

  var nodeByLabel = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    var labels = this.document.getElementsByTagName('label');
    var node = null;
    var label = null;

    //Find the label from all labels on the page
    for (i = 0;i < labels.length; i++){
      if (labels[i].innerHTML.trim() == s.trim()){
        label = labels[i];
      }
    }

    //If we have a label, use its for attrib to get the id of the input
    if (label != null){
      if (windmill.browser.isIE){
        var iid = label.getAttribute('htmlFor');
      }
      else {
        var iid = label.getAttribute('for');
      }
      node = this.document.getElementById(iid);
    }
    //either return the found input node, or null
    return node;
  };

  //Lookup with xpath
  var nodeByXPath = function (xpath, doc) {
    //if there is built in document.evaluate
    if (this.document.evaluate){
      return this.document.evaluate(xpath, this.document, null, 0, null).iterateNext();
    }
    //Else pass the IDE window.document that has a document.evaluate
    else {
      return doc.evaluate(xpath, this.document, null, 0, null).iterateNext();
    }
  };
};<commit_msg>elementslib classname now works on iE<commit_after>var elementslib = new function(){

  var domNode = null;
  //keep track of the locators we cant get via the domNode
  var locators = {};

  //element constructor
  this.Element = function(node){
    if (node){ domNode = node;}
    if (node.id){ id = node.id;}
    if (node.name){ name = node.name;}
    return domNode;
  };
  //getters
  this.Element.exists = function(){
    if (domNode){ return true; }
    else{ return false; }
  };
  this.Element.getNode = function(){
    return domNode;
  };
  //setters
  this.Element.ID = function(s){
    locators.id = s;
    domNode = nodeSearch(nodeById, s);
    return returnOrThrow(s);
  };
  this.Element.NAME = function(s){
     locators.name = s;
     domNode = nodeSearch(nodeByName, s);
     return returnOrThrow(s);
  };
  this.Element.LINK = function(s){
    locators.link = s;
    domNode = nodeSearch(nodeByLink, s);
    return returnOrThrow(s);
  };
  this.Element.CLASSNAME = function(s){
    locators.classname = s;
    domNode = nodeSearch(nodeByClassname, s);
    return returnOrThrow(s);
  };
  this.Element.TAGNAME = function(s){
    locators.tagname = s;
    domNode = nodeSearch(nodeByTagname, s);
    return returnOrThrow(s);
  };
  this.Element.VALUE = function(s){
    locators.value = s;
    domNode = nodeSearch(nodeByValue, s);
    return returnOrThrow(s);
  };
  this.Element.LABEL = function(s){
    locators.labelname = s;
    domNode = nodeSearch(nodeByLabel, s);
    return returnOrThrow(s);
  };
  this.Element.XPATH = function(s){
    locators.xpath = s;
    domNode = nodeSearch(nodeByXPath, s, document);
    //do the lookup, then set the domNode to the result
    return returnOrThrow(s);
  };

  //either returns the element, or throws an exception
  var returnOrThrow = function(s){
    if (!domNode){
      //var e = {};
      //e.message = "Element "+s+" could not be found";
      //throw e;
      return null;
    }
    else{
      return domNode;
    }
  }

  //do the recursive search
  //takes the function for resolving nodes and the string
  var nodeSearch = function(func, s, doc){
    var e = null;
    //inline function to recursively find the element in the DOM, cross frame.
    var recurse = function(w, func, s, doc){
     //do the lookup in the current window
     try{ element = func.call(w, s, doc);}
     catch(err){ element = null; }

      if (!element){
        var fc = w.frames.length;
        var fa = w.frames;
        for (var i=0;i<fc;i++){
          recurse(fa[i], func, s, doc);
        }
     }
     else { e = element; }
    };

    //IE cross window problems require you to talk directly to opener
     try{ element = func.call(windmill.testWin(), s, doc);}
     catch(err){ element = null; }
     if (!element){
       for (var i=0;i<windmill.testWin().frames.length;i++){
         try { element = func.call(windmill.testWin().frames[i], s, doc); }
         catch(err){ element = null; }
       }
     }

    if (element){ return element; }
    recurse(windmill.testWin(), func, s, doc);
    recurse(windmill.baseTestWindow, func, s, doc);

    return e;
  }

  //Lookup by ID
  var nodeById = function (s){
    return this.document.getElementById(s);
  }

  //DOM element lookup functions, private to elementslib
  var nodeByName = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    try{
      var els = this.document.getElementsByName(s);
      if (els.length > 0) {
        return els[0];
      }
    }
    catch(err){};
    return null;
  };

  //Lookup by link
  var nodeByLink = function (s) {//search nodes by link text
    var getText = function(el){
      var text = "";
      if (el.nodeType == 3){ //textNode
        if (el.data != undefined){
          text = el.data;
        }
        else{ text = el.innerHTML; }
        text = text.replace(/\n|\r|\t/g, " ");
      }
      if (el.nodeType == 1){ //elementNode
          for (var i = 0; i < el.childNodes.length; i++) {
              var child = el.childNodes.item(i);
              text += getText(child);
          }
          if (el.tagName == "P" || el.tagName == "BR" ||
            el.tagName == "HR" || el.tagName == "DIV") {
            text += "\n";
          }
      }
      return text;
    }
    //sometimes the windows won't have this function
    try {
      var links = this.document.getElementsByTagName('a');
    }
    catch(err){}
    for (var i = 0; i < links.length; i++) {
      var el = links[i];
      var linkText = getText(el);
      if (linkText.trim() == s.trim()) {
        return el;
      }
    }
    return null;
  };

  //DOM element lookup functions, private to elementslib
  var nodeByTagname = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    if (s.indexOf(',') != -1){
      var cn = s.split(',');
      var idx = cn[1];
      var cn = cn[0];
    }
    else{
      var cn = s;
      var idx = 0;
    }
    return this.document.getElementsByTagName(cn)[idx];
  };

  //DOM element lookup functions, private to elementslib
  var nodeByClassname = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    if (s.indexOf(',') != -1){
      var cn = s.split(',');
      var idx = cn[1];
      var cn = cn[0];
    }
    else{
      var cn = s;
      var idx = 0;
    }
    if (!this.document.getElementsByClassName){
      this.document.getElementsByClassName = function(cl) {
        var retnode = [];
        var myclass = new RegExp('\\b'+cl+'\\b');
        var elem = this.getElementsByTagName('*');
        for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
        }
        return retnode;
      };
    }
    return this.document.getElementsByClassName(cn)[idx];
  };

  //Lookup DOM node by value attribute
  var nodeByValue = function (s) {
    var getElementsByAttribute = function(oElm, strTagName, strAttributeName, strAttributeValue){
        var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
        var arrReturnElements = new Array();
        var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
        var oCurrent;
        var oAttribute;
        for(var i=0; i<arrElements.length; i++){
            oCurrent = arrElements[i];
            oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
            if(typeof oAttribute == "string" && oAttribute.length > 0){
                if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                    arrReturnElements.push(oCurrent);
                }
            }
        }
        return arrReturnElements;
    }
    var node = getElementsByAttribute(this.document, "*", "value", s);
    if (node.length == 0){
      return null;
    }
    return node[0];
  };

  var nodeByLabel = function (s) { //search nodes by name
    //sometimes the win object won't have this object
    var labels = this.document.getElementsByTagName('label');
    var node = null;
    var label = null;

    //Find the label from all labels on the page
    for (i = 0;i < labels.length; i++){
      if (labels[i].innerHTML.trim() == s.trim()){
        label = labels[i];
      }
    }

    //If we have a label, use its for attrib to get the id of the input
    if (label != null){
      if (windmill.browser.isIE){
        var iid = label.getAttribute('htmlFor');
      }
      else {
        var iid = label.getAttribute('for');
      }
      node = this.document.getElementById(iid);
    }
    //either return the found input node, or null
    return node;
  };

  //Lookup with xpath
  var nodeByXPath = function (xpath, doc) {
    //if there is built in document.evaluate
    if (this.document.evaluate){
      return this.document.evaluate(xpath, this.document, null, 0, null).iterateNext();
    }
    //Else pass the IDE window.document that has a document.evaluate
    else {
      return doc.evaluate(xpath, this.document, null, 0, null).iterateNext();
    }
  };
};<|endoftext|>


<commit_before>define([
	"dojo/_base/lang",
	"parser/parser",
	"./newton-raphson",
	"./error-messages"
], function(lang, Parser, NewtonRaphson, messages){
	var solver = null;
	var equations = [];
	var variables = [];
	var maxAttempts = 4; // maximum number of times a system should be solved
	var epsilon = 10e-6;
	var solution = null;

	/**
	* Initialize the system of equations. Checks if an equation is provided
	* in the form of string or a parser object. Creates an object with lhs and rhs parsed
	* equations and pushes it in an array called equations. It updates the total number
	* of variables in the equations as well.
	* @param -  expressions - array of equations as strings or parser objects
	**/
	var _initialize = function(expressions){
		equations = [];
		variables = [];
        var length = expressions.length;
		for(var index = 0; index < length; index++){
			var expression = expressions[index];
			var eq = {};
			if(typeof(expression) == "string" && expression.indexOf("=") > -1){
				var eqs = expression.split("=");
				if(eqs.length > 2)
					throw {
						type: "equation.incorrect.format",
						message: messages.get("equation.incorrect.format")
					};
				eq.lhs = Parser.parse(eqs[0]);
				eq.rhs = Parser.parse(eqs[1]);
			} else if(typeof(expression) == "string"){
				eq.lhs = Parser.parse(expression);
				eq.rhs = Parser.parse(0);
			} else if(typeof(expression) == "object" && expression.length == 2){
				eq.lhs = expression[0];
				eq.rhs = expression[1];
			} else if(typeof(expression) == "object"){
				eq.lhs = expression;
				eq.rhs = Parser.parse(0);
			}
			if(_isValid(eq)){
				equations.push(eq);
				_addVariables(eq);
			}
		}

		if(variables.length == 0)
			throw {
				type: "no.variables",
				message: messages.get("no.variables")
			};
	}

	/**
	* used to add unknown variables in the variables array created at the top.
	* @param -  expression - from which unknown variables are to be added
	**/
	var _addVariables = function(/* object */ expression){
		var update = function(variableArray){
            var length = variableArray.length;
			for(var index = 0; index < length; index++){
				var variable = variableArray[index];
				if(variables.indexOf(variable) < 0)
					variables.push(variable);
			}
		};
		update(expression.lhs.variables());
		if(expression.rhs) update(expression.rhs.variables());
	};

	/**
	* Preprocessing of equations will be part of this function. Currently preprocessing
	* involves removing that equation which does not have any variable in it. 2 = 2 sort
	* of equations.
	* @param -  expression - equation which is to checked
	* @return - isValid - boolean to provide whether expression is correct or not.
	**/
	var _isValid = function(/* object */ expression){
		var isValid = true;
		if((!expression.lhs || expression.lhs.variables().length == 0) &&
			(!expression.rhs || expression.rhs.variables().length == 0))
			isValid = false;

		return isValid;
	};

	/**
	* for over determined system where number of equations are more than the number
	* of variables, this picks up a subset based on removing equations which do not
	* bring any new variables in the system. First they are labelled as redundant
	* and then the appropriate equations are removed.
	* @param -	expressions - array for system of equations to be solved
	*        	start - this is a search algorithm, index is the starting equation
	* @return -	excess - the index of equations that were removed from expressions array
	**/
	var _preprocess = function(/* Array */ expressions, /* integer */ start){
		var l = expressions.length;
		var excess = [];
		var checked = []; // ids that are part of the system
		var numVariablesPerEquation = [];
		var _comparator = function(a, b){
			return a - b;
		};
		var index = start;
		var length = expressions.length;
		for(var i = 0; i < length; i++){
			isRedundant = true;
			if(index == l)
				index = 0;
			var eq = expressions[index];
			var ids = lang.clone(eq.lhs.variables());
			ids = ids.concat(eq.rhs.variables());
			numVariablesPerEquation[i] = ids.length;

			for(var j in ids){
				var id = ids[j];
				if(checked.indexOf(id) < 0){
					isRedundant = false;
					checked.push(id);
				}
			}

			if(isRedundant){
				excess.push(index);
			}
			index++;
		}
		// by pigeonhole principle this can not happen
		// but still for safety purposes
		if(excess.length < l-variables.length)
			throw{
				type: "inconsistent.system",
				message: messages.get("inconsistent.system")
			};

        // excess contains information about those equations which do not have any unique variable.
        // here we sort the excess array based on the count of variables.
		if(start === 0 && excess.length > l - variables.length)
			for(i in excess)
				excess.sort(function(a, b){return numVariablesPerEquation[a] - numVariablesPerEquation[b];});

        // slicing the ones which are less constrained i.e. the ones that have less
        // number of variables in them.
		excess = excess.slice(0, l-variables.length);
		excess.sort(_comparator);

		for(i = excess.length - 1; i >= 0; i--)
			expressions.splice(excess[i], 1);

		return excess;
	};

	/**
	* For over determined system, after a solution is found, check whether
	* the solution point solves the other equations
	* @param -	indexes - array of indexes which were removed from the system before solving
	*        	solution - the solution found using other equations in the system
	* @return -	boolean - whether the solution point solves the equation or not
	**/
	_checkEquations = function(/* Array */ indexes, /* Array */ solution){
		var values = {};
        var length = variables.length;
		for(var i = 0; i < length; i++)
			values[variables[i]] = solution.get(i, 0);

		var _equations = lang.clone(equations);
		for(var index in indexes){
			var diff = _equations[indexes[index]].lhs.evaluate(values) - _equations[indexes[index]].rhs.evaluate(values);

			if(Math.abs(diff) > epsilon){
				return false;
			}
		}

		return true;
	}

	/**
	* Solving the system of equations, preprocessing the equations if the number of
	* equations are more than unknown variables. To add new solver algorithms,
	* add a type in the switch case before the default case and call its solver function.
	* @return -	solution - solution calculated by the solver
	**/
	var solve = function(type){
		var solution;
		var doloop = true;
		var _equations = [];
		var start = 0; // preprocess is a search method to remove equations, so where to start searching
		var indexes = []; // equations that are not part of the solved system
		var attempts = 0;
		var solutionFound = false;
		maxAttempts = variables.length / 2;
		while(doloop){
			_equations = lang.clone(equations);
			if(equations.length == variables.length) doloop = false;
			else if(equations.length > variables.length) indexes = _preprocess(_equations, start);
			else
				throw{
					type: "under.determined.system",
					message: messages.get("under.determined.system")
				};

			switch(type){
				default:
					solver = new NewtonRaphson(_equations, variables);
					solution = solver.solve();
			}

			attempts++;
			if(doloop){
				if(_checkEquations(indexes, solution)){
					start = indexes[indexes.length - 1]
					doloop = false;
				} else if(attempts >= maxAttempts)
					throw{
						type: "overedetermined.no.solution",
						message: messages.get("overdetermined.no.solution")
					};
			}
		}

		return solution;
	};

	/**
	* constructor for the solver, it wraps over any kind of solver. The properties for adding
	* any new solver is to create a solve function and add it as a case in switch in solve function
	* in this file. This object is for parsing the equations and checking whether a system is
	* solvable and doing preprocessing of any kind. Then it calls the actual algorithm to solve.
	* @param -	expressions - system equations to solve
	**/
	var Solver = function(/* Array */expressions){
		_initialize(expressions);
		this.xvars = variables;
		this.eqs = equations;
		this.result = solution;
	};

	Solver.prototype = {
		solve: solve
	};

	return Solver;
});
<commit_msg>error message fixed<commit_after>define([
	"dojo/_base/lang",
	"parser/parser",
	"./newton-raphson",
	"./error-messages"
], function(lang, Parser, NewtonRaphson, messages){
	var solver = null;
	var equations = [];
	var variables = [];
	var maxAttempts = 4; // maximum number of times a system should be solved
	var epsilon = 10e-6;
	var solution = null;

	/**
	* Initialize the system of equations. Checks if an equation is provided
	* in the form of string or a parser object. Creates an object with lhs and rhs parsed
	* equations and pushes it in an array called equations. It updates the total number
	* of variables in the equations as well.
	* @param -  expressions - array of equations as strings or parser objects
	**/
	var _initialize = function(expressions){
		equations = [];
		variables = [];
        var length = expressions.length;
		for(var index = 0; index < length; index++){
			var expression = expressions[index];
			var eq = {};
			if(typeof(expression) == "string" && expression.indexOf("=") > -1){
				var eqs = expression.split("=");
				if(eqs.length > 2)
					throw {
						type: "equation.incorrect.format",
						message: messages.get("equation.incorrect.format")
					};
				eq.lhs = Parser.parse(eqs[0]);
				eq.rhs = Parser.parse(eqs[1]);
			} else if(typeof(expression) == "string"){
				eq.lhs = Parser.parse(expression);
				eq.rhs = Parser.parse(0);
			} else if(typeof(expression) == "object" && expression.length == 2){
				eq.lhs = expression[0];
				eq.rhs = expression[1];
			} else if(typeof(expression) == "object"){
				eq.lhs = expression;
				eq.rhs = Parser.parse(0);
			}
			if(_isValid(eq)){
				equations.push(eq);
				_addVariables(eq);
			}
		}

		if(variables.length == 0)
			throw {
				type: "no.variables",
				message: messages.get("no.variables")
			};
	}

	/**
	* used to add unknown variables in the variables array created at the top.
	* @param -  expression - from which unknown variables are to be added
	**/
	var _addVariables = function(/* object */ expression){
		var update = function(variableArray){
            var length = variableArray.length;
			for(var index = 0; index < length; index++){
				var variable = variableArray[index];
				if(variables.indexOf(variable) < 0)
					variables.push(variable);
			}
		};
		update(expression.lhs.variables());
		if(expression.rhs) update(expression.rhs.variables());
	};

	/**
	* Preprocessing of equations will be part of this function. Currently preprocessing
	* involves removing that equation which does not have any variable in it. 2 = 2 sort
	* of equations.
	* @param -  expression - equation which is to checked
	* @return - isValid - boolean to provide whether expression is correct or not.
	**/
	var _isValid = function(/* object */ expression){
		var isValid = true;
		if((!expression.lhs || expression.lhs.variables().length == 0) &&
			(!expression.rhs || expression.rhs.variables().length == 0))
			isValid = false;

		return isValid;
	};

	/**
	* for over determined system where number of equations are more than the number
	* of variables, this picks up a subset based on removing equations which do not
	* bring any new variables in the system. First they are labelled as redundant
	* and then the appropriate equations are removed.
	* @param -	expressions - array for system of equations to be solved
	*        	start - this is a search algorithm, index is the starting equation
	* @return -	excess - the index of equations that were removed from expressions array
	**/
	var _preprocess = function(/* Array */ expressions, /* integer */ start){
		var l = expressions.length;
		var excess = [];
		var checked = []; // ids that are part of the system
		var numVariablesPerEquation = [];
		var _comparator = function(a, b){
			return a - b;
		};
		var index = start;
		var length = expressions.length;
		for(var i = 0; i < length; i++){
			isRedundant = true;
			if(index == l)
				index = 0;
			var eq = expressions[index];
			var ids = lang.clone(eq.lhs.variables());
			ids = ids.concat(eq.rhs.variables());
			numVariablesPerEquation[i] = ids.length;

			for(var j in ids){
				var id = ids[j];
				if(checked.indexOf(id) < 0){
					isRedundant = false;
					checked.push(id);
				}
			}

			if(isRedundant){
				excess.push(index);
			}
			index++;
		}
		// by pigeonhole principle this can not happen
		// but still for safety purposes
		if(excess.length < l-variables.length)
			throw{
				type: "inconsistent.system",
				message: messages.get("inconsistent.system")
			};

        // excess contains information about those equations which do not have any unique variable.
        // here we sort the excess array based on the count of variables.
		if(start === 0 && excess.length > l - variables.length)
			for(i in excess)
				excess.sort(function(a, b){return numVariablesPerEquation[a] - numVariablesPerEquation[b];});

        // slicing the ones which are less constrained i.e. the ones that have less
        // number of variables in them.
		excess = excess.slice(0, l-variables.length);
		excess.sort(_comparator);

		for(i = excess.length - 1; i >= 0; i--)
			expressions.splice(excess[i], 1);

		return excess;
	};

	/**
	* For over determined system, after a solution is found, check whether
	* the solution point solves the other equations
	* @param -	indexes - array of indexes which were removed from the system before solving
	*        	solution - the solution found using other equations in the system
	* @return -	boolean - whether the solution point solves the equation or not
	**/
	_checkEquations = function(/* Array */ indexes, /* Array */ solution){
		var values = {};
        var length = variables.length;
		for(var i = 0; i < length; i++)
			values[variables[i]] = solution.get(i, 0);

		var _equations = lang.clone(equations);
		for(var index in indexes){
			var diff = _equations[indexes[index]].lhs.evaluate(values) - _equations[indexes[index]].rhs.evaluate(values);

			if(Math.abs(diff) > epsilon){
				return false;
			}
		}

		return true;
	}

	/**
	* Solving the system of equations, preprocessing the equations if the number of
	* equations are more than unknown variables. To add new solver algorithms,
	* add a type in the switch case before the default case and call its solver function.
	* @return -	solution - solution calculated by the solver
	**/
	var solve = function(type){
		var solution;
		var doloop = true;
		var _equations = [];
		var start = 0; // preprocess is a search method to remove equations, so where to start searching
		var indexes = []; // equations that are not part of the solved system
		var attempts = 0;
		var solutionFound = false;
		maxAttempts = variables.length / 2;
		while(doloop){
			_equations = lang.clone(equations);
			if(equations.length == variables.length) doloop = false;
			else if(equations.length > variables.length) indexes = _preprocess(_equations, start);
			else
				throw{
					type: "under.determined.system",
					message: messages.get("under.determined.system")
				};

			switch(type){
				default:
					solver = new NewtonRaphson(_equations, variables);
					solution = solver.solve();
			}

			attempts++;
			if(doloop){
				if(_checkEquations(indexes, solution)){
					start = indexes[indexes.length - 1]
					doloop = false;
				} else if(attempts >= maxAttempts)
					throw{
						type: "overdetermined.no.solution",
						message: messages.get("overdetermined.no.solution")
					};
			}
		}

		return solution;
	};

	/**
	* constructor for the solver, it wraps over any kind of solver. The properties for adding
	* any new solver is to create a solve function and add it as a case in switch in solve function
	* in this file. This object is for parsing the equations and checking whether a system is
	* solvable and doing preprocessing of any kind. Then it calls the actual algorithm to solve.
	* @param -	expressions - system equations to solve
	**/
	var Solver = function(/* Array */expressions){
		_initialize(expressions);
		this.xvars = variables;
		this.eqs = equations;
		this.result = solution;
	};

	Solver.prototype = {
		solve: solve
	};

	return Solver;
});
<|endoftext|>


<commit_before>transpose_scale = ['C','C#','D','Eb','E','F','F#','G','Ab','A','Bb','B','C', 'Db','D','D#','E','F','Gb','G','G#','A','A#','C'];

key2num = {'A': 0, 'Bb': 1, 'B': 2, 'C': 3, 'C#': 4, 'Db': 4, 'D': 5, 'D#': 6, 'Eb': 6, 'E': 7, 'F': 8, 'F#': 9, 'Gb': 9, 'G': 10, 'G#': 11, 'Ab': 11};
num2key = {};
for (var p in key2num) if (key2num.hasOwnProperty(p)) num2key[key2num[p]] = p;

songTextToCanvas = function (text) {
    return text.replace(/\[[^\[]*\]/g, '').replace(/  +/g, ' ');;
};

songTextToHTML = function (text) {
    text = text.replace(/(\r\n|\n|\r)/gm, '
')
    text = text.replace(/\[[^\[]*\]/g, '');
    return text;
};

songTextToChordChart = function (text, transpose) {
    text = text.replace(/(\r\n|\n|\r)/gm, '
');
    text = text.replace(/\[[^\[]*\]/g, function (tag) {
        tag = tag.substring(1, tag.length-1);
        tag = tag.replace(/[CDEFGAB][#b]?/g, function (chord) {
            var n = (transpose_scale.indexOf(chord) + transpose) % transpose_scale.length;
            return transpose_scale[n < 0 ? n + transpose_scale.length : n];
        });

        return '' + tag + '';
    });

    return text;
};
<commit_msg>Fixed elusive off-by-one error in songs transpose<commit_after>transpose_scale = ['C','C#','D','Eb','E','F','F#','G','Ab','A','Bb','B','C', 'Db','D','D#','E','F','Gb','G','G#','A','A#', 'Bb', 'B', 'C'];

key2num = {'A': 0, 'Bb': 1, 'B': 2, 'C': 3, 'C#': 4, 'Db': 4, 'D': 5, 'D#': 6, 'Eb': 6, 'E': 7, 'F': 8, 'F#': 9, 'Gb': 9, 'G': 10, 'G#': 11, 'Ab': 11};
num2key = {};
for (var p in key2num) if (key2num.hasOwnProperty(p)) num2key[key2num[p]] = p;

songTextToCanvas = function (text) {
    return text.replace(/\[[^\[]*\]/g, '').replace(/  +/g, ' ');;
};

songTextToHTML = function (text) {
    text = text.replace(/(\r\n|\n|\r)/gm, '
')
    text = text.replace(/\[[^\[]*\]/g, '');
    return text;
};

songTextToChordChart = function (text, transpose) {
    text = text.replace(/(\r\n|\n|\r)/gm, '
');
    text = text.replace(/\[[^\[]*\]/g, function (tag) {
        tag = tag.substring(1, tag.length-1);
        tag = tag.replace(/[CDEFGAB][#b]?/g, function (chord) {
            var n = (transpose_scale.indexOf(chord) + transpose) % transpose_scale.length;
            return transpose_scale[n < 0 ? n + transpose_scale.length - 1 : n];
        });

        return '' + tag + '';
    });

    return text;
};
<|endoftext|>


<commit_before>/**
 * entry_HOMEPAGE.js
 *
 * Module for loading styles and scripts related to the home page only
 *
 */

 "use strict";

var $ = require( "jquery" ); // require jQuery

require( "./homepage.scss" ); // styles for the homepage only

// Wait for the DOM to be ready before loading in JSON
document.addEventListener( "DOMContentLoaded", function( event ) {

  /*
   * ==================================================================
   * LOOK FOR THE FIRST 11 POSTS VIA THE WP REST API AND PLACE THEM ON * THE HOME PAGE ON A CERTAIN WAY
   * ==================================================================
   */

  /*
   * Grab the first 9 single posts from the WordPress API & sort them
   * by date.
   */
    var getPostsAPI = "/wp-json/posts?filter[orderby]=date&filter[posts_per_page]=9";

  /*
   * Load in post content data with $.getJSON()
   * Refer to this data as "posts" inside the $.getJSON call
   */
    $.getJSON( getPostsAPI ).done( function( posts ) {

      // var reference to
 on the home page
      var articleSection = document.getElementById( "all-articles" ),

      /*
       * Create document fragment to batch-load a single snippet onto
       * the page
       */
      olderPosts = document.createDocumentFragment();

      for( var outerKey in posts ) {

        // Run hasOwnPropertyCheck for the outer for..in loop
        if( posts.hasOwnProperty(outerKey) ) {

          // jQuery-styled single var pattern
          var postImage,
              postLink,
              postTitle,
              postExcerpt,
              postCategory,
              categoryHref,
              snippetContainer = document.createElement( "article" ),
              snippetHeader = document.createElement( "h2" ),
              singleExcerpt = document.createElement( "p" ),
              snippetLink = document.createElement( "a" ),
              snippetImage = document.createElement( "img" ),
              imageDiv = document.createElement( "div" ),
              categoryLink = document.createElement( "a" ),

              // Boolean check for the first post
              isFirstPost = posts[outerKey] == posts[0];

          // SET UP THE
 TAG!!!!

          // Check if we're working with the first post
          if( isFirstPost ) {
            /*
             * If it's the first post, apply the
             * "first-homepage-post-snippet" class to the
 tag
             */
            snippetContainer.setAttribute( "class", "first-homepage-post-snippet" );
          } else {
            /*
             * If it's NOT the first post, apply the
             * "homepage-post-snippet" class to the
 tag
             */
            snippetContainer.setAttribute( "class", "homepage-post-snippet" );
          }
          // STOP
 TAG SETUP!!!!

          // SET UP SINGLE BLOG POST IMAGES!!!!

          /*
           * Featured images are defined by "Featured Image" section of a
           * single WordPress post's page. If it's not defined, a
           * default image is loaded via the "Default featured image"
           * WordPress plugin.
           */
          postImage = posts[outerKey].featured_image.source;

          // Add styles and a "src" attribute to the image
          $( snippetImage ).attr({
            "src": postImage,
            "class": "post-pic post-pic-border"
          });

          // Load post image in a

          imageDiv.appendChild( snippetImage );

          // STOP SINGLE BLOG POST IMAGES SETUP!!!!

          // SET UP SINGLE BLOG LINK & HEADER!!!!

          // Get post title link
          postLink = posts[outerKey].link;

          // Get post title copy
          postTitle = posts[outerKey].title;

          // Set the article link's "href" to be the post link
          $(snippetLink).attr({
            "href": postLink,
            class: "post-link"
          });

          // Load post title copy in the  tag
          snippetLink.innerHTML = postTitle;

          // Load link into the post header
          snippetHeader.appendChild( snippetLink );

          // STOP SINGLE BLOG LINK & HEADER SETUP!!!!

          // SET UP SINGLE BLOG POST EXCERPT!!!!

      // Get post excerpt copy
      postExcerpt = posts[outerKey].excerpt;

      // Load post excerpt copy in the
 tag
      singleExcerpt.innerHTML = postExcerpt;

      // STOP SINGLE BLOG POST EXCERPT SETUP!!!!

      /*
       * APPEND EVERYTHING WE HAVE AT THIS POINT TO THE

       *
       * We have all the post snippet elements...EXCEPT for the
       * category. Append those elements to the
 tag.
       */

      // First, append the post image to the
...
      snippetContainer.appendChild( imageDiv );

      // Second, append the post header to the
...
      snippetContainer.appendChild( snippetHeader );

      // Third, append the post excerpt to the
.
      snippetContainer.appendChild( singleExcerpt );

      /*
       * SET UP THE CATEGORY !!!!
       *
       * The category name object is nested deeper in the WP-API
       * than the other info, so we have to do a an inner for...in
       * loop to find it. This code needs to run last; otherwise,
       * it breaks the process of grabbing post data.
       */

      // Grab the "category" value in the WP-API
      postCategory = posts[outerKey].terms.category;

      // Loop through the category object
      for ( var innerKey in postCategory ) {

        if( postCategory.hasOwnProperty( innerKey ) ){

            // Find category name & put it in "categoryLink" element
            categoryLink.innerHTML = postCategory[innerKey].name;
            categoryHref = "/" + postCategory[innerKey].slug + "/";

            // Give "categoryLink" class name & href attributes
            $(categoryLink).attr({
              "class": "category-name",
              "href": categoryHref
            });

            // Use $.prepend() to put categoryLink at TOP of

            $( snippetContainer ).prepend( categoryLink );

          }  // END INNER "for...in" LOOP's hasOwnProperty() check

        }  // END INNER "for...in" LOOP

        // STOP CATEGORY SETUP !!!!

        /*
         * Load article with title, image, excerpt and category into
         * the document fragment
         */
        olderPosts.appendChild( snippetContainer );
      }
    } // end for...in loop

    /*
     * Exit loop, then load the document fragment with all the content
     * into the "all-articles" element that's already on the page
     */
    articleSection.appendChild( olderPosts );

  }); // end $.getJSON()

}); // end addEventListener<commit_msg>refactor functionality that loads posts onto the homepage (see message) The newest post should load into an element different from the one that contains older posts. Rewrite it so that it does this. Add lots of comments explaining how this works and fix whitespace.<commit_after>/**
 * entry_HOMEPAGE.js
 *
 * Module for loading styles and scripts related to the home page only
 *
 */

 "use strict";

var $ = require( "jquery" ); // require jQuery

require( "./homepage.scss" ); // styles for the homepage only

// Wait for the DOM to be ready before loading in JSON
document.addEventListener( "DOMContentLoaded", function( event ) {

  /*
   * ==================================================================
   * LOOK FOR THE FIRST 11 POSTS VIA THE WP REST API AND PLACE THEM ON * THE HOME PAGE ON A CERTAIN WAY
   * ==================================================================
   */

  /*
   * Grab the first 9 single posts from the WordPress API & sort them
   * by date.
   */
   var getPostsAPI = "/wp-json/posts?filter[orderby]=date&filter[posts_per_page]=9";

  /*
   * Load in post content data with $.getJSON()
   * Refer to this data as "posts" inside the $.getJSON call
   */
   $.getJSON( getPostsAPI ).done( function( posts ) {

      /*
       * Create document fragment to batch-load the newest post and
       * define the target element where the fragment will eventually
       * load into...the elements already on the page
       */
       var newestPostFragment = document.createDocumentFragment(),
           newestPostTarget = document.getElementById( "newest-article" );

      /*
       * Create document fragment to batch-load the older posts and
       * define the target element where the fragment will eventually
       * load into...the elements already on the page
       */
       var olderPostsFragment = document.createDocumentFragment(),
           olderPostsTarget = document.getElementById( "other-articles" );

       for( var outerKey in posts ) {

        // Run hasOwnPropertyCheck for the outer for..in loop
        if( posts.hasOwnProperty( outerKey ) ) {

          // jQuery-styled single var pattern
          var postImage,
          postLink,
          postTitle,
          postExcerpt,
          postCategory,
          categoryHref,
          snippetContainer = document.createElement( "article" ),
          snippetHeader = document.createElement( "h2" ),
          singleExcerpt = document.createElement( "p" ),
          snippetLink = document.createElement( "a" ),
          snippetImage = document.createElement( "img" ),
          imageDiv = document.createElement( "div" ),
          categoryLink = document.createElement( "a" ),

          // Boolean check for the first post
          isFirstPost = posts[outerKey] == posts[0];

          // SET UP THE
 TAG!!!!

        // Check if we're working with the first post
        if( isFirstPost ) {

          /*
           * If it's the first post, apply the
           * "first-homepage-post-snippet" class to the
 tag
           */
          snippetContainer.setAttribute( "class", "first-homepage-post-snippet" );
        } else {

          /*
           * If it's NOT the first post, apply the
           * "homepage-post-snippet" class to the
 tag
           */
          snippetContainer.setAttribute( "class", "homepage-post-snippet" );
        }
        // STOP
 TAG SETUP!!!!

        // SET UP SINGLE BLOG POST IMAGES!!!!

        /*
         * Featured images are defined by "Featured Image" section
         * of a single WordPress post's page. If it's not defined, a
         * default image is loaded via the "Default featured image"
         * WordPress plugin.
         */
        postImage = posts[outerKey].featured_image.source;

        // Add styles and a "src" attribute to the image
        $( snippetImage ).attr({
          "src": postImage,
          "class": "post-pic post-pic-border"
        });

        // Load post image in a

        imageDiv.appendChild( snippetImage );

        // STOP SINGLE BLOG POST IMAGES SETUP!!!!

        // SET UP SINGLE BLOG LINK & HEADER!!!!

        // Get post title link
        postLink = posts[outerKey].link;

        // Get post title copy
        postTitle = posts[outerKey].title;

        // Set the article link's "href" to be the post link
        $(snippetLink).attr({
          "href": postLink,
          class: "post-link"
        });

        // Load post title copy in the  tag
        snippetLink.innerHTML = postTitle;

        // Load link into the post header
        snippetHeader.appendChild( snippetLink );

        // STOP SINGLE BLOG LINK & HEADER SETUP!!!!

        // SET UP SINGLE BLOG POST EXCERPT!!!!

        // Get post excerpt copy
        postExcerpt = posts[outerKey].excerpt;

        // Load post excerpt copy in the
 tag
        singleExcerpt.innerHTML = postExcerpt;

        // STOP SINGLE BLOG POST EXCERPT SETUP!!!!

        /*
         * APPEND EVERYTHING WE HAVE AT THIS POINT TO THE

         *
         * We have all the post snippet elements...EXCEPT for the
         * category. Append those elements to the
 tag.
         */

        // First, append the post image to the
...
        snippetContainer.appendChild( imageDiv );

        // Second, append the post header to the
...
        snippetContainer.appendChild( snippetHeader );

        // Third, append the post excerpt to the
.
        snippetContainer.appendChild( singleExcerpt );

        /*
         * SET UP THE CATEGORY !!!!
         *
         * The category name object is nested deeper in the WP-API
         * than the other info, so we have to do a an inner for...in
         * loop to find it. This code needs to run last; otherwise,
         * it breaks the process of grabbing post data.
         */

        // Grab the "category" value in the WP-API
        postCategory = posts[outerKey].terms.category;

        // Loop through the category object
        for ( var innerKey in postCategory ) {

          if( postCategory.hasOwnProperty( innerKey ) ){

            // Find category name & put it in "categoryLink" element
            categoryLink.innerHTML = postCategory[innerKey].name;

            // create an href with the object's "slug" value
            categoryHref = "/" + postCategory[innerKey].slug + "/";

            // Give "categoryLink" class name & href attributes
            $( categoryLink ).attr({
              "class": "category-name",
              "href": categoryHref
            });

            // Use $.prepend() to put categoryLink at TOP of

            $( snippetContainer ).prepend( categoryLink );

          }  // END INNER "for...in" LOOP's hasOwnProperty() check

        }  // END INNER "for...in" LOOP

        // STOP CATEGORY SETUP !!!!

        /*
         * LOAD ALL ARTICLES ONTO THE PAGE
         * ============================================================
         * Load article with title, image, excerpt and category into
         * two different document fragments. The most-recent post
         * older posts loads into another spot.
         */
        if( isFirstPost ) {
          newestPostFragment.appendChild( snippetContainer );
          newestPostTarget.appendChild( newestPostFragment );
        } else {
          olderPostsFragment.appendChild( snippetContainer );
          olderPostsTarget.appendChild( olderPostsFragment );
        }

      } // END OUTER "for...in" LOOP's hasOwnProperty() check

    } // END OUTER "for...in" LOOP

  }); // end $.getJSON()

}); // end addEventListener<|endoftext|>


<commit_before>var mapObject = require('../mapObject');

module.exports = function(req, res, next) {
    /**
     * @param {Object|Object[]} objectOrArray
     * @param {Object}          map
     * @param {Object}          [meta]
     */
    res.sendObject = function(objectOrArray, map, meta) {
        var promise;

        if (objectOrArray instanceof Array) {
            var arrayPromises = objectOrArray.map(function(object, index) {
                return mapObject(object, map, index, objectOrArray);
            });
            promise = Promise.all(arrayPromises);
        } else {
            promise = mapObject(objectOrArray, map);
        }

        return promise.then(function(data) {
            res.sendData(data, meta);
        });
    };

    next();
};
<commit_msg>renaming<commit_after>var mapObject = require('../mapObject');

module.exports = function(req, res, next) {
    /**
     * @param {Object|Object[]} objectOrArray
     * @param {Object}          map
     * @param {Object}          [meta]
     */
    res.sendObject = function(objectOrArray, map, meta) {
        var mapPromise;

        if (objectOrArray instanceof Array) {
            var promises = objectOrArray.map(function(object, index) {
                return mapObject(object, map, index, objectOrArray);
            });
            mapPromise = Promise.all(promises);
        } else {
            mapPromise = mapObject(objectOrArray, map);
        }

        return mapPromise.then(function(data) {
            res.sendData(data, meta);
        });
    };

    next();
};
<|endoftext|>


<commit_before>var SourceMapConsumer = require('source-map').SourceMapConsumer;
var path = require('path');
var fs = require('fs');

// Only install once if called multiple times
var alreadyInstalled = false;

// If true, the caches are reset before a stack trace formatting operation
var emptyCacheBetweenOperations = false;

// Maps a file path to a string containing the file contents
var fileContentsCache = {};

// Maps a file path to a source map for that file
var sourceMapCache = {};

function isInBrowser() {
  return typeof window !== 'undefined';
}

function retrieveFile(path) {
  if (path in fileContentsCache) {
    return fileContentsCache[path];
  }

  try {
    // Use SJAX if we are in the browser
    if (isInBrowser()) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', path, false);
      xhr.send(null);
      var contents = xhr.readyState === 4 ? xhr.responseText : null;
    }

    // Otherwise, use the filesystem
    else {
      var contents = fs.readFileSync(path, 'utf8');
    }
  } catch (e) {
    var contents = null;
  }

  return fileContentsCache[path] = contents;
}

// Support URLs relative to a directory, but be careful about a protocol prefix
// in case we are in the browser (i.e. directories may start with "http://")
function supportRelativeURL(file, url) {
  if (!file) return url;
  var dir = path.dirname(file);
  var match = /^\w+:\/\/[^\/]*/.exec(dir);
  var protocol = match ? match[0] : '';
  return protocol + path.resolve(dir.slice(protocol.length), url);
}

function retrieveSourceMapURL(source) {
  var fileData;

  if (isInBrowser()) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', source, false);
    xhr.send(null);
    fileData = xhr.readyState === 4 ? xhr.responseText : null;

    // Support providing a sourceMappingURL via the SourceMap header
    var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
                          xhr.getResponseHeader("X-SourceMap");
    if (sourceMapHeader) {
      return sourceMapHeader;
    }
  }

  // Get the URL of the source map
  fileData = retrieveFile(source);
  var match = /\/\/[#@]\s*sourceMappingURL=(.*)\s*$/m.exec(fileData);
  if (!match) return null;
  return match[1];
};

// Can be overridden by the retrieveSourceMap option to install. Takes a
// generated source filename; returns a {map, optional url} object, or null if
// there is no source map.  The map field may be either a string or the parsed
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
// constructor).
function retrieveSourceMap(source) {
  var sourceMappingURL = retrieveSourceMapURL(source);
  if (!sourceMappingURL) return null;

  // Read the contents of the source map
  var sourceMapData;
  var dataUrlPrefix = "data:application/json;base64,";
  if (sourceMappingURL.slice(0, dataUrlPrefix.length).toLowerCase() == dataUrlPrefix) {
    // Support source map URL as a data url
    sourceMapData = new Buffer(sourceMappingURL.slice(dataUrlPrefix.length), "base64").toString();
    sourceMappingURL = null;
  } else {
    // Support source map URLs relative to the source URL
    sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
    sourceMapData = retrieveFile(sourceMappingURL, 'utf8');
  }

  if (!sourceMapData) {
    return null;
  }

  return {
    url: sourceMappingURL,
    map: sourceMapData
  };
}

function mapSourcePosition(position) {
  var sourceMap = sourceMapCache[position.source];
  if (!sourceMap) {
    // Call the (overrideable) retrieveSourceMap function to get the source map.
    var urlAndMap = retrieveSourceMap(position.source);
    if (urlAndMap) {
      sourceMap = sourceMapCache[position.source] = {
        url: urlAndMap.url,
        map: new SourceMapConsumer(urlAndMap.map)
      };

      // Load all sources stored inline with the source map into the file cache
      // to pretend like they are already loaded. They may not exist on disk.
      if (sourceMap.map.sourcesContent) {
        sourceMap.map.sources.forEach(function(source, i) {
          var contents = sourceMap.map.sourcesContent[i];
          if (contents) {
            var url = supportRelativeURL(sourceMap.url, source);
            fileContentsCache[url] = contents;
          }
        });
      }
    } else {
      sourceMap = sourceMapCache[position.source] = {
        url: null,
        map: null
      };
    }
  }

  // Resolve the source URL relative to the URL of the source map
  if (sourceMap && sourceMap.map) {
    var originalPosition = sourceMap.map.originalPositionFor(position);

    // Only return the original position if a matching line was found. If no
    // matching line is found then we return position instead, which will cause
    // the stack trace to print the path and line for the compiled file. It is
    // better to give a precise location in the compiled file than a vague
    // location in the original file.
    if (originalPosition.source !== null) {
      originalPosition.source = supportRelativeURL(
        sourceMap.url, originalPosition.source);
      return originalPosition;
    }
  }

  return position;
}

// Parses code generated by FormatEvalOrigin(), a function inside V8:
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(origin) {
  // Most eval() calls are in this format
  var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  if (match) {
    var position = mapSourcePosition({
      source: match[2],
      line: match[3],
      column: match[4] - 1
    });
    return 'eval at ' + match[1] + ' (' + position.source + ':' +
      position.line + ':' + (position.column + 1) + ')';
  }

  // Parse nested eval() calls using recursion
  match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  if (match) {
    return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  }

  // Make sure we still return useful information if we didn't find anything
  return origin;
}

// This is copied almost verbatim from the V8 source code at
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
// implementation of wrapCallSite() used to just forward to the actual source
// code of CallSite.prototype.toString but unfortunately a new release of V8
// did something to the prototype chain and broke the shim. The only fix I
// could find was copy/paste.
function CallSiteToString() {
  var fileName;
  var fileLocation = "";
  if (this.isNative()) {
    fileLocation = "native";
  } else {
    fileName = this.getScriptNameOrSourceURL();
    if (!fileName && this.isEval()) {
      fileLocation = this.getEvalOrigin();
      fileLocation += ", ";  // Expecting source position to follow.
    }

    if (fileName) {
      fileLocation += fileName;
    } else {
      // Source code does not originate from a file and is not native, but we
      // can still get the source position inside the source string, e.g. in
      // an eval string.
      fileLocation += "<anonymous>";
    }
    var lineNumber = this.getLineNumber();
    if (lineNumber != null) {
      fileLocation += ":" + lineNumber;
      var columnNumber = this.getColumnNumber();
      if (columnNumber) {
        fileLocation += ":" + columnNumber;
      }
    }
  }

  var line = "";
  var functionName = this.getFunctionName();
  var addSuffix = true;
  var isConstructor = this.isConstructor();
  var isMethodCall = !(this.isToplevel() || isConstructor);
  if (isMethodCall) {
    var typeName = this.getTypeName();
    var methodName = this.getMethodName();
    if (functionName) {
      if (typeName && functionName.indexOf(typeName) != 0) {
        line += typeName + ".";
      }
      line += functionName;
      if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
        line += " [as " + methodName + "]";
      }
    } else {
      line += typeName + "." + (methodName || "<anonymous>");
    }
  } else if (isConstructor) {
    line += "new " + (functionName || "<anonymous>");
  } else if (functionName) {
    line += functionName;
  } else {
    line += fileLocation;
    addSuffix = false;
  }
  if (addSuffix) {
    line += " (" + fileLocation + ")";
  }
  return line;
}

function cloneCallSite(frame) {
  var object = {};
  Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
    object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  });
  object.toString = CallSiteToString;
  return object;
}

function wrapCallSite(frame) {
  // Most call sites will return the source file from getFileName(), but code
  // passed to eval() ending in "//# sourceURL=..." will return the source file
  // from getScriptNameOrSourceURL() instead
  var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  if (source) {
    var position = mapSourcePosition({
      source: source,
      line: frame.getLineNumber(),
      column: frame.getColumnNumber() - 1
    });
    frame = cloneCallSite(frame);
    frame.getFileName = function() { return position.source; };
    frame.getLineNumber = function() { return position.line; };
    frame.getColumnNumber = function() { return position.column + 1; };
    frame.getScriptNameOrSourceURL = function() { return position.source; };
    return frame;
  }

  // Code called using eval() needs special handling
  var origin = frame.isEval() && frame.getEvalOrigin();
  if (origin) {
    origin = mapEvalOrigin(origin);
    frame = cloneCallSite(frame);
    frame.getEvalOrigin = function() { return origin; };
    return frame;
  }

  // If we get here then we were unable to change the source position
  return frame;
}

// This function is part of the V8 stack trace API, for more info see:
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
function prepareStackTrace(error, stack) {
  if (emptyCacheBetweenOperations) {
    fileContentsCache = {};
    sourceMapCache = {};
  }
  return error + stack.map(function(frame) {
    return '\n    at ' + wrapCallSite(frame);
  }).join('');
}

// Generate position and snippet of original source with pointer
function getErrorSource(error) {
  var match = /\n    at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  if (match) {
    var source = match[1];
    var line = +match[2];
    var column = +match[3];

    // Support the inline sourceContents inside the source map
    var contents = fileContentsCache[source];

    // Support files on disk
    if (!contents && fs.existsSync(source)) {
      contents = fs.readFileSync(source, 'utf8');
    }

    // Format the line from the original source code like node does
    if (contents) {
      var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
      if (code) {
        return '\n' + source + ':' + line + '\n' + code + '\n' +
          new Array(column).join(' ') + '^';
      }
    }
  }
  return null;
}

// Mimic node's stack trace printing when an exception escapes the process
function handleUncaughtExceptions(error) {
  if (!error || !error.stack) {
    console.log('Uncaught exception:', error);
  } else {
    var source = getErrorSource(error);
    if (source !== null) console.log(source);
    console.log(error.stack);
  }
  process.exit(1);
}

exports.wrapCallSite = wrapCallSite;
exports.getErrorSource = getErrorSource;
exports.mapSourcePosition = mapSourcePosition;
exports.retrieveSourceMap = retrieveSourceMap;

exports.install = function(options) {
  if (!alreadyInstalled) {
    alreadyInstalled = true;
    Error.prepareStackTrace = prepareStackTrace;

    // Configure options
    options = options || {};
    var installHandler = 'handleUncaughtExceptions' in options ?
      options.handleUncaughtExceptions : true;
    emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
      options.emptyCacheBetweenOperations : false;

    // Allow sources to be found by methods other than reading the files
    // directly from disk.
    if (options.retrieveFile)
      retrieveFile = options.retrieveFile;

    // Allow source maps to be found by methods other than reading the files
    // directly from disk.
    if (options.retrieveSourceMap)
      retrieveSourceMap = options.retrieveSourceMap;

    // Provide the option to not install the uncaught exception handler. This is
    // to support other uncaught exception handlers (in test frameworks, for
    // example). If this handler is not installed and there are no other uncaught
    // exception handlers, uncaught exceptions will be caught by node's built-in
    // exception handler and the process will still be terminated. However, the
    // generated JavaScript code will be shown above the stack trace instead of
    // the original source code.
    if (installHandler && !isInBrowser()) {
      process.on('uncaughtException', handleUncaughtExceptions);
    }
  }
};
<commit_msg>Check XMLHttpRequest is a function for isInBrowser<commit_after>var SourceMapConsumer = require('source-map').SourceMapConsumer;
var path = require('path');
var fs = require('fs');

// Only install once if called multiple times
var alreadyInstalled = false;

// If true, the caches are reset before a stack trace formatting operation
var emptyCacheBetweenOperations = false;

// Maps a file path to a string containing the file contents
var fileContentsCache = {};

// Maps a file path to a source map for that file
var sourceMapCache = {};

function isInBrowser() {
  return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function'));
}

function retrieveFile(path) {
  if (path in fileContentsCache) {
    return fileContentsCache[path];
  }

  try {
    // Use SJAX if we are in the browser
    if (isInBrowser()) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', path, false);
      xhr.send(null);
      var contents = xhr.readyState === 4 ? xhr.responseText : null;
    }

    // Otherwise, use the filesystem
    else {
      var contents = fs.readFileSync(path, 'utf8');
    }
  } catch (e) {
    var contents = null;
  }

  return fileContentsCache[path] = contents;
}

// Support URLs relative to a directory, but be careful about a protocol prefix
// in case we are in the browser (i.e. directories may start with "http://")
function supportRelativeURL(file, url) {
  if (!file) return url;
  var dir = path.dirname(file);
  var match = /^\w+:\/\/[^\/]*/.exec(dir);
  var protocol = match ? match[0] : '';
  return protocol + path.resolve(dir.slice(protocol.length), url);
}

function retrieveSourceMapURL(source) {
  var fileData;

  if (isInBrowser()) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', source, false);
    xhr.send(null);
    fileData = xhr.readyState === 4 ? xhr.responseText : null;

    // Support providing a sourceMappingURL via the SourceMap header
    var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
                          xhr.getResponseHeader("X-SourceMap");
    if (sourceMapHeader) {
      return sourceMapHeader;
    }
  }

  // Get the URL of the source map
  fileData = retrieveFile(source);
  var match = /\/\/[#@]\s*sourceMappingURL=(.*)\s*$/m.exec(fileData);
  if (!match) return null;
  return match[1];
};

// Can be overridden by the retrieveSourceMap option to install. Takes a
// generated source filename; returns a {map, optional url} object, or null if
// there is no source map.  The map field may be either a string or the parsed
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
// constructor).
function retrieveSourceMap(source) {
  var sourceMappingURL = retrieveSourceMapURL(source);
  if (!sourceMappingURL) return null;

  // Read the contents of the source map
  var sourceMapData;
  var dataUrlPrefix = "data:application/json;base64,";
  if (sourceMappingURL.slice(0, dataUrlPrefix.length).toLowerCase() == dataUrlPrefix) {
    // Support source map URL as a data url
    sourceMapData = new Buffer(sourceMappingURL.slice(dataUrlPrefix.length), "base64").toString();
    sourceMappingURL = null;
  } else {
    // Support source map URLs relative to the source URL
    sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
    sourceMapData = retrieveFile(sourceMappingURL, 'utf8');
  }

  if (!sourceMapData) {
    return null;
  }

  return {
    url: sourceMappingURL,
    map: sourceMapData
  };
}

function mapSourcePosition(position) {
  var sourceMap = sourceMapCache[position.source];
  if (!sourceMap) {
    // Call the (overrideable) retrieveSourceMap function to get the source map.
    var urlAndMap = retrieveSourceMap(position.source);
    if (urlAndMap) {
      sourceMap = sourceMapCache[position.source] = {
        url: urlAndMap.url,
        map: new SourceMapConsumer(urlAndMap.map)
      };

      // Load all sources stored inline with the source map into the file cache
      // to pretend like they are already loaded. They may not exist on disk.
      if (sourceMap.map.sourcesContent) {
        sourceMap.map.sources.forEach(function(source, i) {
          var contents = sourceMap.map.sourcesContent[i];
          if (contents) {
            var url = supportRelativeURL(sourceMap.url, source);
            fileContentsCache[url] = contents;
          }
        });
      }
    } else {
      sourceMap = sourceMapCache[position.source] = {
        url: null,
        map: null
      };
    }
  }

  // Resolve the source URL relative to the URL of the source map
  if (sourceMap && sourceMap.map) {
    var originalPosition = sourceMap.map.originalPositionFor(position);

    // Only return the original position if a matching line was found. If no
    // matching line is found then we return position instead, which will cause
    // the stack trace to print the path and line for the compiled file. It is
    // better to give a precise location in the compiled file than a vague
    // location in the original file.
    if (originalPosition.source !== null) {
      originalPosition.source = supportRelativeURL(
        sourceMap.url, originalPosition.source);
      return originalPosition;
    }
  }

  return position;
}

// Parses code generated by FormatEvalOrigin(), a function inside V8:
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(origin) {
  // Most eval() calls are in this format
  var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  if (match) {
    var position = mapSourcePosition({
      source: match[2],
      line: match[3],
      column: match[4] - 1
    });
    return 'eval at ' + match[1] + ' (' + position.source + ':' +
      position.line + ':' + (position.column + 1) + ')';
  }

  // Parse nested eval() calls using recursion
  match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  if (match) {
    return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  }

  // Make sure we still return useful information if we didn't find anything
  return origin;
}

// This is copied almost verbatim from the V8 source code at
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
// implementation of wrapCallSite() used to just forward to the actual source
// code of CallSite.prototype.toString but unfortunately a new release of V8
// did something to the prototype chain and broke the shim. The only fix I
// could find was copy/paste.
function CallSiteToString() {
  var fileName;
  var fileLocation = "";
  if (this.isNative()) {
    fileLocation = "native";
  } else {
    fileName = this.getScriptNameOrSourceURL();
    if (!fileName && this.isEval()) {
      fileLocation = this.getEvalOrigin();
      fileLocation += ", ";  // Expecting source position to follow.
    }

    if (fileName) {
      fileLocation += fileName;
    } else {
      // Source code does not originate from a file and is not native, but we
      // can still get the source position inside the source string, e.g. in
      // an eval string.
      fileLocation += "<anonymous>";
    }
    var lineNumber = this.getLineNumber();
    if (lineNumber != null) {
      fileLocation += ":" + lineNumber;
      var columnNumber = this.getColumnNumber();
      if (columnNumber) {
        fileLocation += ":" + columnNumber;
      }
    }
  }

  var line = "";
  var functionName = this.getFunctionName();
  var addSuffix = true;
  var isConstructor = this.isConstructor();
  var isMethodCall = !(this.isToplevel() || isConstructor);
  if (isMethodCall) {
    var typeName = this.getTypeName();
    var methodName = this.getMethodName();
    if (functionName) {
      if (typeName && functionName.indexOf(typeName) != 0) {
        line += typeName + ".";
      }
      line += functionName;
      if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
        line += " [as " + methodName + "]";
      }
    } else {
      line += typeName + "." + (methodName || "<anonymous>");
    }
  } else if (isConstructor) {
    line += "new " + (functionName || "<anonymous>");
  } else if (functionName) {
    line += functionName;
  } else {
    line += fileLocation;
    addSuffix = false;
  }
  if (addSuffix) {
    line += " (" + fileLocation + ")";
  }
  return line;
}

function cloneCallSite(frame) {
  var object = {};
  Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
    object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  });
  object.toString = CallSiteToString;
  return object;
}

function wrapCallSite(frame) {
  // Most call sites will return the source file from getFileName(), but code
  // passed to eval() ending in "//# sourceURL=..." will return the source file
  // from getScriptNameOrSourceURL() instead
  var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  if (source) {
    var position = mapSourcePosition({
      source: source,
      line: frame.getLineNumber(),
      column: frame.getColumnNumber() - 1
    });
    frame = cloneCallSite(frame);
    frame.getFileName = function() { return position.source; };
    frame.getLineNumber = function() { return position.line; };
    frame.getColumnNumber = function() { return position.column + 1; };
    frame.getScriptNameOrSourceURL = function() { return position.source; };
    return frame;
  }

  // Code called using eval() needs special handling
  var origin = frame.isEval() && frame.getEvalOrigin();
  if (origin) {
    origin = mapEvalOrigin(origin);
    frame = cloneCallSite(frame);
    frame.getEvalOrigin = function() { return origin; };
    return frame;
  }

  // If we get here then we were unable to change the source position
  return frame;
}

// This function is part of the V8 stack trace API, for more info see:
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
function prepareStackTrace(error, stack) {
  if (emptyCacheBetweenOperations) {
    fileContentsCache = {};
    sourceMapCache = {};
  }
  return error + stack.map(function(frame) {
    return '\n    at ' + wrapCallSite(frame);
  }).join('');
}

// Generate position and snippet of original source with pointer
function getErrorSource(error) {
  var match = /\n    at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  if (match) {
    var source = match[1];
    var line = +match[2];
    var column = +match[3];

    // Support the inline sourceContents inside the source map
    var contents = fileContentsCache[source];

    // Support files on disk
    if (!contents && fs.existsSync(source)) {
      contents = fs.readFileSync(source, 'utf8');
    }

    // Format the line from the original source code like node does
    if (contents) {
      var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
      if (code) {
        return '\n' + source + ':' + line + '\n' + code + '\n' +
          new Array(column).join(' ') + '^';
      }
    }
  }
  return null;
}

// Mimic node's stack trace printing when an exception escapes the process
function handleUncaughtExceptions(error) {
  if (!error || !error.stack) {
    console.log('Uncaught exception:', error);
  } else {
    var source = getErrorSource(error);
    if (source !== null) console.log(source);
    console.log(error.stack);
  }
  process.exit(1);
}

exports.wrapCallSite = wrapCallSite;
exports.getErrorSource = getErrorSource;
exports.mapSourcePosition = mapSourcePosition;
exports.retrieveSourceMap = retrieveSourceMap;

exports.install = function(options) {
  if (!alreadyInstalled) {
    alreadyInstalled = true;
    Error.prepareStackTrace = prepareStackTrace;

    // Configure options
    options = options || {};
    var installHandler = 'handleUncaughtExceptions' in options ?
      options.handleUncaughtExceptions : true;
    emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
      options.emptyCacheBetweenOperations : false;

    // Allow sources to be found by methods other than reading the files
    // directly from disk.
    if (options.retrieveFile)
      retrieveFile = options.retrieveFile;

    // Allow source maps to be found by methods other than reading the files
    // directly from disk.
    if (options.retrieveSourceMap)
      retrieveSourceMap = options.retrieveSourceMap;

    // Provide the option to not install the uncaught exception handler. This is
    // to support other uncaught exception handlers (in test frameworks, for
    // example). If this handler is not installed and there are no other uncaught
    // exception handlers, uncaught exceptions will be caught by node's built-in
    // exception handler and the process will still be terminated. However, the
    // generated JavaScript code will be shown above the stack trace instead of
    // the original source code.
    if (installHandler && !isInBrowser()) {
      process.on('uncaughtException', handleUncaughtExceptions);
    }
  }
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name           Google personal blocklist
// @namespace      curipha
// @description    Obscure annoying sites from search result
// @include        http://www.google.tld/search?*
// @include        https://www.google.tld/search?*
// @version        0.2.2
// @grant          none
// @noframes
// ==/UserScript==

(function(){
  var block = [
    // General doorways
    'ceron.jp/', 'page2rss.com/', 'zenback.itmedia.co.jp/', 'hatebu-graph.com/',
    'b.hatena.ne.jp/entrylist/',

    // Application doorways
    '([^/]+.)?filehippo.com/', '[^/]+.soft(onic|pedia).(com|jp)/', '[^/]+.uptodown.com/',

    // SNS doorways
    '([^/]+.)?favstar.fm/',
    '([^/]+.)?(tweet|twtr)[^/]+.(com|jp)/', // genocide...

    // Knowledge communities
    'questionbox.jp.msn.com/', 'ziddy.japan.zdnet.com/', 'soudan1.biglobe.ne.jp/', 'qanda.rakuten.ne.jp/', 'www.itmedia.co.jp/qa/',
    'oshiete1?.(nifty.com|goo.ne.jp)/',
    '([^/]+.)?okwave.jp/', '([^/]+.)?chiebukuro(.travel)?.yahoo.co.jp/',

    // EC
    '(e?search|item).rakuten.co.jp/',
    '([^/]+.)?.animate-onlineshop.jp/',

    // Anime leakers
    'anime.dougasouko.com/',
    '([^/]+.)?anitube.se/',
    '([^/]*(anime|youtube)[^/]*|mvnavian).blog[0-9]*.(fc2.com|fc2blog.us)/',

    // Torrents
    '([^/]+.)?nyaa.se/',

    // Dll listing
    'systemexplorer.net/', '[^/]+.dll-files.com/',

    // Mobile pages
    'www.amazon.co.jp/gp/aw/'
  ];

  var opacity = 0.2;
  var pattern = new RegExp('^https?:\/\/(?:' + block.join('|').replace(/([.\/])/g, '\\$1') + ')', 'i');
  var googler = /^https?:\/\/www\.google\.com\/url\?/i;
  var t = 0;

  var blocker = function() {
    var result = document.querySelectorAll('li.g');
    for (var li of result) {
      var a = li.querySelector('h3 > a[href]');
      if (!a) continue;

      if (googler.test(a.href)) {
        var alturi = li.querySelector('cite._Rm').textContent;
        if (typeof(alturi) !== 'string') continue;

        alturi = alturi.replace(/\s+\u203A\s+/g, '/');
        var uri = /^https?:\/\//.test(uri) ? alturi : 'http://' + alturi;
      }
      else {
        var uri = a.href;
      }

      if (pattern.test(uri)) li.style.opacity = opacity;
    }
  };
  var blocker_wrap = function() {
    if (t) return;
    ｔ = setTimeout(function() {
      blocker();
      t = 0;
    }, 120);
  };

  blocker();

  var mo = new MutationObserver(blocker_wrap);
  mo.observe(document.body, { childList: true, subtree: true });
})();
<commit_msg>Revert 3bfd163671667498cf39d396767c90bb842458c7 partially<commit_after>// ==UserScript==
// @name           Google personal blocklist
// @namespace      curipha
// @description    Obscure annoying sites from search result
// @include        http://www.google.tld/search?*
// @include        https://www.google.tld/search?*
// @version        0.2.2
// @grant          none
// @noframes
// ==/UserScript==

(function(){
  var block = [
    // General doorways
    'ceron.jp/', 'page2rss.com/', 'zenback.itmedia.co.jp/', 'hatebu-graph.com/',
    'b.hatena.ne.jp/entrylist/',

    // Application doorways
    'www.altech-ads.com/', 'www.freewarelovers.com/', 'www.appbrain.com/', 'www.vector.co.jp/soft/',
    '([^/]+.)?filehippo.com/', '[^/]+.soft(onic|pedia).(com|jp)/', '[^/]+.uptodown.com/',

    // SNS doorways
    '([^/]+.)?favstar.fm/',
    '([^/]+.)?(tweet|twtr)[^/]+.(com|jp)/', // genocide...

    // Knowledge communities
    'questionbox.jp.msn.com/', 'ziddy.japan.zdnet.com/', 'soudan1.biglobe.ne.jp/', 'qanda.rakuten.ne.jp/', 'www.itmedia.co.jp/qa/',
    'oshiete1?.(nifty.com|goo.ne.jp)/',
    '([^/]+.)?okwave.jp/', '([^/]+.)?chiebukuro(.travel)?.yahoo.co.jp/',

    // EC
    '(e?search|item).rakuten.co.jp/',
    '([^/]+.)?.animate-onlineshop.jp/',

    // Anime leakers
    'anime.dougasouko.com/',
    '([^/]+.)?anitube.se/',
    '([^/]*(anime|youtube)[^/]*|mvnavian).blog[0-9]*.(fc2.com|fc2blog.us)/',

    // Torrents
    '([^/]+.)?nyaa.se/',

    // Dll listing
    'systemexplorer.net/', '[^/]+.dll-files.com/',

    // Mobile pages
    'www.amazon.co.jp/gp/aw/'
  ];

  var opacity = 0.2;
  var pattern = new RegExp('^https?:\/\/(?:' + block.join('|').replace(/([.\/])/g, '\\$1') + ')', 'i');
  var googler = /^https?:\/\/www\.google\.com\/url\?/i;
  var t = 0;

  var blocker = function() {
    var result = document.querySelectorAll('li.g');
    for (var li of result) {
      var a = li.querySelector('h3 > a[href]');
      if (!a) continue;

      if (googler.test(a.href)) {
        var alturi = li.querySelector('cite._Rm').textContent;
        if (typeof(alturi) !== 'string') continue;

        alturi = alturi.replace(/\s+\u203A\s+/g, '/');
        var uri = /^https?:\/\//.test(uri) ? alturi : 'http://' + alturi;
      }
      else {
        var uri = a.href;
      }

      if (pattern.test(uri)) li.style.opacity = opacity;
    }
  };
  var blocker_wrap = function() {
    if (t) return;
    ｔ = setTimeout(function() {
      blocker();
      t = 0;
    }, 120);
  };

  blocker();

  var mo = new MutationObserver(blocker_wrap);
  mo.observe(document.body, { childList: true, subtree: true });
})();
<|endoftext|>


<commit_before>var RefreshWeather = function (options) {
  options = options || {};
  options.update_interval = options.update_interval || 1000 * 60 * 120;
  var update_interval;

  function resetWeatherInfo() {
    $(".weather .weather-box span").html("");
    $(".weather .data-field").html("");
    $(".weather .weather-box").removeClass("new-day"); // Remove "day changed" separator line
    $(".weather-all").children().remove();
  }

  function processData(data) {
    resetWeatherInfo();
    if (data.sun) {
      var sunrise = moment(data.sun.sunrise);
      var sunset = moment(data.sun.sunset);
      $(".sun-info").html(" " + sunrise.format("HH:mm") + " (" + sunrise.fromNow() + ")  " + sunset.format("HH:mm") + " (" + sunset.fromNow() + ")");
    }
    var items = $(".weather"),
        current_index = 1,
        first_date = false,
        new_day = false;
    items.find(".temperature-now").html(data.current.feels_like);
    items.find(".wind-now").html(data.current.wind_speed_readable);
    $.each(data.next, function () {
      var this_item = items.find(".weather-" + current_index);
      if (first_date === false) {
        first_date = this.item.date;
      } else if (new_day === false) {
        if (first_date !== this.item.date) {
          this_item.addClass("new-day");
          new_day = true;
        }
      }
      this_item.find(".timestamp").html(this.name);
      this_item.find(".temperature").html(this.item.feels_like);
      this_item.find(".symbol").html("");
      this_item.find(".temperature-unit").html("°C");
      current_index += 1;
    });
    var now = moment(),
        current_index = 13,
        current_row,
        highlight_set = false,
        last_header,
        new_item = "

°C
: m/s
";
    $.each(data.hours, function () {
      if (this.hour % 2 != 0) {
        return true; // continue
      }
      if (current_index > 11) {
        current_index = 0;
        $(".weather-all").append("

");
        current_row = $(".weather-all .row").last();
        last_header = $(".weather-all h2").last();
        last_header.html(this.weekday_fi+" "+this.date);
      }
      current_row.append(new_item);
      var current_item = current_row.find(".col-md-1").last();

      current_item.find(".timestamp").html(this.hour+":00");
      current_item.find(".temperature").html(this.feels_like);
      current_item.find(".symbol").html("");
      current_item.find(".temperature-unit").html("°C");
      current_item.find(".wind-speed").html(Math.round(this.wind_speed / 3.6));
      current_item.find(".wind-direction").html(this.wind_direction);
      console.log(this.date, now.format("YYYY-MM-DD"), this.hour, now.hour());
      if (!highlight_set && this.date == now.format("YYYY-MM-DD") && this.hour >= now.hour()) {
        current_item.addClass("weather-today");
        highlight_set = true;
      }
      current_index += 1;
    });
  }

  function update() {
    $.get("/homecontroller/weather/get_json", function (data) {
      processData(data);
    });
  }

  function onReceiveItemWS(data) {
    processData(data);
  }

  function startInterval() {
    stopInterval();
    update();
    update_interval = setInterval(update, options.update_interval);
    ws_generic.register("weather", onReceiveItemWS);
    ge_refresh.register("weather", update);
  }

  function stopInterval() {
    if (update_interval) {
      update_interval = clearInterval(update_interval);
    }
    ws_generic.deRegister("weather");
    ge_refresh.deRegister("weather");
  }

  this.startInterval = startInterval;
  this.stopInterval = stopInterval;

};

var refresh_weather;
$(document).ready(function () {
  refresh_weather = new RefreshWeather();
  refresh_weather.startInterval();
  $(".open-weather-modal").on("click", function() {
    switchVisibleContent("#weather-modal");
  });
  $("#weather-modal .close").on("click", function() {
    switchVisibleContent("#main-content");
  });

});
<commit_msg>Remove debug print<commit_after>var RefreshWeather = function (options) {
  options = options || {};
  options.update_interval = options.update_interval || 1000 * 60 * 120;
  var update_interval;

  function resetWeatherInfo() {
    $(".weather .weather-box span").html("");
    $(".weather .data-field").html("");
    $(".weather .weather-box").removeClass("new-day"); // Remove "day changed" separator line
    $(".weather-all").children().remove();
  }

  function processData(data) {
    resetWeatherInfo();
    if (data.sun) {
      var sunrise = moment(data.sun.sunrise);
      var sunset = moment(data.sun.sunset);
      $(".sun-info").html(" " + sunrise.format("HH:mm") + " (" + sunrise.fromNow() + ")  " + sunset.format("HH:mm") + " (" + sunset.fromNow() + ")");
    }
    var items = $(".weather"),
        current_index = 1,
        first_date = false,
        new_day = false;
    items.find(".temperature-now").html(data.current.feels_like);
    items.find(".wind-now").html(data.current.wind_speed_readable);
    $.each(data.next, function () {
      var this_item = items.find(".weather-" + current_index);
      if (first_date === false) {
        first_date = this.item.date;
      } else if (new_day === false) {
        if (first_date !== this.item.date) {
          this_item.addClass("new-day");
          new_day = true;
        }
      }
      this_item.find(".timestamp").html(this.name);
      this_item.find(".temperature").html(this.item.feels_like);
      this_item.find(".symbol").html("");
      this_item.find(".temperature-unit").html("°C");
      current_index += 1;
    });
    var now = moment(),
        current_index = 13,
        current_row,
        highlight_set = false,
        last_header,
        new_item = "

°C
: m/s
";
    $.each(data.hours, function () {
      if (this.hour % 2 != 0) {
        return true; // continue
      }
      if (current_index > 11) {
        current_index = 0;
        $(".weather-all").append("

");
        current_row = $(".weather-all .row").last();
        last_header = $(".weather-all h2").last();
        last_header.html(this.weekday_fi+" "+this.date);
      }
      current_row.append(new_item);
      var current_item = current_row.find(".col-md-1").last();

      current_item.find(".timestamp").html(this.hour+":00");
      current_item.find(".temperature").html(this.feels_like);
      current_item.find(".symbol").html("");
      current_item.find(".temperature-unit").html("°C");
      current_item.find(".wind-speed").html(Math.round(this.wind_speed / 3.6));
      current_item.find(".wind-direction").html(this.wind_direction);
      if (!highlight_set && this.date == now.format("YYYY-MM-DD") && this.hour >= now.hour()) {
        current_item.addClass("weather-today");
        highlight_set = true;
      }
      current_index += 1;
    });
  }

  function update() {
    $.get("/homecontroller/weather/get_json", function (data) {
      processData(data);
    });
  }

  function onReceiveItemWS(data) {
    processData(data);
  }

  function startInterval() {
    stopInterval();
    update();
    update_interval = setInterval(update, options.update_interval);
    ws_generic.register("weather", onReceiveItemWS);
    ge_refresh.register("weather", update);
  }

  function stopInterval() {
    if (update_interval) {
      update_interval = clearInterval(update_interval);
    }
    ws_generic.deRegister("weather");
    ge_refresh.deRegister("weather");
  }

  this.startInterval = startInterval;
  this.stopInterval = stopInterval;

};

var refresh_weather;
$(document).ready(function () {
  refresh_weather = new RefreshWeather();
  refresh_weather.startInterval();
  $(".open-weather-modal").on("click", function() {
    switchVisibleContent("#weather-modal");
  });
  $("#weather-modal .close").on("click", function() {
    switchVisibleContent("#main-content");
  });

});
<|endoftext|>


<commit_before>/*
 * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * selectToToggle - Show/hide an HTML block(s) according to value selected in a <select>, or <input type="radio"> element
 * Reserved JS class prefix: _stt
 * Reserved CSS class prefix: none
 * Note: Be careful if there are more than one selectToToggle elements on a page with one or more options having same values (use className on the option tags in those cases)
 **/
(function ($) {
  $.selectToToggle = function (el) {
    var toggle = function () {
      var data      = $(this).data('selectToToggle');
      var wrapper   = data.wrapper;
      var toggleMap = data.toggleMap;
      for (var val in toggleMap) {
        if (val != this.value) {
          wrapper.find(toggleMap[val]).hide().removeAttr('checked').filter('option').each(function() { // if hiding an option element, also disable it to make it work in webkit
            var option = $(this);

            if (typeof option.data('sttDisabled') === 'undefined') {
              option.data('sttDisabled', !!this.disabled); // remember original disabled attribute
            }
          }).prop('disabled', true);
        }
      }

      wrapper.find(toggleMap[this.value]).show().filter('option').prop('disabled', function() {
        return $(this).data('sttDisabled');
      }).filter('select option').parent().each(function() { //show the requried html block
        var dropdown = $(this);
        if (!dropdown.find('option:selected:enabled').length) { //in case any selected option gets hidden in this, select the first visible option
          dropdown.find('option:enabled').first().prop('selected', true);
          if (dropdown.data('selectToToggle')) {
            dropdown.trigger('change.selectToToggle');
          }
        }
      });
    };

    el.off('.selectToToggle').on('change.selectToToggle', toggle);

    toggle.apply(el.filter('select, input:checked')[0]);

  };

  $.fn.selectToToggle = function (
    toggleMap,  // map of select element's option value to corresponding jquery selectors strings (as accepted by find() method) (Optional - defaults to '._stt_[className]' if class name uses prefix _stt__, or '._stt_[value]' otherwise)
                // string 'trigger' to trigger toggling for an existing element (this is useful is option is selected by JS)
                // string 'destroy' to remove all selectToToggle data and events from the element
    wrapper     // wrapper element to call method 'find(selectors)' on - defaults to $(document.body)
  ) {

    return this.each(function () {
      var el        = $(this);
      var data      = el.data('selectToToggle');

      var getAllEls = function(el, wrapper) {
        return el[0].nodeName === 'INPUT' ? wrapper.find('input[name=' + el[0].name + ']') : el;
      };

      if (data) {
        if (toggleMap === 'trigger') {
          el.trigger('change.selectToToggle');
        } else if (toggleMap === 'destroy') {
          getAllEls(el, data.wrapper).off('.selectToToggle').removeData('selectToToggle');
        }

      } else {
        var tMap  = $.extend({}, toggleMap);
        wrapper   = wrapper || $(document.body);
        el        = getAllEls(el, wrapper);

        if ($.isEmptyObject(tMap)) {
          (this.nodeName == 'SELECT' ? el.find('option') : el).each(function() {
            if (this.value) {
              var filters = $.map(this.className.match(/(\s+|^)_stt__([^\s]+)/g) || [], function(str) { return str.replace('_stt__', '._stt_') });
                  filters.push('._stt_' + this.value);
              tMap[this.value] = this.className.match(/(\s+|^)_sttmulti($|\s+)/) ? filters.join(',') : filters[0];
            }
          });
        }

        el.data('selectToToggle', {'wrapper' : wrapper, 'toggleMap': tMap});

        $.selectToToggle(el);
      }
    });
  };
})(jQuery);<commit_msg>Trigger selectToToggle only for selected radio box<commit_after>/*
 * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * selectToToggle - Show/hide an HTML block(s) according to value selected in a <select>, or <input type="radio"> element
 * Reserved JS class prefix: _stt
 * Reserved CSS class prefix: none
 * Note: Be careful if there are more than one selectToToggle elements on a page with one or more options having same values (use className on the option tags in those cases)
 **/
(function ($) {
  $.selectToToggle = function (el) {
    var toggle = function () {
      var data      = $(this).data('selectToToggle');
      var wrapper   = data.wrapper;
      var toggleMap = data.toggleMap;
      for (var val in toggleMap) {
        if (val != this.value) {
          wrapper.find(toggleMap[val]).hide().removeAttr('checked').filter('option').each(function() { // if hiding an option element, also disable it to make it work in webkit
            var option = $(this);

            if (typeof option.data('sttDisabled') === 'undefined') {
              option.data('sttDisabled', !!this.disabled); // remember original disabled attribute
            }
          }).prop('disabled', true);
        }
      }

      wrapper.find(toggleMap[this.value]).show().filter('option').prop('disabled', function() {
        return $(this).data('sttDisabled');
      }).filter('select option').parent().each(function() { //show the requried html block
        var dropdown = $(this);
        if (!dropdown.find('option:selected:enabled').length) { //in case any selected option gets hidden in this, select the first visible option
          dropdown.find('option:enabled').first().prop('selected', true);
          if (dropdown.data('selectToToggle')) {
            dropdown.trigger('change.selectToToggle');
          }
        }
      });
    };

    el.off('.selectToToggle').on('change.selectToToggle', toggle);

    toggle.apply(el.filter('select, input:checked')[0]);

  };

  $.fn.selectToToggle = function (
    toggleMap,  // map of select element's option value to corresponding jquery selectors strings (as accepted by find() method) (Optional - defaults to '._stt_[className]' if class name uses prefix _stt__, or '._stt_[value]' otherwise)
                // string 'trigger' to trigger toggling for an existing element (this is useful is option is selected by JS)
                // string 'destroy' to remove all selectToToggle data and events from the element
    wrapper     // wrapper element to call method 'find(selectors)' on - defaults to $(document.body)
  ) {

    return this.each(function () {
      var el        = $(this);
      var data      = el.data('selectToToggle');

      var getAllEls = function(el, wrapper) {
        return el[0].nodeName === 'INPUT' ? wrapper.find('input[name=' + el[0].name + ']') : el;
      };

      if (data) {
        if (toggleMap === 'trigger') {
          if (el[0].nodeName === 'SELECT' || el[0].checked) {
            el.trigger('change.selectToToggle');
          }
        } else if (toggleMap === 'destroy') {
          getAllEls(el, data.wrapper).off('.selectToToggle').removeData('selectToToggle');
        }

      } else {
        var tMap  = $.extend({}, toggleMap);
        wrapper   = wrapper || $(document.body);
        el        = getAllEls(el, wrapper);

        if ($.isEmptyObject(tMap)) {
          (this.nodeName == 'SELECT' ? el.find('option') : el).each(function() {
            if (this.value) {
              var filters = $.map(this.className.match(/(\s+|^)_stt__([^\s]+)/g) || [], function(str) { return str.replace('_stt__', '._stt_') });
                  filters.push('._stt_' + this.value);
              tMap[this.value] = this.className.match(/(\s+|^)_sttmulti($|\s+)/) ? filters.join(',') : filters[0];
            }
          });
        }

        el.data('selectToToggle', {'wrapper' : wrapper, 'toggleMap': tMap});

        $.selectToToggle(el);
      }
    });
  };
})(jQuery);<|endoftext|>