<commit_before>/* See LICENSE file for terms of use */

/*
 * Text diff implementation.
 *
 * This library supports the following APIS:
 * JsDiff.diffChars: Character by character diff
 * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
 * JsDiff.diffLines: Line based diff
 *
 * JsDiff.diffCss: Diff targeted at CSS content
 *
 * These methods are based on the implementation proposed in
 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
 */
var JsDiff = (function() {
  function clonePath(path) {
    return { newPos: path.newPos, components: path.components.slice(0) };
  }
  function removeEmpty(array) {
    var ret = [];
    for (var i = 0; i < array.length; i++) {
      if (array[i]) {
        ret.push(array[i]);
      }
    }
    return ret;
  }
  function escapeHTML(s) {
    var n = s;
    n = n.replace(/&/g, "&");
    n = n.replace(/</g, "<");
    n = n.replace(/>/g, ">");
    n = n.replace(/"/g, """);

    return n;
  }

  var fbDiff = function(ignoreWhitespace) {
    this.ignoreWhitespace = ignoreWhitespace;
  };
  fbDiff.prototype = {
      diff: function(oldString, newString) {
        // Handle the identity case (this is due to unrolling editLength == 0
        if (newString == oldString) {
          return [{ value: newString }];
        }
        if (!newString) {
          return [{ value: oldString, removed: true }];
        }
        if (!oldString) {
          return [{ value: newString, added: true }];
        }

        newString = this.tokenize(newString);
        oldString = this.tokenize(oldString);

        var newLen = newString.length, oldLen = oldString.length;
        var maxEditLength = newLen + oldLen;
        var bestPath = [{ newPos: -1, components: [] }];

        // Seed editLength = 0
        var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
        if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
          return bestPath[0].components;
        }

        for (var editLength = 1; editLength <= maxEditLength; editLength++) {
          for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
            var basePath;
            var addPath = bestPath[diagonalPath-1],
                removePath = bestPath[diagonalPath+1];
            oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
            if (addPath) {
              // No one else is going to attempt to use this value, clear it
              bestPath[diagonalPath-1] = undefined;
            }

            var canAdd = addPath && addPath.newPos+1 < newLen;
            var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
            if (!canAdd && !canRemove) {
              bestPath[diagonalPath] = undefined;
              continue;
            }

            // Select the diagonal that we want to branch from. We select the prior
            // path whose position in the new string is the farthest from the origin
            // and does not pass the bounds of the diff graph
            if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
              basePath = clonePath(removePath);
              this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
            } else {
              basePath = clonePath(addPath);
              basePath.newPos++;
              this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
            }

            var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);

            if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
              return basePath.components;
            } else {
              bestPath[diagonalPath] = basePath;
            }
          }
        }
      },

      pushComponent: function(components, value, added, removed) {
        var last = components[components.length-1];
        if (last && last.added === added && last.removed === removed) {
          // We need to clone here as the component clone operation is just
          // as shallow array clone
          components[components.length-1] =
            {value: this.join(last.value, value), added: added, removed: removed };
        } else {
          components.push({value: value, added: added, removed: removed });
        }
      },
      extractCommon: function(basePath, newString, oldString, diagonalPath) {
        var newLen = newString.length,
            oldLen = oldString.length,
            newPos = basePath.newPos,
            oldPos = newPos - diagonalPath;
        while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
          newPos++;
          oldPos++;

          this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
        }
        basePath.newPos = newPos;
        return oldPos;
      },

      equals: function(left, right) {
        var reWhitespace = /\S/;
        if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
          return true;
        } else {
          return left == right;
        }
      },
      join: function(left, right) {
        return left + right;
      },
      tokenize: function(value) {
        return value;
      }
  };

  var CharDiff = new fbDiff();

  var WordDiff = new fbDiff(true);
  WordDiff.tokenize = function(value) {
    return removeEmpty(value.split(/(\s+|\b)/));
  };

  var CssDiff = new fbDiff(true);
  CssDiff.tokenize = function(value) {
    return removeEmpty(value.split(/([{}:;,]|\s+)/));
  };

  var LineDiff = new fbDiff();
  LineDiff.tokenize = function(value) {
    return value.split(/^/m);
  };

  return {
    diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
    diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
    diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },

    diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },

    createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
      var ret = [];

      ret.push("Index: " + fileName);
      ret.push("===================================================================");
      ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader));
      ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader));

      var diff = LineDiff.diff(oldStr, newStr);
      if (!diff[diff.length-1].value) {
        diff.pop();   // Remove trailing newline add
      }
      diff.push({value: "", lines: []});   // Append an empty value to make cleanup easier

      function contextLines(lines) {
        return lines.map(function(entry) { return ' ' + entry; });
      }
      function eofNL(curRange, i, current) {
        var last = diff[diff.length-2],
            isLast = i === diff.length-2,
            isLastOfType = i === diff.length-3 && (current.added === !last.added || current.removed === !last.removed);

        // Figure out if this is the last line for the given file and missing NL
        if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
          curRange.push('\\ No newline at end of file');
        }
      }

      var oldRangeStart = 0, newRangeStart = 0, curRange = [],
          oldLine = 1, newLine = 1;
      for (var i = 0; i < diff.length; i++) {
        var current = diff[i],
            lines = current.lines || current.value.replace(/\n$/, "").split("\n");
        current.lines = lines;

        if (current.added || current.removed) {
          if (!oldRangeStart) {
            var prev = diff[i-1];
            oldRangeStart = oldLine;
            newRangeStart = newLine;

            if (prev) {
              curRange = contextLines(prev.lines.slice(-4));
              oldRangeStart -= curRange.length;
              newRangeStart -= curRange.length;
            }
          }
          curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; }));
          eofNL(curRange, i, current);

          if (current.added) {
            newLine += lines.length;
          } else {
            oldLine += lines.length;
          }
        } else {
          if (oldRangeStart) {
            // Close out any changes that have been output (or join overlapping)
            if (lines.length <= 8 && i < diff.length-2) {
              // Overlapping
              curRange.push.apply(curRange, contextLines(lines));
            } else {
              // end the range and output
              var contextSize = Math.min(lines.length, 4);
              ret.push(
                  "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize)
                  + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize)
                  + " @@");
              ret.push.apply(ret, curRange);
              ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
              if (lines.length <= 4) {
                eofNL(ret, i, current);
              }

              oldRangeStart = 0;  newRangeStart = 0; curRange = [];
            }
          }
          oldLine += lines.length;
          newLine += lines.length;
        }
      }

      return ret.join('\n') + '\n';
    },

    applyPatch: function(oldStr, uniDiff) {
      var diffstr = uniDiff.split("\n");
      var diff = [];
      var remEOFNL = false,
          addEOFNL = false;
      for (var i = (diffstr[0][0]=="I"?4:0); i < diffstr.length; i++) {
        if(diffstr[i][0] == "@") {
          var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
          diff.unshift({
            start:meh[3],
            oldlength:meh[2],
            oldlines:[],
            newlength:meh[4],
            newlines:[]
          });
        } else
        if(diffstr[i][0] == "+") {
          diff[0].newlines.push(diffstr[i].substr(1));
        } else
        if(diffstr[i][0] == "-") {
          diff[0].oldlines.push(diffstr[i].substr(1));
        } else
        if(diffstr[i][0] == " ") {
          diff[0].newlines.push(diffstr[i].substr(1));
          diff[0].oldlines.push(diffstr[i].substr(1));
        } else
        if(diffstr[i][0] == "\\") {
          if(diffstr[i-1][0] == "+") remEOFNL = true;
          if(diffstr[i-1][0] == "-") addEOFNL = true;
        }
      };
      var str = oldStr.split("\n");
      for (var i = diff.length - 1; i >= 0; i--) {
        var d = diff[i];
        for (var j = 0; j < d.oldlength; j++) {
          if(str[d.start-1+j] != d.oldlines[j]) {
            return false;
          }
        };
        Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
      }
      if(remEOFNL) while(str[str.length-1]=="") str.pop();
      else if(addEOFNL) str.push("");
      return str.join("\n");
    },

    convertChangesToXML: function(changes){
      var ret = [];
      for ( var i = 0; i < changes.length; i++) {
        var change = changes[i];
        if (change.added) {
          ret.push("");
        } else if (change.removed) {
          ret.push("");
        }

        ret.push(escapeHTML(change.value));

        if (change.added) {
          ret.push("");
        } else if (change.removed) {
          ret.push("");
        }
      }
      return ret.join("");
    },

    // See: http://code.google.com/p/google-diff-match-patch/wiki/API
    convertChangesToDMP: function(changes){
      var ret = [], change;
      for ( var i = 0; i < changes.length; i++) {
        change = changes[i];
        ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
      }
      return ret;
    }
  };
})();

if (typeof module !== "undefined") {
    module.exports = JsDiff;
}
<commit_msg>Style updates<commit_after>/* See LICENSE file for terms of use */

/*
 * Text diff implementation.
 *
 * This library supports the following APIS:
 * JsDiff.diffChars: Character by character diff
 * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
 * JsDiff.diffLines: Line based diff
 *
 * JsDiff.diffCss: Diff targeted at CSS content
 *
 * These methods are based on the implementation proposed in
 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
 */
var JsDiff = (function() {
  function clonePath(path) {
    return { newPos: path.newPos, components: path.components.slice(0) };
  }
  function removeEmpty(array) {
    var ret = [];
    for (var i = 0; i < array.length; i++) {
      if (array[i]) {
        ret.push(array[i]);
      }
    }
    return ret;
  }
  function escapeHTML(s) {
    var n = s;
    n = n.replace(/&/g, "&");
    n = n.replace(/</g, "<");
    n = n.replace(/>/g, ">");
    n = n.replace(/"/g, """);

    return n;
  }

  var fbDiff = function(ignoreWhitespace) {
    this.ignoreWhitespace = ignoreWhitespace;
  };
  fbDiff.prototype = {
      diff: function(oldString, newString) {
        // Handle the identity case (this is due to unrolling editLength == 0
        if (newString == oldString) {
          return [{ value: newString }];
        }
        if (!newString) {
          return [{ value: oldString, removed: true }];
        }
        if (!oldString) {
          return [{ value: newString, added: true }];
        }

        newString = this.tokenize(newString);
        oldString = this.tokenize(oldString);

        var newLen = newString.length, oldLen = oldString.length;
        var maxEditLength = newLen + oldLen;
        var bestPath = [{ newPos: -1, components: [] }];

        // Seed editLength = 0
        var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
        if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
          return bestPath[0].components;
        }

        for (var editLength = 1; editLength <= maxEditLength; editLength++) {
          for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
            var basePath;
            var addPath = bestPath[diagonalPath-1],
                removePath = bestPath[diagonalPath+1];
            oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
            if (addPath) {
              // No one else is going to attempt to use this value, clear it
              bestPath[diagonalPath-1] = undefined;
            }

            var canAdd = addPath && addPath.newPos+1 < newLen;
            var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
            if (!canAdd && !canRemove) {
              bestPath[diagonalPath] = undefined;
              continue;
            }

            // Select the diagonal that we want to branch from. We select the prior
            // path whose position in the new string is the farthest from the origin
            // and does not pass the bounds of the diff graph
            if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
              basePath = clonePath(removePath);
              this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
            } else {
              basePath = clonePath(addPath);
              basePath.newPos++;
              this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
            }

            var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);

            if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
              return basePath.components;
            } else {
              bestPath[diagonalPath] = basePath;
            }
          }
        }
      },

      pushComponent: function(components, value, added, removed) {
        var last = components[components.length-1];
        if (last && last.added === added && last.removed === removed) {
          // We need to clone here as the component clone operation is just
          // as shallow array clone
          components[components.length-1] =
            {value: this.join(last.value, value), added: added, removed: removed };
        } else {
          components.push({value: value, added: added, removed: removed });
        }
      },
      extractCommon: function(basePath, newString, oldString, diagonalPath) {
        var newLen = newString.length,
            oldLen = oldString.length,
            newPos = basePath.newPos,
            oldPos = newPos - diagonalPath;
        while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
          newPos++;
          oldPos++;

          this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
        }
        basePath.newPos = newPos;
        return oldPos;
      },

      equals: function(left, right) {
        var reWhitespace = /\S/;
        if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
          return true;
        } else {
          return left == right;
        }
      },
      join: function(left, right) {
        return left + right;
      },
      tokenize: function(value) {
        return value;
      }
  };

  var CharDiff = new fbDiff();

  var WordDiff = new fbDiff(true);
  WordDiff.tokenize = function(value) {
    return removeEmpty(value.split(/(\s+|\b)/));
  };

  var CssDiff = new fbDiff(true);
  CssDiff.tokenize = function(value) {
    return removeEmpty(value.split(/([{}:;,]|\s+)/));
  };

  var LineDiff = new fbDiff();
  LineDiff.tokenize = function(value) {
    return value.split(/^/m);
  };

  return {
    diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
    diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
    diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },

    diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },

    createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
      var ret = [];

      ret.push("Index: " + fileName);
      ret.push("===================================================================");
      ret.push("--- " + fileName + (typeof oldHeader === "undefined" ? "" : "\t" + oldHeader));
      ret.push("+++ " + fileName + (typeof newHeader === "undefined" ? "" : "\t" + newHeader));

      var diff = LineDiff.diff(oldStr, newStr);
      if (!diff[diff.length-1].value) {
        diff.pop();   // Remove trailing newline add
      }
      diff.push({value: "", lines: []});   // Append an empty value to make cleanup easier

      function contextLines(lines) {
        return lines.map(function(entry) { return ' ' + entry; });
      }
      function eofNL(curRange, i, current) {
        var last = diff[diff.length-2],
            isLast = i === diff.length-2,
            isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);

        // Figure out if this is the last line for the given file and missing NL
        if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
          curRange.push('\\ No newline at end of file');
        }
      }

      var oldRangeStart = 0, newRangeStart = 0, curRange = [],
          oldLine = 1, newLine = 1;
      for (var i = 0; i < diff.length; i++) {
        var current = diff[i],
            lines = current.lines || current.value.replace(/\n$/, "").split("\n");
        current.lines = lines;

        if (current.added || current.removed) {
          if (!oldRangeStart) {
            var prev = diff[i-1];
            oldRangeStart = oldLine;
            newRangeStart = newLine;

            if (prev) {
              curRange = contextLines(prev.lines.slice(-4));
              oldRangeStart -= curRange.length;
              newRangeStart -= curRange.length;
            }
          }
          curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?"+":"-") + entry; }));
          eofNL(curRange, i, current);

          if (current.added) {
            newLine += lines.length;
          } else {
            oldLine += lines.length;
          }
        } else {
          if (oldRangeStart) {
            // Close out any changes that have been output (or join overlapping)
            if (lines.length <= 8 && i < diff.length-2) {
              // Overlapping
              curRange.push.apply(curRange, contextLines(lines));
            } else {
              // end the range and output
              var contextSize = Math.min(lines.length, 4);
              ret.push(
                  "@@ -" + oldRangeStart + "," + (oldLine-oldRangeStart+contextSize)
                  + " +" + newRangeStart + "," + (newLine-newRangeStart+contextSize)
                  + " @@");
              ret.push.apply(ret, curRange);
              ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
              if (lines.length <= 4) {
                eofNL(ret, i, current);
              }

              oldRangeStart = 0;  newRangeStart = 0; curRange = [];
            }
          }
          oldLine += lines.length;
          newLine += lines.length;
        }
      }

      return ret.join('\n') + '\n';
    },

    applyPatch: function(oldStr, uniDiff) {
      var diffstr = uniDiff.split("\n");
      var diff = [];
      var remEOFNL = false,
          addEOFNL = false;

      for (var i = (diffstr[0][0]=="I"?4:0); i < diffstr.length; i++) {
        if(diffstr[i][0] == "@") {
          var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
          diff.unshift({
            start:meh[3],
            oldlength:meh[2],
            oldlines:[],
            newlength:meh[4],
            newlines:[]
          });
        } else if(diffstr[i][0] == '+') {
          diff[0].newlines.push(diffstr[i].substr(1));
        } else if(diffstr[i][0] == '-') {
          diff[0].oldlines.push(diffstr[i].substr(1));
        } else if(diffstr[i][0] == ' ') {
          diff[0].newlines.push(diffstr[i].substr(1));
          diff[0].oldlines.push(diffstr[i].substr(1));
        } else if(diffstr[i][0] == '\\') {
          if (diffstr[i-1][0] == '+') {
            remEOFNL = true;
          } else if(diffstr[i-1][0] == '-') {
            addEOFNL = true;
          }
        }
      }

      var str = oldStr.split("\n");
      for (var i = diff.length - 1; i >= 0; i--) {
        var d = diff[i];
        for (var j = 0; j < d.oldlength; j++) {
          if(str[d.start-1+j] != d.oldlines[j]) {
            return false;
          }
        }
        Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
      }

      if (remEOFNL) {
        while (!str[str.length-1]) {
          str.pop();
        }
      } else if (addEOFNL) {
        str.push('');
      }
      return str.join('\n');
    },

    convertChangesToXML: function(changes){
      var ret = [];
      for ( var i = 0; i < changes.length; i++) {
        var change = changes[i];
        if (change.added) {
          ret.push("");
        } else if (change.removed) {
          ret.push("");
        }

        ret.push(escapeHTML(change.value));

        if (change.added) {
          ret.push("");
        } else if (change.removed) {
          ret.push("");
        }
      }
      return ret.join("");
    },

    // See: http://code.google.com/p/google-diff-match-patch/wiki/API
    convertChangesToDMP: function(changes){
      var ret = [], change;
      for ( var i = 0; i < changes.length; i++) {
        change = changes[i];
        ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
      }
      return ret;
    }
  };
})();

if (typeof module !== "undefined") {
    module.exports = JsDiff;
}
<|endoftext|>


<commit_before>(function () {

	var should = require('should');
	var path = require('path');
	var Translator = require('../lib/Translator');

	var translator = new Translator;
	translator.language = 'en';
	translator.directory = path.resolve('./data');

	describe('Translator', function() {

		describe('#normalizeTranslations()', function() {
			it('should return normalized object with dictionary', function() {
				translator.normalizeTranslations({car: 'car', bus: ['bus']}).should.eql({car: ['car'], bus: ['bus']});
			});
		});

		describe('#getMessageInfO()', function() {
			it('should return information about dictionary from message to translate', function() {
				translator.getMessageInfo('web.pages.homepage.promo.title').should.eql({
					path: 'web/pages/homepage',
					category: 'promo',
					name: 'title'
				});
			});
		});

		describe('#loadCategory()', function() {
			it('should load parsed dictionary', function() {
				translator.loadCategory('web/pages/homepage', 'promo').should.eql({
					title: ['Title of promo box']
				});
			});

			it('should return empty object if dictionary does not exists', function() {
				translator.loadCategory('some/unknown', 'translation').should.eql({});
			});
		});

		describe('#findTranslation()', function() {
			it('should return english translations from dictionary', function() {
				translator.findTranslation('web.pages.homepage.promo.title').should.eql(['Title of promo box']);
			});

			it('should return null when translation does not exists', function() {
				should.not.exist(translator.findTranslation('some.unknown.translation'));
			});
		});

		describe('#pluralize()', function() {
			it('should return right version of translation(s) by count', function() {
				var cars = ['1 car', '%count% cars'];
				translator.pluralize('car', cars, 1).should.be.equal('1 car');
				translator.pluralize('car', cars, 4).should.be.equal('%count% cars');

				var fruits = [['1 apple', '%count% apples'], ['1 orange', '%count% oranges']];
				translator.pluralize('list', fruits, 1).should.eql(['1 apple', '1 orange']);
				translator.pluralize('list', fruits, 4).should.eql(['%count% apples', '%count% oranges']);
			});
		});

		describe('#prepareTranslation()', function() {
			it('should return expanded translation with arguments', function() {
				translator.addReplacement('item', 'car');
				translator.prepareTranslation('%item% has got %count% %append%.', 5, {append: 'things'}).should.be.equal('car has got 5 things.');
				translator.removeReplacement('item');
			});
		});

		describe('#translate()', function() {
			it('should return translated text from dictionary', function() {
				translator.translate('web.pages.homepage.promo.title').should.be.equal('Title of promo box');
			});

			it('should return original text if text is eclosed in \':\'', function() {
				translator.translate(':do.not.translate.me:').should.be.equal('do.not.translate.me');
			});
		});

	});

})();<commit_msg>added test for containing plural forms; each test create new translator<commit_after>(function () {

	var should = require('should');
	var path = require('path');
	var Translator = require('../lib/Translator');

	var _path = path.resolve('./data');

	var translator;

	describe('Translator', function() {

		beforeEach(function() {
			translator = new Translator;
			translator.language = 'en';
			translator.directory = _path;
		});

		afterEach(function() {
			translator = null;
		});

		describe('#constructor', function() {
			it('should contain some plural forms', function() {
				translator.plurals.should.not.be.eql({});
			});
		});

		describe('#normalizeTranslations()', function() {
			it('should return normalized object with dictionary', function() {
				translator.normalizeTranslations({car: 'car', bus: ['bus']}).should.eql({car: ['car'], bus: ['bus']});
			});
		});

		describe('#getMessageInfO()', function() {
			it('should return information about dictionary from message to translate', function() {
				translator.getMessageInfo('web.pages.homepage.promo.title').should.eql({
					path: 'web/pages/homepage',
					category: 'promo',
					name: 'title'
				});
			});
		});

		describe('#loadCategory()', function() {
			it('should load parsed dictionary', function() {
				translator.loadCategory('web/pages/homepage', 'promo').should.eql({
					title: ['Title of promo box']
				});
			});

			it('should return empty object if dictionary does not exists', function() {
				translator.loadCategory('some/unknown', 'translation').should.eql({});
			});
		});

		describe('#findTranslation()', function() {
			it('should return english translations from dictionary', function() {
				translator.findTranslation('web.pages.homepage.promo.title').should.eql(['Title of promo box']);
			});

			it('should return null when translation does not exists', function() {
				should.not.exist(translator.findTranslation('some.unknown.translation'));
			});
		});

		describe('#pluralize()', function() {
			it('should return right version of translation(s) by count', function() {
				var cars = ['1 car', '%count% cars'];
				translator.pluralize('car', cars, 1).should.be.equal('1 car');
				translator.pluralize('car', cars, 4).should.be.equal('%count% cars');

				var fruits = [['1 apple', '%count% apples'], ['1 orange', '%count% oranges']];
				translator.pluralize('list', fruits, 1).should.eql(['1 apple', '1 orange']);
				translator.pluralize('list', fruits, 4).should.eql(['%count% apples', '%count% oranges']);
			});
		});

		describe('#prepareTranslation()', function() {
			it('should return expanded translation with arguments', function() {
				translator.addReplacement('item', 'car');
				translator.prepareTranslation('%item% has got %count% %append%.', 5, {append: 'things'}).should.be.equal('car has got 5 things.');
				translator.removeReplacement('item');
			});
		});

		describe('#translate()', function() {
			it('should return translated text from dictionary', function() {
				translator.translate('web.pages.homepage.promo.title').should.be.equal('Title of promo box');
			});

			it('should return original text if text is eclosed in \':\'', function() {
				translator.translate(':do.not.translate.me:').should.be.equal('do.not.translate.me');
			});
		});

	});

})();<|endoftext|>


<commit_before>var sinon = require('sinon');
var chai = require("chai");
var expect = chai.expect;
var sinonChai = require("sinon-chai");
var shelltest = require("../shelltest");
var process = require('child_process');

chai.use(sinonChai);

describe('shelltest', function(){

  var testCmd = "echo 'testing123'";

  var exec;
  before(function(){
    exec = sinon.stub(process, "exec");
    exec.yields(null, "test_stdout", null);
  });

  describe('.send', function(){
    it('should run the command', function(){
      shelltest().cmd(testCmd).end();
      expect(exec).to.have.been.calledWith(testCmd);
    });
  });

  describe('.cwd', function(){
    it('should run the command with cwd option', function(){
      shelltest().cmd(testCmd).cwd("testcwd").end();
      expect(exec).to.have.been.calledWith(testCmd, {"cwd": "testcwd"});
    });
  });

  describe('.env', function(){
    it('should run the command with env option', function(){
      shelltest().cmd(testCmd).env({"testkey": "testval"}).end();
      expect(exec).to.have.been.calledWith(testCmd, {"env": {"testkey": "testval"}});
    });
  });

  describe('.timeout', function(){
    it('should run the command with timeout option', function(){
      shelltest().cmd(testCmd).timeout(10).end();
      expect(exec).to.have.been.calledWith(testCmd, {"timeout": 10});
    });
  });

  describe('.uid', function(){
    it('should run the command with uid option', function(){
      shelltest().cmd(testCmd).uid(11).end();
      expect(exec).to.have.been.calledWith(testCmd, {"uid": 11});
    });
  });

  describe('.gid', function(){
    it('should run the command with gid option', function(){
      shelltest().cmd(testCmd).gid(12).end();
      expect(exec).to.have.been.calledWith(testCmd, {"gid": 12});
    });
  });

});
<commit_msg>Rewording test cases<commit_after>var sinon = require('sinon');
var chai = require("chai");
var expect = chai.expect;
var sinonChai = require("sinon-chai");
var shelltest = require("../shelltest");
var process = require('child_process');

chai.use(sinonChai);

describe('shelltest', function(){

  var testCmd = "echo 'testing123'";

  var exec;
  before(function(){
    exec = sinon.stub(process, "exec");
    exec.yields(null, "test_stdout", null);
  });

  it('should run the command', function(){
    shelltest().cmd(testCmd).end();
    expect(exec).to.have.been.calledWith(testCmd);
  });

  it('should honor configuration of the cwd', function(){
    shelltest().cmd(testCmd).cwd("testcwd").end();
    expect(exec).to.have.been.calledWith(testCmd, {"cwd": "testcwd"});
  });

  it('should honor configuration of the env', function(){
    shelltest().cmd(testCmd).env({"testkey": "testval"}).end();
    expect(exec).to.have.been.calledWith(testCmd, {"env": {"testkey": "testval"}});
  });

  it('should honor configuration of the timeout', function(){
    shelltest().cmd(testCmd).timeout(10).end();
    expect(exec).to.have.been.calledWith(testCmd, {"timeout": 10});
  });

  it('should honor configuration of the uid', function(){
    shelltest().cmd(testCmd).uid(11).end();
    expect(exec).to.have.been.calledWith(testCmd, {"uid": 11});
  });

  it('should honor configuration of the gid', function(){
    shelltest().cmd(testCmd).gid(12).end();
    expect(exec).to.have.been.calledWith(testCmd, {"gid": 12});
  });

});
<|endoftext|>


<commit_before>// audio-test.js
//
// Test the audio module
//
// Copyright 2012, StatusNet Inc.
//
// 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.

var assert = require('assert'),
    vows = require('vows'),
    databank = require('databank'),
    URLMaker = require('../lib/urlmaker').URLMaker,
    modelBatch = reuqire('./lib/model').modelBatch,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

// Need this to make IDs

URLMaker.hostname = "example.net";

// Dummy databank

DatabankObject.bank = Databank.get('memory', {});

var suite = vows.describe('audio module interface');

var testSchema = {
    pkey: "id",
    fields: ['author',
             'displayName',
             'embedCode',
             'published',
             'stream',
             'summary',
             'updated']
};

var testData = {
    'create': {
        displayName: "Shake Your Rump",
        url: "http://example.com/beastie-boys/pauls-boutique/2",
        stream: {
            url: "http://example.com/beastie-boys/pauls-boutique/shake-your-rump.ogg",
            duration: 388
        }
    },
    'update': {
        displayName: "Shake Your Rump (Extended Mix)"
    }
};

suite.addBatch(modelBatch('audio', 'Audio', testSchema, testData));

suite.export(module);

<commit_msg>typo in requiring<commit_after>// audio-test.js
//
// Test the audio module
//
// Copyright 2012, StatusNet Inc.
//
// 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.

var assert = require('assert'),
    vows = require('vows'),
    databank = require('databank'),
    URLMaker = require('../lib/urlmaker').URLMaker,
    modelBatch = require('./lib/model').modelBatch,
    Databank = databank.Databank,
    DatabankObject = databank.DatabankObject;

// Need this to make IDs

URLMaker.hostname = "example.net";

// Dummy databank

DatabankObject.bank = Databank.get('memory', {});

var suite = vows.describe('audio module interface');

var testSchema = {
    pkey: "id",
    fields: ['author',
             'displayName',
             'embedCode',
             'published',
             'stream',
             'summary',
             'updated']
};

var testData = {
    'create': {
        displayName: "Shake Your Rump",
        url: "http://example.com/beastie-boys/pauls-boutique/2",
        stream: {
            url: "http://example.com/beastie-boys/pauls-boutique/shake-your-rump.ogg",
            duration: 388
        }
    },
    'update': {
        displayName: "Shake Your Rump (Extended Mix)"
    }
};

suite.addBatch(modelBatch('audio', 'Audio', testSchema, testData));

suite.export(module);

<|endoftext|>


<commit_before>var assert = require('assert')
var auth = require('..')

function request (authorization) {
  return {
    headers: {
      authorization: authorization
    }
  }
}

describe('auth(req)', function () {
  describe('arguments', function () {
    describe('req', function () {
      it('should be required', function () {
        assert.throws(auth, /argument req is required/)
      })

      it('should accept a request', function () {
        var req = request('basic Zm9vOmJhcg==')
        var creds = auth(req)
        assert.strictEqual(creds.name, 'foo')
        assert.strictEqual(creds.pass, 'bar')
      })

      it('should reject null', function () {
        assert.throws(auth.bind(null, null), /argument req is required/)
      })

      it('should reject a number', function () {
        assert.throws(auth.bind(null, 42), /argument req is required/)
      })

      it('should reject an object without headers', function () {
        assert.throws(auth.bind(null, {}), /argument req is required/)
      })
    })
  })

  describe('with no Authorization field', function () {
    it('should return undefined', function () {
      var req = request()
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with malformed Authorization field', function () {
    it('should return undefined', function () {
      var req = request('Something')
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with malformed Authorization scheme', function () {
    it('should return undefined', function () {
      var req = request('basic_Zm9vOmJhcg==')
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with malformed credentials', function () {
    it('should return undefined', function () {
      var req = request('basic Zm9vcgo=')
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with valid credentials', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with empty password', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Zm9vOg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with empty userid', function () {
    it('should return .name and .pass', function () {
      var req = request('basic OnBhc3M=')
      var creds = auth(req)
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, 'pass')
    })
  })

  describe('with empty userid and pass', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Og==')
      var creds = auth(req)
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with colon in pass', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Zm9vOnBhc3M6d29yZA==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'pass:word')
    })
  })
})

describe('auth.parse(string)', function () {
  describe('with undefined string', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse(), undefined)
    })
  })

  describe('with malformed string', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse('Something'), undefined)
    })
  })

  describe('with malformed scheme', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse('basic_Zm9vOmJhcg=='), undefined)
    })
  })

  describe('with malformed credentials', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse('basic Zm9vcgo='), undefined)
    })
  })

  describe('with valid credentials', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Zm9vOmJhcg==')
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with empty password', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Zm9vOg==')
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with empty userid', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic OnBhc3M=')
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, 'pass')
    })
  })

  describe('with empty userid and pass', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Og==')
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with colon in pass', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Zm9vOnBhc3M6d29yZA==')
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'pass:word')
    })
  })
})
<commit_msg>tests: add case-insensitive scheme tests<commit_after>var assert = require('assert')
var auth = require('..')

function request (authorization) {
  return {
    headers: {
      authorization: authorization
    }
  }
}

describe('auth(req)', function () {
  describe('arguments', function () {
    describe('req', function () {
      it('should be required', function () {
        assert.throws(auth, /argument req is required/)
      })

      it('should accept a request', function () {
        var req = request('basic Zm9vOmJhcg==')
        var creds = auth(req)
        assert.strictEqual(creds.name, 'foo')
        assert.strictEqual(creds.pass, 'bar')
      })

      it('should reject null', function () {
        assert.throws(auth.bind(null, null), /argument req is required/)
      })

      it('should reject a number', function () {
        assert.throws(auth.bind(null, 42), /argument req is required/)
      })

      it('should reject an object without headers', function () {
        assert.throws(auth.bind(null, {}), /argument req is required/)
      })
    })
  })

  describe('with no Authorization field', function () {
    it('should return undefined', function () {
      var req = request()
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with malformed Authorization field', function () {
    it('should return undefined', function () {
      var req = request('Something')
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with malformed Authorization scheme', function () {
    it('should return undefined', function () {
      var req = request('basic_Zm9vOmJhcg==')
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with malformed credentials', function () {
    it('should return undefined', function () {
      var req = request('basic Zm9vcgo=')
      assert.strictEqual(auth(req), undefined)
    })
  })

  describe('with valid credentials', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with empty password', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Zm9vOg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with empty userid', function () {
    it('should return .name and .pass', function () {
      var req = request('basic OnBhc3M=')
      var creds = auth(req)
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, 'pass')
    })
  })

  describe('with empty userid and pass', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Og==')
      var creds = auth(req)
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with colon in pass', function () {
    it('should return .name and .pass', function () {
      var req = request('basic Zm9vOnBhc3M6d29yZA==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'pass:word')
    })
  })

  describe('with scheme "Basic"', function () {
    it('should return .name and .pass', function () {
      var req = request('Basic Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with scheme "BASIC"', function () {
    it('should return .name and .pass', function () {
      var req = request('BASIC Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with scheme "BaSiC"', function () {
    it('should return .name and .pass', function () {
      var req = request('BaSiC Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })
})

describe('auth.parse(string)', function () {
  describe('with undefined string', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse(), undefined)
    })
  })

  describe('with malformed string', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse('Something'), undefined)
    })
  })

  describe('with malformed scheme', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse('basic_Zm9vOmJhcg=='), undefined)
    })
  })

  describe('with malformed credentials', function () {
    it('should return undefined', function () {
      assert.strictEqual(auth.parse('basic Zm9vcgo='), undefined)
    })
  })

  describe('with valid credentials', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Zm9vOmJhcg==')
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with empty password', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Zm9vOg==')
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with empty userid', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic OnBhc3M=')
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, 'pass')
    })
  })

  describe('with empty userid and pass', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Og==')
      assert.strictEqual(creds.name, '')
      assert.strictEqual(creds.pass, '')
    })
  })

  describe('with colon in pass', function () {
    it('should return .name and .pass', function () {
      var creds = auth.parse('basic Zm9vOnBhc3M6d29yZA==')
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'pass:word')
    })
  })

  describe('with scheme "Basic"', function () {
    it('should return .name and .pass', function () {
      var req = request('Basic Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with scheme "BASIC"', function () {
    it('should return .name and .pass', function () {
      var req = request('BASIC Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })

  describe('with scheme "BaSiC"', function () {
    it('should return .name and .pass', function () {
      var req = request('BaSiC Zm9vOmJhcg==')
      var creds = auth(req)
      assert.strictEqual(creds.name, 'foo')
      assert.strictEqual(creds.pass, 'bar')
    })
  })
})
<|endoftext|>


<commit_before>import { deepEqual, strictEqual, throws } from 'assert'
import { batch } from '../src'

describe('batch', () => {
  it('should run all the functions', () => {
    const c = counter()
    strictEqual(batch(c, c, c)(), 3)
    function counter() {
      let count = 0
      return function() {
        return ++count
      }
    }
  })

  it('should throw if any parameter is not a function', () => {
    throws(() => {
      batch(()=> console.log('ok'), '(x_x)', () => console.log('ko'))()
    })
  })

  it('should pass the argument to all the batched functions', () => {
    batch(
      (d) => strictEqual(d, 666)
    , (d) => strictEqual(d, 666)
    , (d) => strictEqual(d, 666)
    , (d) => strictEqual(d, 666)
    )(666)
  })

  it('should return the result of the last function', () => {
    strictEqual(
      batch(
        (d) => d * d
      , (d) => d + 1
      , (d) => d * 5
      )(10)
    , 50
    )
  })

})
<commit_msg>minor cleanup: remove unused reference.<commit_after>import { strictEqual, throws } from 'assert'
import { batch } from '../src'

describe('batch', () => {
  it('should run all the functions', () => {
    const c = counter()
    strictEqual(batch(c, c, c)(), 3)
    function counter() {
      let count = 0
      return function() {
        return ++count
      }
    }
  })

  it('should throw if any parameter is not a function', () => {
    throws(() => {
      batch(()=> console.log('ok'), '(x_x)', () => console.log('ko'))()
    })
  })

  it('should pass the argument to all the batched functions', () => {
    batch(
      (d) => strictEqual(d, 666)
    , (d) => strictEqual(d, 666)
    , (d) => strictEqual(d, 666)
    , (d) => strictEqual(d, 666)
    )(666)
  })

  it('should return the result of the last function', () => {
    strictEqual(
      batch(
        (d) => d * d
      , (d) => d + 1
      , (d) => d * 5
      )(10)
    , 50
    )
  })

})
<|endoftext|>


<commit_before>"use strict";

function $(loc) {
	loc = String(loc);
	var els = document.querySelectorAll(loc);
	return els.length > 0 ? els : els[0];
}

window.addEventListener("load", addStructure);
window.addEventListener("load", addAnchors);
window.addEventListener("load", addToc);
window.addEventListener("load", paginate);
window.addEventListener("load", insertHeader);
window.addEventListener("load", insertFooter);
window.addEventListener("load", populateHeaderYs);
window.addEventListener("load", populateTocEls);
window.addEventListener("scroll", trackHeaders);
window.addEventListener("scroll", moveToc);

function addStructure() {}

function addAnchors() {
	var whitelist = "abcdefghijklmnopqrstuvwxyz0123456789 ";
	function sanitise(s) {
		if (!s)
			return;
		s = s.trim().toLowerCase();
		s = Array.prototype.filter.call(s, (c) => { return whitelist.indexOf(c) >= 0 }).join("");
		return s.replace(/\s/g, "_")
	}
	var hs = $("h1, h2, h3, h4, h5, h6");
	for (var h of hs) {
		h.id = sanitise(h.textContent);
	}
}

function addToc() {
	var toc = document.createElement("nav");
	toc.id = "toc";
	toc.innerHTML = "
Table of Contents
";
	for (var h of $("h1, h2, h3, h4, h5, h6")) {
		var level = h.tagName.substring(1);
		if (level == 1)
			continue;
		toc.innerHTML += "" + h.textContent + ""
	}
	document.body.insertBefore(toc, document.body.firstChild);
}

function paginate() {
	var prev = document.querySelector("link[rel=prev]");
	var next = document.querySelector("link[rel=next]");
	var nav = document.createElement("nav");
	nav.id = "pagination";
	if (prev)
		nav.innerHTML = "" + prev.title + "";
	if (next)
		nav.innerHTML += "" + next.title + "";
	if (prev || next)
		document.body.appendChild(nav);
}

function insertHeader() {
	var header = document.createElement("header");
	header.innerHTML = "
Selenium Documentation
";
	document.body.insertBefore(header, document.body.firstChild);
}

// TODO(ato): Warning, this is unsafe.
function insertFooter() {
	var footer = document.createElement("footer");
	var path = window.location.pathname;
	if (path === "/docs" || path === "/docs/")
		path = "/docs/index.html";
	var file = path.substring(path.lastIndexOf("/") + 1);

	footer.innerHTML = "
" +
		"
" +
		"
" +
		"
© 2013-2015, Software Freedom Conservancy." +
		"
Last updated " + document.lastModified +
		"
" +
		"
" +
		"
Report a bug" +
		"
Edit" +
		"
" +
		"
";

	document.body.appendChild(footer);
}

var hs = [];
var headerYs = {};
var curHeader = null;
var tocEls = {};

function populateHeaderYs() {
	for (var h of $("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]")) {
		hs.push(h);
		headerYs[h.offsetTop] = h.id;
	};
}

function populateTocEls() {
	for (var el of $("nav#toc > a")) {
		var anchor = el.href.substring(el.href.indexOf("#"));
		tocEls[anchor] = el;
	}
}

function trackHeaders(ev) {
	var pageY = ev.pageY;
	var cur = hs[0].id;
	var gone = Object.keys(headerYs).filter((y, h) => { return y <= pageY });
	if (gone.length > 0) {
		var curY = gone[gone.length - 1];
		cur = headerYs[curY];
	}
	updateToc(cur);
}

function updateToc(id) {
	if (curHeader == id) {
		return;
	}
	Object.keys(tocEls).map((id) => { tocEls[id].classList.remove("current") });
	var sel = "#" + id;
	if (!(sel in tocEls))
		return;
	curHeader = tocEls[sel];
	curHeader.classList.add("current");
}

function moveToc(ev) {
	var toc = $("nav#toc")[0];
	var firstEl = $("nav + h1")[0];
	var firstElSt = firstEl.getBoundingClientRect();
	var offset = document.body.classList.contains("front") ? 300 : 200;

	var firstElRealTop = firstElSt.bottom - (firstElSt.height - offset);
	if (firstElRealTop - 50 < 0) {
		toc.style.top = "50px";
	} else {
		toc.style.top = firstElSt.y + offset + "px";
	}
}
<commit_msg>fat arrows don't work in chrome<commit_after>"use strict";

function $(loc) {
	loc = String(loc);
	var els = document.querySelectorAll(loc);
	return els.length > 0 ? els : els[0];
}

window.addEventListener("load", addStructure);
window.addEventListener("load", addAnchors);
window.addEventListener("load", addToc);
window.addEventListener("load", paginate);
window.addEventListener("load", insertHeader);
window.addEventListener("load", insertFooter);
window.addEventListener("load", populateHeaderYs);
window.addEventListener("load", populateTocEls);
window.addEventListener("scroll", trackHeaders);
window.addEventListener("scroll", moveToc);

function addStructure() {}

function addAnchors() {
	var whitelist = "abcdefghijklmnopqrstuvwxyz0123456789 ";
	function sanitise(s) {
		if (!s)
			return;
		s = s.trim().toLowerCase();
		s = Array.prototype.filter.call(s, function(c) { return whitelist.indexOf(c) >= 0 }).join("");
		return s.replace(/\s/g, "_")
	}
	var hs = $("h1, h2, h3, h4, h5, h6");
	for (var h of hs) {
		h.id = sanitise(h.textContent);
	}
}

function addToc() {
	var toc = document.createElement("nav");
	toc.id = "toc";
	toc.innerHTML = "
Table of Contents
";
	for (var h of $("h1, h2, h3, h4, h5, h6")) {
		var level = h.tagName.substring(1);
		if (level == 1)
			continue;
		toc.innerHTML += "" + h.textContent + ""
	}
	document.body.insertBefore(toc, document.body.firstChild);
}

function paginate() {
	var prev = document.querySelector("link[rel=prev]");
	var next = document.querySelector("link[rel=next]");
	var nav = document.createElement("nav");
	nav.id = "pagination";
	if (prev)
		nav.innerHTML = "" + prev.title + "";
	if (next)
		nav.innerHTML += "" + next.title + "";
	if (prev || next)
		document.body.appendChild(nav);
}

function insertHeader() {
	var header = document.createElement("header");
	header.innerHTML = "
Selenium Documentation
";
	document.body.insertBefore(header, document.body.firstChild);
}

// TODO(ato): Warning, this is unsafe.
function insertFooter() {
	var footer = document.createElement("footer");
	var path = window.location.pathname;
	if (path === "/docs" || path === "/docs/")
		path = "/docs/index.html";
	var file = path.substring(path.lastIndexOf("/") + 1);

	footer.innerHTML = "
" +
		"
" +
		"
" +
		"
© 2013-2015, Software Freedom Conservancy." +
		"
Last updated " + document.lastModified +
		"
" +
		"
" +
		"
Report a bug" +
		"
Edit" +
		"
" +
		"
";

	document.body.appendChild(footer);
}

var hs = [];
var headerYs = {};
var curHeader = null;
var tocEls = {};

function populateHeaderYs() {
	for (var h of $("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]")) {
		hs.push(h);
		headerYs[h.offsetTop] = h.id;
	};
}

function populateTocEls() {
	for (var el of $("nav#toc > a")) {
		var anchor = el.href.substring(el.href.indexOf("#"));
		tocEls[anchor] = el;
	}
}

function trackHeaders(ev) {
	var pageY = ev.pageY;
	var cur = hs[0].id;
	var gone = Object.keys(headerYs).filter(function(y, h) { return y <= pageY });
	if (gone.length > 0) {
		var curY = gone[gone.length - 1];
		cur = headerYs[curY];
	}
	updateToc(cur);
}

function updateToc(id) {
	if (curHeader == id) {
		return;
	}
	Object.keys(tocEls).map(function(id) { tocEls[id].classList.remove("current") });
	var sel = "#" + id;
	if (!(sel in tocEls))
		return;
	curHeader = tocEls[sel];
	curHeader.classList.add("current");
}

function moveToc(ev) {
	var toc = $("nav#toc")[0];
	var firstEl = $("nav + h1")[0];
	var firstElSt = firstEl.getBoundingClientRect();
	var offset = document.body.classList.contains("front") ? 300 : 200;

	var firstElRealTop = firstElSt.bottom - (firstElSt.height - offset);
	if (firstElRealTop - 50 < 0) {
		toc.style.top = "50px";
	} else {
		toc.style.top = firstElSt.y + offset + "px";
	}
}
<|endoftext|>


<commit_before>const chai = require('chai');
const assert = chai.assert;
const _ = require('lodash');

var Board = require('../lib/board.js');
var Light = require('../lib/light.js');
var Levels = require('../lib/levels.js');

describe('Creating a new board', () => {

  it("has a set width", () => {
    let board = new Board();
    assert.equal(board.width, 5);
  });

  it("can create empty light grid", () => {
    let board = new Board();
    assert.lengthOf(_.flatten(board.createEmptyGrid(5,5)), 25);
  });

  it("can place light objects on grid", () => {
    let board = new Board();

    for(var i = 0; i < board.width; i++){
      for(var j = 0; j < board.width; j++){
        assert.instanceOf(board.lightGrid[i][j], Light);
      }
    }
  });

  it("can be initialized with a level", () => {
    var levels = new Levels();
    let board = new Board(levels.list[0]);

    assert.isFalse(board.lightGrid[0][0].lit);
    assert(board.lightGrid[1][0].lit);
  });

});

<commit_msg>Resolve merge conflict in board-test<commit_after>const chai = require('chai');
const assert = chai.assert;
const _ = require('lodash');

var Board = require('../lib/board.js');
var Light = require('../lib/light.js');
var Levels = require('../lib/levels.js');

describe('Creating a new board', () => {

  it("has a set width", () => {
    let board = new Board();
    assert.equal(board.width, 5);
  });

  it("can create empty light grid", () => {
    let board = new Board();
    assert.lengthOf(_.flatten(board.createEmptyGrid(5,5)), 25);
  });

  it("can place light objects on grid", () => {
    let board = new Board();

    for(var i = 0; i < board.width; i++){
      for(var j = 0; j < board.width; j++){
        assert.instanceOf(board.lightGrid[i][j], Light, "each lightGrid is an instance of Light");
      }
    }
  });

  it("can be initialized with a level", () => {
    var levels = new Levels();
    let board = new Board(levels.list[0]);

    assert.isFalse(board.lightGrid[0][0].lit);
    assert(board.lightGrid[1][0].lit);
  });
});

// describe("updating board", () => {

  // it("can find all neightbors for a particular light", () => {
    // var board = new Board();

    // light towards middle of board
    // var light = board.lightGrid[2][2];
    // assert.equal(2,light.x);
    // assert.equal(2,light.y);

    // all neighbor lights
    // var lights = board.getNeighbors(light);

    // expected coordinates of neightbor lights
    // var expected = [[1, 2],[2, 1],[3, 2],[2, ]].sort();
    // lights = lights.sort();

    // for(var i = 0; i < expected.length; i++){
      // console.log([lights[i].x, lights[i].y]);
      // assert.deepEqual(expected[i], [lights[i].x, lights[i].y])
    // }

    // assert.lengthOf(lights, 4);
  // });

  // it("only updates lights visible on the board", function(){
  //   var board = new Board();
  //
  //   // light on corner of board
  //   var light = board.lightGrid[0][0];
  //   assert.equal(0,light.x);
  //   assert.equal(0,light.y);
  //
  //   // all neighbor lights
  //   var lights = board.getNeighbors(light);
  //   assert.lengthOf(lights, 2);
  //
  //   // each neighbor light
  //   var firstNeighbor = lights[0];
  //   var secondNeighbor = lights[1];
  //
  //   // neighbor to the left
  //   assert.equal(firstNeighbor.x, 1);
  //   assert.equal(firstNeighbor.y, 0);
  //
  //   // neighbor to the top
  //   assert.equal(secondNeighbor.x, 0);
  //   assert.equal(secondNeighbor.y, 1);
  // });
// });
<|endoftext|>


<commit_before>var root = React.createClass({
  render: function() {
    return JSML(["p", "hey!"]);
  }
});

function dispatch(event, arg, noRedraw) {
  switch(event) {
    case "load":
      break;
    default:
      console.error("Dispatch for unknown event: ", event, arg);
      break;
  }

  if(!noRedraw) {
    React.render(React.createElement(root), document.body);
  }
}

dispatch("load");
<commit_msg>a little structure<commit_after>//---------------------------------------------------------
// Root component
//---------------------------------------------------------

var root = React.createClass({
  render: function() {
    return JSML(["p", "hey!"]);
  }
});

//---------------------------------------------------------
// Grid components
//---------------------------------------------------------

//---------------------------------------------------------
// Table components
//---------------------------------------------------------

//---------------------------------------------------------
// View components
//---------------------------------------------------------

//---------------------------------------------------------
// UI editor components
//---------------------------------------------------------

//---------------------------------------------------------
// Event dispatch
//---------------------------------------------------------

function dispatch(event, arg, noRedraw) {
  switch(event) {
    case "load":
      break;
    default:
      console.error("Dispatch for unknown event: ", event, arg);
      break;
  }

  if(!noRedraw) {
    React.render(React.createElement(root), document.body);
  }
}

//---------------------------------------------------------
// Go
//---------------------------------------------------------

dispatch("load");
<|endoftext|>


<commit_before>// Check that brightness is not changes after rescale
/*global describe, it*/
'use strict';

var resize = require('../lib/pure/resize');
var assert = require('assert');

function createTest(color) {
  var srcSize = 4 * 100 * 100,
      resultSize = 4 * 10 * 10,
      hexColor = color.toString(16),
      src = new Uint8Array(srcSize),
      correct = new Uint8Array(resultSize);

  src.fill(color);
  correct.fill(color);

  it('test 100x100 -> 10x10 with color #' + hexColor + hexColor + hexColor, function () {
    var result = resize({
      src: src,
      width: 100,
      height: 100,
      toWidth: 10,
      toHeight: 10,
      alpha: true
    });

    assert.deepEqual(result, correct);
    // console.log(result);
  });
}

describe('Brightness should not change', function () {
  createTest(255);
  createTest(127);
  createTest(0);
});
<commit_msg>Improved node 0.12 test compatibility<commit_after>// Check that brightness is not changes after rescale
/*global describe, it*/
'use strict';

var resize = require('../lib/pure/resize');
var assert = require('assert');

function fill(arr, val) {
  for (var i = 0; i < arr.length; i++) { arr[i] = val; }
}

function createTest(color) {
  var srcSize = 4 * 100 * 100,
      resultSize = 4 * 10 * 10,
      hexColor = color.toString(16),
      src = new Uint8Array(srcSize),
      correct = new Uint8Array(resultSize);

  fill(src, color);
  fill(correct, color);

  it('test 100x100 -> 10x10 with color #' + hexColor + hexColor + hexColor, function () {
    var result = resize({
      src: src,
      width: 100,
      height: 100,
      toWidth: 10,
      toHeight: 10,
      alpha: true
    });

    assert.deepEqual(result, correct);
    // console.log(result);
  });
}

describe('Brightness should not change', function () {
  createTest(255);
  createTest(127);
  createTest(0);
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');

var co = require('co');
var cothunkify = require('co-thunkify');
var sleep = require('co-sleep');

var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var sinonChai = require("sinon-chai");

var session = require(path.resolve('./'));
var modulePath = './cache';
var underTest = require(path.resolve(modulePath));
var sessionData = {
      elec: {accountNumber: '1234567890'},
      gas: {accountNumber: '1234567890'}
    };
var token;

chai.use(sinonChai);

describe('su-apisession/cache', function() {
  it('should cache a response if it\'s valid', cothunkify(function* () {
    token = yield session.set(sessionData);

    yield underTest.set.call({
      data : { foo : 'bar' },
      r : {
        xcsrf : token
      },
      request : {
        method : 'GET',
        url : '/foo/bar'
      },
      status : 200
    }, function* () {});

    var data = yield session.getCached(token, 'GET:/foo/bar');

    expect(data).to.deep.equal({ foo : 'bar' });
  }));

  it('should get the `cached` data on the context if there iseses one', cothunkify(function* () {
    var ctx = {
        r : {
          xcsrf : token
        },
        request : {
          method : 'GET',
          url : '/foo/bar'
        }
      };

    yield underTest.get.call(ctx, function* () {});

    expect(ctx.r.cached).to.deep.equal({ foo : 'bar' });
  }));
});
<commit_msg>fix b0rken test<commit_after>'use strict';
var path = require('path');

var co = require('co');
var cothunkify = require('co-thunkify');
var sleep = require('co-sleep');

var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var sinonChai = require("sinon-chai");

var session = require(path.resolve('./'));
var modulePath = './cache';
var underTest = require(path.resolve(modulePath));
var sessionData = {
      elec: {accountNumber: '1234567890'},
      gas: {accountNumber: '1234567890'}
    };
var token;

chai.use(sinonChai);

describe('su-apisession/cache', function() {
  it('should cache a response if it\'s valid', cothunkify(function* () {
    token = yield session.set(sessionData);

    yield underTest.set.call({
      data : { foo : 'bar' },
      su : { req : {
        xcsrf : token
      } },
      request : {
        method : 'GET',
        url : '/foo/bar'
      },
      status : 200
    }, function* () {});

    var data = yield session.getCached(token, 'GET:/foo/bar');

    expect(data).to.deep.equal({ foo : 'bar' });
  }));

  it('should get the `cached` data on the context if there iseses one', cothunkify(function* () {
    var ctx = {
        su : { req : {
          xcsrf : token
        } },
        request : {
          method : 'GET',
          url : '/foo/bar'
        }
      };

    yield underTest.get.call(ctx, function* () {});

    expect(ctx.su.req.cached).to.deep.equal({ foo : 'bar' });
  }));
});
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var request = require("request");
var redis = require("redis");
var scale = require("./scale.js");

//Setup Redis
client = redis.createClient();
client.on("error", function (err) {
    console.log("Error " + err);
});

//var connectedServers = {}
var serverQueue = []

http.listen(3000, function(){
    console.log('listening on *:3000');
});

//Returns the IP of the next server in the round-robin
function nextServer(){
    var ip = serverQueue.shift();
    if(ip !== undefined){
        serverQueue.push(ip);
    }

    return ip;
}

var cpuUsages = []
var time = 0;
var recordingInterval = 1000 * 10;
var endtime = 7440000;
var training = false;
var recording = false;
var ended = false;
var keyPrefix = training ? "training:" : "testing:";

//Clear data from previous runs
client.keys(keyPrefix + "*", function(err, keys){
    keys.forEach(function(key){
        client.del(key);
    });
    console.log("Flushed Keys");
});

var requests = 0;
var serverResponses = {};

function startRecordingUsage() {
    scale.emitTrainingData(client, io);
    var recordUsage = setInterval(function(){
        if(!ended){
            var count = cpuUsages.length;
            if(count == 0){
                return;
            }

            var sum = 0;
            while(cpuUsages.length > 0){
                sum += cpuUsages.pop();
            }

            var average = sum / count;

            console.log(JSON.stringify({ip: "Average",
            usage: average.toString()}));

            io.emit('cpu-ip', JSON.stringify({ip: "Average",
            usage: average.toString()}));

            time += recordingInterval;

            client.set(keyPrefix + time, average, redis.print);
            client.set(keyPrefix + "requests:" + time, requests, function(){
                scale.emitTestData(client, time, io);
            });

            if(!training){
                setTimeout(function() {
                    scale.scale(client, time + 1000 * 10, io, average);
                }, recordingInterval - (1000 * 3));
            }

            for (var server in serverResponses) {
                if (serverResponses.hasOwnProperty(server)) {
                    client.set(keyPrefix + "responses:" + server + ":" + time, serverResponses[server])
                }
            }

            requests = 0;
            serverResponses = {};

            if(time > endtime){
                ended = true;
            }

        }

    }, recordingInterval);
}

function removeFromServerList(ip){
    var index = serverQueue.indexOf(ip);
    if(index > -1){
        serverQueue.splice(index, 1);
    }
}

io.on('connection', function(socket){
    console.log(socket.request.connection._peername.address);
    var ip = socket.request.connection._peername.address;

    socket.on('cpu-usage', function(msg){
        if(serverQueue.indexOf(ip) === -1){
            serverQueue.push(ip);
        }

        if(recording){
            cpuUsages.push(msg);
        }
    });

    socket.on('scale-instructions-req', function(msg){
        scale.scale(client, time + 1000 * 10, io);
    });

    socket.on('shutdown', function(){
        console.log('Shutdown Request Received');
        removeFromServerList(ip);
        socket.emit('shutdown-complete', "");
    });

    socket.on('disconnect', function(){
        //Call again incase of unexpected shutdown
        removeFromServerList(ip);
    });
});

app.get('/', function(req, res){
    if(!recording){
        recording = true;
        startRecordingUsage();
    }

    //Count the amount of requests received
    requests++;

    var server = nextServer();
    request("http://" + server + ":3005" , function(error, response, body) {
        res.end(JSON.Stringify({"time": time, "response": response}));

        if(serverResponses[server] === undefined){
            serverResponses[server] = 1;
        }
        else {
            serverResponses[server]++;
        }
    });
});
<commit_msg>Fix case of stringify func<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var request = require("request");
var redis = require("redis");
var scale = require("./scale.js");

//Setup Redis
client = redis.createClient();
client.on("error", function (err) {
    console.log("Error " + err);
});

//var connectedServers = {}
var serverQueue = []

http.listen(3000, function(){
    console.log('listening on *:3000');
});

//Returns the IP of the next server in the round-robin
function nextServer(){
    var ip = serverQueue.shift();
    if(ip !== undefined){
        serverQueue.push(ip);
    }

    return ip;
}

var cpuUsages = []
var time = 0;
var recordingInterval = 1000 * 10;
var endtime = 7440000;
var training = false;
var recording = false;
var ended = false;
var keyPrefix = training ? "training:" : "testing:";

//Clear data from previous runs
client.keys(keyPrefix + "*", function(err, keys){
    keys.forEach(function(key){
        client.del(key);
    });
    console.log("Flushed Keys");
});

var requests = 0;
var serverResponses = {};

function startRecordingUsage() {
    scale.emitTrainingData(client, io);
    var recordUsage = setInterval(function(){
        if(!ended){
            var count = cpuUsages.length;
            if(count == 0){
                return;
            }

            var sum = 0;
            while(cpuUsages.length > 0){
                sum += cpuUsages.pop();
            }

            var average = sum / count;

            console.log(JSON.stringify({ip: "Average",
            usage: average.toString()}));

            io.emit('cpu-ip', JSON.stringify({ip: "Average",
            usage: average.toString()}));

            time += recordingInterval;

            client.set(keyPrefix + time, average, redis.print);
            client.set(keyPrefix + "requests:" + time, requests, function(){
                scale.emitTestData(client, time, io);
            });

            if(!training){
                setTimeout(function() {
                    scale.scale(client, time + 1000 * 10, io, average);
                }, recordingInterval - (1000 * 3));
            }

            for (var server in serverResponses) {
                if (serverResponses.hasOwnProperty(server)) {
                    client.set(keyPrefix + "responses:" + server + ":" + time, serverResponses[server])
                }
            }

            requests = 0;
            serverResponses = {};

            if(time > endtime){
                ended = true;
            }

        }

    }, recordingInterval);
}

function removeFromServerList(ip){
    var index = serverQueue.indexOf(ip);
    if(index > -1){
        serverQueue.splice(index, 1);
    }
}

io.on('connection', function(socket){
    console.log(socket.request.connection._peername.address);
    var ip = socket.request.connection._peername.address;

    socket.on('cpu-usage', function(msg){
        if(serverQueue.indexOf(ip) === -1){
            serverQueue.push(ip);
        }

        if(recording){
            cpuUsages.push(msg);
        }
    });

    socket.on('scale-instructions-req', function(msg){
        scale.scale(client, time + 1000 * 10, io);
    });

    socket.on('shutdown', function(){
        console.log('Shutdown Request Received');
        removeFromServerList(ip);
        socket.emit('shutdown-complete', "");
    });

    socket.on('disconnect', function(){
        //Call again incase of unexpected shutdown
        removeFromServerList(ip);
    });
});

app.get('/', function(req, res){
    if(!recording){
        recording = true;
        startRecordingUsage();
    }

    //Count the amount of requests received
    requests++;

    var server = nextServer();
    request("http://" + server + ":3005" , function(error, response, body) {
        res.end(JSON.stringify({"time": time, "response": response}));

        if(serverResponses[server] === undefined){
            serverResponses[server] = 1;
        }
        else {
            serverResponses[server]++;
        }
    });
});
<|endoftext|>


<commit_before>var Conversion = function(unitName, scaleToAnchor) { //add wet or dry, imperial or metric, and the name of the anchor measurement
  this.unitName = unitName;
  this.unit = Unit.unitFromName(this.unitName)
  this.scaleToAnchor = scaleToAnchor;

  this.convert = function(amount, relatedConversion) {
    var quantityAtAnchor = amount.quantity * relatedConversion.scaleToAnchor;
    return new Amount(quantityAtAnchor / this.scaleToAnchor, this.unit, amount.ingredientName);
  }.bind(this);
};

var conversions = {
  dryImperial: [
    new Conversion('cup', 48),
    new Conversion('tablespoon', 3),
    new Conversion('teaspoon', 1),
    new Conversion('pinch', 1.0 / 16),
    new Conversion('dash', 1.0 / 8),
  ],
  wetImperial: [
    new Conversion('gallon', 768),
    new Conversion('quart', 192),
    new Conversion('pint', 96),
    new Conversion('cup', 48),
    new Conversion('tablespoon', 3),
    new Conversion('teaspoon', 1),
    new Conversion('dash', 1.0 / 8),
  ],
  fluidMetric: [
    new Conversion('liter', 1000),
    new Conversion('milliliter', 1),
  ],
  weightMetric: [
    new Conversion('kilogram', 1000),
    new Conversion('gram', 1),
  ],
};

var UnitReducer = function(amount) {
  this.amount = amount;

  for (var key in conversions) {
    var conversionTable = conversions[key];
    var validConversion = conversionTable.some(function(conversion) {
      return conversion.unitName === this.amount.unit.name;
    }.bind(this))
    if (validConversion) {
      this.conversionTable = conversionTable;
      break;
    }
  }

  this.conversion = this.conversionTable.find(function(conversion) {
    return conversion.unitName === this.amount.unit.name;
  }.bind(this))

  this.quantityAtAnchor = this.amount.quantity * this.conversion.scaleToAnchor;

  this.convertedAmounts = this.conversionTable.map(function(conversion) {
    return conversion.convert(this.amount, this.conversion);
  }.bind(this));

  this.reducedAmount = this.convertedAmounts.reduce(function(bestConvertedAmount, convertedAmount) {
    if (convertedAmount.quantity >= convertedAmount.unit.smallestMeasure
      && convertedAmount.quantity < bestConvertedAmount.quantity) {
        return convertedAmount;
      } else {
        return bestConvertedAmount;
      }
  }, this.amount);
};
<commit_msg>simplify back to a .find<commit_after>var Conversion = function(unitName, scaleToAnchor) { //add wet or dry, imperial or metric, and the name of the anchor measurement
  this.unitName = unitName;
  this.unit = Unit.unitFromName(this.unitName)
  this.scaleToAnchor = scaleToAnchor;

  this.convert = function(amount, relatedConversion) {
    var quantityAtAnchor = amount.quantity * relatedConversion.scaleToAnchor;
    return new Amount(quantityAtAnchor / this.scaleToAnchor, this.unit, amount.ingredientName);
  }.bind(this);
};

var conversions = [
  {
    measure: 'dry',
    standard: 'imperial',
    conversions: [
      new Conversion('cup', 48),
      new Conversion('tablespoon', 3),
      new Conversion('teaspoon', 1),
      new Conversion('pinch', 1.0 / 16),
      new Conversion('dash', 1.0 / 8),
    ],
  },
  {
    measure: 'wet',
    standard: 'imperial',
    conversions: [
      new Conversion('gallon', 768),
      new Conversion('quart', 192),
      new Conversion('pint', 96),
      new Conversion('cup', 48),
      new Conversion('tablespoon', 3),
      new Conversion('teaspoon', 1),
      new Conversion('dash', 1.0 / 8),
    ],
  },
  {
    measure: 'wet',
    standard: 'metric',
    conversions: [
      new Conversion('liter', 1000),
      new Conversion('milliliter', 1),
    ],
  },
  {
    measure: 'dry',
    standard: 'metric',
    conversions: [
      new Conversion('kilogram', 1000),
      new Conversion('gram', 1),
    ],
  }
];

var UnitReducer = function(amount) {
  this.amount = amount;

  this.conversionTable = conversions.find(function(conversionTable) {
    return conversionTable.conversions.some(function(conversion) {
      return conversion.unitName === this.amount.unit.name;
    }.bind(this));
  }.bind(this));

  this.conversions = this.conversionTable.conversions;

  this.conversion = this.conversions.find(function(conversion) {
    return conversion.unitName === this.amount.unit.name;
  }.bind(this))

  this.quantityAtAnchor = this.amount.quantity * this.conversion.scaleToAnchor;

  this.convertedAmounts = this.conversions.map(function(conversion) {
    return conversion.convert(this.amount, this.conversion);
  }.bind(this));

  this.reducedAmount = this.convertedAmounts.reduce(function(bestConvertedAmount, convertedAmount) {
    if (convertedAmount.quantity >= convertedAmount.unit.smallestMeasure && convertedAmount.quantity < bestConvertedAmount.quantity) {
      return convertedAmount;
    } else {
      return bestConvertedAmount;
    }
  }, this.amount);
};
<|endoftext|>


<commit_before>'use strict'

describe('set', function () {
  var server, receiver
  var Hub = require('../../lib')
  var mock = require('../../lib/protocol/mock')
  var Mock = require('../../lib/protocol/mock/constructor')
  var Observable = require('vigour-js/lib/observable')
  var something = new Observable({ bla: true })
  var Event = require('vigour-js/lib/event')

  it('can create multiple hubs', function () {
    server = new Hub({
      key: 'server'
    })
    receiver = new Hub({
      key: 'reciever'
    })
  })

  it('can set the adapater using a mock protocol on a', function () {
    server.set({
      adapter: {
        id: 'set_server',
        inject: mock,
        mock: {}
      }
    })
    expect(server.adapter.mock).to.be.instanceof(Mock)
    expect(server.adapter.id).to.equal('set_server')
  })

  it('can set the adapater using a mock protocol on b', function () {
    receiver.set({
      adapter: {
        id: 'set_reciever',
        inject: mock,
        mock: {}
      }
    })
    expect(receiver.adapter.mock).to.be.instanceof(Mock)
    expect(receiver.adapter.id).to.equal('set_reciever')
  })

  it('can create a server "server"', function () {
    server.adapter.set({
      mock: {
        server: 'set_server'
      }
    })
  })

  it('receiver can connect to server', function (done) {
    receiver.adapter.set({ mock: 'set_server' })
    // maybe make this a bit easier to access e.g. protocol will get a connected observable
    receiver.adapter.mock.client.origin.connection.origin.on('connect', done)
  })

  it('receiver can send data to server', function () {
    receiver.set({
      somefield: true
    })
    expect(server).to.have.property('somefield')
    .which.has.property('_input').equals(true)
  })

  it('server can send data to receiver', function () {
    server.set({
      anotherfield: true
    })
    expect(receiver).to.have.property('anotherfield')
      .which.has.property('_input').equals(true)
  })

  it('server can send referenced data to receiver', function () {
    server.set({ a: true }, false)
    server.set({ referenced: server.a })
    expect(receiver).to.have.property('a')
    expect(receiver).to.have.property('referenced')
      .which.has.property('_input')
      .which.equals(receiver.a)
  })

  it('receiver can send referenced data to server', function () {
    receiver.set({ field: receiver.referenced })
    expect(server).to.have.property('field')
      .which.has.property('_input')
      .which.equals(server.referenced)
  })

  it('server can send referenced data to receiver, changing a reference', function () {
    server.set({ field: server.a })
    expect(receiver).to.have.property('field')
      .which.has.property('_input')
      .which.equals(receiver.a)
  })

  it('server can send out of adapter scope references to receiver', function () {
    server.set({ something: something })
    expect(receiver).to.have.property('something')
      .which.has.property('bla')
      .which.has.property('_input').which.equals(true)
  })

  it('server can send out of adapter scope references to receiver, updates from the references value', function () {
    something.set({ otherfield: true })
    expect(receiver.something).to.have.property('otherfield')
  })

  it('receiver can send custom stamps over the server to another receiver', function (done) {
    var receiver2 = new Hub({
      adapter: {
        id: 'set_reciever2',
        inject: mock
      }
    })

    receiver2.adapter.set({
      mock: 'set_server'
    })

    receiver2.adapter.mock.once('connect', function () {
      var event = new Event(receiver, 'data', 'danillo')
      receiver2.once(function (data, event) {
        expect(event.stamp.split('|')[1]).equal('danillo')
        expect(receiver2).to.have.property('danillo')
        done()
      })
      receiver.set({
        danillo: true
      }, event)
    })
  })

  it('get should not get synced', function (done) {
    function guard () {
      throw new Error('gets should not fire!')
    }
    receiver.once(guard)
    receiver.get('afield', true)
    receiver.off(guard)
  })
})
<commit_msg>correct test<commit_after>'use strict'

describe('set', function () {
  var server, receiver
  var Hub = require('../../lib')
  var mock = require('../../lib/protocol/mock')
  var Mock = require('../../lib/protocol/mock/constructor')
  var Observable = require('vigour-js/lib/observable')
  var something = new Observable({ bla: true })
  var Event = require('vigour-js/lib/event')

  it('can create multiple hubs', function () {
    server = new Hub({
      key: 'server'
    })
    receiver = new Hub({
      key: 'reciever'
    })
  })

  it('can set the adapater using a mock protocol on a', function () {
    server.set({
      adapter: {
        id: 'set_server',
        inject: mock,
        mock: {}
      }
    })
    expect(server.adapter.mock).to.be.instanceof(Mock)
    expect(server.adapter.id).to.equal('set_server')
  })

  it('can set the adapater using a mock protocol on b', function () {
    receiver.set({
      adapter: {
        id: 'set_reciever',
        inject: mock,
        mock: {}
      }
    })
    expect(receiver.adapter.mock).to.be.instanceof(Mock)
    expect(receiver.adapter.id).to.equal('set_reciever')
  })

  it('can create a server "server"', function () {
    server.adapter.set({
      mock: {
        server: 'set_server'
      }
    })
  })

  it('receiver can connect to server', function (done) {
    receiver.adapter.set({ mock: 'set_server' })
    // maybe make this a bit easier to access e.g. protocol will get a connected observable
    receiver.adapter.mock.client.origin.connection.origin.on('connect', done)
  })

  it('receiver can send data to server', function () {
    receiver.set({
      somefield: true
    })
    expect(server).to.have.property('somefield')
    .which.has.property('_input').equals(true)
  })

  it('server can send data to receiver', function () {
    server.set({
      anotherfield: true
    })
    expect(receiver).to.have.property('anotherfield')
      .which.has.property('_input').equals(true)
  })

  it('server can send referenced data to receiver', function () {
    server.set({ a: true }, false)
    server.set({ referenced: server.a })
    expect(receiver).to.have.property('a')
    expect(receiver).to.have.property('referenced')
      .which.has.property('_input')
      .which.equals(receiver.a)
  })

  it('receiver can send referenced data to server', function () {
    receiver.set({ field: receiver.referenced })
    expect(server).to.have.property('field')
      .which.has.property('_input')
      .which.equals(server.referenced)
  })

  it('server can send referenced data to receiver, changing a reference', function () {
    server.set({ field: server.a })
    expect(receiver).to.have.property('field')
      .which.has.property('_input')
      .which.equals(receiver.a)
  })

  it('server can send out of adapter scope references to receiver', function () {
    server.set({ something: something })
    expect(receiver).to.have.property('something')
      .which.has.property('bla')
      .which.has.property('_input').which.equals(true)
  })

  it('server can send out of adapter scope references to receiver, updates from the references value', function () {
    something.set({ otherfield: true })
    expect(receiver.something).to.have.property('otherfield')
  })

  it('receiver can send custom stamps over the server to another receiver', function (done) {
    var receiver2 = new Hub({
      adapter: {
        id: 'set_reciever2',
        inject: mock
      }
    })

    receiver2.adapter.set({
      mock: 'set_server'
    })

    receiver2.adapter.mock.once('connect', function () {
      var event = new Event(receiver, 'data', 'danillo')
      receiver2.once(function (data, event) {
        expect(event.stamp.split('|')[1]).equal('danillo')
        expect(receiver2).to.have.property('danillo')
        done()
      })
      receiver.set({
        danillo: true
      }, event)
    })
  })

  it('get should not get synced', function () {
    function guard () {
      throw new Error('gets should not fire!')
    }
    receiver.once(guard)
    receiver.get('afield', true)
    receiver.off(guard)
  })
})
<|endoftext|>