<commit_before>/* See license.txt for terms of usage */
var FireDiff  = FireDiff || {};

/**
 * Classes used to iterate over DOM content and search Firediff pages.
 */
FireDiff.search = FBL.ns(function() { with (FBL) {

const Events = FireDiff.events,
      VersionCompat = FireDiff.VersionCompat,
      DiffDomplate = FireDiff.domplate,
      Search = this;

/**
 * @class Search for use in pages where all content is available and visible at all times.
 */
this.PageSearch = function() {
  var currentSearch;

  /**
   * Execute the search
   *
   * @param {String} text Search text
   * @param {boolean} reverse true to perform a reverse search
   * @param {Element} panel Panel to search
   */
  this.search = function(text, reverse, panel) {
    var panelNode = panel.panelNode;
    if (!text) {
      currentSearch = undefined;
      return false;
    }

    var row;
    if (currentSearch && text == currentSearch.text) {
      row = currentSearch.findNext(true, false, reverse, Firebug.searchCaseSensitive);
    } else {
      function findRow(node) { return node.nodeType == 1 ? node : node.parentNode; }
      currentSearch = new TextSearch(panelNode, findRow);
      row = currentSearch.find(text, reverse, Firebug.searchCaseSensitive);
    }

    // TODO : What a11y events should this produce?
    if (row) {
      panel.document.defaultView.getSelection().selectAllChildren(row);
      scrollIntoCenterView(row, panelNode);
      return true;
    } else {
      return false;
    }
  };
};

/**
 * Constructs a NodeSearch instance.
 *
 * @class Class used to search a DOM tree for the given text. Will display
 *        the search results in a IO Box.
 *
 * @constructor
 * @param {String} text Text to search for
 * @param {Object} root Root of search. This may be an element or a document
 * @param {Object} panelNode Panel node containing the IO Box representing the DOM tree.
 * @param {Object} ioBox IO Box to display the search results in
 */
this.DOMDiffNodeSearch = function(text, root, panelNode, ioBox) {
  VersionCompat.NodeSearch.call(
      this, text, root, panelNode, ioBox, new Search.DOMDiffWalker(root));
  var re = new ReversibleRegExp(text, "m");

  /**
   * Checks a given node for a search match.
   *
   * @private
   */
  this.checkNode = function(node, reverse, caseSensitive, firstStep) {
    var originalNode = node;
    node = node.clone || node;

    var checkOrder, checkValues = [];
    if (originalNode.attrNode) {
      originalNode = node.attrNode;

      var diff = DiffDomplate.DomUtil.diffAttr(node);
      diff = diff.reduce(function(prev, current) { return prev + current.value; }, "");

      var nameCheck = { value: originalNode.nodeName, isValue: false, caseSensitive: false };
      var valueCheck = { value: diff, isValue: true, caseSensitive: caseSensitive };
      checkOrder = reverse ? [ valueCheck, nameCheck ] : [ nameCheck, valueCheck ];
    } else if (originalNode.subType == "char_data_modified") {
      var diff = DiffDomplate.DomUtil.diffText(originalNode);
      diff = diff.reduce(function(prev, current) { return prev + current.value; }, "");
      FBTrace.sysout("Char Diff: " + diff, originalNode);

      checkOrder = [{value: diff, isValue: false, caseSensitive: caseSensitive }];
    } else if (node.nodeType != Node.TEXT_NODE) {
      var nameCheck = { value: node.nodeName, isValue: false, caseSensitive: false };
      var valueCheck = { value: node.nodeValue, isValue: true, caseSensitive: caseSensitive };
      checkOrder = reverse ? [ valueCheck, nameCheck ] : [ nameCheck, valueCheck ];
    } else {
      checkOrder = [{value: node.nodeValue, isValue: false, caseSensitive: caseSensitive }];
    }

    for (var i = firstStep || 0; i < checkOrder.length; i++) {
      var m = re.exec(checkOrder[i].value, reverse, checkOrder[i].caseSensitive);
      if (m) {
        return {
            node: originalNode,
            isValue: checkOrder[i].isValue,
            match: m
        };
      }
    }
  };

  var super_openToNode = this.openToNode;
  this.openToNode = function(node, isValue) {
    var ret = super_openToNode.call(this, node, isValue);
    if (!ret) {
      // Fail over to the node if it's not supported by the base impl
      ret = ioBox.openToObject(node);
    }
    return ret;
  };
};

/**
 * Constructs a DOMDiffWalker instance.
 *
 * @constructor
 * @class Implements an ordered traveral of the document, including diff events,
 *        attributes and iframe contents within the results.
 *
 *        Note that the order for attributes is not defined. This will follow the
 *        same order as the Element.attributes accessor.
 * @param {Element} root Element to traverse
 */
this.DOMDiffWalker = function(root) {
  var stack = [];
  var pastStart, pastEnd;

  function pushStack(currentNode, reverse) {
    if (currentNode) {
      var attrs = Search.getAttributes(currentNode),
          children = [];

      // Precache the child elements to make the logic easier. If this becomes
      // a performance issue then this can be revisited using an inline selection
      // algorithm
      try {
        var baseIter;
        var removeIter = new Search.RemovedIterator(
            new Search.DOMIterator(currentNode.clone || currentNode),
            currentNode[Events.AnnotateAttrs.REMOVE_CHANGES]);
        while (1) {
          children.push(removeIter.next());
        }
      } catch (err) {
        /* NOP */
      }

      stack.unshift({
        node: currentNode,
        attrs: attrs,
        attrIndex: reverse ? attrs.length-1 : -1,
        children: children,
        childIndex: reverse ? children.length-1 : -1
      });
      return stack[0];
    }
  }

  function pushDescendents(el) {
    while (el) {
      pushStack(el, true);
      if (((el.nodeName || "").toUpperCase() == "IFRAME")) {
        el = el.contentDocument.documentElement;
      } else {
        el = stack[0].children[stack[0].children.length-1];
      }
    }
  }

  /**
   * Move to the next node.
   *
   * @return The next node if one exists, otherwise undefined.
   */
  this.nextNode = function() {
    if (pastEnd) {
      return undefined;
    }

    if (!stack.length) {
      // We are working with a new tree walker
      pushStack(root);
    } else {
      var stackEl = stack[0];

      // First check attributes
      if (stackEl.attrIndex < stackEl.attrs.length-1) {
        stackEl.attrIndex++;
      } else if ((stackEl.node.nodeName || "").toUpperCase() == "IFRAME"
          && stackEl.node.contentDocument) {
        // Attributes have completed, check for iframe contents
        pushStack(stackEl.node.contentDocument.documentElement);
      } else {
        while (stack.length) {
          stackEl = stack[0];
          stackEl.childIndex++;
          if (stackEl.childIndex < stackEl.children.length) {
            pushStack(stackEl.children[stackEl.childIndex]);
            break;
          } else {
            // The end, pop
            stack.shift();
          }
        }
      }
    }

    if (!stack.length) {
      pastEnd = true;
    } else {
      pastStart = false;
    }

    return this.currentNode();
  };

  /**
   * Move to the previous node.
   *
   * @return The previous node if one exists, undefined otherwise.
   */
  this.previousNode = function() {
    if (pastStart) {
      return undefined;
    }

    var stackEl = stack[0];
    if (!stackEl) {
      // Generate the stack up to the last element
      pushDescendents(root);
    } else if (stackEl.childIndex >= 0) {
      stackEl.childIndex--;
      pushDescendents(stackEl.children[stackEl.childIndex]);
    } else if (stackEl.attrIndex >= 0) {
      stackEl.attrIndex--;
    } else {
      stack.shift();
      stackEl = stack[0];
      if (stackEl && stackEl.childIndex >= 0) {
        stackEl.childIndex--;
        pushDescendents(stackEl.children[stackEl.childIndex]);
      }
    }

    if (!stack.length) {
      pastStart = true;
    } else {
      pastEnd = false;
    }

    return this.currentNode();
  };

  /**
   * Retrieves the current node.
   *
   * @return The current node, if not past the beginning or end of the iteration.
   */
  this.currentNode = function() {
    var stackEl = stack[0];
    if (stackEl) {
      if (stackEl.attrIndex >= 0) {
        return stackEl.attrs[stackEl.attrIndex];
      } else {
        return stackEl.node;
      }
    }
  };

  /**
   * Resets the walker position back to the initial position.
   */
  this.reset = function() {
    pastStart = false;
    pastEnd = false;
    stack = [];
  };

  this.reset();
};

/**
 * @class Iterates over the contents of an array
 */
this.ArrayIterator = function(array) {
  var index = -1;

  /**
   * Retrieves the next element in the iteration.
   */
  this.next = function() {
    if (++index >= array.length)    $break();
    return array[index];
  };
};

/**
 * @class Iterates over the children of a given node.
 */
this.DOMIterator = function(node) {
  var curNode = node.firstChild;

  /**
   * Retrieves the next element in the iteration.
   */
  this.next = function() {
    var ret = curNode;
    if (!curNode)    $break();
    curNode = curNode.nextSibling;
    return ret;
  }
}

/**
 * @class Iterates over a child iterator and a set of removed events, merging
 *        the remove events at the proper location in the iteration.
 */
this.RemovedIterator = function(content, removed, includeFilter) {
  removed = removed || [];

  var nodeIndex = 1, removedIndex = 0,
      lastId;

  /**
   * Retrieves the next element in the iteration.
   */
  this.next = function() {
    // Check for removed at the current position
    while (true) {
      while (removedIndex < removed.length) {
        var curChange = removed[removedIndex];
        lastId = lastId || FireDiff.Path.getIdentifier(curChange.xpath);
        if (lastId.index <= nodeIndex || nodeIndex < 0) {
          removedIndex++;   lastId = undefined;
          if (!includeFilter || includeFilter(curChange)) {
            return curChange;
          }
        } else {
          break;
        }
      }

      // Read the content list
      nodeIndex++;
      if (content) {
        try {
          var ret = content.next();
          if (ret && (!includeFilter || includeFilter(ret))) {
            if (ret.nodeType == Node.TEXT_NODE && ret[Events.AnnotateAttrs.CHANGES]) {
              return ret[Events.AnnotateAttrs.CHANGES];
            } else {
              return ret;
            }
          }
        } catch (err) {
          // Assume this is StopIteration
          content = undefined;
        }
      } else if (removedIndex >= removed.length) {
        // Content and removed exhausted
        $break();
      }
    }
  };
};

/**
 * Retrieves all attributes for a given change or element. This includes all
 * changes and existing attributes.
 */
this.getAttributes = function(change) {
  var attrs = [], attrSeen = {};
  var idAttr, classAttr, changeAttr;
  var el = change.clone || change;

  var changes = el[Events.AnnotateAttrs.ATTR_CHANGES] || {};
  if (change.clone && change.attrName) {
    changes = {};
    changes[change.attrName] = change;
  }

  if (el.attributes) {
    for (var i = 0; i < el.attributes.length; ++i) {
      var attr = el.attributes[i];
      if (attr.localName.indexOf("firebug-") != -1)
         continue;

      // We need to include the change object as domplate does not have an easy way
      // to pass multiple arguments to a processing method
      var curChange = changes[attr.localName];
      if (curChange) {
          changeAttr = {
              localName: attr.localName,
              nodeValue: attr.nodeValue,
              attrNode: attr,
              change: curChange
          };
          attr = changeAttr;
      }

      attrSeen[attr.localName] = true;
      if (attr.localName == "id") {
        idAttr = attr;
      }
      else if (attr.localName == "class") {
       classAttr = attr;
      }
      else {
        attrs.push(attr);
      }
    }
  }
  if (classAttr) {
    attrs.splice(0, 0, classAttr);
  }
  if (idAttr) {
    attrs.splice(0, 0, idAttr);
  }

  // Handle any removed attributes
  for (var i in changes) {
    if (changes.hasOwnProperty(i) && !attrSeen.hasOwnProperty(i)) {
      attrs.push({
          localName: i,
          nodeValue: changes[i].previousValue,
          change: changes[i]
      });
    }
  }

  return attrs;
};

}});<commit_msg>Remove unnecessary tracing.<commit_after>/* See license.txt for terms of usage */
var FireDiff  = FireDiff || {};

/**
 * Classes used to iterate over DOM content and search Firediff pages.
 */
FireDiff.search = FBL.ns(function() { with (FBL) {

const Events = FireDiff.events,
      VersionCompat = FireDiff.VersionCompat,
      DiffDomplate = FireDiff.domplate,
      Search = this;

/**
 * @class Search for use in pages where all content is available and visible at all times.
 */
this.PageSearch = function() {
  var currentSearch;

  /**
   * Execute the search
   *
   * @param {String} text Search text
   * @param {boolean} reverse true to perform a reverse search
   * @param {Element} panel Panel to search
   */
  this.search = function(text, reverse, panel) {
    var panelNode = panel.panelNode;
    if (!text) {
      currentSearch = undefined;
      return false;
    }

    var row;
    if (currentSearch && text == currentSearch.text) {
      row = currentSearch.findNext(true, false, reverse, Firebug.searchCaseSensitive);
    } else {
      function findRow(node) { return node.nodeType == 1 ? node : node.parentNode; }
      currentSearch = new TextSearch(panelNode, findRow);
      row = currentSearch.find(text, reverse, Firebug.searchCaseSensitive);
    }

    // TODO : What a11y events should this produce?
    if (row) {
      panel.document.defaultView.getSelection().selectAllChildren(row);
      scrollIntoCenterView(row, panelNode);
      return true;
    } else {
      return false;
    }
  };
};

/**
 * Constructs a NodeSearch instance.
 *
 * @class Class used to search a DOM tree for the given text. Will display
 *        the search results in a IO Box.
 *
 * @constructor
 * @param {String} text Text to search for
 * @param {Object} root Root of search. This may be an element or a document
 * @param {Object} panelNode Panel node containing the IO Box representing the DOM tree.
 * @param {Object} ioBox IO Box to display the search results in
 */
this.DOMDiffNodeSearch = function(text, root, panelNode, ioBox) {
  VersionCompat.NodeSearch.call(
      this, text, root, panelNode, ioBox, new Search.DOMDiffWalker(root));
  var re = new ReversibleRegExp(text, "m");

  /**
   * Checks a given node for a search match.
   *
   * @private
   */
  this.checkNode = function(node, reverse, caseSensitive, firstStep) {
    var originalNode = node;
    node = node.clone || node;

    var checkOrder, checkValues = [];
    if (originalNode.attrNode) {
      originalNode = node.attrNode;

      var diff = DiffDomplate.DomUtil.diffAttr(node);
      diff = diff.reduce(function(prev, current) { return prev + current.value; }, "");

      var nameCheck = { value: originalNode.nodeName, isValue: false, caseSensitive: false };
      var valueCheck = { value: diff, isValue: true, caseSensitive: caseSensitive };
      checkOrder = reverse ? [ valueCheck, nameCheck ] : [ nameCheck, valueCheck ];
    } else if (originalNode.subType == "char_data_modified") {
      var diff = DiffDomplate.DomUtil.diffText(originalNode);
      diff = diff.reduce(function(prev, current) { return prev + current.value; }, "");

      checkOrder = [{value: diff, isValue: false, caseSensitive: caseSensitive }];
    } else if (node.nodeType != Node.TEXT_NODE) {
      var nameCheck = { value: node.nodeName, isValue: false, caseSensitive: false };
      var valueCheck = { value: node.nodeValue, isValue: true, caseSensitive: caseSensitive };
      checkOrder = reverse ? [ valueCheck, nameCheck ] : [ nameCheck, valueCheck ];
    } else {
      checkOrder = [{value: node.nodeValue, isValue: false, caseSensitive: caseSensitive }];
    }

    for (var i = firstStep || 0; i < checkOrder.length; i++) {
      var m = re.exec(checkOrder[i].value, reverse, checkOrder[i].caseSensitive);
      if (m) {
        return {
            node: originalNode,
            isValue: checkOrder[i].isValue,
            match: m
        };
      }
    }
  };

  var super_openToNode = this.openToNode;
  this.openToNode = function(node, isValue) {
    var ret = super_openToNode.call(this, node, isValue);
    if (!ret) {
      // Fail over to the node if it's not supported by the base impl
      ret = ioBox.openToObject(node);
    }
    return ret;
  };
};

/**
 * Constructs a DOMDiffWalker instance.
 *
 * @constructor
 * @class Implements an ordered traveral of the document, including diff events,
 *        attributes and iframe contents within the results.
 *
 *        Note that the order for attributes is not defined. This will follow the
 *        same order as the Element.attributes accessor.
 * @param {Element} root Element to traverse
 */
this.DOMDiffWalker = function(root) {
  var stack = [];
  var pastStart, pastEnd;

  function pushStack(currentNode, reverse) {
    if (currentNode) {
      var attrs = Search.getAttributes(currentNode),
          children = [];

      // Precache the child elements to make the logic easier. If this becomes
      // a performance issue then this can be revisited using an inline selection
      // algorithm
      try {
        var baseIter;
        var removeIter = new Search.RemovedIterator(
            new Search.DOMIterator(currentNode.clone || currentNode),
            currentNode[Events.AnnotateAttrs.REMOVE_CHANGES]);
        while (1) {
          children.push(removeIter.next());
        }
      } catch (err) {
        /* NOP */
      }

      stack.unshift({
        node: currentNode,
        attrs: attrs,
        attrIndex: reverse ? attrs.length-1 : -1,
        children: children,
        childIndex: reverse ? children.length-1 : -1
      });
      return stack[0];
    }
  }

  function pushDescendents(el) {
    while (el) {
      pushStack(el, true);
      if (((el.nodeName || "").toUpperCase() == "IFRAME")) {
        el = el.contentDocument.documentElement;
      } else {
        el = stack[0].children[stack[0].children.length-1];
      }
    }
  }

  /**
   * Move to the next node.
   *
   * @return The next node if one exists, otherwise undefined.
   */
  this.nextNode = function() {
    if (pastEnd) {
      return undefined;
    }

    if (!stack.length) {
      // We are working with a new tree walker
      pushStack(root);
    } else {
      var stackEl = stack[0];

      // First check attributes
      if (stackEl.attrIndex < stackEl.attrs.length-1) {
        stackEl.attrIndex++;
      } else if ((stackEl.node.nodeName || "").toUpperCase() == "IFRAME"
          && stackEl.node.contentDocument) {
        // Attributes have completed, check for iframe contents
        pushStack(stackEl.node.contentDocument.documentElement);
      } else {
        while (stack.length) {
          stackEl = stack[0];
          stackEl.childIndex++;
          if (stackEl.childIndex < stackEl.children.length) {
            pushStack(stackEl.children[stackEl.childIndex]);
            break;
          } else {
            // The end, pop
            stack.shift();
          }
        }
      }
    }

    if (!stack.length) {
      pastEnd = true;
    } else {
      pastStart = false;
    }

    return this.currentNode();
  };

  /**
   * Move to the previous node.
   *
   * @return The previous node if one exists, undefined otherwise.
   */
  this.previousNode = function() {
    if (pastStart) {
      return undefined;
    }

    var stackEl = stack[0];
    if (!stackEl) {
      // Generate the stack up to the last element
      pushDescendents(root);
    } else if (stackEl.childIndex >= 0) {
      stackEl.childIndex--;
      pushDescendents(stackEl.children[stackEl.childIndex]);
    } else if (stackEl.attrIndex >= 0) {
      stackEl.attrIndex--;
    } else {
      stack.shift();
      stackEl = stack[0];
      if (stackEl && stackEl.childIndex >= 0) {
        stackEl.childIndex--;
        pushDescendents(stackEl.children[stackEl.childIndex]);
      }
    }

    if (!stack.length) {
      pastStart = true;
    } else {
      pastEnd = false;
    }

    return this.currentNode();
  };

  /**
   * Retrieves the current node.
   *
   * @return The current node, if not past the beginning or end of the iteration.
   */
  this.currentNode = function() {
    var stackEl = stack[0];
    if (stackEl) {
      if (stackEl.attrIndex >= 0) {
        return stackEl.attrs[stackEl.attrIndex];
      } else {
        return stackEl.node;
      }
    }
  };

  /**
   * Resets the walker position back to the initial position.
   */
  this.reset = function() {
    pastStart = false;
    pastEnd = false;
    stack = [];
  };

  this.reset();
};

/**
 * @class Iterates over the contents of an array
 */
this.ArrayIterator = function(array) {
  var index = -1;

  /**
   * Retrieves the next element in the iteration.
   */
  this.next = function() {
    if (++index >= array.length)    $break();
    return array[index];
  };
};

/**
 * @class Iterates over the children of a given node.
 */
this.DOMIterator = function(node) {
  var curNode = node.firstChild;

  /**
   * Retrieves the next element in the iteration.
   */
  this.next = function() {
    var ret = curNode;
    if (!curNode)    $break();
    curNode = curNode.nextSibling;
    return ret;
  }
}

/**
 * @class Iterates over a child iterator and a set of removed events, merging
 *        the remove events at the proper location in the iteration.
 */
this.RemovedIterator = function(content, removed, includeFilter) {
  removed = removed || [];

  var nodeIndex = 1, removedIndex = 0,
      lastId;

  /**
   * Retrieves the next element in the iteration.
   */
  this.next = function() {
    // Check for removed at the current position
    while (true) {
      while (removedIndex < removed.length) {
        var curChange = removed[removedIndex];
        lastId = lastId || FireDiff.Path.getIdentifier(curChange.xpath);
        if (lastId.index <= nodeIndex || nodeIndex < 0) {
          removedIndex++;   lastId = undefined;
          if (!includeFilter || includeFilter(curChange)) {
            return curChange;
          }
        } else {
          break;
        }
      }

      // Read the content list
      nodeIndex++;
      if (content) {
        try {
          var ret = content.next();
          if (ret && (!includeFilter || includeFilter(ret))) {
            if (ret.nodeType == Node.TEXT_NODE && ret[Events.AnnotateAttrs.CHANGES]) {
              return ret[Events.AnnotateAttrs.CHANGES];
            } else {
              return ret;
            }
          }
        } catch (err) {
          // Assume this is StopIteration
          content = undefined;
        }
      } else if (removedIndex >= removed.length) {
        // Content and removed exhausted
        $break();
      }
    }
  };
};

/**
 * Retrieves all attributes for a given change or element. This includes all
 * changes and existing attributes.
 */
this.getAttributes = function(change) {
  var attrs = [], attrSeen = {};
  var idAttr, classAttr, changeAttr;
  var el = change.clone || change;

  var changes = el[Events.AnnotateAttrs.ATTR_CHANGES] || {};
  if (change.clone && change.attrName) {
    changes = {};
    changes[change.attrName] = change;
  }

  if (el.attributes) {
    for (var i = 0; i < el.attributes.length; ++i) {
      var attr = el.attributes[i];
      if (attr.localName.indexOf("firebug-") != -1)
         continue;

      // We need to include the change object as domplate does not have an easy way
      // to pass multiple arguments to a processing method
      var curChange = changes[attr.localName];
      if (curChange) {
          changeAttr = {
              localName: attr.localName,
              nodeValue: attr.nodeValue,
              attrNode: attr,
              change: curChange
          };
          attr = changeAttr;
      }

      attrSeen[attr.localName] = true;
      if (attr.localName == "id") {
        idAttr = attr;
      }
      else if (attr.localName == "class") {
       classAttr = attr;
      }
      else {
        attrs.push(attr);
      }
    }
  }
  if (classAttr) {
    attrs.splice(0, 0, classAttr);
  }
  if (idAttr) {
    attrs.splice(0, 0, idAttr);
  }

  // Handle any removed attributes
  for (var i in changes) {
    if (changes.hasOwnProperty(i) && !attrSeen.hasOwnProperty(i)) {
      attrs.push({
          localName: i,
          nodeValue: changes[i].previousValue,
          change: changes[i]
      });
    }
  }

  return attrs;
};

}});<|endoftext|>


<commit_before>describe("HTML Document Utility functions", function () {
    var doc,
        setHtml = function (html) {
            doc.documentElement.innerHTML = html;
        };

    beforeEach(function () {
        doc = document.implementation.createHTMLDocument('');
    });

    describe("rewriteCssSelectorWith", function () {
        it("should rewrite CSS rules with the new selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/a.myFakeHover \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle complex selectors", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/body.myFakeHover span \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle simple selector occurrence", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/.myFakeHover \{\s*color: blue;\s*\}/);
        });

        it("should not match partial selector occurrence", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, '.my', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/.myClass \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle multiple selector occurrence in same rule selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/i.myFakeHover, a.myFakeHover \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle multiple sub-selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':active', '.myFakeActive');

            expect(doc.querySelector('style').textContent).toMatch(/i.myFakeActive::?after \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle multiple selector occurrences in different rules", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':active', '.myFakeActive');

            expect(doc.querySelector('style').textContent).toMatch(/i.myFakeActive \{\s*color: blue;\s*\}/);
        });

        it("should cope with non CSSStyleRule", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');
        });

        it("should not touch style elements without a matching selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            // Use the fact that comments are discarded when processing a style sheet
            expect(doc.querySelector('style').textContent).toMatch(/a comment/);
        });

        it("should match pseudo selector independent of letter case", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/a.myFakeHover/);
        });

        // On Firefox this needs a work around because of https://bugzilla.mozilla.org/show_bug.cgi?id=925493
        ifNotInPhantomJsIt("should integrate with a document loaded through ajax", function (done) {
            testHelper.readHTMLDocumentFixture("hover.html").then(function (doc) {
                documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myfakehover');

                expect(doc.querySelector('style').textContent).toMatch(/body.myfakehover/);
                done();
            });
        });
    });

    describe("lowercaseCssTypeSelectors", function () {
        it("should convert matching tag name to lower case", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['a']);

            expect(doc.querySelector('style').textContent).toMatch(/a \{/);
        });

        it("should convert matching tag name with mixed letter case to lower case", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['span']);

            expect(doc.querySelector('style').textContent).toMatch(/span \{/);
        });

        it("should convert matching tag name from a list of names to lower case", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['a', 'span']);

            expect(doc.querySelector('style').textContent).toMatch(/span \{/);
        });

        it("should not touch selector parts outside of the tag name", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['span']);

            expect(doc.querySelector('style').textContent).toMatch(/span.aClassName \{/);
        });

        it("should not match any tag names with a matching suffix", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['i']);

            expect(doc.querySelector('style').textContent).toMatch(/LI \{/);
        });

        ifNotInPhantomJsIt("should convert complex selectors", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['li']);

            expect(doc.querySelector('style').textContent).toMatch(/BODY li.COMPLEX:active \{/);
        });

        it("should convert multiple different matches", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['body', 'li']);

            expect(doc.querySelector('style').textContent).toMatch(/body li \{/);
        });
    });

    describe("addClassNameRecursively", function () {
        it("should attach class to selected element", function () {
            setHtml("a span");

            documentUtil.addClassNameRecursively(doc.querySelector('span'), '.myClass');

            expect(doc.querySelector('span').className).toMatch(/myClass/);
        });

        it("should attach the fake hover class to select the parent's elements", function () {
            setHtml("

a list entry

");

            documentUtil.addClassNameRecursively(doc.querySelector('li'), '.myClass');

            expect(doc.querySelector('ol').className).toMatch(/myClass/);
            expect(doc.querySelector('div').className).toMatch(/myClass/);
            expect(doc.querySelector('body').className).toMatch(/myClass/);
            expect(doc.querySelector('html').className).toMatch(/myClass/);
        });

        it("should not attach the fake hover class to siblings or parent's siblings", function () {
            setHtml("
a span
a list entrytext

");

            documentUtil.addClassNameRecursively(doc.querySelector('a'), '.myClass');

            expect(doc.querySelector('i').className).toEqual('');
            expect(doc.querySelector('span').className).toEqual('');
        });
    });

    describe("findHtmlOnlyNodeNames", function () {
        it("should find html node names", function () {
            setHtml("

content
");

            var nodeNames = documentUtil.findHtmlOnlyNodeNames(doc);

            expect(nodeNames).toEqual(['html', 'head', 'body', 'p', 'span', 'br']);
        });

        it("should not include tags from other namespaces", function () {
            setHtml("<svg xmlns='http://www.w3.org/2000/svg'><rect/></svg>");

            var nodeNames = documentUtil.findHtmlOnlyNodeNames(doc);

            expect(nodeNames).toEqual(['html', 'head', 'body']);
        });

        it("should not include HTML tags if they conflict with ones from other namespaces", function () {
            setHtml('' +
                    '<svg width="10" height="10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' +
                    '' +
                    '</svg>' +
                    '');

            var nodeNames = documentUtil.findHtmlOnlyNodeNames(doc);

            expect(nodeNames).toEqual(['html', 'head', 'body']);
        });
    });
});
<commit_msg>Document tag name case sensitivity issue with Chrome & Safari<commit_after>describe("HTML Document Utility functions", function () {
    var doc,
        setHtml = function (html) {
            doc.documentElement.innerHTML = html;
        };

    beforeEach(function () {
        doc = document.implementation.createHTMLDocument('');
    });

    describe("rewriteCssSelectorWith", function () {
        it("should rewrite CSS rules with the new selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/a.myFakeHover \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle complex selectors", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/body.myFakeHover span \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle simple selector occurrence", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/.myFakeHover \{\s*color: blue;\s*\}/);
        });

        it("should not match partial selector occurrence", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, '.my', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/.myClass \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle multiple selector occurrence in same rule selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/i.myFakeHover, a.myFakeHover \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle multiple sub-selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':active', '.myFakeActive');

            expect(doc.querySelector('style').textContent).toMatch(/i.myFakeActive::?after \{\s*color: blue;\s*\}/);
        });

        it("should correctly handle multiple selector occurrences in different rules", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':active', '.myFakeActive');

            expect(doc.querySelector('style').textContent).toMatch(/i.myFakeActive \{\s*color: blue;\s*\}/);
        });

        it("should cope with non CSSStyleRule", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');
        });

        it("should not touch style elements without a matching selector", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            // Use the fact that comments are discarded when processing a style sheet
            expect(doc.querySelector('style').textContent).toMatch(/a comment/);
        });

        it("should match pseudo selector independent of letter case", function () {
            setHtml('');

            documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myFakeHover');

            expect(doc.querySelector('style').textContent).toMatch(/a.myFakeHover/);
        });

        // On Firefox this needs a work around because of https://bugzilla.mozilla.org/show_bug.cgi?id=925493
        ifNotInPhantomJsIt("should integrate with a document loaded through ajax", function (done) {
            testHelper.readHTMLDocumentFixture("hover.html").then(function (doc) {
                documentUtil.rewriteCssSelectorWith(doc, ':hover', '.myfakehover');

                expect(doc.querySelector('style').textContent).toMatch(/body.myfakehover/);
                done();
            });
        });
    });

    describe("lowercaseCssTypeSelectors", function () {
        it("should convert matching tag name to lower case", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['a']);

            expect(doc.querySelector('style').textContent).toMatch(/a \{/);
        });

        it("should convert matching tag name with mixed letter case to lower case", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['span']);

            expect(doc.querySelector('style').textContent).toMatch(/span \{/);
        });

        it("should convert matching tag name from a list of names to lower case", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['a', 'span']);

            expect(doc.querySelector('style').textContent).toMatch(/span \{/);
        });

        it("should not touch selector parts outside of the tag name", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['span']);

            expect(doc.querySelector('style').textContent).toMatch(/span.aClassName \{/);
        });

        it("should not match any tag names with a matching suffix", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['i']);

            expect(doc.querySelector('style').textContent).toMatch(/LI \{/);
        });

        it("should convert complex selectors", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['li']);

            expect(doc.querySelector('style').textContent).toMatch(/li.COMPLEX:active \{/);
        });

        // Chrome and WebKit don't seem to care about tag name selector case sensitivity for XML documents. Why should we?
        ifNotInWebkitIt("should only convert mentioned tag names", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['li']);

            expect(doc.querySelector('style').textContent).toMatch(/BODY li \{/);
        });

        it("should convert multiple different matches", function () {
            setHtml('');

            documentUtil.lowercaseCssTypeSelectors(doc, ['body', 'li']);

            expect(doc.querySelector('style').textContent).toMatch(/body li \{/);
        });
    });

    describe("addClassNameRecursively", function () {
        it("should attach class to selected element", function () {
            setHtml("a span");

            documentUtil.addClassNameRecursively(doc.querySelector('span'), '.myClass');

            expect(doc.querySelector('span').className).toMatch(/myClass/);
        });

        it("should attach the fake hover class to select the parent's elements", function () {
            setHtml("

a list entry

");

            documentUtil.addClassNameRecursively(doc.querySelector('li'), '.myClass');

            expect(doc.querySelector('ol').className).toMatch(/myClass/);
            expect(doc.querySelector('div').className).toMatch(/myClass/);
            expect(doc.querySelector('body').className).toMatch(/myClass/);
            expect(doc.querySelector('html').className).toMatch(/myClass/);
        });

        it("should not attach the fake hover class to siblings or parent's siblings", function () {
            setHtml("
a span
a list entrytext

");

            documentUtil.addClassNameRecursively(doc.querySelector('a'), '.myClass');

            expect(doc.querySelector('i').className).toEqual('');
            expect(doc.querySelector('span').className).toEqual('');
        });
    });

    describe("findHtmlOnlyNodeNames", function () {
        it("should find html node names", function () {
            setHtml("

content
");

            var nodeNames = documentUtil.findHtmlOnlyNodeNames(doc);

            expect(nodeNames).toEqual(['html', 'head', 'body', 'p', 'span', 'br']);
        });

        it("should not include tags from other namespaces", function () {
            setHtml("<svg xmlns='http://www.w3.org/2000/svg'><rect/></svg>");

            var nodeNames = documentUtil.findHtmlOnlyNodeNames(doc);

            expect(nodeNames).toEqual(['html', 'head', 'body']);
        });

        it("should not include HTML tags if they conflict with ones from other namespaces", function () {
            setHtml('' +
                    '<svg width="10" height="10" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' +
                    '' +
                    '</svg>' +
                    '');

            var nodeNames = documentUtil.findHtmlOnlyNodeNames(doc);

            expect(nodeNames).toEqual(['html', 'head', 'body']);
        });
    });
});
<|endoftext|>


<commit_before>var CLIEngine = require( 'eslint' ).CLIEngine,
  cli = new CLIEngine( {
    useEslintrc: false,
    configFile: '.eslintrc'
  } );

exports.executeOnText = function executeOnText( text ) {
  return cli.executeOnText( text );
};

exports.executeOnFiles = function executeOnFiles( files ) {
  return cli.executeOnFiles( files );
};

exports.formatReportResults = function formatReportResults( results ) {
  return cli.getFormatter( 'compact' )( results );
};
<commit_msg>Run tests only on idiomatic style rules (core)<commit_after>var CLIEngine = require( 'eslint' ).CLIEngine,
  cli = new CLIEngine( {
    useEslintrc: false,
    configFile: '.eslintrc-core'
  } );

exports.executeOnText = function executeOnText( text ) {
  return cli.executeOnText( text );
};

exports.executeOnFiles = function executeOnFiles( files ) {
  return cli.executeOnFiles( files );
};

exports.formatReportResults = function formatReportResults( results ) {
  return cli.getFormatter( 'compact' )( results );
};
<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: Ganaraj.Pr
 * Date: 11/10/13
 * Time: 11:27
 * To change this template use File | Settings | File Templates.
 */

(function(){

function isDnDsSupported(){
    return 'draggable' in document.createElement("span");
}

if(!isDnDsSupported()){
    return;
}

if (window.jQuery && (-1 == window.jQuery.event.props.indexOf("dataTransfer"))) {
    window.jQuery.event.props.push("dataTransfer");
}

var currentData;

angular.module("ang-drag-drop",[])
    .directive("uiDraggable", [
        '$parse',
        '$rootScope',
        '$dragImage',
        function ($parse, $rootScope, $dragImage) {
            return function (scope, element, attrs) {
                var dragData = "",
                    isDragHandleUsed = false,
                    dragHandleClass,
                    draggingClass = attrs.draggingClass || "on-dragging",
                    dragTarget;

                element.attr("draggable", false);

                attrs.$observe("uiDraggable", function (newValue) {
                    if(newValue){
                        element.attr("draggable", newValue);
                    }
                    else{
                        element.removeAttr("draggable");
                    }

                });

                if (attrs.drag) {
                    scope.$watch(attrs.drag, function (newValue) {
                        dragData = newValue || "";
                    });
                }

                if (angular.isString(attrs.dragHandleClass)) {
                    isDragHandleUsed = true;
                    dragHandleClass = attrs.dragHandleClass.trim() || "drag-handle";

                    element.bind("mousedown", function (e) {
                        dragTarget = e.target;
                    });
                }

                function dragendHandler(e) {
                    setTimeout(function() {
                      element.unbind('$destroy', dragendHandler);
                    }, 0);
                    var sendChannel = attrs.dragChannel || "defaultchannel";
                    $rootScope.$broadcast("ANGULAR_DRAG_END", sendChannel);
                    if (e.dataTransfer && e.dataTransfer.dropEffect !== "none") {
                        if (attrs.onDropSuccess) {
                            var fn = $parse(attrs.onDropSuccess);
                            scope.$apply(function () {
                                fn(scope, {$event: e});
                            });
                        } else {
                            if (attrs.onDropFailure) {
                                var fn = $parse(attrs.onDropFailure);
                                scope.$apply(function () {
                                    fn(scope, {$event: e});
                                });
                            }
                        }
                    }
                    element.removeClass(draggingClass);
                }

                element.bind("dragend", dragendHandler);

                element.bind("dragstart", function (e) {
                    var isDragAllowed = !isDragHandleUsed || dragTarget.classList.contains(dragHandleClass);

                    if (isDragAllowed) {
                        var sendChannel = attrs.dragChannel || "defaultchannel";
                        var sendData = angular.toJson({ data: dragData, channel: sendChannel });
                        var dragImage = attrs.dragImage || null;

                        element.addClass(draggingClass);
                        element.bind('$destroy', dragendHandler);

                        if (dragImage) {
                            var dragImageFn = $parse(attrs.dragImage);
                            scope.$apply(function() {
                                var dragImageParameters = dragImageFn(scope, {$event: e});
                                if (dragImageParameters) {
                                    if (angular.isString(dragImageParameters)) {
                                        dragImageParameters = $dragImage.generate(dragImageParameters);
                                    }
                                    if (dragImageParameters.image) {
                                        var xOffset = dragImageParameters.xOffset || 0,
                                            yOffset = dragImageParameters.yOffset || 0;
                                        e.dataTransfer.setDragImage(dragImageParameters.image, xOffset, yOffset);
                                    }
                                }
                            });
                        }

                        e.dataTransfer.setData("dataToSend", sendData);
                        currentData = angular.fromJson(sendData);
                        e.dataTransfer.effectAllowed = "copyMove";
                        $rootScope.$broadcast("ANGULAR_DRAG_START", sendChannel, sendData);
                    }
                    else {
                        e.preventDefault();
                    }
                });
            };
        }
    ])
    .directive("uiOnDrop", [
        '$parse',
        '$rootScope',
        function ($parse, $rootScope) {
            return function (scope, element, attr) {
                var dragging = 0; //Ref. http://stackoverflow.com/a/10906204
                var dropChannel = attr.dropChannel || "defaultchannel" ;
                var dragChannel = "";
                var dragEnterClass = attr.dragEnterClass || "on-drag-enter";
                var dragHoverClass = attr.dragHoverClass || "on-drag-hover";

                function onDragOver(e) {
                    if (e.preventDefault) {
                        e.preventDefault(); // Necessary. Allows us to drop.
                    }

                    if (e.stopPropagation) {
                        e.stopPropagation();
                    }

                    e.dataTransfer.dropEffect = e.shiftKey ? 'copy' : 'move';
                    return false;
                }

                function onDragLeave(e) {
                  dragging--;
                  if (dragging == 0) {
                    element.removeClass(dragHoverClass);
                  }
                }

                function onDragEnter(e) {
                    dragging++;
                    $rootScope.$broadcast("ANGULAR_HOVER", dragChannel);
                    element.addClass(dragHoverClass);
                }

                function onDrop(e) {
                    if (e.preventDefault) {
                        e.preventDefault(); // Necessary. Allows us to drop.
                    }
                    if (e.stopPropagation) {
                        e.stopPropagation(); // Necessary. Allows us to drop.
                    }

                    var sendData = e.dataTransfer.getData("dataToSend");
                    sendData = angular.fromJson(sendData);

                    var fn = $parse(attr.uiOnDrop);
                    scope.$apply(function () {
                        fn(scope, {$data: sendData.data, $event: e, $channel: sendData.channel});
                    });
                    element.removeClass(dragEnterClass);
                    dragging = 0;
                }

                function isDragChannelAccepted(dragChannel, dropChannel) {
                    if (dropChannel === "*") {
                        return true;
                    }

                    var channelMatchPattern = new RegExp("(\\s|[,])+(" + dragChannel + ")(\\s|[,])+", "i");

                    return channelMatchPattern.test("," + dropChannel + ",");
                }

                function preventNativeDnD(e) {
                    if (e.preventDefault) {
                        e.preventDefault();
                    }
                    if (e.stopPropagation) {
                        e.stopPropagation();
                    }
                    e.dataTransfer.dropEffect = "none";
                    return false;
                }

			var deregisterDragStart = $rootScope.$on("ANGULAR_DRAG_START", function (event, channel) {
                    dragChannel = channel;
                    if (isDragChannelAccepted(channel, dropChannel)) {
                        if (attr.dropValidate) {
                            var validateFn = $parse(attr.dropValidate);
                            var valid = validateFn(scope, {$data: currentData.data, $channel: currentData.channel});
                            if (!valid) {
                                element.bind("dragover", preventNativeDnD);
                                element.bind("dragenter", preventNativeDnD);
                                element.bind("dragleave", preventNativeDnD);
                                element.bind("drop", preventNativeDnD);
								return;
                            }
                        }

                        element.bind("dragover", onDragOver);
                        element.bind("dragenter", onDragEnter);
                        element.bind("dragleave", onDragLeave);

                        element.bind("drop", onDrop);
                        element.addClass(dragEnterClass);
                    }
					else {
					    element.bind("dragover", preventNativeDnD);
					    element.bind("dragenter", preventNativeDnD);
					    element.bind("dragleave", preventNativeDnD);
					    element.bind("drop", preventNativeDnD);
					}

                });

                var deregisterDragEnd = $rootScope.$on("ANGULAR_DRAG_END", function (e, channel) {
                    dragChannel = "";
                    if (isDragChannelAccepted(channel, dropChannel)) {

                        element.unbind("dragover", onDragOver);
                        element.unbind("dragenter", onDragEnter);
                        element.unbind("dragleave", onDragLeave);

                        element.unbind("drop", onDrop);
                        element.removeClass(dragHoverClass);
                        element.removeClass(dragEnterClass);
                    }

					element.unbind("dragover", preventNativeDnD);
					element.unbind("dragenter", preventNativeDnD);
					element.unbind("dragleave", preventNativeDnD);
					element.unbind("drop", preventNativeDnD);
                });

                var deregisterDragHover = $rootScope.$on("ANGULAR_HOVER", function (e, channel) {
                    if (isDragChannelAccepted(channel, dropChannel)) {
                      element.removeClass(dragHoverClass);
                    }
                });

                scope.$on('$destroy', function () {
                    deregisterDragStart();
                    deregisterDragEnd();
                    deregisterDragHover();
                });

                attr.$observe('dropChannel', function (value) {
                    if (value) {
                        dropChannel = value;
                    }
                });

            };
        }
    ])
    .constant("$dragImageConfig", {
        height: 20,
        width: 200,
        padding: 10,
        font: 'bold 11px Arial',
        fontColor: '#eee8d5',
        backgroundColor: '#93a1a1',
        xOffset: 0,
        yOffset: 0
    })
    .service("$dragImage", [
        '$dragImageConfig',
        function (defaultConfig) {
            var ELLIPSIS = '…';

            function fitString(canvas, text, config) {
                var width = canvas.measureText(text).width;
                if (width < config.width) {
                    return text;
                }
                while (width + config.padding > config.width) {
                    text = text.substring(0, text.length - 1);
                    width = canvas.measureText(text + ELLIPSIS).width;
                }
                return text + ELLIPSIS;
            };

            this.generate = function (text, options) {
                var config = angular.extend({}, defaultConfig, options || {});
                var el = document.createElement('canvas');

                el.height = config.height;
                el.width = config.width;

                var canvas = el.getContext('2d');

                canvas.fillStyle = config.backgroundColor;
                canvas.fillRect(0, 0, config.width, config.height);
                canvas.font = config.font;
                canvas.fillStyle = config.fontColor;

                var title = fitString(canvas, text, config);
                canvas.fillText(title, 4, config.padding + 4);

                var image = new Image();
                image.src = el.toDataURL();

                return {
                    image: image,
                    xOffset: config.xOffset,
                    yOffset: config.yOffset
                };
            }
        }
    ]);

}());
<commit_msg>Preventing event bubbling on hover (for class changes), so that we can trigger the most specific class change in the case of nested drop zones.<commit_after>/**
 * Created with IntelliJ IDEA.
 * User: Ganaraj.Pr
 * Date: 11/10/13
 * Time: 11:27
 * To change this template use File | Settings | File Templates.
 */

(function(){

function isDnDsSupported(){
    return 'draggable' in document.createElement("span");
}

if(!isDnDsSupported()){
    return;
}

if (window.jQuery && (-1 == window.jQuery.event.props.indexOf("dataTransfer"))) {
    window.jQuery.event.props.push("dataTransfer");
}

var currentData;

angular.module("ang-drag-drop",[])
    .directive("uiDraggable", [
        '$parse',
        '$rootScope',
        '$dragImage',
        function ($parse, $rootScope, $dragImage) {
            return function (scope, element, attrs) {
                var dragData = "",
                    isDragHandleUsed = false,
                    dragHandleClass,
                    draggingClass = attrs.draggingClass || "on-dragging",
                    dragTarget;

                element.attr("draggable", false);

                attrs.$observe("uiDraggable", function (newValue) {
                    if(newValue){
                        element.attr("draggable", newValue);
                    }
                    else{
                        element.removeAttr("draggable");
                    }

                });

                if (attrs.drag) {
                    scope.$watch(attrs.drag, function (newValue) {
                        dragData = newValue || "";
                    });
                }

                if (angular.isString(attrs.dragHandleClass)) {
                    isDragHandleUsed = true;
                    dragHandleClass = attrs.dragHandleClass.trim() || "drag-handle";

                    element.bind("mousedown", function (e) {
                        dragTarget = e.target;
                    });
                }

                function dragendHandler(e) {
                    setTimeout(function() {
                      element.unbind('$destroy', dragendHandler);
                    }, 0);
                    var sendChannel = attrs.dragChannel || "defaultchannel";
                    $rootScope.$broadcast("ANGULAR_DRAG_END", sendChannel);
                    if (e.dataTransfer && e.dataTransfer.dropEffect !== "none") {
                        if (attrs.onDropSuccess) {
                            var fn = $parse(attrs.onDropSuccess);
                            scope.$apply(function () {
                                fn(scope, {$event: e});
                            });
                        } else {
                            if (attrs.onDropFailure) {
                                var fn = $parse(attrs.onDropFailure);
                                scope.$apply(function () {
                                    fn(scope, {$event: e});
                                });
                            }
                        }
                    }
                    element.removeClass(draggingClass);
                }

                element.bind("dragend", dragendHandler);

                element.bind("dragstart", function (e) {
                    var isDragAllowed = !isDragHandleUsed || dragTarget.classList.contains(dragHandleClass);

                    if (isDragAllowed) {
                        var sendChannel = attrs.dragChannel || "defaultchannel";
                        var sendData = angular.toJson({ data: dragData, channel: sendChannel });
                        var dragImage = attrs.dragImage || null;

                        element.addClass(draggingClass);
                        element.bind('$destroy', dragendHandler);

                        if (dragImage) {
                            var dragImageFn = $parse(attrs.dragImage);
                            scope.$apply(function() {
                                var dragImageParameters = dragImageFn(scope, {$event: e});
                                if (dragImageParameters) {
                                    if (angular.isString(dragImageParameters)) {
                                        dragImageParameters = $dragImage.generate(dragImageParameters);
                                    }
                                    if (dragImageParameters.image) {
                                        var xOffset = dragImageParameters.xOffset || 0,
                                            yOffset = dragImageParameters.yOffset || 0;
                                        e.dataTransfer.setDragImage(dragImageParameters.image, xOffset, yOffset);
                                    }
                                }
                            });
                        }

                        e.dataTransfer.setData("dataToSend", sendData);
                        currentData = angular.fromJson(sendData);
                        e.dataTransfer.effectAllowed = "copyMove";
                        $rootScope.$broadcast("ANGULAR_DRAG_START", sendChannel, sendData);
                    }
                    else {
                        e.preventDefault();
                    }
                });
            };
        }
    ])
    .directive("uiOnDrop", [
        '$parse',
        '$rootScope',
        function ($parse, $rootScope) {
            return function (scope, element, attr) {
                var dragging = 0; //Ref. http://stackoverflow.com/a/10906204
                var dropChannel = attr.dropChannel || "defaultchannel" ;
                var dragChannel = "";
                var dragEnterClass = attr.dragEnterClass || "on-drag-enter";
                var dragHoverClass = attr.dragHoverClass || "on-drag-hover";

                function onDragOver(e) {
                    if (e.preventDefault) {
                        e.preventDefault(); // Necessary. Allows us to drop.
                    }

                    if (e.stopPropagation) {
                        e.stopPropagation();
                    }

                    e.dataTransfer.dropEffect = e.shiftKey ? 'copy' : 'move';
                    return false;
                }

                function onDragLeave(e) {
		  if (e.preventDefault) {
			e.preventDefault();
		  }

		  if (e.stopPropagation) {
			e.stopPropagation();
		  }
		  dragging--;

                  if (dragging == 0) {
                    element.removeClass(dragHoverClass);
                  }
                }

                function onDragEnter(e) {
		    if (e.preventDefault) {
                        e.preventDefault();
                    }

                    if (e.stopPropagation) {
                        e.stopPropagation();
                    }
		    dragging++;

                    $rootScope.$broadcast("ANGULAR_HOVER", dragChannel);
                    element.addClass(dragHoverClass);
                }

                function onDrop(e) {
                    if (e.preventDefault) {
                        e.preventDefault(); // Necessary. Allows us to drop.
                    }
                    if (e.stopPropagation) {
                        e.stopPropagation(); // Necessary. Allows us to drop.
                    }

                    var sendData = e.dataTransfer.getData("dataToSend");
                    sendData = angular.fromJson(sendData);

                    var fn = $parse(attr.uiOnDrop);
                    scope.$apply(function () {
                        fn(scope, {$data: sendData.data, $event: e, $channel: sendData.channel});
                    });
                    element.removeClass(dragEnterClass);
                    dragging = 0;
                }

                function isDragChannelAccepted(dragChannel, dropChannel) {
                    if (dropChannel === "*") {
                        return true;
                    }

                    var channelMatchPattern = new RegExp("(\\s|[,])+(" + dragChannel + ")(\\s|[,])+", "i");

                    return channelMatchPattern.test("," + dropChannel + ",");
                }

                function preventNativeDnD(e) {
                    if (e.preventDefault) {
                        e.preventDefault();
                    }
                    if (e.stopPropagation) {
                        e.stopPropagation();
                    }
                    e.dataTransfer.dropEffect = "none";
                    return false;
                }

			var deregisterDragStart = $rootScope.$on("ANGULAR_DRAG_START", function (event, channel) {
                    dragChannel = channel;
                    if (isDragChannelAccepted(channel, dropChannel)) {
                        if (attr.dropValidate) {
                            var validateFn = $parse(attr.dropValidate);
                            var valid = validateFn(scope, {$data: currentData.data, $channel: currentData.channel});
                            if (!valid) {
                                element.bind("dragover", preventNativeDnD);
                                element.bind("dragenter", preventNativeDnD);
                                element.bind("dragleave", preventNativeDnD);
                                element.bind("drop", preventNativeDnD);
								return;
                            }
                        }

                        element.bind("dragover", onDragOver);
                        element.bind("dragenter", onDragEnter);
                        element.bind("dragleave", onDragLeave);

                        element.bind("drop", onDrop);
                        element.addClass(dragEnterClass);
                    }
					else {
					    element.bind("dragover", preventNativeDnD);
					    element.bind("dragenter", preventNativeDnD);
					    element.bind("dragleave", preventNativeDnD);
					    element.bind("drop", preventNativeDnD);
					}

                });

                var deregisterDragEnd = $rootScope.$on("ANGULAR_DRAG_END", function (e, channel) {
                    dragChannel = "";
                    if (isDragChannelAccepted(channel, dropChannel)) {

                        element.unbind("dragover", onDragOver);
                        element.unbind("dragenter", onDragEnter);
                        element.unbind("dragleave", onDragLeave);

                        element.unbind("drop", onDrop);
                        element.removeClass(dragHoverClass);
                        element.removeClass(dragEnterClass);
                    }

					element.unbind("dragover", preventNativeDnD);
					element.unbind("dragenter", preventNativeDnD);
					element.unbind("dragleave", preventNativeDnD);
					element.unbind("drop", preventNativeDnD);
                });

                var deregisterDragHover = $rootScope.$on("ANGULAR_HOVER", function (e, channel) {
                    if (isDragChannelAccepted(channel, dropChannel)) {
                      element.removeClass(dragHoverClass);
                    }
                });

                scope.$on('$destroy', function () {
                    deregisterDragStart();
                    deregisterDragEnd();
                    deregisterDragHover();
                });

                attr.$observe('dropChannel', function (value) {
                    if (value) {
                        dropChannel = value;
                    }
                });

            };
        }
    ])
    .constant("$dragImageConfig", {
        height: 20,
        width: 200,
        padding: 10,
        font: 'bold 11px Arial',
        fontColor: '#eee8d5',
        backgroundColor: '#93a1a1',
        xOffset: 0,
        yOffset: 0
    })
    .service("$dragImage", [
        '$dragImageConfig',
        function (defaultConfig) {
            var ELLIPSIS = '…';

            function fitString(canvas, text, config) {
                var width = canvas.measureText(text).width;
                if (width < config.width) {
                    return text;
                }
                while (width + config.padding > config.width) {
                    text = text.substring(0, text.length - 1);
                    width = canvas.measureText(text + ELLIPSIS).width;
                }
                return text + ELLIPSIS;
            };

            this.generate = function (text, options) {
                var config = angular.extend({}, defaultConfig, options || {});
                var el = document.createElement('canvas');

                el.height = config.height;
                el.width = config.width;

                var canvas = el.getContext('2d');

                canvas.fillStyle = config.backgroundColor;
                canvas.fillRect(0, 0, config.width, config.height);
                canvas.font = config.font;
                canvas.fillStyle = config.fontColor;

                var title = fitString(canvas, text, config);
                canvas.fillText(title, 4, config.padding + 4);

                var image = new Image();
                image.src = el.toDataURL();

                return {
                    image: image,
                    xOffset: config.xOffset,
                    yOffset: config.yOffset
                };
            }
        }
    ]);

}());
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var conf = require('./gulp/conf');

module.exports = {
  sourceFiles: 'api/example.apib',
  serverPort: 3010,
  //discover: true,
  //stealthmode: true,
  //disableCORS: true,
  CORS: {
    origin: 'http://localhost:3000',
    headers: 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
    credentials: true
  },
  autoOptions: true,
  originCORS: 'http://localhost:3000'
  //sslKeyFile: '/path/to/ssl/key.key',
  //sslCrtFile: '/path/to/ssl/cert.crt',
  //delay: 2000,
  //method: ['DELETE','OPTIONS']
};
<commit_msg>Cleaned drakov options<commit_after>'use strict';

var path = require('path');
var conf = require('./gulp/conf');

module.exports = {
  sourceFiles: 'api/example.apib',
  serverPort: 3010,
  //discover: true,
  //stealthmode: true,
  //disableCORS: true,
  CORS: {
    origin: 'http://localhost:3000',
    headers: 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
    credentials: true
  },
  autoOptions: true
  //sslKeyFile: '/path/to/ssl/key.key',
  //sslCrtFile: '/path/to/ssl/cert.crt',
  //delay: 2000,
  //method: ['DELETE','OPTIONS']
};
<|endoftext|>


<commit_before>import './setup';
import {Container} from 'aurelia-dependency-injection';
import {TemplatingEngine} from '../src/templating-engine';
import {ViewResources} from '../src/view-resources';
import {DOM} from 'aurelia-pal';

describe('enhance', () => {
  let container;
  let element;
  let templatingEngine;

  beforeEach(() => {
    container = new Container();
    element = DOM.createElement('div');
    templatingEngine = container.get(TemplatingEngine);
  });

  it('passes bindingContext and overrideContext to .bind()', () => {
    let bindingContext = { some: 'var' };
    let overrideContext = { foo: 'bar' };

    let view = templatingEngine.enhance({
      element: element,
      bindingContext: bindingContext,
      overrideContext: overrideContext
    });

    expect(view.bindingContext).toBe(bindingContext);
    expect(view.overrideContext).toBe(overrideContext);
    expect(view.bindingContext.some).toBe('var');
    expect(view.overrideContext.foo).toBe('bar');
  });

  it('supports passing of ViewResources to the view-compiler', () => {
    let compileNodeSpy = spyOn(templatingEngine._viewCompiler, '_compileNode');
    let resources = new ViewResources();

    templatingEngine.enhance({
      element: element,
      resources: resources
    });

    let r = compileNodeSpy.calls.argsFor(0)[1];

    expect(r).toBe(resources);
  });
});
<commit_msg>test(templating-engine): use createOverrideContext<commit_after>import './setup';
import {Container} from 'aurelia-dependency-injection';
import {createOverrideContext} from 'aurelia-binding';
import {TemplatingEngine} from '../src/templating-engine';
import {ViewResources} from '../src/view-resources';
import {DOM} from 'aurelia-pal';

describe('enhance', () => {
  let container;
  let element;
  let templatingEngine;

  beforeEach(() => {
    container = new Container();
    element = DOM.createElement('div');
    templatingEngine = container.get(TemplatingEngine);
  });

  it('passes bindingContext and overrideContext to .bind()', () => {
    let bindingContext = { some: 'var' };
    let overrideContext = createOverrideContext(bindingContext);
    overrideContext.foo = 'bar';

    let view = templatingEngine.enhance({
      element: element,
      bindingContext: bindingContext,
      overrideContext: overrideContext
    });

    expect(view.bindingContext).toBe(bindingContext);
    expect(view.overrideContext).toBe(overrideContext);
    expect(view.bindingContext.some).toBe('var');
    expect(view.overrideContext.foo).toBe('bar');
  });

  it('supports passing of ViewResources to the view-compiler', () => {
    let compileNodeSpy = spyOn(templatingEngine._viewCompiler, '_compileNode');
    let resources = new ViewResources();

    templatingEngine.enhance({
      element: element,
      resources: resources
    });

    let r = compileNodeSpy.calls.argsFor(0)[1];

    expect(r).toBe(resources);
  });
});
<|endoftext|>


<commit_before>// Copyright (c) 2010 - 2012  John Reese
// Copyright (c) 2012 - 2017  MantisBT Team - mantisbt-dev@lists.sourceforge.net
// Licensed under the MIT license

jQuery(document).ready(function($) {
	"use strict";

	/**
	 * Return MantisBT XMLHttpRequest URL for given endpoint
	 * @param {string} entrypoint
	 * @returns {string} XMLHttpRequest URL
	 */
	function xhrurl(entrypoint) {
		return "xmlhttprequest.php?entrypoint=plugin_snippets_" + entrypoint;
	}

	/**
	 * Primary Snippets functionality.
	 * Use an AJAX request to retrieve the user's available snippets, and
	 * then insert select boxes into the DOM for each supported textarea.
	 */
	function SnippetsInit() {
		/**
		 * Initialize Snippets user interface.
		 * Adds a selection list before each textarea.
		 * @param {object} data - JSON object returned by XHR (see PHPDoc for
		 *                        xmlhttprequest_plugin_snippets_data() for details)
		 * @param {string} data.selector
		 * @param {string} data.label
		 * @param {string} data.default
		 * @param {object} data.snippets - Snippets list
		 */
		function SnippetsUI(data) {
			$(data.selector).each(function() {
				var textarea = $(this);

				// Only display snippets selector if there are any
				if (data.snippets) {
					try {
						// Create Snippets select
						var select = $("<select></select>");
						select.append("<option title='' value=''>" + data.default + "</option>");

						$.each(data.snippets, function(key, snippet) {
							// Escape single quotes
							var value = snippet.value.replace(/'/g, "'");

							select.append(
								"<option value='" + value + "' title='" + value + "'>" + snippet.name + "</option>"
							);
						});

						select.change(function() {
							var text = $(this).val();
							textarea.textrange('replace', text);
							$(this).val("");
						});

						var label = $("" + data.label + " ");
						label.append(select);

						textarea.before(label);
						textarea.before('

');
					} catch(e) {
						console.error('Error occured while generating Snippets UI', e);
					}
				}
			});
		}

		// If we have any textareas (excluding those in the plugin's own
		// edit pages) then fetch Snippets
		if ($("textarea").not(".snippetspatternhelp textarea").length > 0) {
			var bug_id = 0;

			$("form[name='bugnoteadd'] input[name='bug_id']").each(function() {
				bug_id = $(this).val();
			});
			$("form[action='bug_update.php'] input[name='bug_id']").each(function() {
				bug_id = $(this).val();
			});

			var url = xhrurl('data');
			if (bug_id > 0) {
				url += "&bug_id=" + bug_id;
			}

			$.getJSON(url)
				.done(SnippetsUI)
				.fail(function() {
					console.error('Error occured while retrieving Snippets');
				});
		}
	}

	/**
	 * Initialize Placeholder help tooltip for given object
	 * @param {object} domObject
	 * @param {object} data - JSON object returned by XHR
	 */
	function AddTooltip(domObject, data) {
		domObject.qtip({
			content: {
				text: data.text,
				title: data.title,
				button: true
			},
			position: {
				target: domObject.children('textarea'),
				my: 'bottom right',
				at: 'top right',
				viewport: $(window),
				adjust: {
					method: 'flip'
				}
			},
			hide: {
				fixed: true
			}
		});
	}

	try {
		SnippetsInit();
	} catch(e) {
		alert(e);
	}

	// Snippet list behaviors
	$("input.snippets_select_all").change(function() {
		$("input[name='snippet_list[]']").prop("checked", $(this).prop("checked"));
	});

	// Snippet pattern help
	var selector = $(".snippetspatternhelp");
	if (selector.length > 0 ) {
		$.get(xhrurl('pattern_help'))
			.done(function(data) {
				selector.each(function() {
					AddTooltip($(this), data);
				});
			})
			.fail(function () {
				console.error('Error occured while retrieving Snippets pattern help');
			});
	}

});
<commit_msg>Fix typo in error message<commit_after>// Copyright (c) 2010 - 2012  John Reese
// Copyright (c) 2012 - 2017  MantisBT Team - mantisbt-dev@lists.sourceforge.net
// Licensed under the MIT license

jQuery(document).ready(function($) {
	"use strict";

	/**
	 * Return MantisBT XMLHttpRequest URL for given endpoint
	 * @param {string} entrypoint
	 * @returns {string} XMLHttpRequest URL
	 */
	function xhrurl(entrypoint) {
		return "xmlhttprequest.php?entrypoint=plugin_snippets_" + entrypoint;
	}

	/**
	 * Primary Snippets functionality.
	 * Use an AJAX request to retrieve the user's available snippets, and
	 * then insert select boxes into the DOM for each supported textarea.
	 */
	function SnippetsInit() {
		/**
		 * Initialize Snippets user interface.
		 * Adds a selection list before each textarea.
		 * @param {object} data - JSON object returned by XHR (see PHPDoc for
		 *                        xmlhttprequest_plugin_snippets_data() for details)
		 * @param {string} data.selector
		 * @param {string} data.label
		 * @param {string} data.default
		 * @param {object} data.snippets - Snippets list
		 */
		function SnippetsUI(data) {
			$(data.selector).each(function() {
				var textarea = $(this);

				// Only display snippets selector if there are any
				if (data.snippets) {
					try {
						// Create Snippets select
						var select = $("<select></select>");
						select.append("<option title='' value=''>" + data.default + "</option>");

						$.each(data.snippets, function(key, snippet) {
							// Escape single quotes
							var value = snippet.value.replace(/'/g, "'");

							select.append(
								"<option value='" + value + "' title='" + value + "'>" + snippet.name + "</option>"
							);
						});

						select.change(function() {
							var text = $(this).val();
							textarea.textrange('replace', text);
							$(this).val("");
						});

						var label = $("" + data.label + " ");
						label.append(select);

						textarea.before(label);
						textarea.before('

');
					} catch(e) {
						console.error('Error occured while generating Snippets UI', e);
					}
				}
			});
		}

		// If we have any textareas (excluding those in the plugin's own
		// edit pages) then fetch Snippets
		if ($("textarea").not(".snippetspatternhelp textarea").length > 0) {
			var bug_id = 0;

			$("form[name='bugnoteadd'] input[name='bug_id']").each(function() {
				bug_id = $(this).val();
			});
			$("form[action='bug_update.php'] input[name='bug_id']").each(function() {
				bug_id = $(this).val();
			});

			var url = xhrurl('data');
			if (bug_id > 0) {
				url += "&bug_id=" + bug_id;
			}

			$.getJSON(url)
				.done(SnippetsUI)
				.fail(function() {
					console.error('Error occured while retrieving Snippets');
				});
		}
	}

	/**
	 * Initialize Placeholder help tooltip for given object
	 * @param {object} domObject
	 * @param {object} data - JSON object returned by XHR
	 */
	function AddTooltip(domObject, data) {
		domObject.qtip({
			content: {
				text: data.text,
				title: data.title,
				button: true
			},
			position: {
				target: domObject.children('textarea'),
				my: 'bottom right',
				at: 'top right',
				viewport: $(window),
				adjust: {
					method: 'flip'
				}
			},
			hide: {
				fixed: true
			}
		});
	}

	try {
		SnippetsInit();
	} catch(e) {
		alert(e);
	}

	// Snippet list behaviors
	$("input.snippets_select_all").change(function() {
		$("input[name='snippet_list[]']").prop("checked", $(this).prop("checked"));
	});

	// Snippet pattern help
	var selector = $(".snippetspatternhelp");
	if (selector.length > 0 ) {
		$.get(xhrurl('pattern_help'))
			.done(function(data) {
				selector.each(function() {
					AddTooltip($(this), data);
				});
			})
			.fail(function () {
				console.error('Error occurred while retrieving Snippets pattern help');
			});
	}

});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var MongoClient = require('mongodb').MongoClient;
    fs          = require('fs');
var sizes = process.argv.slice(2);

var bin_lut = {},
    bin_idx = {},
    bin_nts = {};

sizes.forEach(function(mb) {
  bin_idx[mb] = 0;
  bin_nts[mb] = mb*1000000;
});

MongoClient.connect('mongodb://127.0.0.1:27017/cmap', function(err, cmapdb) {
  if (err) throw err;
  var maps = cmapdb.collection("maps");
  // retrieve the maps sorted by taxonomy id
  maps.find({type:'genome'}, {}).sort({'taxon_id' : 1}).toArray(function(err, genomes) {
    if (err) throw err;
    genomes.forEach(function(map) {
      bin_lut[map.taxon_id] = {};
      // iterate over the regions in the order provided
      // update genes in the region.
      for(var i=0;i<map.regions.names.length;i++) {
        var region = map.regions.names[i];
        var rlength = map.regions.lengths[i];
        bin_lut[map.taxon_id][region] = {l:rlength,b:[]};
        sizes.forEach(function(mb) {
          bin_lut[map.taxon_id][region].b.push(bin_idx[mb]);
          if (region === 'UNANCHORED') {
            bin_idx[mb]++;
          }
          else {
            bin_idx[mb] += Math.ceil(rlength / bin_nts[mb]);
          }
        });
      }
    });
    cmapdb.close();
    fs.writeFileSync('bin_lut.json',JSON.stringify({sizes:sizes,lut:bin_lut}));
  });
});<commit_msg>make bin sizes numeric<commit_after>#!/usr/bin/env node

var MongoClient = require('mongodb').MongoClient;
    fs          = require('fs');
var sizes = process.argv.slice(2).map(function(mb) {return +mb;});

var bin_lut = {},
    bin_idx = {},
    bin_nts = {};

sizes.forEach(function(mb) {
  bin_idx[mb] = 0;
  bin_nts[mb] = mb*1000000;
});

MongoClient.connect('mongodb://127.0.0.1:27017/cmap', function(err, cmapdb) {
  if (err) throw err;
  var maps = cmapdb.collection("maps");
  // retrieve the maps sorted by taxonomy id
  maps.find({type:'genome'}, {}).sort({'taxon_id' : 1}).toArray(function(err, genomes) {
    if (err) throw err;
    genomes.forEach(function(map) {
      bin_lut[map.taxon_id] = {};
      // iterate over the regions in the order provided
      // update genes in the region.
      for(var i=0;i<map.regions.names.length;i++) {
        var region = map.regions.names[i];
        var rlength = map.regions.lengths[i];
        bin_lut[map.taxon_id][region] = {l:rlength,b:[]};
        sizes.forEach(function(mb) {
          bin_lut[map.taxon_id][region].b.push(bin_idx[mb]);
          if (region === 'UNANCHORED') {
            bin_idx[mb]++;
          }
          else {
            bin_idx[mb] += Math.ceil(rlength / bin_nts[mb]);
          }
        });
      }
    });
    cmapdb.close();
    fs.writeFileSync('bin_lut.json',JSON.stringify({sizes:sizes,lut:bin_lut}));
  });
});<|endoftext|>


<commit_before>/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};
<commit_msg>Use babel polyfill in EmberApp. Fixes #1<commit_after>/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    // Add options here
    babel: {
      includePolyfill: true
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  return app.toTree();
};
<|endoftext|>