(self["webpackChunkipypetrinet"] = self["webpackChunkipypetrinet"] || []).push([["vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_dagre_index_js-node_modules_-7114b2"],{

/***/ "./node_modules/css-loader/dist/runtime/api.js":
/*!*****************************************************!*\
  !*** ./node_modules/css-loader/dist/runtime/api.js ***!
  \*****************************************************/
/***/ ((module) => {

"use strict";


/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
  var list = []; // return the list of modules as css string

  list.toString = function toString() {
    return this.map(function (item) {
      var content = cssWithMappingToString(item, useSourceMap);

      if (item[2]) {
        return "@media ".concat(item[2], " {").concat(content, "}");
      }

      return content;
    }).join('');
  }; // import a list of modules into the list
  // eslint-disable-next-line func-names


  list.i = function (modules, mediaQuery, dedupe) {
    if (typeof modules === 'string') {
      // eslint-disable-next-line no-param-reassign
      modules = [[null, modules, '']];
    }

    var alreadyImportedModules = {};

    if (dedupe) {
      for (var i = 0; i < this.length; i++) {
        // eslint-disable-next-line prefer-destructuring
        var id = this[i][0];

        if (id != null) {
          alreadyImportedModules[id] = true;
        }
      }
    }

    for (var _i = 0; _i < modules.length; _i++) {
      var item = [].concat(modules[_i]);

      if (dedupe && alreadyImportedModules[item[0]]) {
        // eslint-disable-next-line no-continue
        continue;
      }

      if (mediaQuery) {
        if (!item[2]) {
          item[2] = mediaQuery;
        } else {
          item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
        }
      }

      list.push(item);
    }
  };

  return list;
};

function cssWithMappingToString(item, useSourceMap) {
  var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring

  var cssMapping = item[3];

  if (!cssMapping) {
    return content;
  }

  if (useSourceMap && typeof btoa === 'function') {
    var sourceMapping = toComment(cssMapping);
    var sourceURLs = cssMapping.sources.map(function (source) {
      return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
    });
    return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
  }

  return [content].join('\n');
} // Adapted from convert-source-map (MIT)


function toComment(sourceMap) {
  // eslint-disable-next-line no-undef
  var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
  var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
  return "/*# ".concat(data, " */");
}

/***/ }),

/***/ "./node_modules/dagre/index.js":
/*!*************************************!*\
  !*** ./node_modules/dagre/index.js ***!
  \*************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/*
Copyright (c) 2012-2014 Chris Pettitt

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

module.exports = {
  graphlib: __webpack_require__(/*! ./lib/graphlib */ "./node_modules/dagre/lib/graphlib.js"),

  layout: __webpack_require__(/*! ./lib/layout */ "./node_modules/dagre/lib/layout.js"),
  debug: __webpack_require__(/*! ./lib/debug */ "./node_modules/dagre/lib/debug.js"),
  util: {
    time: (__webpack_require__(/*! ./lib/util */ "./node_modules/dagre/lib/util.js").time),
    notime: (__webpack_require__(/*! ./lib/util */ "./node_modules/dagre/lib/util.js").notime)
  },
  version: __webpack_require__(/*! ./lib/version */ "./node_modules/dagre/lib/version.js")
};


/***/ }),

/***/ "./node_modules/dagre/lib/acyclic.js":
/*!*******************************************!*\
  !*** ./node_modules/dagre/lib/acyclic.js ***!
  \*******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var greedyFAS = __webpack_require__(/*! ./greedy-fas */ "./node_modules/dagre/lib/greedy-fas.js");

module.exports = {
  run: run,
  undo: undo
};

function run(g) {
  var fas = (g.graph().acyclicer === "greedy"
    ? greedyFAS(g, weightFn(g))
    : dfsFAS(g));
  _.forEach(fas, function(e) {
    var label = g.edge(e);
    g.removeEdge(e);
    label.forwardName = e.name;
    label.reversed = true;
    g.setEdge(e.w, e.v, label, _.uniqueId("rev"));
  });

  function weightFn(g) {
    return function(e) {
      return g.edge(e).weight;
    };
  }
}

function dfsFAS(g) {
  var fas = [];
  var stack = {};
  var visited = {};

  function dfs(v) {
    if (_.has(visited, v)) {
      return;
    }
    visited[v] = true;
    stack[v] = true;
    _.forEach(g.outEdges(v), function(e) {
      if (_.has(stack, e.w)) {
        fas.push(e);
      } else {
        dfs(e.w);
      }
    });
    delete stack[v];
  }

  _.forEach(g.nodes(), dfs);
  return fas;
}

function undo(g) {
  _.forEach(g.edges(), function(e) {
    var label = g.edge(e);
    if (label.reversed) {
      g.removeEdge(e);

      var forwardName = label.forwardName;
      delete label.reversed;
      delete label.forwardName;
      g.setEdge(e.w, e.v, label, forwardName);
    }
  });
}


/***/ }),

/***/ "./node_modules/dagre/lib/add-border-segments.js":
/*!*******************************************************!*\
  !*** ./node_modules/dagre/lib/add-border-segments.js ***!
  \*******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var util = __webpack_require__(/*! ./util */ "./node_modules/dagre/lib/util.js");

module.exports = addBorderSegments;

function addBorderSegments(g) {
  function dfs(v) {
    var children = g.children(v);
    var node = g.node(v);
    if (children.length) {
      _.forEach(children, dfs);
    }

    if (_.has(node, "minRank")) {
      node.borderLeft = [];
      node.borderRight = [];
      for (var rank = node.minRank, maxRank = node.maxRank + 1;
        rank < maxRank;
        ++rank) {
        addBorderNode(g, "borderLeft", "_bl", v, node, rank);
        addBorderNode(g, "borderRight", "_br", v, node, rank);
      }
    }
  }

  _.forEach(g.children(), dfs);
}

function addBorderNode(g, prop, prefix, sg, sgNode, rank) {
  var label = { width: 0, height: 0, rank: rank, borderType: prop };
  var prev = sgNode[prop][rank - 1];
  var curr = util.addDummyNode(g, "border", label, prefix);
  sgNode[prop][rank] = curr;
  g.setParent(curr, sg);
  if (prev) {
    g.setEdge(prev, curr, { weight: 1 });
  }
}


/***/ }),

/***/ "./node_modules/dagre/lib/coordinate-system.js":
/*!*****************************************************!*\
  !*** ./node_modules/dagre/lib/coordinate-system.js ***!
  \*****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = {
  adjust: adjust,
  undo: undo
};

function adjust(g) {
  var rankDir = g.graph().rankdir.toLowerCase();
  if (rankDir === "lr" || rankDir === "rl") {
    swapWidthHeight(g);
  }
}

function undo(g) {
  var rankDir = g.graph().rankdir.toLowerCase();
  if (rankDir === "bt" || rankDir === "rl") {
    reverseY(g);
  }

  if (rankDir === "lr" || rankDir === "rl") {
    swapXY(g);
    swapWidthHeight(g);
  }
}

function swapWidthHeight(g) {
  _.forEach(g.nodes(), function(v) { swapWidthHeightOne(g.node(v)); });
  _.forEach(g.edges(), function(e) { swapWidthHeightOne(g.edge(e)); });
}

function swapWidthHeightOne(attrs) {
  var w = attrs.width;
  attrs.width = attrs.height;
  attrs.height = w;
}

function reverseY(g) {
  _.forEach(g.nodes(), function(v) { reverseYOne(g.node(v)); });

  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    _.forEach(edge.points, reverseYOne);
    if (_.has(edge, "y")) {
      reverseYOne(edge);
    }
  });
}

function reverseYOne(attrs) {
  attrs.y = -attrs.y;
}

function swapXY(g) {
  _.forEach(g.nodes(), function(v) { swapXYOne(g.node(v)); });

  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    _.forEach(edge.points, swapXYOne);
    if (_.has(edge, "x")) {
      swapXYOne(edge);
    }
  });
}

function swapXYOne(attrs) {
  var x = attrs.x;
  attrs.x = attrs.y;
  attrs.y = x;
}


/***/ }),

/***/ "./node_modules/dagre/lib/data/list.js":
/*!*********************************************!*\
  !*** ./node_modules/dagre/lib/data/list.js ***!
  \*********************************************/
/***/ ((module) => {

/*
 * Simple doubly linked list implementation derived from Cormen, et al.,
 * "Introduction to Algorithms".
 */

module.exports = List;

function List() {
  var sentinel = {};
  sentinel._next = sentinel._prev = sentinel;
  this._sentinel = sentinel;
}

List.prototype.dequeue = function() {
  var sentinel = this._sentinel;
  var entry = sentinel._prev;
  if (entry !== sentinel) {
    unlink(entry);
    return entry;
  }
};

List.prototype.enqueue = function(entry) {
  var sentinel = this._sentinel;
  if (entry._prev && entry._next) {
    unlink(entry);
  }
  entry._next = sentinel._next;
  sentinel._next._prev = entry;
  sentinel._next = entry;
  entry._prev = sentinel;
};

List.prototype.toString = function() {
  var strs = [];
  var sentinel = this._sentinel;
  var curr = sentinel._prev;
  while (curr !== sentinel) {
    strs.push(JSON.stringify(curr, filterOutLinks));
    curr = curr._prev;
  }
  return "[" + strs.join(", ") + "]";
};

function unlink(entry) {
  entry._prev._next = entry._next;
  entry._next._prev = entry._prev;
  delete entry._next;
  delete entry._prev;
}

function filterOutLinks(k, v) {
  if (k !== "_next" && k !== "_prev") {
    return v;
  }
}


/***/ }),

/***/ "./node_modules/dagre/lib/debug.js":
/*!*****************************************!*\
  !*** ./node_modules/dagre/lib/debug.js ***!
  \*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var util = __webpack_require__(/*! ./util */ "./node_modules/dagre/lib/util.js");
var Graph = (__webpack_require__(/*! ./graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);

module.exports = {
  debugOrdering: debugOrdering
};

/* istanbul ignore next */
function debugOrdering(g) {
  var layerMatrix = util.buildLayerMatrix(g);

  var h = new Graph({ compound: true, multigraph: true }).setGraph({});

  _.forEach(g.nodes(), function(v) {
    h.setNode(v, { label: v });
    h.setParent(v, "layer" + g.node(v).rank);
  });

  _.forEach(g.edges(), function(e) {
    h.setEdge(e.v, e.w, {}, e.name);
  });

  _.forEach(layerMatrix, function(layer, i) {
    var layerV = "layer" + i;
    h.setNode(layerV, { rank: "same" });
    _.reduce(layer, function(u, v) {
      h.setEdge(u, v, { style: "invis" });
      return v;
    });
  });

  return h;
}


/***/ }),

/***/ "./node_modules/dagre/lib/graphlib.js":
/*!********************************************!*\
  !*** ./node_modules/dagre/lib/graphlib.js ***!
  \********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/* global window */

var graphlib;

if (true) {
  try {
    graphlib = __webpack_require__(/*! graphlib */ "webpack/sharing/consume/default/graphlib/graphlib");
  } catch (e) {
    // continue regardless of error
  }
}

if (!graphlib) {
  graphlib = window.graphlib;
}

module.exports = graphlib;


/***/ }),

/***/ "./node_modules/dagre/lib/greedy-fas.js":
/*!**********************************************!*\
  !*** ./node_modules/dagre/lib/greedy-fas.js ***!
  \**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var Graph = (__webpack_require__(/*! ./graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);
var List = __webpack_require__(/*! ./data/list */ "./node_modules/dagre/lib/data/list.js");

/*
 * A greedy heuristic for finding a feedback arc set for a graph. A feedback
 * arc set is a set of edges that can be removed to make a graph acyclic.
 * The algorithm comes from: P. Eades, X. Lin, and W. F. Smyth, "A fast and
 * effective heuristic for the feedback arc set problem." This implementation
 * adjusts that from the paper to allow for weighted edges.
 */
module.exports = greedyFAS;

var DEFAULT_WEIGHT_FN = _.constant(1);

function greedyFAS(g, weightFn) {
  if (g.nodeCount() <= 1) {
    return [];
  }
  var state = buildState(g, weightFn || DEFAULT_WEIGHT_FN);
  var results = doGreedyFAS(state.graph, state.buckets, state.zeroIdx);

  // Expand multi-edges
  return _.flatten(_.map(results, function(e) {
    return g.outEdges(e.v, e.w);
  }), true);
}

function doGreedyFAS(g, buckets, zeroIdx) {
  var results = [];
  var sources = buckets[buckets.length - 1];
  var sinks = buckets[0];

  var entry;
  while (g.nodeCount()) {
    while ((entry = sinks.dequeue()))   { removeNode(g, buckets, zeroIdx, entry); }
    while ((entry = sources.dequeue())) { removeNode(g, buckets, zeroIdx, entry); }
    if (g.nodeCount()) {
      for (var i = buckets.length - 2; i > 0; --i) {
        entry = buckets[i].dequeue();
        if (entry) {
          results = results.concat(removeNode(g, buckets, zeroIdx, entry, true));
          break;
        }
      }
    }
  }

  return results;
}

function removeNode(g, buckets, zeroIdx, entry, collectPredecessors) {
  var results = collectPredecessors ? [] : undefined;

  _.forEach(g.inEdges(entry.v), function(edge) {
    var weight = g.edge(edge);
    var uEntry = g.node(edge.v);

    if (collectPredecessors) {
      results.push({ v: edge.v, w: edge.w });
    }

    uEntry.out -= weight;
    assignBucket(buckets, zeroIdx, uEntry);
  });

  _.forEach(g.outEdges(entry.v), function(edge) {
    var weight = g.edge(edge);
    var w = edge.w;
    var wEntry = g.node(w);
    wEntry["in"] -= weight;
    assignBucket(buckets, zeroIdx, wEntry);
  });

  g.removeNode(entry.v);

  return results;
}

function buildState(g, weightFn) {
  var fasGraph = new Graph();
  var maxIn = 0;
  var maxOut = 0;

  _.forEach(g.nodes(), function(v) {
    fasGraph.setNode(v, { v: v, "in": 0, out: 0 });
  });

  // Aggregate weights on nodes, but also sum the weights across multi-edges
  // into a single edge for the fasGraph.
  _.forEach(g.edges(), function(e) {
    var prevWeight = fasGraph.edge(e.v, e.w) || 0;
    var weight = weightFn(e);
    var edgeWeight = prevWeight + weight;
    fasGraph.setEdge(e.v, e.w, edgeWeight);
    maxOut = Math.max(maxOut, fasGraph.node(e.v).out += weight);
    maxIn  = Math.max(maxIn,  fasGraph.node(e.w)["in"]  += weight);
  });

  var buckets = _.range(maxOut + maxIn + 3).map(function() { return new List(); });
  var zeroIdx = maxIn + 1;

  _.forEach(fasGraph.nodes(), function(v) {
    assignBucket(buckets, zeroIdx, fasGraph.node(v));
  });

  return { graph: fasGraph, buckets: buckets, zeroIdx: zeroIdx };
}

function assignBucket(buckets, zeroIdx, entry) {
  if (!entry.out) {
    buckets[0].enqueue(entry);
  } else if (!entry["in"]) {
    buckets[buckets.length - 1].enqueue(entry);
  } else {
    buckets[entry.out - entry["in"] + zeroIdx].enqueue(entry);
  }
}


/***/ }),

/***/ "./node_modules/dagre/lib/layout.js":
/*!******************************************!*\
  !*** ./node_modules/dagre/lib/layout.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var acyclic = __webpack_require__(/*! ./acyclic */ "./node_modules/dagre/lib/acyclic.js");
var normalize = __webpack_require__(/*! ./normalize */ "./node_modules/dagre/lib/normalize.js");
var rank = __webpack_require__(/*! ./rank */ "./node_modules/dagre/lib/rank/index.js");
var normalizeRanks = (__webpack_require__(/*! ./util */ "./node_modules/dagre/lib/util.js").normalizeRanks);
var parentDummyChains = __webpack_require__(/*! ./parent-dummy-chains */ "./node_modules/dagre/lib/parent-dummy-chains.js");
var removeEmptyRanks = (__webpack_require__(/*! ./util */ "./node_modules/dagre/lib/util.js").removeEmptyRanks);
var nestingGraph = __webpack_require__(/*! ./nesting-graph */ "./node_modules/dagre/lib/nesting-graph.js");
var addBorderSegments = __webpack_require__(/*! ./add-border-segments */ "./node_modules/dagre/lib/add-border-segments.js");
var coordinateSystem = __webpack_require__(/*! ./coordinate-system */ "./node_modules/dagre/lib/coordinate-system.js");
var order = __webpack_require__(/*! ./order */ "./node_modules/dagre/lib/order/index.js");
var position = __webpack_require__(/*! ./position */ "./node_modules/dagre/lib/position/index.js");
var util = __webpack_require__(/*! ./util */ "./node_modules/dagre/lib/util.js");
var Graph = (__webpack_require__(/*! ./graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);

module.exports = layout;

function layout(g, opts) {
  var time = opts && opts.debugTiming ? util.time : util.notime;
  time("layout", function() {
    var layoutGraph = 
      time("  buildLayoutGraph", function() { return buildLayoutGraph(g); });
    time("  runLayout",        function() { runLayout(layoutGraph, time); });
    time("  updateInputGraph", function() { updateInputGraph(g, layoutGraph); });
  });
}

function runLayout(g, time) {
  time("    makeSpaceForEdgeLabels", function() { makeSpaceForEdgeLabels(g); });
  time("    removeSelfEdges",        function() { removeSelfEdges(g); });
  time("    acyclic",                function() { acyclic.run(g); });
  time("    nestingGraph.run",       function() { nestingGraph.run(g); });
  time("    rank",                   function() { rank(util.asNonCompoundGraph(g)); });
  time("    injectEdgeLabelProxies", function() { injectEdgeLabelProxies(g); });
  time("    removeEmptyRanks",       function() { removeEmptyRanks(g); });
  time("    nestingGraph.cleanup",   function() { nestingGraph.cleanup(g); });
  time("    normalizeRanks",         function() { normalizeRanks(g); });
  time("    assignRankMinMax",       function() { assignRankMinMax(g); });
  time("    removeEdgeLabelProxies", function() { removeEdgeLabelProxies(g); });
  time("    normalize.run",          function() { normalize.run(g); });
  time("    parentDummyChains",      function() { parentDummyChains(g); });
  time("    addBorderSegments",      function() { addBorderSegments(g); });
  time("    order",                  function() { order(g); });
  time("    insertSelfEdges",        function() { insertSelfEdges(g); });
  time("    adjustCoordinateSystem", function() { coordinateSystem.adjust(g); });
  time("    position",               function() { position(g); });
  time("    positionSelfEdges",      function() { positionSelfEdges(g); });
  time("    removeBorderNodes",      function() { removeBorderNodes(g); });
  time("    normalize.undo",         function() { normalize.undo(g); });
  time("    fixupEdgeLabelCoords",   function() { fixupEdgeLabelCoords(g); });
  time("    undoCoordinateSystem",   function() { coordinateSystem.undo(g); });
  time("    translateGraph",         function() { translateGraph(g); });
  time("    assignNodeIntersects",   function() { assignNodeIntersects(g); });
  time("    reversePoints",          function() { reversePointsForReversedEdges(g); });
  time("    acyclic.undo",           function() { acyclic.undo(g); });
}

/*
 * Copies final layout information from the layout graph back to the input
 * graph. This process only copies whitelisted attributes from the layout graph
 * to the input graph, so it serves as a good place to determine what
 * attributes can influence layout.
 */
function updateInputGraph(inputGraph, layoutGraph) {
  _.forEach(inputGraph.nodes(), function(v) {
    var inputLabel = inputGraph.node(v);
    var layoutLabel = layoutGraph.node(v);

    if (inputLabel) {
      inputLabel.x = layoutLabel.x;
      inputLabel.y = layoutLabel.y;

      if (layoutGraph.children(v).length) {
        inputLabel.width = layoutLabel.width;
        inputLabel.height = layoutLabel.height;
      }
    }
  });

  _.forEach(inputGraph.edges(), function(e) {
    var inputLabel = inputGraph.edge(e);
    var layoutLabel = layoutGraph.edge(e);

    inputLabel.points = layoutLabel.points;
    if (_.has(layoutLabel, "x")) {
      inputLabel.x = layoutLabel.x;
      inputLabel.y = layoutLabel.y;
    }
  });

  inputGraph.graph().width = layoutGraph.graph().width;
  inputGraph.graph().height = layoutGraph.graph().height;
}

var graphNumAttrs = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"];
var graphDefaults = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb" };
var graphAttrs = ["acyclicer", "ranker", "rankdir", "align"];
var nodeNumAttrs = ["width", "height"];
var nodeDefaults = { width: 0, height: 0 };
var edgeNumAttrs = ["minlen", "weight", "width", "height", "labeloffset"];
var edgeDefaults = {
  minlen: 1, weight: 1, width: 0, height: 0,
  labeloffset: 10, labelpos: "r"
};
var edgeAttrs = ["labelpos"];

/*
 * Constructs a new graph from the input graph, which can be used for layout.
 * This process copies only whitelisted attributes from the input graph to the
 * layout graph. Thus this function serves as a good place to determine what
 * attributes can influence layout.
 */
function buildLayoutGraph(inputGraph) {
  var g = new Graph({ multigraph: true, compound: true });
  var graph = canonicalize(inputGraph.graph());

  g.setGraph(_.merge({},
    graphDefaults,
    selectNumberAttrs(graph, graphNumAttrs),
    _.pick(graph, graphAttrs)));

  _.forEach(inputGraph.nodes(), function(v) {
    var node = canonicalize(inputGraph.node(v));
    g.setNode(v, _.defaults(selectNumberAttrs(node, nodeNumAttrs), nodeDefaults));
    g.setParent(v, inputGraph.parent(v));
  });

  _.forEach(inputGraph.edges(), function(e) {
    var edge = canonicalize(inputGraph.edge(e));
    g.setEdge(e, _.merge({},
      edgeDefaults,
      selectNumberAttrs(edge, edgeNumAttrs),
      _.pick(edge, edgeAttrs)));
  });

  return g;
}

/*
 * This idea comes from the Gansner paper: to account for edge labels in our
 * layout we split each rank in half by doubling minlen and halving ranksep.
 * Then we can place labels at these mid-points between nodes.
 *
 * We also add some minimal padding to the width to push the label for the edge
 * away from the edge itself a bit.
 */
function makeSpaceForEdgeLabels(g) {
  var graph = g.graph();
  graph.ranksep /= 2;
  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    edge.minlen *= 2;
    if (edge.labelpos.toLowerCase() !== "c") {
      if (graph.rankdir === "TB" || graph.rankdir === "BT") {
        edge.width += edge.labeloffset;
      } else {
        edge.height += edge.labeloffset;
      }
    }
  });
}

/*
 * Creates temporary dummy nodes that capture the rank in which each edge's
 * label is going to, if it has one of non-zero width and height. We do this
 * so that we can safely remove empty ranks while preserving balance for the
 * label's position.
 */
function injectEdgeLabelProxies(g) {
  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    if (edge.width && edge.height) {
      var v = g.node(e.v);
      var w = g.node(e.w);
      var label = { rank: (w.rank - v.rank) / 2 + v.rank, e: e };
      util.addDummyNode(g, "edge-proxy", label, "_ep");
    }
  });
}

function assignRankMinMax(g) {
  var maxRank = 0;
  _.forEach(g.nodes(), function(v) {
    var node = g.node(v);
    if (node.borderTop) {
      node.minRank = g.node(node.borderTop).rank;
      node.maxRank = g.node(node.borderBottom).rank;
      maxRank = _.max(maxRank, node.maxRank);
    }
  });
  g.graph().maxRank = maxRank;
}

function removeEdgeLabelProxies(g) {
  _.forEach(g.nodes(), function(v) {
    var node = g.node(v);
    if (node.dummy === "edge-proxy") {
      g.edge(node.e).labelRank = node.rank;
      g.removeNode(v);
    }
  });
}

function translateGraph(g) {
  var minX = Number.POSITIVE_INFINITY;
  var maxX = 0;
  var minY = Number.POSITIVE_INFINITY;
  var maxY = 0;
  var graphLabel = g.graph();
  var marginX = graphLabel.marginx || 0;
  var marginY = graphLabel.marginy || 0;

  function getExtremes(attrs) {
    var x = attrs.x;
    var y = attrs.y;
    var w = attrs.width;
    var h = attrs.height;
    minX = Math.min(minX, x - w / 2);
    maxX = Math.max(maxX, x + w / 2);
    minY = Math.min(minY, y - h / 2);
    maxY = Math.max(maxY, y + h / 2);
  }

  _.forEach(g.nodes(), function(v) { getExtremes(g.node(v)); });
  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    if (_.has(edge, "x")) {
      getExtremes(edge);
    }
  });

  minX -= marginX;
  minY -= marginY;

  _.forEach(g.nodes(), function(v) {
    var node = g.node(v);
    node.x -= minX;
    node.y -= minY;
  });

  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    _.forEach(edge.points, function(p) {
      p.x -= minX;
      p.y -= minY;
    });
    if (_.has(edge, "x")) { edge.x -= minX; }
    if (_.has(edge, "y")) { edge.y -= minY; }
  });

  graphLabel.width = maxX - minX + marginX;
  graphLabel.height = maxY - minY + marginY;
}

function assignNodeIntersects(g) {
  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    var nodeV = g.node(e.v);
    var nodeW = g.node(e.w);
    var p1, p2;
    if (!edge.points) {
      edge.points = [];
      p1 = nodeW;
      p2 = nodeV;
    } else {
      p1 = edge.points[0];
      p2 = edge.points[edge.points.length - 1];
    }
    edge.points.unshift(util.intersectRect(nodeV, p1));
    edge.points.push(util.intersectRect(nodeW, p2));
  });
}

function fixupEdgeLabelCoords(g) {
  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    if (_.has(edge, "x")) {
      if (edge.labelpos === "l" || edge.labelpos === "r") {
        edge.width -= edge.labeloffset;
      }
      switch (edge.labelpos) {
      case "l": edge.x -= edge.width / 2 + edge.labeloffset; break;
      case "r": edge.x += edge.width / 2 + edge.labeloffset; break;
      }
    }
  });
}

function reversePointsForReversedEdges(g) {
  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    if (edge.reversed) {
      edge.points.reverse();
    }
  });
}

function removeBorderNodes(g) {
  _.forEach(g.nodes(), function(v) {
    if (g.children(v).length) {
      var node = g.node(v);
      var t = g.node(node.borderTop);
      var b = g.node(node.borderBottom);
      var l = g.node(_.last(node.borderLeft));
      var r = g.node(_.last(node.borderRight));

      node.width = Math.abs(r.x - l.x);
      node.height = Math.abs(b.y - t.y);
      node.x = l.x + node.width / 2;
      node.y = t.y + node.height / 2;
    }
  });

  _.forEach(g.nodes(), function(v) {
    if (g.node(v).dummy === "border") {
      g.removeNode(v);
    }
  });
}

function removeSelfEdges(g) {
  _.forEach(g.edges(), function(e) {
    if (e.v === e.w) {
      var node = g.node(e.v);
      if (!node.selfEdges) {
        node.selfEdges = [];
      }
      node.selfEdges.push({ e: e, label: g.edge(e) });
      g.removeEdge(e);
    }
  });
}

function insertSelfEdges(g) {
  var layers = util.buildLayerMatrix(g);
  _.forEach(layers, function(layer) {
    var orderShift = 0;
    _.forEach(layer, function(v, i) {
      var node = g.node(v);
      node.order = i + orderShift;
      _.forEach(node.selfEdges, function(selfEdge) {
        util.addDummyNode(g, "selfedge", {
          width: selfEdge.label.width,
          height: selfEdge.label.height,
          rank: node.rank,
          order: i + (++orderShift),
          e: selfEdge.e,
          label: selfEdge.label
        }, "_se");
      });
      delete node.selfEdges;
    });
  });
}

function positionSelfEdges(g) {
  _.forEach(g.nodes(), function(v) {
    var node = g.node(v);
    if (node.dummy === "selfedge") {
      var selfNode = g.node(node.e.v);
      var x = selfNode.x + selfNode.width / 2;
      var y = selfNode.y;
      var dx = node.x - x;
      var dy = selfNode.height / 2;
      g.setEdge(node.e, node.label);
      g.removeNode(v);
      node.label.points = [
        { x: x + 2 * dx / 3, y: y - dy },
        { x: x + 5 * dx / 6, y: y - dy },
        { x: x +     dx    , y: y },
        { x: x + 5 * dx / 6, y: y + dy },
        { x: x + 2 * dx / 3, y: y + dy }
      ];
      node.label.x = node.x;
      node.label.y = node.y;
    }
  });
}

function selectNumberAttrs(obj, attrs) {
  return _.mapValues(_.pick(obj, attrs), Number);
}

function canonicalize(attrs) {
  var newAttrs = {};
  _.forEach(attrs, function(v, k) {
    newAttrs[k.toLowerCase()] = v;
  });
  return newAttrs;
}


/***/ }),

/***/ "./node_modules/dagre/lib/lodash.js":
/*!******************************************!*\
  !*** ./node_modules/dagre/lib/lodash.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/* global window */

var lodash;

if (true) {
  try {
    lodash = {
      cloneDeep: __webpack_require__(/*! lodash/cloneDeep */ "./node_modules/lodash/cloneDeep.js"),
      constant: __webpack_require__(/*! lodash/constant */ "./node_modules/lodash/constant.js"),
      defaults: __webpack_require__(/*! lodash/defaults */ "./node_modules/lodash/defaults.js"),
      each: __webpack_require__(/*! lodash/each */ "./node_modules/lodash/each.js"),
      filter: __webpack_require__(/*! lodash/filter */ "./node_modules/lodash/filter.js"),
      find: __webpack_require__(/*! lodash/find */ "./node_modules/lodash/find.js"),
      flatten: __webpack_require__(/*! lodash/flatten */ "./node_modules/lodash/flatten.js"),
      forEach: __webpack_require__(/*! lodash/forEach */ "./node_modules/lodash/forEach.js"),
      forIn: __webpack_require__(/*! lodash/forIn */ "./node_modules/lodash/forIn.js"),
      has:  __webpack_require__(/*! lodash/has */ "./node_modules/lodash/has.js"),
      isUndefined: __webpack_require__(/*! lodash/isUndefined */ "./node_modules/lodash/isUndefined.js"),
      last: __webpack_require__(/*! lodash/last */ "./node_modules/lodash/last.js"),
      map: __webpack_require__(/*! lodash/map */ "./node_modules/lodash/map.js"),
      mapValues: __webpack_require__(/*! lodash/mapValues */ "./node_modules/lodash/mapValues.js"),
      max: __webpack_require__(/*! lodash/max */ "./node_modules/lodash/max.js"),
      merge: __webpack_require__(/*! lodash/merge */ "./node_modules/lodash/merge.js"),
      min: __webpack_require__(/*! lodash/min */ "./node_modules/lodash/min.js"),
      minBy: __webpack_require__(/*! lodash/minBy */ "./node_modules/lodash/minBy.js"),
      now: __webpack_require__(/*! lodash/now */ "./node_modules/lodash/now.js"),
      pick: __webpack_require__(/*! lodash/pick */ "./node_modules/lodash/pick.js"),
      range: __webpack_require__(/*! lodash/range */ "./node_modules/lodash/range.js"),
      reduce: __webpack_require__(/*! lodash/reduce */ "./node_modules/lodash/reduce.js"),
      sortBy: __webpack_require__(/*! lodash/sortBy */ "./node_modules/lodash/sortBy.js"),
      uniqueId: __webpack_require__(/*! lodash/uniqueId */ "./node_modules/lodash/uniqueId.js"),
      values: __webpack_require__(/*! lodash/values */ "./node_modules/lodash/values.js"),
      zipObject: __webpack_require__(/*! lodash/zipObject */ "./node_modules/lodash/zipObject.js"),
    };
  } catch (e) {
    // continue regardless of error
  }
}

if (!lodash) {
  lodash = window._;
}

module.exports = lodash;


/***/ }),

/***/ "./node_modules/dagre/lib/nesting-graph.js":
/*!*************************************************!*\
  !*** ./node_modules/dagre/lib/nesting-graph.js ***!
  \*************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var util = __webpack_require__(/*! ./util */ "./node_modules/dagre/lib/util.js");

module.exports = {
  run: run,
  cleanup: cleanup
};

/*
 * A nesting graph creates dummy nodes for the tops and bottoms of subgraphs,
 * adds appropriate edges to ensure that all cluster nodes are placed between
 * these boundries, and ensures that the graph is connected.
 *
 * In addition we ensure, through the use of the minlen property, that nodes
 * and subgraph border nodes to not end up on the same rank.
 *
 * Preconditions:
 *
 *    1. Input graph is a DAG
 *    2. Nodes in the input graph has a minlen attribute
 *
 * Postconditions:
 *
 *    1. Input graph is connected.
 *    2. Dummy nodes are added for the tops and bottoms of subgraphs.
 *    3. The minlen attribute for nodes is adjusted to ensure nodes do not
 *       get placed on the same rank as subgraph border nodes.
 *
 * The nesting graph idea comes from Sander, "Layout of Compound Directed
 * Graphs."
 */
function run(g) {
  var root = util.addDummyNode(g, "root", {}, "_root");
  var depths = treeDepths(g);
  var height = _.max(_.values(depths)) - 1; // Note: depths is an Object not an array
  var nodeSep = 2 * height + 1;

  g.graph().nestingRoot = root;

  // Multiply minlen by nodeSep to align nodes on non-border ranks.
  _.forEach(g.edges(), function(e) { g.edge(e).minlen *= nodeSep; });

  // Calculate a weight that is sufficient to keep subgraphs vertically compact
  var weight = sumWeights(g) + 1;

  // Create border nodes and link them up
  _.forEach(g.children(), function(child) {
    dfs(g, root, nodeSep, weight, height, depths, child);
  });

  // Save the multiplier for node layers for later removal of empty border
  // layers.
  g.graph().nodeRankFactor = nodeSep;
}

function dfs(g, root, nodeSep, weight, height, depths, v) {
  var children = g.children(v);
  if (!children.length) {
    if (v !== root) {
      g.setEdge(root, v, { weight: 0, minlen: nodeSep });
    }
    return;
  }

  var top = util.addBorderNode(g, "_bt");
  var bottom = util.addBorderNode(g, "_bb");
  var label = g.node(v);

  g.setParent(top, v);
  label.borderTop = top;
  g.setParent(bottom, v);
  label.borderBottom = bottom;

  _.forEach(children, function(child) {
    dfs(g, root, nodeSep, weight, height, depths, child);

    var childNode = g.node(child);
    var childTop = childNode.borderTop ? childNode.borderTop : child;
    var childBottom = childNode.borderBottom ? childNode.borderBottom : child;
    var thisWeight = childNode.borderTop ? weight : 2 * weight;
    var minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;

    g.setEdge(top, childTop, {
      weight: thisWeight,
      minlen: minlen,
      nestingEdge: true
    });

    g.setEdge(childBottom, bottom, {
      weight: thisWeight,
      minlen: minlen,
      nestingEdge: true
    });
  });

  if (!g.parent(v)) {
    g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
  }
}

function treeDepths(g) {
  var depths = {};
  function dfs(v, depth) {
    var children = g.children(v);
    if (children && children.length) {
      _.forEach(children, function(child) {
        dfs(child, depth + 1);
      });
    }
    depths[v] = depth;
  }
  _.forEach(g.children(), function(v) { dfs(v, 1); });
  return depths;
}

function sumWeights(g) {
  return _.reduce(g.edges(), function(acc, e) {
    return acc + g.edge(e).weight;
  }, 0);
}

function cleanup(g) {
  var graphLabel = g.graph();
  g.removeNode(graphLabel.nestingRoot);
  delete graphLabel.nestingRoot;
  _.forEach(g.edges(), function(e) {
    var edge = g.edge(e);
    if (edge.nestingEdge) {
      g.removeEdge(e);
    }
  });
}


/***/ }),

/***/ "./node_modules/dagre/lib/normalize.js":
/*!*********************************************!*\
  !*** ./node_modules/dagre/lib/normalize.js ***!
  \*********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var util = __webpack_require__(/*! ./util */ "./node_modules/dagre/lib/util.js");

module.exports = {
  run: run,
  undo: undo
};

/*
 * Breaks any long edges in the graph into short segments that span 1 layer
 * each. This operation is undoable with the denormalize function.
 *
 * Pre-conditions:
 *
 *    1. The input graph is a DAG.
 *    2. Each node in the graph has a "rank" property.
 *
 * Post-condition:
 *
 *    1. All edges in the graph have a length of 1.
 *    2. Dummy nodes are added where edges have been split into segments.
 *    3. The graph is augmented with a "dummyChains" attribute which contains
 *       the first dummy in each chain of dummy nodes produced.
 */
function run(g) {
  g.graph().dummyChains = [];
  _.forEach(g.edges(), function(edge) { normalizeEdge(g, edge); });
}

function normalizeEdge(g, e) {
  var v = e.v;
  var vRank = g.node(v).rank;
  var w = e.w;
  var wRank = g.node(w).rank;
  var name = e.name;
  var edgeLabel = g.edge(e);
  var labelRank = edgeLabel.labelRank;

  if (wRank === vRank + 1) return;

  g.removeEdge(e);

  var dummy, attrs, i;
  for (i = 0, ++vRank; vRank < wRank; ++i, ++vRank) {
    edgeLabel.points = [];
    attrs = {
      width: 0, height: 0,
      edgeLabel: edgeLabel, edgeObj: e,
      rank: vRank
    };
    dummy = util.addDummyNode(g, "edge", attrs, "_d");
    if (vRank === labelRank) {
      attrs.width = edgeLabel.width;
      attrs.height = edgeLabel.height;
      attrs.dummy = "edge-label";
      attrs.labelpos = edgeLabel.labelpos;
    }
    g.setEdge(v, dummy, { weight: edgeLabel.weight }, name);
    if (i === 0) {
      g.graph().dummyChains.push(dummy);
    }
    v = dummy;
  }

  g.setEdge(v, w, { weight: edgeLabel.weight }, name);
}

function undo(g) {
  _.forEach(g.graph().dummyChains, function(v) {
    var node = g.node(v);
    var origLabel = node.edgeLabel;
    var w;
    g.setEdge(node.edgeObj, origLabel);
    while (node.dummy) {
      w = g.successors(v)[0];
      g.removeNode(v);
      origLabel.points.push({ x: node.x, y: node.y });
      if (node.dummy === "edge-label") {
        origLabel.x = node.x;
        origLabel.y = node.y;
        origLabel.width = node.width;
        origLabel.height = node.height;
      }
      v = w;
      node = g.node(v);
    }
  });
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/add-subgraph-constraints.js":
/*!******************************************************************!*\
  !*** ./node_modules/dagre/lib/order/add-subgraph-constraints.js ***!
  \******************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = addSubgraphConstraints;

function addSubgraphConstraints(g, cg, vs) {
  var prev = {},
    rootPrev;

  _.forEach(vs, function(v) {
    var child = g.parent(v),
      parent,
      prevChild;
    while (child) {
      parent = g.parent(child);
      if (parent) {
        prevChild = prev[parent];
        prev[parent] = child;
      } else {
        prevChild = rootPrev;
        rootPrev = child;
      }
      if (prevChild && prevChild !== child) {
        cg.setEdge(prevChild, child);
        return;
      }
      child = parent;
    }
  });

  /*
  function dfs(v) {
    var children = v ? g.children(v) : g.children();
    if (children.length) {
      var min = Number.POSITIVE_INFINITY,
          subgraphs = [];
      _.each(children, function(child) {
        var childMin = dfs(child);
        if (g.children(child).length) {
          subgraphs.push({ v: child, order: childMin });
        }
        min = Math.min(min, childMin);
      });
      _.reduce(_.sortBy(subgraphs, "order"), function(prev, curr) {
        cg.setEdge(prev.v, curr.v);
        return curr;
      });
      return min;
    }
    return g.node(v).order;
  }
  dfs(undefined);
  */
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/barycenter.js":
/*!****************************************************!*\
  !*** ./node_modules/dagre/lib/order/barycenter.js ***!
  \****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = barycenter;

function barycenter(g, movable) {
  return _.map(movable, function(v) {
    var inV = g.inEdges(v);
    if (!inV.length) {
      return { v: v };
    } else {
      var result = _.reduce(inV, function(acc, e) {
        var edge = g.edge(e),
          nodeU = g.node(e.v);
        return {
          sum: acc.sum + (edge.weight * nodeU.order),
          weight: acc.weight + edge.weight
        };
      }, { sum: 0, weight: 0 });

      return {
        v: v,
        barycenter: result.sum / result.weight,
        weight: result.weight
      };
    }
  });
}



/***/ }),

/***/ "./node_modules/dagre/lib/order/build-layer-graph.js":
/*!***********************************************************!*\
  !*** ./node_modules/dagre/lib/order/build-layer-graph.js ***!
  \***********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var Graph = (__webpack_require__(/*! ../graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);

module.exports = buildLayerGraph;

/*
 * Constructs a graph that can be used to sort a layer of nodes. The graph will
 * contain all base and subgraph nodes from the request layer in their original
 * hierarchy and any edges that are incident on these nodes and are of the type
 * requested by the "relationship" parameter.
 *
 * Nodes from the requested rank that do not have parents are assigned a root
 * node in the output graph, which is set in the root graph attribute. This
 * makes it easy to walk the hierarchy of movable nodes during ordering.
 *
 * Pre-conditions:
 *
 *    1. Input graph is a DAG
 *    2. Base nodes in the input graph have a rank attribute
 *    3. Subgraph nodes in the input graph has minRank and maxRank attributes
 *    4. Edges have an assigned weight
 *
 * Post-conditions:
 *
 *    1. Output graph has all nodes in the movable rank with preserved
 *       hierarchy.
 *    2. Root nodes in the movable layer are made children of the node
 *       indicated by the root attribute of the graph.
 *    3. Non-movable nodes incident on movable nodes, selected by the
 *       relationship parameter, are included in the graph (without hierarchy).
 *    4. Edges incident on movable nodes, selected by the relationship
 *       parameter, are added to the output graph.
 *    5. The weights for copied edges are aggregated as need, since the output
 *       graph is not a multi-graph.
 */
function buildLayerGraph(g, rank, relationship) {
  var root = createRootNode(g),
    result = new Graph({ compound: true }).setGraph({ root: root })
      .setDefaultNodeLabel(function(v) { return g.node(v); });

  _.forEach(g.nodes(), function(v) {
    var node = g.node(v),
      parent = g.parent(v);

    if (node.rank === rank || node.minRank <= rank && rank <= node.maxRank) {
      result.setNode(v);
      result.setParent(v, parent || root);

      // This assumes we have only short edges!
      _.forEach(g[relationship](v), function(e) {
        var u = e.v === v ? e.w : e.v,
          edge = result.edge(u, v),
          weight = !_.isUndefined(edge) ? edge.weight : 0;
        result.setEdge(u, v, { weight: g.edge(e).weight + weight });
      });

      if (_.has(node, "minRank")) {
        result.setNode(v, {
          borderLeft: node.borderLeft[rank],
          borderRight: node.borderRight[rank]
        });
      }
    }
  });

  return result;
}

function createRootNode(g) {
  var v;
  while (g.hasNode((v = _.uniqueId("_root"))));
  return v;
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/cross-count.js":
/*!*****************************************************!*\
  !*** ./node_modules/dagre/lib/order/cross-count.js ***!
  \*****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = crossCount;

/*
 * A function that takes a layering (an array of layers, each with an array of
 * ordererd nodes) and a graph and returns a weighted crossing count.
 *
 * Pre-conditions:
 *
 *    1. Input graph must be simple (not a multigraph), directed, and include
 *       only simple edges.
 *    2. Edges in the input graph must have assigned weights.
 *
 * Post-conditions:
 *
 *    1. The graph and layering matrix are left unchanged.
 *
 * This algorithm is derived from Barth, et al., "Bilayer Cross Counting."
 */
function crossCount(g, layering) {
  var cc = 0;
  for (var i = 1; i < layering.length; ++i) {
    cc += twoLayerCrossCount(g, layering[i-1], layering[i]);
  }
  return cc;
}

function twoLayerCrossCount(g, northLayer, southLayer) {
  // Sort all of the edges between the north and south layers by their position
  // in the north layer and then the south. Map these edges to the position of
  // their head in the south layer.
  var southPos = _.zipObject(southLayer,
    _.map(southLayer, function (v, i) { return i; }));
  var southEntries = _.flatten(_.map(northLayer, function(v) {
    return _.sortBy(_.map(g.outEdges(v), function(e) {
      return { pos: southPos[e.w], weight: g.edge(e).weight };
    }), "pos");
  }), true);

  // Build the accumulator tree
  var firstIndex = 1;
  while (firstIndex < southLayer.length) firstIndex <<= 1;
  var treeSize = 2 * firstIndex - 1;
  firstIndex -= 1;
  var tree = _.map(new Array(treeSize), function() { return 0; });

  // Calculate the weighted crossings
  var cc = 0;
  _.forEach(southEntries.forEach(function(entry) {
    var index = entry.pos + firstIndex;
    tree[index] += entry.weight;
    var weightSum = 0;
    while (index > 0) {
      if (index % 2) {
        weightSum += tree[index + 1];
      }
      index = (index - 1) >> 1;
      tree[index] += entry.weight;
    }
    cc += entry.weight * weightSum;
  }));

  return cc;
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/index.js":
/*!***********************************************!*\
  !*** ./node_modules/dagre/lib/order/index.js ***!
  \***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var initOrder = __webpack_require__(/*! ./init-order */ "./node_modules/dagre/lib/order/init-order.js");
var crossCount = __webpack_require__(/*! ./cross-count */ "./node_modules/dagre/lib/order/cross-count.js");
var sortSubgraph = __webpack_require__(/*! ./sort-subgraph */ "./node_modules/dagre/lib/order/sort-subgraph.js");
var buildLayerGraph = __webpack_require__(/*! ./build-layer-graph */ "./node_modules/dagre/lib/order/build-layer-graph.js");
var addSubgraphConstraints = __webpack_require__(/*! ./add-subgraph-constraints */ "./node_modules/dagre/lib/order/add-subgraph-constraints.js");
var Graph = (__webpack_require__(/*! ../graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);
var util = __webpack_require__(/*! ../util */ "./node_modules/dagre/lib/util.js");

module.exports = order;

/*
 * Applies heuristics to minimize edge crossings in the graph and sets the best
 * order solution as an order attribute on each node.
 *
 * Pre-conditions:
 *
 *    1. Graph must be DAG
 *    2. Graph nodes must be objects with a "rank" attribute
 *    3. Graph edges must have the "weight" attribute
 *
 * Post-conditions:
 *
 *    1. Graph nodes will have an "order" attribute based on the results of the
 *       algorithm.
 */
function order(g) {
  var maxRank = util.maxRank(g),
    downLayerGraphs = buildLayerGraphs(g, _.range(1, maxRank + 1), "inEdges"),
    upLayerGraphs = buildLayerGraphs(g, _.range(maxRank - 1, -1, -1), "outEdges");

  var layering = initOrder(g);
  assignOrder(g, layering);

  var bestCC = Number.POSITIVE_INFINITY,
    best;

  for (var i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
    sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);

    layering = util.buildLayerMatrix(g);
    var cc = crossCount(g, layering);
    if (cc < bestCC) {
      lastBest = 0;
      best = _.cloneDeep(layering);
      bestCC = cc;
    }
  }

  assignOrder(g, best);
}

function buildLayerGraphs(g, ranks, relationship) {
  return _.map(ranks, function(rank) {
    return buildLayerGraph(g, rank, relationship);
  });
}

function sweepLayerGraphs(layerGraphs, biasRight) {
  var cg = new Graph();
  _.forEach(layerGraphs, function(lg) {
    var root = lg.graph().root;
    var sorted = sortSubgraph(lg, root, cg, biasRight);
    _.forEach(sorted.vs, function(v, i) {
      lg.node(v).order = i;
    });
    addSubgraphConstraints(lg, cg, sorted.vs);
  });
}

function assignOrder(g, layering) {
  _.forEach(layering, function(layer) {
    _.forEach(layer, function(v, i) {
      g.node(v).order = i;
    });
  });
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/init-order.js":
/*!****************************************************!*\
  !*** ./node_modules/dagre/lib/order/init-order.js ***!
  \****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = initOrder;

/*
 * Assigns an initial order value for each node by performing a DFS search
 * starting from nodes in the first rank. Nodes are assigned an order in their
 * rank as they are first visited.
 *
 * This approach comes from Gansner, et al., "A Technique for Drawing Directed
 * Graphs."
 *
 * Returns a layering matrix with an array per layer and each layer sorted by
 * the order of its nodes.
 */
function initOrder(g) {
  var visited = {};
  var simpleNodes = _.filter(g.nodes(), function(v) {
    return !g.children(v).length;
  });
  var maxRank = _.max(_.map(simpleNodes, function(v) { return g.node(v).rank; }));
  var layers = _.map(_.range(maxRank + 1), function() { return []; });

  function dfs(v) {
    if (_.has(visited, v)) return;
    visited[v] = true;
    var node = g.node(v);
    layers[node.rank].push(v);
    _.forEach(g.successors(v), dfs);
  }

  var orderedVs = _.sortBy(simpleNodes, function(v) { return g.node(v).rank; });
  _.forEach(orderedVs, dfs);

  return layers;
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/resolve-conflicts.js":
/*!***********************************************************!*\
  !*** ./node_modules/dagre/lib/order/resolve-conflicts.js ***!
  \***********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = resolveConflicts;

/*
 * Given a list of entries of the form {v, barycenter, weight} and a
 * constraint graph this function will resolve any conflicts between the
 * constraint graph and the barycenters for the entries. If the barycenters for
 * an entry would violate a constraint in the constraint graph then we coalesce
 * the nodes in the conflict into a new node that respects the contraint and
 * aggregates barycenter and weight information.
 *
 * This implementation is based on the description in Forster, "A Fast and
 * Simple Hueristic for Constrained Two-Level Crossing Reduction," thought it
 * differs in some specific details.
 *
 * Pre-conditions:
 *
 *    1. Each entry has the form {v, barycenter, weight}, or if the node has
 *       no barycenter, then {v}.
 *
 * Returns:
 *
 *    A new list of entries of the form {vs, i, barycenter, weight}. The list
 *    `vs` may either be a singleton or it may be an aggregation of nodes
 *    ordered such that they do not violate constraints from the constraint
 *    graph. The property `i` is the lowest original index of any of the
 *    elements in `vs`.
 */
function resolveConflicts(entries, cg) {
  var mappedEntries = {};
  _.forEach(entries, function(entry, i) {
    var tmp = mappedEntries[entry.v] = {
      indegree: 0,
      "in": [],
      out: [],
      vs: [entry.v],
      i: i
    };
    if (!_.isUndefined(entry.barycenter)) {
      tmp.barycenter = entry.barycenter;
      tmp.weight = entry.weight;
    }
  });

  _.forEach(cg.edges(), function(e) {
    var entryV = mappedEntries[e.v];
    var entryW = mappedEntries[e.w];
    if (!_.isUndefined(entryV) && !_.isUndefined(entryW)) {
      entryW.indegree++;
      entryV.out.push(mappedEntries[e.w]);
    }
  });

  var sourceSet = _.filter(mappedEntries, function(entry) {
    return !entry.indegree;
  });

  return doResolveConflicts(sourceSet);
}

function doResolveConflicts(sourceSet) {
  var entries = [];

  function handleIn(vEntry) {
    return function(uEntry) {
      if (uEntry.merged) {
        return;
      }
      if (_.isUndefined(uEntry.barycenter) ||
          _.isUndefined(vEntry.barycenter) ||
          uEntry.barycenter >= vEntry.barycenter) {
        mergeEntries(vEntry, uEntry);
      }
    };
  }

  function handleOut(vEntry) {
    return function(wEntry) {
      wEntry["in"].push(vEntry);
      if (--wEntry.indegree === 0) {
        sourceSet.push(wEntry);
      }
    };
  }

  while (sourceSet.length) {
    var entry = sourceSet.pop();
    entries.push(entry);
    _.forEach(entry["in"].reverse(), handleIn(entry));
    _.forEach(entry.out, handleOut(entry));
  }

  return _.map(_.filter(entries, function(entry) { return !entry.merged; }),
    function(entry) {
      return _.pick(entry, ["vs", "i", "barycenter", "weight"]);
    });

}

function mergeEntries(target, source) {
  var sum = 0;
  var weight = 0;

  if (target.weight) {
    sum += target.barycenter * target.weight;
    weight += target.weight;
  }

  if (source.weight) {
    sum += source.barycenter * source.weight;
    weight += source.weight;
  }

  target.vs = source.vs.concat(target.vs);
  target.barycenter = sum / weight;
  target.weight = weight;
  target.i = Math.min(source.i, target.i);
  source.merged = true;
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/sort-subgraph.js":
/*!*******************************************************!*\
  !*** ./node_modules/dagre/lib/order/sort-subgraph.js ***!
  \*******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var barycenter = __webpack_require__(/*! ./barycenter */ "./node_modules/dagre/lib/order/barycenter.js");
var resolveConflicts = __webpack_require__(/*! ./resolve-conflicts */ "./node_modules/dagre/lib/order/resolve-conflicts.js");
var sort = __webpack_require__(/*! ./sort */ "./node_modules/dagre/lib/order/sort.js");

module.exports = sortSubgraph;

function sortSubgraph(g, v, cg, biasRight) {
  var movable = g.children(v);
  var node = g.node(v);
  var bl = node ? node.borderLeft : undefined;
  var br = node ? node.borderRight: undefined;
  var subgraphs = {};

  if (bl) {
    movable = _.filter(movable, function(w) {
      return w !== bl && w !== br;
    });
  }

  var barycenters = barycenter(g, movable);
  _.forEach(barycenters, function(entry) {
    if (g.children(entry.v).length) {
      var subgraphResult = sortSubgraph(g, entry.v, cg, biasRight);
      subgraphs[entry.v] = subgraphResult;
      if (_.has(subgraphResult, "barycenter")) {
        mergeBarycenters(entry, subgraphResult);
      }
    }
  });

  var entries = resolveConflicts(barycenters, cg);
  expandSubgraphs(entries, subgraphs);

  var result = sort(entries, biasRight);

  if (bl) {
    result.vs = _.flatten([bl, result.vs, br], true);
    if (g.predecessors(bl).length) {
      var blPred = g.node(g.predecessors(bl)[0]),
        brPred = g.node(g.predecessors(br)[0]);
      if (!_.has(result, "barycenter")) {
        result.barycenter = 0;
        result.weight = 0;
      }
      result.barycenter = (result.barycenter * result.weight +
                           blPred.order + brPred.order) / (result.weight + 2);
      result.weight += 2;
    }
  }

  return result;
}

function expandSubgraphs(entries, subgraphs) {
  _.forEach(entries, function(entry) {
    entry.vs = _.flatten(entry.vs.map(function(v) {
      if (subgraphs[v]) {
        return subgraphs[v].vs;
      }
      return v;
    }), true);
  });
}

function mergeBarycenters(target, other) {
  if (!_.isUndefined(target.barycenter)) {
    target.barycenter = (target.barycenter * target.weight +
                         other.barycenter * other.weight) /
                        (target.weight + other.weight);
    target.weight += other.weight;
  } else {
    target.barycenter = other.barycenter;
    target.weight = other.weight;
  }
}


/***/ }),

/***/ "./node_modules/dagre/lib/order/sort.js":
/*!**********************************************!*\
  !*** ./node_modules/dagre/lib/order/sort.js ***!
  \**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var util = __webpack_require__(/*! ../util */ "./node_modules/dagre/lib/util.js");

module.exports = sort;

function sort(entries, biasRight) {
  var parts = util.partition(entries, function(entry) {
    return _.has(entry, "barycenter");
  });
  var sortable = parts.lhs,
    unsortable = _.sortBy(parts.rhs, function(entry) { return -entry.i; }),
    vs = [],
    sum = 0,
    weight = 0,
    vsIndex = 0;

  sortable.sort(compareWithBias(!!biasRight));

  vsIndex = consumeUnsortable(vs, unsortable, vsIndex);

  _.forEach(sortable, function (entry) {
    vsIndex += entry.vs.length;
    vs.push(entry.vs);
    sum += entry.barycenter * entry.weight;
    weight += entry.weight;
    vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  });

  var result = { vs: _.flatten(vs, true) };
  if (weight) {
    result.barycenter = sum / weight;
    result.weight = weight;
  }
  return result;
}

function consumeUnsortable(vs, unsortable, index) {
  var last;
  while (unsortable.length && (last = _.last(unsortable)).i <= index) {
    unsortable.pop();
    vs.push(last.vs);
    index++;
  }
  return index;
}

function compareWithBias(bias) {
  return function(entryV, entryW) {
    if (entryV.barycenter < entryW.barycenter) {
      return -1;
    } else if (entryV.barycenter > entryW.barycenter) {
      return 1;
    }

    return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
  };
}


/***/ }),

/***/ "./node_modules/dagre/lib/parent-dummy-chains.js":
/*!*******************************************************!*\
  !*** ./node_modules/dagre/lib/parent-dummy-chains.js ***!
  \*******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = parentDummyChains;

function parentDummyChains(g) {
  var postorderNums = postorder(g);

  _.forEach(g.graph().dummyChains, function(v) {
    var node = g.node(v);
    var edgeObj = node.edgeObj;
    var pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w);
    var path = pathData.path;
    var lca = pathData.lca;
    var pathIdx = 0;
    var pathV = path[pathIdx];
    var ascending = true;

    while (v !== edgeObj.w) {
      node = g.node(v);

      if (ascending) {
        while ((pathV = path[pathIdx]) !== lca &&
               g.node(pathV).maxRank < node.rank) {
          pathIdx++;
        }

        if (pathV === lca) {
          ascending = false;
        }
      }

      if (!ascending) {
        while (pathIdx < path.length - 1 &&
               g.node(pathV = path[pathIdx + 1]).minRank <= node.rank) {
          pathIdx++;
        }
        pathV = path[pathIdx];
      }

      g.setParent(v, pathV);
      v = g.successors(v)[0];
    }
  });
}

// Find a path from v to w through the lowest common ancestor (LCA). Return the
// full path and the LCA.
function findPath(g, postorderNums, v, w) {
  var vPath = [];
  var wPath = [];
  var low = Math.min(postorderNums[v].low, postorderNums[w].low);
  var lim = Math.max(postorderNums[v].lim, postorderNums[w].lim);
  var parent;
  var lca;

  // Traverse up from v to find the LCA
  parent = v;
  do {
    parent = g.parent(parent);
    vPath.push(parent);
  } while (parent &&
           (postorderNums[parent].low > low || lim > postorderNums[parent].lim));
  lca = parent;

  // Traverse from w to LCA
  parent = w;
  while ((parent = g.parent(parent)) !== lca) {
    wPath.push(parent);
  }

  return { path: vPath.concat(wPath.reverse()), lca: lca };
}

function postorder(g) {
  var result = {};
  var lim = 0;

  function dfs(v) {
    var low = lim;
    _.forEach(g.children(v), dfs);
    result[v] = { low: low, lim: lim++ };
  }
  _.forEach(g.children(), dfs);

  return result;
}


/***/ }),

/***/ "./node_modules/dagre/lib/position/bk.js":
/*!***********************************************!*\
  !*** ./node_modules/dagre/lib/position/bk.js ***!
  \***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var Graph = (__webpack_require__(/*! ../graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);
var util = __webpack_require__(/*! ../util */ "./node_modules/dagre/lib/util.js");

/*
 * This module provides coordinate assignment based on Brandes and Köpf, "Fast
 * and Simple Horizontal Coordinate Assignment."
 */

module.exports = {
  positionX: positionX,
  findType1Conflicts: findType1Conflicts,
  findType2Conflicts: findType2Conflicts,
  addConflict: addConflict,
  hasConflict: hasConflict,
  verticalAlignment: verticalAlignment,
  horizontalCompaction: horizontalCompaction,
  alignCoordinates: alignCoordinates,
  findSmallestWidthAlignment: findSmallestWidthAlignment,
  balance: balance
};

/*
 * Marks all edges in the graph with a type-1 conflict with the "type1Conflict"
 * property. A type-1 conflict is one where a non-inner segment crosses an
 * inner segment. An inner segment is an edge with both incident nodes marked
 * with the "dummy" property.
 *
 * This algorithm scans layer by layer, starting with the second, for type-1
 * conflicts between the current layer and the previous layer. For each layer
 * it scans the nodes from left to right until it reaches one that is incident
 * on an inner segment. It then scans predecessors to determine if they have
 * edges that cross that inner segment. At the end a final scan is done for all
 * nodes on the current rank to see if they cross the last visited inner
 * segment.
 *
 * This algorithm (safely) assumes that a dummy node will only be incident on a
 * single node in the layers being scanned.
 */
function findType1Conflicts(g, layering) {
  var conflicts = {};

  function visitLayer(prevLayer, layer) {
    var
      // last visited node in the previous layer that is incident on an inner
      // segment.
      k0 = 0,
      // Tracks the last node in this layer scanned for crossings with a type-1
      // segment.
      scanPos = 0,
      prevLayerLength = prevLayer.length,
      lastNode = _.last(layer);

    _.forEach(layer, function(v, i) {
      var w = findOtherInnerSegmentNode(g, v),
        k1 = w ? g.node(w).order : prevLayerLength;

      if (w || v === lastNode) {
        _.forEach(layer.slice(scanPos, i +1), function(scanNode) {
          _.forEach(g.predecessors(scanNode), function(u) {
            var uLabel = g.node(u),
              uPos = uLabel.order;
            if ((uPos < k0 || k1 < uPos) &&
                !(uLabel.dummy && g.node(scanNode).dummy)) {
              addConflict(conflicts, u, scanNode);
            }
          });
        });
        scanPos = i + 1;
        k0 = k1;
      }
    });

    return layer;
  }

  _.reduce(layering, visitLayer);
  return conflicts;
}

function findType2Conflicts(g, layering) {
  var conflicts = {};

  function scan(south, southPos, southEnd, prevNorthBorder, nextNorthBorder) {
    var v;
    _.forEach(_.range(southPos, southEnd), function(i) {
      v = south[i];
      if (g.node(v).dummy) {
        _.forEach(g.predecessors(v), function(u) {
          var uNode = g.node(u);
          if (uNode.dummy &&
              (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
            addConflict(conflicts, u, v);
          }
        });
      }
    });
  }


  function visitLayer(north, south) {
    var prevNorthPos = -1,
      nextNorthPos,
      southPos = 0;

    _.forEach(south, function(v, southLookahead) {
      if (g.node(v).dummy === "border") {
        var predecessors = g.predecessors(v);
        if (predecessors.length) {
          nextNorthPos = g.node(predecessors[0]).order;
          scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
          southPos = southLookahead;
          prevNorthPos = nextNorthPos;
        }
      }
      scan(south, southPos, south.length, nextNorthPos, north.length);
    });

    return south;
  }

  _.reduce(layering, visitLayer);
  return conflicts;
}

function findOtherInnerSegmentNode(g, v) {
  if (g.node(v).dummy) {
    return _.find(g.predecessors(v), function(u) {
      return g.node(u).dummy;
    });
  }
}

function addConflict(conflicts, v, w) {
  if (v > w) {
    var tmp = v;
    v = w;
    w = tmp;
  }

  var conflictsV = conflicts[v];
  if (!conflictsV) {
    conflicts[v] = conflictsV = {};
  }
  conflictsV[w] = true;
}

function hasConflict(conflicts, v, w) {
  if (v > w) {
    var tmp = v;
    v = w;
    w = tmp;
  }
  return _.has(conflicts[v], w);
}

/*
 * Try to align nodes into vertical "blocks" where possible. This algorithm
 * attempts to align a node with one of its median neighbors. If the edge
 * connecting a neighbor is a type-1 conflict then we ignore that possibility.
 * If a previous node has already formed a block with a node after the node
 * we're trying to form a block with, we also ignore that possibility - our
 * blocks would be split in that scenario.
 */
function verticalAlignment(g, layering, conflicts, neighborFn) {
  var root = {},
    align = {},
    pos = {};

  // We cache the position here based on the layering because the graph and
  // layering may be out of sync. The layering matrix is manipulated to
  // generate different extreme alignments.
  _.forEach(layering, function(layer) {
    _.forEach(layer, function(v, order) {
      root[v] = v;
      align[v] = v;
      pos[v] = order;
    });
  });

  _.forEach(layering, function(layer) {
    var prevIdx = -1;
    _.forEach(layer, function(v) {
      var ws = neighborFn(v);
      if (ws.length) {
        ws = _.sortBy(ws, function(w) { return pos[w]; });
        var mp = (ws.length - 1) / 2;
        for (var i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) {
          var w = ws[i];
          if (align[v] === v &&
              prevIdx < pos[w] &&
              !hasConflict(conflicts, v, w)) {
            align[w] = v;
            align[v] = root[v] = root[w];
            prevIdx = pos[w];
          }
        }
      }
    });
  });

  return { root: root, align: align };
}

function horizontalCompaction(g, layering, root, align, reverseSep) {
  // This portion of the algorithm differs from BK due to a number of problems.
  // Instead of their algorithm we construct a new block graph and do two
  // sweeps. The first sweep places blocks with the smallest possible
  // coordinates. The second sweep removes unused space by moving blocks to the
  // greatest coordinates without violating separation.
  var xs = {},
    blockG = buildBlockGraph(g, layering, root, reverseSep),
    borderType = reverseSep ? "borderLeft" : "borderRight";

  function iterate(setXsFunc, nextNodesFunc) {
    var stack = blockG.nodes();
    var elem = stack.pop();
    var visited = {};
    while (elem) {
      if (visited[elem]) {
        setXsFunc(elem);
      } else {
        visited[elem] = true;
        stack.push(elem);
        stack = stack.concat(nextNodesFunc(elem));
      }

      elem = stack.pop();
    }
  }

  // First pass, assign smallest coordinates
  function pass1(elem) {
    xs[elem] = blockG.inEdges(elem).reduce(function(acc, e) {
      return Math.max(acc, xs[e.v] + blockG.edge(e));
    }, 0);
  }

  // Second pass, assign greatest coordinates
  function pass2(elem) {
    var min = blockG.outEdges(elem).reduce(function(acc, e) {
      return Math.min(acc, xs[e.w] - blockG.edge(e));
    }, Number.POSITIVE_INFINITY);

    var node = g.node(elem);
    if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
      xs[elem] = Math.max(xs[elem], min);
    }
  }

  iterate(pass1, blockG.predecessors.bind(blockG));
  iterate(pass2, blockG.successors.bind(blockG));

  // Assign x coordinates to all nodes
  _.forEach(align, function(v) {
    xs[v] = xs[root[v]];
  });

  return xs;
}


function buildBlockGraph(g, layering, root, reverseSep) {
  var blockGraph = new Graph(),
    graphLabel = g.graph(),
    sepFn = sep(graphLabel.nodesep, graphLabel.edgesep, reverseSep);

  _.forEach(layering, function(layer) {
    var u;
    _.forEach(layer, function(v) {
      var vRoot = root[v];
      blockGraph.setNode(vRoot);
      if (u) {
        var uRoot = root[u],
          prevMax = blockGraph.edge(uRoot, vRoot);
        blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0));
      }
      u = v;
    });
  });

  return blockGraph;
}

/*
 * Returns the alignment that has the smallest width of the given alignments.
 */
function findSmallestWidthAlignment(g, xss) {
  return _.minBy(_.values(xss), function (xs) {
    var max = Number.NEGATIVE_INFINITY;
    var min = Number.POSITIVE_INFINITY;

    _.forIn(xs, function (x, v) {
      var halfWidth = width(g, v) / 2;

      max = Math.max(x + halfWidth, max);
      min = Math.min(x - halfWidth, min);
    });

    return max - min;
  });
}

/*
 * Align the coordinates of each of the layout alignments such that
 * left-biased alignments have their minimum coordinate at the same point as
 * the minimum coordinate of the smallest width alignment and right-biased
 * alignments have their maximum coordinate at the same point as the maximum
 * coordinate of the smallest width alignment.
 */
function alignCoordinates(xss, alignTo) {
  var alignToVals = _.values(alignTo),
    alignToMin = _.min(alignToVals),
    alignToMax = _.max(alignToVals);

  _.forEach(["u", "d"], function(vert) {
    _.forEach(["l", "r"], function(horiz) {
      var alignment = vert + horiz,
        xs = xss[alignment],
        delta;
      if (xs === alignTo) return;

      var xsVals = _.values(xs);
      delta = horiz === "l" ? alignToMin - _.min(xsVals) : alignToMax - _.max(xsVals);

      if (delta) {
        xss[alignment] = _.mapValues(xs, function(x) { return x + delta; });
      }
    });
  });
}

function balance(xss, align) {
  return _.mapValues(xss.ul, function(ignore, v) {
    if (align) {
      return xss[align.toLowerCase()][v];
    } else {
      var xs = _.sortBy(_.map(xss, v));
      return (xs[1] + xs[2]) / 2;
    }
  });
}

function positionX(g) {
  var layering = util.buildLayerMatrix(g);
  var conflicts = _.merge(
    findType1Conflicts(g, layering),
    findType2Conflicts(g, layering));

  var xss = {};
  var adjustedLayering;
  _.forEach(["u", "d"], function(vert) {
    adjustedLayering = vert === "u" ? layering : _.values(layering).reverse();
    _.forEach(["l", "r"], function(horiz) {
      if (horiz === "r") {
        adjustedLayering = _.map(adjustedLayering, function(inner) {
          return _.values(inner).reverse();
        });
      }

      var neighborFn = (vert === "u" ? g.predecessors : g.successors).bind(g);
      var align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn);
      var xs = horizontalCompaction(g, adjustedLayering,
        align.root, align.align, horiz === "r");
      if (horiz === "r") {
        xs = _.mapValues(xs, function(x) { return -x; });
      }
      xss[vert + horiz] = xs;
    });
  });

  var smallestWidth = findSmallestWidthAlignment(g, xss);
  alignCoordinates(xss, smallestWidth);
  return balance(xss, g.graph().align);
}

function sep(nodeSep, edgeSep, reverseSep) {
  return function(g, v, w) {
    var vLabel = g.node(v);
    var wLabel = g.node(w);
    var sum = 0;
    var delta;

    sum += vLabel.width / 2;
    if (_.has(vLabel, "labelpos")) {
      switch (vLabel.labelpos.toLowerCase()) {
      case "l": delta = -vLabel.width / 2; break;
      case "r": delta = vLabel.width / 2; break;
      }
    }
    if (delta) {
      sum += reverseSep ? delta : -delta;
    }
    delta = 0;

    sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
    sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;

    sum += wLabel.width / 2;
    if (_.has(wLabel, "labelpos")) {
      switch (wLabel.labelpos.toLowerCase()) {
      case "l": delta = wLabel.width / 2; break;
      case "r": delta = -wLabel.width / 2; break;
      }
    }
    if (delta) {
      sum += reverseSep ? delta : -delta;
    }
    delta = 0;

    return sum;
  };
}

function width(g, v) {
  return g.node(v).width;
}


/***/ }),

/***/ "./node_modules/dagre/lib/position/index.js":
/*!**************************************************!*\
  !*** ./node_modules/dagre/lib/position/index.js ***!
  \**************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var util = __webpack_require__(/*! ../util */ "./node_modules/dagre/lib/util.js");
var positionX = (__webpack_require__(/*! ./bk */ "./node_modules/dagre/lib/position/bk.js").positionX);

module.exports = position;

function position(g) {
  g = util.asNonCompoundGraph(g);

  positionY(g);
  _.forEach(positionX(g), function(x, v) {
    g.node(v).x = x;
  });
}

function positionY(g) {
  var layering = util.buildLayerMatrix(g);
  var rankSep = g.graph().ranksep;
  var prevY = 0;
  _.forEach(layering, function(layer) {
    var maxHeight = _.max(_.map(layer, function(v) { return g.node(v).height; }));
    _.forEach(layer, function(v) {
      g.node(v).y = prevY + maxHeight / 2;
    });
    prevY += maxHeight + rankSep;
  });
}



/***/ }),

/***/ "./node_modules/dagre/lib/rank/feasible-tree.js":
/*!******************************************************!*\
  !*** ./node_modules/dagre/lib/rank/feasible-tree.js ***!
  \******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var Graph = (__webpack_require__(/*! ../graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);
var slack = (__webpack_require__(/*! ./util */ "./node_modules/dagre/lib/rank/util.js").slack);

module.exports = feasibleTree;

/*
 * Constructs a spanning tree with tight edges and adjusted the input node's
 * ranks to achieve this. A tight edge is one that is has a length that matches
 * its "minlen" attribute.
 *
 * The basic structure for this function is derived from Gansner, et al., "A
 * Technique for Drawing Directed Graphs."
 *
 * Pre-conditions:
 *
 *    1. Graph must be a DAG.
 *    2. Graph must be connected.
 *    3. Graph must have at least one node.
 *    5. Graph nodes must have been previously assigned a "rank" property that
 *       respects the "minlen" property of incident edges.
 *    6. Graph edges must have a "minlen" property.
 *
 * Post-conditions:
 *
 *    - Graph nodes will have their rank adjusted to ensure that all edges are
 *      tight.
 *
 * Returns a tree (undirected graph) that is constructed using only "tight"
 * edges.
 */
function feasibleTree(g) {
  var t = new Graph({ directed: false });

  // Choose arbitrary node from which to start our tree
  var start = g.nodes()[0];
  var size = g.nodeCount();
  t.setNode(start, {});

  var edge, delta;
  while (tightTree(t, g) < size) {
    edge = findMinSlackEdge(t, g);
    delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
    shiftRanks(t, g, delta);
  }

  return t;
}

/*
 * Finds a maximal tree of tight edges and returns the number of nodes in the
 * tree.
 */
function tightTree(t, g) {
  function dfs(v) {
    _.forEach(g.nodeEdges(v), function(e) {
      var edgeV = e.v,
        w = (v === edgeV) ? e.w : edgeV;
      if (!t.hasNode(w) && !slack(g, e)) {
        t.setNode(w, {});
        t.setEdge(v, w, {});
        dfs(w);
      }
    });
  }

  _.forEach(t.nodes(), dfs);
  return t.nodeCount();
}

/*
 * Finds the edge with the smallest slack that is incident on tree and returns
 * it.
 */
function findMinSlackEdge(t, g) {
  return _.minBy(g.edges(), function(e) {
    if (t.hasNode(e.v) !== t.hasNode(e.w)) {
      return slack(g, e);
    }
  });
}

function shiftRanks(t, g, delta) {
  _.forEach(t.nodes(), function(v) {
    g.node(v).rank += delta;
  });
}


/***/ }),

/***/ "./node_modules/dagre/lib/rank/index.js":
/*!**********************************************!*\
  !*** ./node_modules/dagre/lib/rank/index.js ***!
  \**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var rankUtil = __webpack_require__(/*! ./util */ "./node_modules/dagre/lib/rank/util.js");
var longestPath = rankUtil.longestPath;
var feasibleTree = __webpack_require__(/*! ./feasible-tree */ "./node_modules/dagre/lib/rank/feasible-tree.js");
var networkSimplex = __webpack_require__(/*! ./network-simplex */ "./node_modules/dagre/lib/rank/network-simplex.js");

module.exports = rank;

/*
 * Assigns a rank to each node in the input graph that respects the "minlen"
 * constraint specified on edges between nodes.
 *
 * This basic structure is derived from Gansner, et al., "A Technique for
 * Drawing Directed Graphs."
 *
 * Pre-conditions:
 *
 *    1. Graph must be a connected DAG
 *    2. Graph nodes must be objects
 *    3. Graph edges must have "weight" and "minlen" attributes
 *
 * Post-conditions:
 *
 *    1. Graph nodes will have a "rank" attribute based on the results of the
 *       algorithm. Ranks can start at any index (including negative), we'll
 *       fix them up later.
 */
function rank(g) {
  switch(g.graph().ranker) {
  case "network-simplex": networkSimplexRanker(g); break;
  case "tight-tree": tightTreeRanker(g); break;
  case "longest-path": longestPathRanker(g); break;
  default: networkSimplexRanker(g);
  }
}

// A fast and simple ranker, but results are far from optimal.
var longestPathRanker = longestPath;

function tightTreeRanker(g) {
  longestPath(g);
  feasibleTree(g);
}

function networkSimplexRanker(g) {
  networkSimplex(g);
}


/***/ }),

/***/ "./node_modules/dagre/lib/rank/network-simplex.js":
/*!********************************************************!*\
  !*** ./node_modules/dagre/lib/rank/network-simplex.js ***!
  \********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");
var feasibleTree = __webpack_require__(/*! ./feasible-tree */ "./node_modules/dagre/lib/rank/feasible-tree.js");
var slack = (__webpack_require__(/*! ./util */ "./node_modules/dagre/lib/rank/util.js").slack);
var initRank = (__webpack_require__(/*! ./util */ "./node_modules/dagre/lib/rank/util.js").longestPath);
var preorder = (__webpack_require__(/*! ../graphlib */ "./node_modules/dagre/lib/graphlib.js").alg.preorder);
var postorder = (__webpack_require__(/*! ../graphlib */ "./node_modules/dagre/lib/graphlib.js").alg.postorder);
var simplify = (__webpack_require__(/*! ../util */ "./node_modules/dagre/lib/util.js").simplify);

module.exports = networkSimplex;

// Expose some internals for testing purposes
networkSimplex.initLowLimValues = initLowLimValues;
networkSimplex.initCutValues = initCutValues;
networkSimplex.calcCutValue = calcCutValue;
networkSimplex.leaveEdge = leaveEdge;
networkSimplex.enterEdge = enterEdge;
networkSimplex.exchangeEdges = exchangeEdges;

/*
 * The network simplex algorithm assigns ranks to each node in the input graph
 * and iteratively improves the ranking to reduce the length of edges.
 *
 * Preconditions:
 *
 *    1. The input graph must be a DAG.
 *    2. All nodes in the graph must have an object value.
 *    3. All edges in the graph must have "minlen" and "weight" attributes.
 *
 * Postconditions:
 *
 *    1. All nodes in the graph will have an assigned "rank" attribute that has
 *       been optimized by the network simplex algorithm. Ranks start at 0.
 *
 *
 * A rough sketch of the algorithm is as follows:
 *
 *    1. Assign initial ranks to each node. We use the longest path algorithm,
 *       which assigns ranks to the lowest position possible. In general this
 *       leads to very wide bottom ranks and unnecessarily long edges.
 *    2. Construct a feasible tight tree. A tight tree is one such that all
 *       edges in the tree have no slack (difference between length of edge
 *       and minlen for the edge). This by itself greatly improves the assigned
 *       rankings by shorting edges.
 *    3. Iteratively find edges that have negative cut values. Generally a
 *       negative cut value indicates that the edge could be removed and a new
 *       tree edge could be added to produce a more compact graph.
 *
 * Much of the algorithms here are derived from Gansner, et al., "A Technique
 * for Drawing Directed Graphs." The structure of the file roughly follows the
 * structure of the overall algorithm.
 */
function networkSimplex(g) {
  g = simplify(g);
  initRank(g);
  var t = feasibleTree(g);
  initLowLimValues(t);
  initCutValues(t, g);

  var e, f;
  while ((e = leaveEdge(t))) {
    f = enterEdge(t, g, e);
    exchangeEdges(t, g, e, f);
  }
}

/*
 * Initializes cut values for all edges in the tree.
 */
function initCutValues(t, g) {
  var vs = postorder(t, t.nodes());
  vs = vs.slice(0, vs.length - 1);
  _.forEach(vs, function(v) {
    assignCutValue(t, g, v);
  });
}

function assignCutValue(t, g, child) {
  var childLab = t.node(child);
  var parent = childLab.parent;
  t.edge(child, parent).cutvalue = calcCutValue(t, g, child);
}

/*
 * Given the tight tree, its graph, and a child in the graph calculate and
 * return the cut value for the edge between the child and its parent.
 */
function calcCutValue(t, g, child) {
  var childLab = t.node(child);
  var parent = childLab.parent;
  // True if the child is on the tail end of the edge in the directed graph
  var childIsTail = true;
  // The graph's view of the tree edge we're inspecting
  var graphEdge = g.edge(child, parent);
  // The accumulated cut value for the edge between this node and its parent
  var cutValue = 0;

  if (!graphEdge) {
    childIsTail = false;
    graphEdge = g.edge(parent, child);
  }

  cutValue = graphEdge.weight;

  _.forEach(g.nodeEdges(child), function(e) {
    var isOutEdge = e.v === child,
      other = isOutEdge ? e.w : e.v;

    if (other !== parent) {
      var pointsToHead = isOutEdge === childIsTail,
        otherWeight = g.edge(e).weight;

      cutValue += pointsToHead ? otherWeight : -otherWeight;
      if (isTreeEdge(t, child, other)) {
        var otherCutValue = t.edge(child, other).cutvalue;
        cutValue += pointsToHead ? -otherCutValue : otherCutValue;
      }
    }
  });

  return cutValue;
}

function initLowLimValues(tree, root) {
  if (arguments.length < 2) {
    root = tree.nodes()[0];
  }
  dfsAssignLowLim(tree, {}, 1, root);
}

function dfsAssignLowLim(tree, visited, nextLim, v, parent) {
  var low = nextLim;
  var label = tree.node(v);

  visited[v] = true;
  _.forEach(tree.neighbors(v), function(w) {
    if (!_.has(visited, w)) {
      nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v);
    }
  });

  label.low = low;
  label.lim = nextLim++;
  if (parent) {
    label.parent = parent;
  } else {
    // TODO should be able to remove this when we incrementally update low lim
    delete label.parent;
  }

  return nextLim;
}

function leaveEdge(tree) {
  return _.find(tree.edges(), function(e) {
    return tree.edge(e).cutvalue < 0;
  });
}

function enterEdge(t, g, edge) {
  var v = edge.v;
  var w = edge.w;

  // For the rest of this function we assume that v is the tail and w is the
  // head, so if we don't have this edge in the graph we should flip it to
  // match the correct orientation.
  if (!g.hasEdge(v, w)) {
    v = edge.w;
    w = edge.v;
  }

  var vLabel = t.node(v);
  var wLabel = t.node(w);
  var tailLabel = vLabel;
  var flip = false;

  // If the root is in the tail of the edge then we need to flip the logic that
  // checks for the head and tail nodes in the candidates function below.
  if (vLabel.lim > wLabel.lim) {
    tailLabel = wLabel;
    flip = true;
  }

  var candidates = _.filter(g.edges(), function(edge) {
    return flip === isDescendant(t, t.node(edge.v), tailLabel) &&
           flip !== isDescendant(t, t.node(edge.w), tailLabel);
  });

  return _.minBy(candidates, function(edge) { return slack(g, edge); });
}

function exchangeEdges(t, g, e, f) {
  var v = e.v;
  var w = e.w;
  t.removeEdge(v, w);
  t.setEdge(f.v, f.w, {});
  initLowLimValues(t);
  initCutValues(t, g);
  updateRanks(t, g);
}

function updateRanks(t, g) {
  var root = _.find(t.nodes(), function(v) { return !g.node(v).parent; });
  var vs = preorder(t, root);
  vs = vs.slice(1);
  _.forEach(vs, function(v) {
    var parent = t.node(v).parent,
      edge = g.edge(v, parent),
      flipped = false;

    if (!edge) {
      edge = g.edge(parent, v);
      flipped = true;
    }

    g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen);
  });
}

/*
 * Returns true if the edge is in the tree.
 */
function isTreeEdge(tree, u, v) {
  return tree.hasEdge(u, v);
}

/*
 * Returns true if the specified node is descendant of the root node per the
 * assigned low and lim attributes in the tree.
 */
function isDescendant(tree, vLabel, rootLabel) {
  return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;
}


/***/ }),

/***/ "./node_modules/dagre/lib/rank/util.js":
/*!*********************************************!*\
  !*** ./node_modules/dagre/lib/rank/util.js ***!
  \*********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var _ = __webpack_require__(/*! ../lodash */ "./node_modules/dagre/lib/lodash.js");

module.exports = {
  longestPath: longestPath,
  slack: slack
};

/*
 * Initializes ranks for the input graph using the longest path algorithm. This
 * algorithm scales well and is fast in practice, it yields rather poor
 * solutions. Nodes are pushed to the lowest layer possible, leaving the bottom
 * ranks wide and leaving edges longer than necessary. However, due to its
 * speed, this algorithm is good for getting an initial ranking that can be fed
 * into other algorithms.
 *
 * This algorithm does not normalize layers because it will be used by other
 * algorithms in most cases. If using this algorithm directly, be sure to
 * run normalize at the end.
 *
 * Pre-conditions:
 *
 *    1. Input graph is a DAG.
 *    2. Input graph node labels can be assigned properties.
 *
 * Post-conditions:
 *
 *    1. Each node will be assign an (unnormalized) "rank" property.
 */
function longestPath(g) {
  var visited = {};

  function dfs(v) {
    var label = g.node(v);
    if (_.has(visited, v)) {
      return label.rank;
    }
    visited[v] = true;

    var rank = _.min(_.map(g.outEdges(v), function(e) {
      return dfs(e.w) - g.edge(e).minlen;
    }));

    if (rank === Number.POSITIVE_INFINITY || // return value of _.map([]) for Lodash 3
        rank === undefined || // return value of _.map([]) for Lodash 4
        rank === null) { // return value of _.map([null])
      rank = 0;
    }

    return (label.rank = rank);
  }

  _.forEach(g.sources(), dfs);
}

/*
 * Returns the amount of slack for the given edge. The slack is defined as the
 * difference between the length of the edge and its minimum length.
 */
function slack(g, e) {
  return g.node(e.w).rank - g.node(e.v).rank - g.edge(e).minlen;
}


/***/ }),

/***/ "./node_modules/dagre/lib/util.js":
/*!****************************************!*\
  !*** ./node_modules/dagre/lib/util.js ***!
  \****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";
/* eslint "no-console": off */



var _ = __webpack_require__(/*! ./lodash */ "./node_modules/dagre/lib/lodash.js");
var Graph = (__webpack_require__(/*! ./graphlib */ "./node_modules/dagre/lib/graphlib.js").Graph);

module.exports = {
  addDummyNode: addDummyNode,
  simplify: simplify,
  asNonCompoundGraph: asNonCompoundGraph,
  successorWeights: successorWeights,
  predecessorWeights: predecessorWeights,
  intersectRect: intersectRect,
  buildLayerMatrix: buildLayerMatrix,
  normalizeRanks: normalizeRanks,
  removeEmptyRanks: removeEmptyRanks,
  addBorderNode: addBorderNode,
  maxRank: maxRank,
  partition: partition,
  time: time,
  notime: notime
};

/*
 * Adds a dummy node to the graph and return v.
 */
function addDummyNode(g, type, attrs, name) {
  var v;
  do {
    v = _.uniqueId(name);
  } while (g.hasNode(v));

  attrs.dummy = type;
  g.setNode(v, attrs);
  return v;
}

/*
 * Returns a new graph with only simple edges. Handles aggregation of data
 * associated with multi-edges.
 */
function simplify(g) {
  var simplified = new Graph().setGraph(g.graph());
  _.forEach(g.nodes(), function(v) { simplified.setNode(v, g.node(v)); });
  _.forEach(g.edges(), function(e) {
    var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 };
    var label = g.edge(e);
    simplified.setEdge(e.v, e.w, {
      weight: simpleLabel.weight + label.weight,
      minlen: Math.max(simpleLabel.minlen, label.minlen)
    });
  });
  return simplified;
}

function asNonCompoundGraph(g) {
  var simplified = new Graph({ multigraph: g.isMultigraph() }).setGraph(g.graph());
  _.forEach(g.nodes(), function(v) {
    if (!g.children(v).length) {
      simplified.setNode(v, g.node(v));
    }
  });
  _.forEach(g.edges(), function(e) {
    simplified.setEdge(e, g.edge(e));
  });
  return simplified;
}

function successorWeights(g) {
  var weightMap = _.map(g.nodes(), function(v) {
    var sucs = {};
    _.forEach(g.outEdges(v), function(e) {
      sucs[e.w] = (sucs[e.w] || 0) + g.edge(e).weight;
    });
    return sucs;
  });
  return _.zipObject(g.nodes(), weightMap);
}

function predecessorWeights(g) {
  var weightMap = _.map(g.nodes(), function(v) {
    var preds = {};
    _.forEach(g.inEdges(v), function(e) {
      preds[e.v] = (preds[e.v] || 0) + g.edge(e).weight;
    });
    return preds;
  });
  return _.zipObject(g.nodes(), weightMap);
}

/*
 * Finds where a line starting at point ({x, y}) would intersect a rectangle
 * ({x, y, width, height}) if it were pointing at the rectangle's center.
 */
function intersectRect(rect, point) {
  var x = rect.x;
  var y = rect.y;

  // Rectangle intersection algorithm from:
  // http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  var dx = point.x - x;
  var dy = point.y - y;
  var w = rect.width / 2;
  var h = rect.height / 2;

  if (!dx && !dy) {
    throw new Error("Not possible to find intersection inside of the rectangle");
  }

  var sx, sy;
  if (Math.abs(dy) * w > Math.abs(dx) * h) {
    // Intersection is top or bottom of rect.
    if (dy < 0) {
      h = -h;
    }
    sx = h * dx / dy;
    sy = h;
  } else {
    // Intersection is left or right of rect.
    if (dx < 0) {
      w = -w;
    }
    sx = w;
    sy = w * dy / dx;
  }

  return { x: x + sx, y: y + sy };
}

/*
 * Given a DAG with each node assigned "rank" and "order" properties, this
 * function will produce a matrix with the ids of each node.
 */
function buildLayerMatrix(g) {
  var layering = _.map(_.range(maxRank(g) + 1), function() { return []; });
  _.forEach(g.nodes(), function(v) {
    var node = g.node(v);
    var rank = node.rank;
    if (!_.isUndefined(rank)) {
      layering[rank][node.order] = v;
    }
  });
  return layering;
}

/*
 * Adjusts the ranks for all nodes in the graph such that all nodes v have
 * rank(v) >= 0 and at least one node w has rank(w) = 0.
 */
function normalizeRanks(g) {
  var min = _.min(_.map(g.nodes(), function(v) { return g.node(v).rank; }));
  _.forEach(g.nodes(), function(v) {
    var node = g.node(v);
    if (_.has(node, "rank")) {
      node.rank -= min;
    }
  });
}

function removeEmptyRanks(g) {
  // Ranks may not start at 0, so we need to offset them
  var offset = _.min(_.map(g.nodes(), function(v) { return g.node(v).rank; }));

  var layers = [];
  _.forEach(g.nodes(), function(v) {
    var rank = g.node(v).rank - offset;
    if (!layers[rank]) {
      layers[rank] = [];
    }
    layers[rank].push(v);
  });

  var delta = 0;
  var nodeRankFactor = g.graph().nodeRankFactor;
  _.forEach(layers, function(vs, i) {
    if (_.isUndefined(vs) && i % nodeRankFactor !== 0) {
      --delta;
    } else if (delta) {
      _.forEach(vs, function(v) { g.node(v).rank += delta; });
    }
  });
}

function addBorderNode(g, prefix, rank, order) {
  var node = {
    width: 0,
    height: 0
  };
  if (arguments.length >= 4) {
    node.rank = rank;
    node.order = order;
  }
  return addDummyNode(g, "border", node, prefix);
}

function maxRank(g) {
  return _.max(_.map(g.nodes(), function(v) {
    var rank = g.node(v).rank;
    if (!_.isUndefined(rank)) {
      return rank;
    }
  }));
}

/*
 * Partition a collection into two groups: `lhs` and `rhs`. If the supplied
 * function returns true for an entry it goes into `lhs`. Otherwise it goes
 * into `rhs.
 */
function partition(collection, fn) {
  var result = { lhs: [], rhs: [] };
  _.forEach(collection, function(value) {
    if (fn(value)) {
      result.lhs.push(value);
    } else {
      result.rhs.push(value);
    }
  });
  return result;
}

/*
 * Returns a new function that wraps `fn` with a timer. The wrapper logs the
 * time it takes to execute the function.
 */
function time(name, fn) {
  var start = _.now();
  try {
    return fn();
  } finally {
    console.log(name + " time: " + (_.now() - start) + "ms");
  }
}

function notime(name, fn) {
  return fn();
}


/***/ }),

/***/ "./node_modules/dagre/lib/version.js":
/*!*******************************************!*\
  !*** ./node_modules/dagre/lib/version.js ***!
  \*******************************************/
/***/ ((module) => {

module.exports = "0.8.5";


/***/ }),

/***/ "./node_modules/jointjs/dist/joint.js":
/*!********************************************!*\
  !*** ./node_modules/jointjs/dist/joint.js ***!
  \********************************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

/*! JointJS v3.4.4 (2021-09-27) - JavaScript diagramming library


This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
(function (global, factory) {
	 true ? factory(exports, __webpack_require__(/*! backbone */ "./node_modules/jointjs/node_modules/backbone/backbone.js"), __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"), __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js")) :
	0;
}(this, function (exports, Backbone, _, $) { 'use strict';

	Backbone = Backbone && Backbone.hasOwnProperty('default') ? Backbone['default'] : Backbone;
	_ = _ && _.hasOwnProperty('default') ? _['default'] : _;
	$ = $ && $.hasOwnProperty('default') ? $['default'] : $;

	var commonjsGlobal = typeof window !== 'undefined' ? window : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof self !== 'undefined' ? self : {};

	function commonjsRequire () {
		throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
	}

	function unwrapExports (x) {
		return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
	}

	function createCommonjsModule(fn, module) {
		return module = { exports: {} }, fn(module, module.exports), module.exports;
	}

	function getCjsExportFromNamespace (n) {
		return n && n.default || n;
	}

	var check = function (it) {
	  return it && it.Math == Math && it;
	};

	// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
	var global_1 =
	  // eslint-disable-next-line no-undef
	  check(typeof globalThis == 'object' && globalThis) ||
	  check(typeof window == 'object' && window) ||
	  check(typeof self == 'object' && self) ||
	  check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
	  // eslint-disable-next-line no-new-func
	  (function () { return this; })() || Function('return this')();

	var fails = function (exec) {
	  try {
	    return !!exec();
	  } catch (error) {
	    return true;
	  }
	};

	// Detect IE8's incomplete defineProperty implementation
	var descriptors = !fails(function () {
	  return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
	});

	'use strict';
	var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
	var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

	// Nashorn ~ JDK8 bug
	var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);

	// `Object.prototype.propertyIsEnumerable` method implementation
	// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
	var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
	  var descriptor = getOwnPropertyDescriptor(this, V);
	  return !!descriptor && descriptor.enumerable;
	} : nativePropertyIsEnumerable;

	var objectPropertyIsEnumerable = {
		f: f
	};

	var createPropertyDescriptor = function (bitmap, value) {
	  return {
	    enumerable: !(bitmap & 1),
	    configurable: !(bitmap & 2),
	    writable: !(bitmap & 4),
	    value: value
	  };
	};

	var toString = {}.toString;

	var classofRaw = function (it) {
	  return toString.call(it).slice(8, -1);
	};

	var split = ''.split;

	// fallback for non-array-like ES3 and non-enumerable old V8 strings
	var indexedObject = fails(function () {
	  // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
	  // eslint-disable-next-line no-prototype-builtins
	  return !Object('z').propertyIsEnumerable(0);
	}) ? function (it) {
	  return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
	} : Object;

	// `RequireObjectCoercible` abstract operation
	// https://tc39.es/ecma262/#sec-requireobjectcoercible
	var requireObjectCoercible = function (it) {
	  if (it == undefined) { throw TypeError("Can't call method on " + it); }
	  return it;
	};

	// toObject with fallback for non-array-like ES3 strings



	var toIndexedObject = function (it) {
	  return indexedObject(requireObjectCoercible(it));
	};

	var isObject = function (it) {
	  return typeof it === 'object' ? it !== null : typeof it === 'function';
	};

	// `ToPrimitive` abstract operation
	// https://tc39.es/ecma262/#sec-toprimitive
	// instead of the ES6 spec version, we didn't implement @@toPrimitive case
	// and the second argument - flag - preferred type is a string
	var toPrimitive = function (input, PREFERRED_STRING) {
	  if (!isObject(input)) { return input; }
	  var fn, val;
	  if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) { return val; }
	  if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) { return val; }
	  if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) { return val; }
	  throw TypeError("Can't convert object to primitive value");
	};

	var hasOwnProperty = {}.hasOwnProperty;

	var has = function (it, key) {
	  return hasOwnProperty.call(it, key);
	};

	var document$1 = global_1.document;
	// typeof document.createElement is 'object' in old IE
	var EXISTS = isObject(document$1) && isObject(document$1.createElement);

	var documentCreateElement = function (it) {
	  return EXISTS ? document$1.createElement(it) : {};
	};

	// Thank's IE8 for his funny defineProperty
	var ie8DomDefine = !descriptors && !fails(function () {
	  return Object.defineProperty(documentCreateElement('div'), 'a', {
	    get: function () { return 7; }
	  }).a != 7;
	});

	var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

	// `Object.getOwnPropertyDescriptor` method
	// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
	var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
	  O = toIndexedObject(O);
	  P = toPrimitive(P, true);
	  if (ie8DomDefine) { try {
	    return nativeGetOwnPropertyDescriptor(O, P);
	  } catch (error) { /* empty */ } }
	  if (has(O, P)) { return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]); }
	};

	var objectGetOwnPropertyDescriptor = {
		f: f$1
	};

	var anObject = function (it) {
	  if (!isObject(it)) {
	    throw TypeError(String(it) + ' is not an object');
	  } return it;
	};

	var nativeDefineProperty = Object.defineProperty;

	// `Object.defineProperty` method
	// https://tc39.es/ecma262/#sec-object.defineproperty
	var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
	  anObject(O);
	  P = toPrimitive(P, true);
	  anObject(Attributes);
	  if (ie8DomDefine) { try {
	    return nativeDefineProperty(O, P, Attributes);
	  } catch (error) { /* empty */ } }
	  if ('get' in Attributes || 'set' in Attributes) { throw TypeError('Accessors not supported'); }
	  if ('value' in Attributes) { O[P] = Attributes.value; }
	  return O;
	};

	var objectDefineProperty = {
		f: f$2
	};

	var createNonEnumerableProperty = descriptors ? function (object, key, value) {
	  return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
	} : function (object, key, value) {
	  object[key] = value;
	  return object;
	};

	var setGlobal = function (key, value) {
	  try {
	    createNonEnumerableProperty(global_1, key, value);
	  } catch (error) {
	    global_1[key] = value;
	  } return value;
	};

	var SHARED = '__core-js_shared__';
	var store = global_1[SHARED] || setGlobal(SHARED, {});

	var sharedStore = store;

	var functionToString = Function.toString;

	// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper
	if (typeof sharedStore.inspectSource != 'function') {
	  sharedStore.inspectSource = function (it) {
	    return functionToString.call(it);
	  };
	}

	var inspectSource = sharedStore.inspectSource;

	var WeakMap = global_1.WeakMap;

	var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));

	var isPure = false;

	var shared = createCommonjsModule(function (module) {
	(module.exports = function (key, value) {
	  return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {});
	})('versions', []).push({
	  version: '3.8.3',
	  mode: isPure ? 'pure' : 'global',
	  copyright: '© 2021 Denis Pushkarev (zloirock.ru)'
	});
	});

	var id = 0;
	var postfix = Math.random();

	var uid = function (key) {
	  return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
	};

	var keys = shared('keys');

	var sharedKey = function (key) {
	  return keys[key] || (keys[key] = uid(key));
	};

	var hiddenKeys = {};

	var WeakMap$1 = global_1.WeakMap;
	var set, get, has$1;

	var enforce = function (it) {
	  return has$1(it) ? get(it) : set(it, {});
	};

	var getterFor = function (TYPE) {
	  return function (it) {
	    var state;
	    if (!isObject(it) || (state = get(it)).type !== TYPE) {
	      throw TypeError('Incompatible receiver, ' + TYPE + ' required');
	    } return state;
	  };
	};

	if (nativeWeakMap) {
	  var store$1 = sharedStore.state || (sharedStore.state = new WeakMap$1());
	  var wmget = store$1.get;
	  var wmhas = store$1.has;
	  var wmset = store$1.set;
	  set = function (it, metadata) {
	    metadata.facade = it;
	    wmset.call(store$1, it, metadata);
	    return metadata;
	  };
	  get = function (it) {
	    return wmget.call(store$1, it) || {};
	  };
	  has$1 = function (it) {
	    return wmhas.call(store$1, it);
	  };
	} else {
	  var STATE = sharedKey('state');
	  hiddenKeys[STATE] = true;
	  set = function (it, metadata) {
	    metadata.facade = it;
	    createNonEnumerableProperty(it, STATE, metadata);
	    return metadata;
	  };
	  get = function (it) {
	    return has(it, STATE) ? it[STATE] : {};
	  };
	  has$1 = function (it) {
	    return has(it, STATE);
	  };
	}

	var internalState = {
	  set: set,
	  get: get,
	  has: has$1,
	  enforce: enforce,
	  getterFor: getterFor
	};
	var internalState_1 = internalState.set;
	var internalState_2 = internalState.get;
	var internalState_3 = internalState.has;
	var internalState_4 = internalState.enforce;
	var internalState_5 = internalState.getterFor;

	var redefine = createCommonjsModule(function (module) {
	var getInternalState = internalState.get;
	var enforceInternalState = internalState.enforce;
	var TEMPLATE = String(String).split('String');

	(module.exports = function (O, key, value, options) {
	  var unsafe = options ? !!options.unsafe : false;
	  var simple = options ? !!options.enumerable : false;
	  var noTargetGet = options ? !!options.noTargetGet : false;
	  var state;
	  if (typeof value == 'function') {
	    if (typeof key == 'string' && !has(value, 'name')) {
	      createNonEnumerableProperty(value, 'name', key);
	    }
	    state = enforceInternalState(value);
	    if (!state.source) {
	      state.source = TEMPLATE.join(typeof key == 'string' ? key : '');
	    }
	  }
	  if (O === global_1) {
	    if (simple) { O[key] = value; }
	    else { setGlobal(key, value); }
	    return;
	  } else if (!unsafe) {
	    delete O[key];
	  } else if (!noTargetGet && O[key]) {
	    simple = true;
	  }
	  if (simple) { O[key] = value; }
	  else { createNonEnumerableProperty(O, key, value); }
	// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
	})(Function.prototype, 'toString', function toString() {
	  return typeof this == 'function' && getInternalState(this).source || inspectSource(this);
	});
	});

	var path = global_1;

	var aFunction = function (variable) {
	  return typeof variable == 'function' ? variable : undefined;
	};

	var getBuiltIn = function (namespace, method) {
	  return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace])
	    : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
	};

	var ceil = Math.ceil;
	var floor = Math.floor;

	// `ToInteger` abstract operation
	// https://tc39.es/ecma262/#sec-tointeger
	var toInteger = function (argument) {
	  return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
	};

	var min = Math.min;

	// `ToLength` abstract operation
	// https://tc39.es/ecma262/#sec-tolength
	var toLength = function (argument) {
	  return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
	};

	var max = Math.max;
	var min$1 = Math.min;

	// Helper for a popular repeating case of the spec:
	// Let integer be ? ToInteger(index).
	// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
	var toAbsoluteIndex = function (index, length) {
	  var integer = toInteger(index);
	  return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
	};

	// `Array.prototype.{ indexOf, includes }` methods implementation
	var createMethod = function (IS_INCLUDES) {
	  return function ($this, el, fromIndex) {
	    var O = toIndexedObject($this);
	    var length = toLength(O.length);
	    var index = toAbsoluteIndex(fromIndex, length);
	    var value;
	    // Array#includes uses SameValueZero equality algorithm
	    // eslint-disable-next-line no-self-compare
	    if (IS_INCLUDES && el != el) { while (length > index) {
	      value = O[index++];
	      // eslint-disable-next-line no-self-compare
	      if (value != value) { return true; }
	    // Array#indexOf ignores holes, Array#includes - not
	    } } else { for (;length > index; index++) {
	      if ((IS_INCLUDES || index in O) && O[index] === el) { return IS_INCLUDES || index || 0; }
	    } } return !IS_INCLUDES && -1;
	  };
	};

	var arrayIncludes = {
	  // `Array.prototype.includes` method
	  // https://tc39.es/ecma262/#sec-array.prototype.includes
	  includes: createMethod(true),
	  // `Array.prototype.indexOf` method
	  // https://tc39.es/ecma262/#sec-array.prototype.indexof
	  indexOf: createMethod(false)
	};
	var arrayIncludes_1 = arrayIncludes.includes;
	var arrayIncludes_2 = arrayIncludes.indexOf;

	var indexOf = arrayIncludes.indexOf;


	var objectKeysInternal = function (object, names) {
	  var O = toIndexedObject(object);
	  var i = 0;
	  var result = [];
	  var key;
	  for (key in O) { !has(hiddenKeys, key) && has(O, key) && result.push(key); }
	  // Don't enum bug & hidden keys
	  while (names.length > i) { if (has(O, key = names[i++])) {
	    ~indexOf(result, key) || result.push(key);
	  } }
	  return result;
	};

	// IE8- don't enum bug keys
	var enumBugKeys = [
	  'constructor',
	  'hasOwnProperty',
	  'isPrototypeOf',
	  'propertyIsEnumerable',
	  'toLocaleString',
	  'toString',
	  'valueOf'
	];

	var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype');

	// `Object.getOwnPropertyNames` method
	// https://tc39.es/ecma262/#sec-object.getownpropertynames
	var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
	  return objectKeysInternal(O, hiddenKeys$1);
	};

	var objectGetOwnPropertyNames = {
		f: f$3
	};

	var f$4 = Object.getOwnPropertySymbols;

	var objectGetOwnPropertySymbols = {
		f: f$4
	};

	// all object keys, includes non-enumerable and symbols
	var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
	  var keys = objectGetOwnPropertyNames.f(anObject(it));
	  var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
	  return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
	};

	var copyConstructorProperties = function (target, source) {
	  var keys = ownKeys(source);
	  var defineProperty = objectDefineProperty.f;
	  var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
	  for (var i = 0; i < keys.length; i++) {
	    var key = keys[i];
	    if (!has(target, key)) { defineProperty(target, key, getOwnPropertyDescriptor(source, key)); }
	  }
	};

	var replacement = /#|\.prototype\./;

	var isForced = function (feature, detection) {
	  var value = data[normalize(feature)];
	  return value == POLYFILL ? true
	    : value == NATIVE ? false
	    : typeof detection == 'function' ? fails(detection)
	    : !!detection;
	};

	var normalize = isForced.normalize = function (string) {
	  return String(string).replace(replacement, '.').toLowerCase();
	};

	var data = isForced.data = {};
	var NATIVE = isForced.NATIVE = 'N';
	var POLYFILL = isForced.POLYFILL = 'P';

	var isForced_1 = isForced;

	var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;






	/*
	  options.target      - name of the target object
	  options.global      - target is the global object
	  options.stat        - export as static methods of target
	  options.proto       - export as prototype methods of target
	  options.real        - real prototype method for the `pure` version
	  options.forced      - export even if the native feature is available
	  options.bind        - bind methods to the target, required for the `pure` version
	  options.wrap        - wrap constructors to preventing global pollution, required for the `pure` version
	  options.unsafe      - use the simple assignment of property instead of delete + defineProperty
	  options.sham        - add a flag to not completely full polyfills
	  options.enumerable  - export as enumerable property
	  options.noTargetGet - prevent calling a getter on target
	*/
	var _export = function (options, source) {
	  var TARGET = options.target;
	  var GLOBAL = options.global;
	  var STATIC = options.stat;
	  var FORCED, target, key, targetProperty, sourceProperty, descriptor;
	  if (GLOBAL) {
	    target = global_1;
	  } else if (STATIC) {
	    target = global_1[TARGET] || setGlobal(TARGET, {});
	  } else {
	    target = (global_1[TARGET] || {}).prototype;
	  }
	  if (target) { for (key in source) {
	    sourceProperty = source[key];
	    if (options.noTargetGet) {
	      descriptor = getOwnPropertyDescriptor$1(target, key);
	      targetProperty = descriptor && descriptor.value;
	    } else { targetProperty = target[key]; }
	    FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
	    // contained in target
	    if (!FORCED && targetProperty !== undefined) {
	      if (typeof sourceProperty === typeof targetProperty) { continue; }
	      copyConstructorProperties(sourceProperty, targetProperty);
	    }
	    // add a flag to not completely full polyfills
	    if (options.sham || (targetProperty && targetProperty.sham)) {
	      createNonEnumerableProperty(sourceProperty, 'sham', true);
	    }
	    // extend global
	    redefine(target, key, sourceProperty, options);
	  } }
	};

	var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
	  // Chrome 38 Symbol has incorrect toString conversion
	  // eslint-disable-next-line no-undef
	  return !String(Symbol());
	});

	var useSymbolAsUid = nativeSymbol
	  // eslint-disable-next-line no-undef
	  && !Symbol.sham
	  // eslint-disable-next-line no-undef
	  && typeof Symbol.iterator == 'symbol';

	var WellKnownSymbolsStore = shared('wks');
	var Symbol$1 = global_1.Symbol;
	var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid;

	var wellKnownSymbol = function (name) {
	  if (!has(WellKnownSymbolsStore, name)) {
	    if (nativeSymbol && has(Symbol$1, name)) { WellKnownSymbolsStore[name] = Symbol$1[name]; }
	    else { WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); }
	  } return WellKnownSymbolsStore[name];
	};

	// `Object.keys` method
	// https://tc39.es/ecma262/#sec-object.keys
	var objectKeys = Object.keys || function keys(O) {
	  return objectKeysInternal(O, enumBugKeys);
	};

	// `Object.defineProperties` method
	// https://tc39.es/ecma262/#sec-object.defineproperties
	var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) {
	  anObject(O);
	  var keys = objectKeys(Properties);
	  var length = keys.length;
	  var index = 0;
	  var key;
	  while (length > index) { objectDefineProperty.f(O, key = keys[index++], Properties[key]); }
	  return O;
	};

	var html = getBuiltIn('document', 'documentElement');

	var GT = '>';
	var LT = '<';
	var PROTOTYPE = 'prototype';
	var SCRIPT = 'script';
	var IE_PROTO = sharedKey('IE_PROTO');

	var EmptyConstructor = function () { /* empty */ };

	var scriptTag = function (content) {
	  return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
	};

	// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
	var NullProtoObjectViaActiveX = function (activeXDocument) {
	  activeXDocument.write(scriptTag(''));
	  activeXDocument.close();
	  var temp = activeXDocument.parentWindow.Object;
	  activeXDocument = null; // avoid memory leak
	  return temp;
	};

	// Create object with fake `null` prototype: use iframe Object with cleared prototype
	var NullProtoObjectViaIFrame = function () {
	  // Thrash, waste and sodomy: IE GC bug
	  var iframe = documentCreateElement('iframe');
	  var JS = 'java' + SCRIPT + ':';
	  var iframeDocument;
	  iframe.style.display = 'none';
	  html.appendChild(iframe);
	  // https://github.com/zloirock/core-js/issues/475
	  iframe.src = String(JS);
	  iframeDocument = iframe.contentWindow.document;
	  iframeDocument.open();
	  iframeDocument.write(scriptTag('document.F=Object'));
	  iframeDocument.close();
	  return iframeDocument.F;
	};

	// Check for document.domain and active x support
	// No need to use active x approach when document.domain is not set
	// see https://github.com/es-shims/es5-shim/issues/150
	// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
	// avoid IE GC bug
	var activeXDocument;
	var NullProtoObject = function () {
	  try {
	    /* global ActiveXObject */
	    activeXDocument = document.domain && new ActiveXObject('htmlfile');
	  } catch (error) { /* ignore */ }
	  NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();
	  var length = enumBugKeys.length;
	  while (length--) { delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; }
	  return NullProtoObject();
	};

	hiddenKeys[IE_PROTO] = true;

	// `Object.create` method
	// https://tc39.es/ecma262/#sec-object.create
	var objectCreate = Object.create || function create(O, Properties) {
	  var result;
	  if (O !== null) {
	    EmptyConstructor[PROTOTYPE] = anObject(O);
	    result = new EmptyConstructor();
	    EmptyConstructor[PROTOTYPE] = null;
	    // add "__proto__" for Object.getPrototypeOf polyfill
	    result[IE_PROTO] = O;
	  } else { result = NullProtoObject(); }
	  return Properties === undefined ? result : objectDefineProperties(result, Properties);
	};

	var UNSCOPABLES = wellKnownSymbol('unscopables');
	var ArrayPrototype = Array.prototype;

	// Array.prototype[@@unscopables]
	// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
	if (ArrayPrototype[UNSCOPABLES] == undefined) {
	  objectDefineProperty.f(ArrayPrototype, UNSCOPABLES, {
	    configurable: true,
	    value: objectCreate(null)
	  });
	}

	// add a key to Array.prototype[@@unscopables]
	var addToUnscopables = function (key) {
	  ArrayPrototype[UNSCOPABLES][key] = true;
	};

	var defineProperty = Object.defineProperty;
	var cache = {};

	var thrower = function (it) { throw it; };

	var arrayMethodUsesToLength = function (METHOD_NAME, options) {
	  if (has(cache, METHOD_NAME)) { return cache[METHOD_NAME]; }
	  if (!options) { options = {}; }
	  var method = [][METHOD_NAME];
	  var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false;
	  var argument0 = has(options, 0) ? options[0] : thrower;
	  var argument1 = has(options, 1) ? options[1] : undefined;

	  return cache[METHOD_NAME] = !!method && !fails(function () {
	    if (ACCESSORS && !descriptors) { return true; }
	    var O = { length: -1 };

	    if (ACCESSORS) { defineProperty(O, 1, { enumerable: true, get: thrower }); }
	    else { O[1] = 1; }

	    method.call(O, argument0, argument1);
	  });
	};

	'use strict';

	var $includes = arrayIncludes.includes;



	var USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });

	// `Array.prototype.includes` method
	// https://tc39.es/ecma262/#sec-array.prototype.includes
	_export({ target: 'Array', proto: true, forced: !USES_TO_LENGTH }, {
	  includes: function includes(el /* , fromIndex = 0 */) {
	    return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
	  }
	});

	// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
	addToUnscopables('includes');

	var es_array_includes = {

	};

	var aFunction$1 = function (it) {
	  if (typeof it != 'function') {
	    throw TypeError(String(it) + ' is not a function');
	  } return it;
	};

	// optional / simple context binding
	var functionBindContext = function (fn, that, length) {
	  aFunction$1(fn);
	  if (that === undefined) { return fn; }
	  switch (length) {
	    case 0: return function () {
	      return fn.call(that);
	    };
	    case 1: return function (a) {
	      return fn.call(that, a);
	    };
	    case 2: return function (a, b) {
	      return fn.call(that, a, b);
	    };
	    case 3: return function (a, b, c) {
	      return fn.call(that, a, b, c);
	    };
	  }
	  return function (/* ...args */) {
	    return fn.apply(that, arguments);
	  };
	};

	var call = Function.call;

	var entryUnbind = function (CONSTRUCTOR, METHOD, length) {
	  return functionBindContext(call, global_1[CONSTRUCTOR].prototype[METHOD], length);
	};

	var includes = entryUnbind('Array', 'includes');

	var includes$1 = includes;

	// `ToObject` abstract operation
	// https://tc39.es/ecma262/#sec-toobject
	var toObject = function (argument) {
	  return Object(requireObjectCoercible(argument));
	};

	// `IsArray` abstract operation
	// https://tc39.es/ecma262/#sec-isarray
	var isArray = Array.isArray || function isArray(arg) {
	  return classofRaw(arg) == 'Array';
	};

	var SPECIES = wellKnownSymbol('species');

	// `ArraySpeciesCreate` abstract operation
	// https://tc39.es/ecma262/#sec-arrayspeciescreate
	var arraySpeciesCreate = function (originalArray, length) {
	  var C;
	  if (isArray(originalArray)) {
	    C = originalArray.constructor;
	    // cross-realm fallback
	    if (typeof C == 'function' && (C === Array || isArray(C.prototype))) { C = undefined; }
	    else if (isObject(C)) {
	      C = C[SPECIES];
	      if (C === null) { C = undefined; }
	    }
	  } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
	};

	var push = [].push;

	// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterOut }` methods implementation
	var createMethod$1 = function (TYPE) {
	  var IS_MAP = TYPE == 1;
	  var IS_FILTER = TYPE == 2;
	  var IS_SOME = TYPE == 3;
	  var IS_EVERY = TYPE == 4;
	  var IS_FIND_INDEX = TYPE == 6;
	  var IS_FILTER_OUT = TYPE == 7;
	  var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
	  return function ($this, callbackfn, that, specificCreate) {
	    var O = toObject($this);
	    var self = indexedObject(O);
	    var boundFunction = functionBindContext(callbackfn, that, 3);
	    var length = toLength(self.length);
	    var index = 0;
	    var create = specificCreate || arraySpeciesCreate;
	    var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_OUT ? create($this, 0) : undefined;
	    var value, result;
	    for (;length > index; index++) { if (NO_HOLES || index in self) {
	      value = self[index];
	      result = boundFunction(value, index, O);
	      if (TYPE) {
	        if (IS_MAP) { target[index] = result; } // map
	        else if (result) { switch (TYPE) {
	          case 3: return true;              // some
	          case 5: return value;             // find
	          case 6: return index;             // findIndex
	          case 2: push.call(target, value); // filter
	        } } else { switch (TYPE) {
	          case 4: return false;             // every
	          case 7: push.call(target, value); // filterOut
	        } }
	      }
	    } }
	    return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
	  };
	};

	var arrayIteration = {
	  // `Array.prototype.forEach` method
	  // https://tc39.es/ecma262/#sec-array.prototype.foreach
	  forEach: createMethod$1(0),
	  // `Array.prototype.map` method
	  // https://tc39.es/ecma262/#sec-array.prototype.map
	  map: createMethod$1(1),
	  // `Array.prototype.filter` method
	  // https://tc39.es/ecma262/#sec-array.prototype.filter
	  filter: createMethod$1(2),
	  // `Array.prototype.some` method
	  // https://tc39.es/ecma262/#sec-array.prototype.some
	  some: createMethod$1(3),
	  // `Array.prototype.every` method
	  // https://tc39.es/ecma262/#sec-array.prototype.every
	  every: createMethod$1(4),
	  // `Array.prototype.find` method
	  // https://tc39.es/ecma262/#sec-array.prototype.find
	  find: createMethod$1(5),
	  // `Array.prototype.findIndex` method
	  // https://tc39.es/ecma262/#sec-array.prototype.findIndex
	  findIndex: createMethod$1(6),
	  // `Array.prototype.filterOut` method
	  // https://github.com/tc39/proposal-array-filtering
	  filterOut: createMethod$1(7)
	};
	var arrayIteration_1 = arrayIteration.forEach;
	var arrayIteration_2 = arrayIteration.map;
	var arrayIteration_3 = arrayIteration.filter;
	var arrayIteration_4 = arrayIteration.some;
	var arrayIteration_5 = arrayIteration.every;
	var arrayIteration_6 = arrayIteration.find;
	var arrayIteration_7 = arrayIteration.findIndex;
	var arrayIteration_8 = arrayIteration.filterOut;

	'use strict';

	var $find = arrayIteration.find;



	var FIND = 'find';
	var SKIPS_HOLES = true;

	var USES_TO_LENGTH$1 = arrayMethodUsesToLength(FIND);

	// Shouldn't skip holes
	if (FIND in []) { Array(1)[FIND](function () { SKIPS_HOLES = false; }); }

	// `Array.prototype.find` method
	// https://tc39.es/ecma262/#sec-array.prototype.find
	_export({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH$1 }, {
	  find: function find(callbackfn /* , that = undefined */) {
	    return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
	  }
	});

	// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
	addToUnscopables(FIND);

	var es_array_find = {

	};

	var find = entryUnbind('Array', 'find');

	var find$1 = find;

	// `String.prototype.{ codePointAt, at }` methods implementation
	var createMethod$2 = function (CONVERT_TO_STRING) {
	  return function ($this, pos) {
	    var S = String(requireObjectCoercible($this));
	    var position = toInteger(pos);
	    var size = S.length;
	    var first, second;
	    if (position < 0 || position >= size) { return CONVERT_TO_STRING ? '' : undefined; }
	    first = S.charCodeAt(position);
	    return first < 0xD800 || first > 0xDBFF || position + 1 === size
	      || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
	        ? CONVERT_TO_STRING ? S.charAt(position) : first
	        : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
	  };
	};

	var stringMultibyte = {
	  // `String.prototype.codePointAt` method
	  // https://tc39.es/ecma262/#sec-string.prototype.codepointat
	  codeAt: createMethod$2(false),
	  // `String.prototype.at` method
	  // https://github.com/mathiasbynens/String.prototype.at
	  charAt: createMethod$2(true)
	};
	var stringMultibyte_1 = stringMultibyte.codeAt;
	var stringMultibyte_2 = stringMultibyte.charAt;

	var correctPrototypeGetter = !fails(function () {
	  function F() { /* empty */ }
	  F.prototype.constructor = null;
	  return Object.getPrototypeOf(new F()) !== F.prototype;
	});

	var IE_PROTO$1 = sharedKey('IE_PROTO');
	var ObjectPrototype = Object.prototype;

	// `Object.getPrototypeOf` method
	// https://tc39.es/ecma262/#sec-object.getprototypeof
	var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) {
	  O = toObject(O);
	  if (has(O, IE_PROTO$1)) { return O[IE_PROTO$1]; }
	  if (typeof O.constructor == 'function' && O instanceof O.constructor) {
	    return O.constructor.prototype;
	  } return O instanceof Object ? ObjectPrototype : null;
	};

	'use strict';







	var ITERATOR = wellKnownSymbol('iterator');
	var BUGGY_SAFARI_ITERATORS = false;

	var returnThis = function () { return this; };

	// `%IteratorPrototype%` object
	// https://tc39.es/ecma262/#sec-%iteratorprototype%-object
	var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;

	if ([].keys) {
	  arrayIterator = [].keys();
	  // Safari 8 has buggy iterators w/o `next`
	  if (!('next' in arrayIterator)) { BUGGY_SAFARI_ITERATORS = true; }
	  else {
	    PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator));
	    if (PrototypeOfArrayIteratorPrototype !== Object.prototype) { IteratorPrototype = PrototypeOfArrayIteratorPrototype; }
	  }
	}

	var NEW_ITERATOR_PROTOTYPE = IteratorPrototype == undefined || fails(function () {
	  var test = {};
	  // FF44- legacy iterators case
	  return IteratorPrototype[ITERATOR].call(test) !== test;
	});

	if (NEW_ITERATOR_PROTOTYPE) { IteratorPrototype = {}; }

	// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
	if ((!isPure || NEW_ITERATOR_PROTOTYPE) && !has(IteratorPrototype, ITERATOR)) {
	  createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);
	}

	var iteratorsCore = {
	  IteratorPrototype: IteratorPrototype,
	  BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
	};
	var iteratorsCore_1 = iteratorsCore.IteratorPrototype;
	var iteratorsCore_2 = iteratorsCore.BUGGY_SAFARI_ITERATORS;

	var defineProperty$1 = objectDefineProperty.f;



	var TO_STRING_TAG = wellKnownSymbol('toStringTag');

	var setToStringTag = function (it, TAG, STATIC) {
	  if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
	    defineProperty$1(it, TO_STRING_TAG, { configurable: true, value: TAG });
	  }
	};

	var iterators = {};

	'use strict';
	var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;





	var returnThis$1 = function () { return this; };

	var createIteratorConstructor = function (IteratorConstructor, NAME, next) {
	  var TO_STRING_TAG = NAME + ' Iterator';
	  IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) });
	  setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
	  iterators[TO_STRING_TAG] = returnThis$1;
	  return IteratorConstructor;
	};

	var aPossiblePrototype = function (it) {
	  if (!isObject(it) && it !== null) {
	    throw TypeError("Can't set " + String(it) + ' as a prototype');
	  } return it;
	};

	// `Object.setPrototypeOf` method
	// https://tc39.es/ecma262/#sec-object.setprototypeof
	// Works with __proto__ only. Old v8 can't work with null proto objects.
	/* eslint-disable no-proto */
	var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
	  var CORRECT_SETTER = false;
	  var test = {};
	  var setter;
	  try {
	    setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
	    setter.call(test, []);
	    CORRECT_SETTER = test instanceof Array;
	  } catch (error) { /* empty */ }
	  return function setPrototypeOf(O, proto) {
	    anObject(O);
	    aPossiblePrototype(proto);
	    if (CORRECT_SETTER) { setter.call(O, proto); }
	    else { O.__proto__ = proto; }
	    return O;
	  };
	}() : undefined);

	'use strict';












	var IteratorPrototype$2 = iteratorsCore.IteratorPrototype;
	var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS;
	var ITERATOR$1 = wellKnownSymbol('iterator');
	var KEYS = 'keys';
	var VALUES = 'values';
	var ENTRIES = 'entries';

	var returnThis$2 = function () { return this; };

	var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
	  createIteratorConstructor(IteratorConstructor, NAME, next);

	  var getIterationMethod = function (KIND) {
	    if (KIND === DEFAULT && defaultIterator) { return defaultIterator; }
	    if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) { return IterablePrototype[KIND]; }
	    switch (KIND) {
	      case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
	      case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
	      case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
	    } return function () { return new IteratorConstructor(this); };
	  };

	  var TO_STRING_TAG = NAME + ' Iterator';
	  var INCORRECT_VALUES_NAME = false;
	  var IterablePrototype = Iterable.prototype;
	  var nativeIterator = IterablePrototype[ITERATOR$1]
	    || IterablePrototype['@@iterator']
	    || DEFAULT && IterablePrototype[DEFAULT];
	  var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT);
	  var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
	  var CurrentIteratorPrototype, methods, KEY;

	  // fix native
	  if (anyNativeIterator) {
	    CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable()));
	    if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) {
	      if (!isPure && objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype$2) {
	        if (objectSetPrototypeOf) {
	          objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype$2);
	        } else if (typeof CurrentIteratorPrototype[ITERATOR$1] != 'function') {
	          createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR$1, returnThis$2);
	        }
	      }
	      // Set @@toStringTag to native iterators
	      setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
	      if (isPure) { iterators[TO_STRING_TAG] = returnThis$2; }
	    }
	  }

	  // fix Array#{values, @@iterator}.name in V8 / FF
	  if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
	    INCORRECT_VALUES_NAME = true;
	    defaultIterator = function values() { return nativeIterator.call(this); };
	  }

	  // define iterator
	  if ((!isPure || FORCED) && IterablePrototype[ITERATOR$1] !== defaultIterator) {
	    createNonEnumerableProperty(IterablePrototype, ITERATOR$1, defaultIterator);
	  }
	  iterators[NAME] = defaultIterator;

	  // export additional methods
	  if (DEFAULT) {
	    methods = {
	      values: getIterationMethod(VALUES),
	      keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
	      entries: getIterationMethod(ENTRIES)
	    };
	    if (FORCED) { for (KEY in methods) {
	      if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
	        redefine(IterablePrototype, KEY, methods[KEY]);
	      }
	    } } else { _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods); }
	  }

	  return methods;
	};

	'use strict';
	var charAt = stringMultibyte.charAt;



	var STRING_ITERATOR = 'String Iterator';
	var setInternalState = internalState.set;
	var getInternalState = internalState.getterFor(STRING_ITERATOR);

	// `String.prototype[@@iterator]` method
	// https://tc39.es/ecma262/#sec-string.prototype-@@iterator
	defineIterator(String, 'String', function (iterated) {
	  setInternalState(this, {
	    type: STRING_ITERATOR,
	    string: String(iterated),
	    index: 0
	  });
	// `%StringIteratorPrototype%.next` method
	// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
	}, function next() {
	  var state = getInternalState(this);
	  var string = state.string;
	  var index = state.index;
	  var point;
	  if (index >= string.length) { return { value: undefined, done: true }; }
	  point = charAt(string, index);
	  state.index += point.length;
	  return { value: point, done: false };
	});

	var es_string_iterator = {

	};

	var iteratorClose = function (iterator) {
	  var returnMethod = iterator['return'];
	  if (returnMethod !== undefined) {
	    return anObject(returnMethod.call(iterator)).value;
	  }
	};

	// call something on iterator step with safe closing on error
	var callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
	  try {
	    return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
	  // 7.4.6 IteratorClose(iterator, completion)
	  } catch (error) {
	    iteratorClose(iterator);
	    throw error;
	  }
	};

	var ITERATOR$2 = wellKnownSymbol('iterator');
	var ArrayPrototype$1 = Array.prototype;

	// check on default Array iterator
	var isArrayIteratorMethod = function (it) {
	  return it !== undefined && (iterators.Array === it || ArrayPrototype$1[ITERATOR$2] === it);
	};

	'use strict';




	var createProperty = function (object, key, value) {
	  var propertyKey = toPrimitive(key);
	  if (propertyKey in object) { objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value)); }
	  else { object[propertyKey] = value; }
	};

	var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag');
	var test = {};

	test[TO_STRING_TAG$1] = 'z';

	var toStringTagSupport = String(test) === '[object z]';

	var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag');
	// ES3 wrong here
	var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';

	// fallback for IE11 Script Access Denied error
	var tryGet = function (it, key) {
	  try {
	    return it[key];
	  } catch (error) { /* empty */ }
	};

	// getting tag from ES6+ `Object.prototype.toString`
	var classof = toStringTagSupport ? classofRaw : function (it) {
	  var O, tag, result;
	  return it === undefined ? 'Undefined' : it === null ? 'Null'
	    // @@toStringTag case
	    : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$2)) == 'string' ? tag
	    // builtinTag case
	    : CORRECT_ARGUMENTS ? classofRaw(O)
	    // ES3 arguments fallback
	    : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
	};

	var ITERATOR$3 = wellKnownSymbol('iterator');

	var getIteratorMethod = function (it) {
	  if (it != undefined) { return it[ITERATOR$3]
	    || it['@@iterator']
	    || iterators[classof(it)]; }
	};

	'use strict';








	// `Array.from` method implementation
	// https://tc39.es/ecma262/#sec-array.from
	var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
	  var O = toObject(arrayLike);
	  var C = typeof this == 'function' ? this : Array;
	  var argumentsLength = arguments.length;
	  var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
	  var mapping = mapfn !== undefined;
	  var iteratorMethod = getIteratorMethod(O);
	  var index = 0;
	  var length, result, step, iterator, next, value;
	  if (mapping) { mapfn = functionBindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); }
	  // if the target is not iterable or it's an array with the default iterator - use a simple case
	  if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {
	    iterator = iteratorMethod.call(O);
	    next = iterator.next;
	    result = new C();
	    for (;!(step = next.call(iterator)).done; index++) {
	      value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
	      createProperty(result, index, value);
	    }
	  } else {
	    length = toLength(O.length);
	    result = new C(length);
	    for (;length > index; index++) {
	      value = mapping ? mapfn(O[index], index) : O[index];
	      createProperty(result, index, value);
	    }
	  }
	  result.length = index;
	  return result;
	};

	var ITERATOR$4 = wellKnownSymbol('iterator');
	var SAFE_CLOSING = false;

	try {
	  var called = 0;
	  var iteratorWithReturn = {
	    next: function () {
	      return { done: !!called++ };
	    },
	    'return': function () {
	      SAFE_CLOSING = true;
	    }
	  };
	  iteratorWithReturn[ITERATOR$4] = function () {
	    return this;
	  };
	  // eslint-disable-next-line no-throw-literal
	  Array.from(iteratorWithReturn, function () { throw 2; });
	} catch (error) { /* empty */ }

	var checkCorrectnessOfIteration = function (exec, SKIP_CLOSING) {
	  if (!SKIP_CLOSING && !SAFE_CLOSING) { return false; }
	  var ITERATION_SUPPORT = false;
	  try {
	    var object = {};
	    object[ITERATOR$4] = function () {
	      return {
	        next: function () {
	          return { done: ITERATION_SUPPORT = true };
	        }
	      };
	    };
	    exec(object);
	  } catch (error) { /* empty */ }
	  return ITERATION_SUPPORT;
	};

	var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
	  Array.from(iterable);
	});

	// `Array.from` method
	// https://tc39.es/ecma262/#sec-array.from
	_export({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
	  from: arrayFrom
	});

	var es_array_from = {

	};

	var from_1 = path.Array.from;

	var from_1$1 = from_1;

	'use strict';

	var $findIndex = arrayIteration.findIndex;



	var FIND_INDEX = 'findIndex';
	var SKIPS_HOLES$1 = true;

	var USES_TO_LENGTH$2 = arrayMethodUsesToLength(FIND_INDEX);

	// Shouldn't skip holes
	if (FIND_INDEX in []) { Array(1)[FIND_INDEX](function () { SKIPS_HOLES$1 = false; }); }

	// `Array.prototype.findIndex` method
	// https://tc39.es/ecma262/#sec-array.prototype.findindex
	_export({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 || !USES_TO_LENGTH$2 }, {
	  findIndex: function findIndex(callbackfn /* , that = undefined */) {
	    return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
	  }
	});

	// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables
	addToUnscopables(FIND_INDEX);

	var es_array_findIndex = {

	};

	var findIndex = entryUnbind('Array', 'findIndex');

	var findIndex$1 = findIndex;

	var base64 = createCommonjsModule(function (module, exports) {
	(function() {

	    /**
	     * version: 0.3.0
	     * git://github.com/davidchambers/Base64.js.git
	     */

	    var object =  true ? exports : 0; // #8: web workers
	    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

	    function InvalidCharacterError(message) {
	        this.message = message;
	    }

	    InvalidCharacterError.prototype = new Error;
	    InvalidCharacterError.prototype.name = 'InvalidCharacterError';

	    // encoder
	    // [https://gist.github.com/999166] by [https://github.com/nignag]
	    object.btoa || (
	        object.btoa = function(input) {
	            var str = String(input);
	            for (
	                // initialize result and counter
	                var block, charCode, idx = 0, map = chars, output = '';
	                // if the next str index does not exist:
	                //   change the mapping table to "="
	                //   check if d has no fractional digits
	                str.charAt(idx | 0) || (map = '=', idx % 1);
	                // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
	                output += map.charAt(63 & block >> 8 - idx % 1 * 8)
	            ) {
	                charCode = str.charCodeAt(idx += 3 / 4);
	                if (charCode > 0xFF) {
	                    throw new InvalidCharacterError('\'btoa\' failed: The string to be encoded contains characters outside of the Latin1 range.');
	                }
	                block = block << 8 | charCode;
	            }
	            return output;
	        });

	    // decoder
	    // [https://gist.github.com/1020396] by [https://github.com/atk]
	    object.atob || (
	        object.atob = function(input) {
	            var str = String(input).replace(/=+$/, '');
	            if (str.length % 4 == 1) {
	                throw new InvalidCharacterError('\'atob\' failed: The string to be decoded is not correctly encoded.');
	            }
	            for (
	                // initialize result and counters
	                var bc = 0, bs, buffer, idx = 0, output = '';
	                // get next character
	                // eslint-disable-next-line no-cond-assign
	                buffer = str.charAt(idx++);
	                // character found in table? initialize bit storage and add its ascii value;
	                ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
	                // and if not first of each 4 characters,
	                // convert the first 8 bits to one ascii character
	                bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
	            ) {
	                // try to find character in table (0-63, not found => -1)
	                buffer = chars.indexOf(buffer);
	            }
	            return output;
	        });

	}());
	});

	// `Number.isNaN` method
	// https://tc39.es/ecma262/#sec-number.isnan
	_export({ target: 'Number', stat: true }, {
	  isNaN: function isNaN(number) {
	    // eslint-disable-next-line no-self-compare
	    return number != number;
	  }
	});

	var es_number_isNan = {

	};

	var isNan = path.Number.isNaN;

	var isNan$1 = isNan;

	var globalIsFinite = global_1.isFinite;

	// `Number.isFinite` method
	// https://tc39.es/ecma262/#sec-number.isfinite
	var numberIsFinite = Number.isFinite || function isFinite(it) {
	  return typeof it == 'number' && globalIsFinite(it);
	};

	// `Number.isFinite` method
	// https://tc39.es/ecma262/#sec-number.isfinite
	_export({ target: 'Number', stat: true }, { isFinite: numberIsFinite });

	var es_number_isFinite = {

	};

	var _isFinite = path.Number.isFinite;

	var _isFinite$1 = _isFinite;

	var MATCH = wellKnownSymbol('match');

	// `IsRegExp` abstract operation
	// https://tc39.es/ecma262/#sec-isregexp
	var isRegexp = function (it) {
	  var isRegExp;
	  return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp');
	};

	var notARegexp = function (it) {
	  if (isRegexp(it)) {
	    throw TypeError("The method doesn't accept regular expressions");
	  } return it;
	};

	var MATCH$1 = wellKnownSymbol('match');

	var correctIsRegexpLogic = function (METHOD_NAME) {
	  var regexp = /./;
	  try {
	    '/./'[METHOD_NAME](regexp);
	  } catch (error1) {
	    try {
	      regexp[MATCH$1] = false;
	      return '/./'[METHOD_NAME](regexp);
	    } catch (error2) { /* empty */ }
	  } return false;
	};

	'use strict';





	// `String.prototype.includes` method
	// https://tc39.es/ecma262/#sec-string.prototype.includes
	_export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, {
	  includes: function includes(searchString /* , position = 0 */) {
	    return !!~String(requireObjectCoercible(this))
	      .indexOf(notARegexp(searchString), arguments.length > 1 ? arguments[1] : undefined);
	  }
	});

	var es_string_includes = {

	};

	var includes$2 = entryUnbind('String', 'includes');

	var includes$3 = includes$2;

	'use strict';

	var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;






	var nativeStartsWith = ''.startsWith;
	var min$2 = Math.min;

	var CORRECT_IS_REGEXP_LOGIC = correctIsRegexpLogic('startsWith');
	// https://github.com/zloirock/core-js/pull/702
	var MDN_POLYFILL_BUG = !isPure && !CORRECT_IS_REGEXP_LOGIC && !!function () {
	  var descriptor = getOwnPropertyDescriptor$2(String.prototype, 'startsWith');
	  return descriptor && !descriptor.writable;
	}();

	// `String.prototype.startsWith` method
	// https://tc39.es/ecma262/#sec-string.prototype.startswith
	_export({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {
	  startsWith: function startsWith(searchString /* , position = 0 */) {
	    var that = String(requireObjectCoercible(this));
	    notARegexp(searchString);
	    var index = toLength(min$2(arguments.length > 1 ? arguments[1] : undefined, that.length));
	    var search = String(searchString);
	    return nativeStartsWith
	      ? nativeStartsWith.call(that, search, index)
	      : that.slice(index, index + search.length) === search;
	  }
	});

	var es_string_startsWith = {

	};

	var startsWith = entryUnbind('String', 'startsWith');

	var startsWith$1 = startsWith;

	(function() {

	    if (typeof Uint8Array !== 'undefined' || typeof window === 'undefined') {
	        return;
	    }

	    function subarray(start, end) {
	        return this.slice(start, end);
	    }

	    function set_(array, offset) {

	        if (arguments.length < 2) {
	            offset = 0;
	        }
	        for (var i = 0, n = array.length; i < n; ++i, ++offset) {
	            this[offset] = array[i] & 0xFF;
	        }
	    }

	    // we need typed arrays
	    function TypedArray(arg1) {

	        var result;
	        if (typeof arg1 === 'number') {
	            result = new Array(arg1);
	            for (var i = 0; i < arg1; ++i) {
	                result[i] = 0;
	            }
	        } else {
	            result = arg1.slice(0);
	        }
	        result.subarray = subarray;
	        result.buffer = result;
	        result.byteLength = result.length;
	        result.set = set_;
	        if (typeof arg1 === 'object' && arg1.buffer) {
	            result.buffer = arg1.buffer;
	        }

	        return result;
	    }

	    window.Uint8Array = TypedArray;
	    window.Uint32Array = TypedArray;
	    window.Int32Array = TypedArray;
	})();

	// Declare shorthands to the most used math functions.
	var round = Math.round;
	var floor$1 = Math.floor;
	var PI = Math.PI;

	var scale = {

	    // Return the `value` from the `domain` interval scaled to the `range` interval.
	    linear: function(domain, range, value) {

	        var domainSpan = domain[1] - domain[0];
	        var rangeSpan = range[1] - range[0];
	        return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0;
	    }
	};

	var normalizeAngle = function(angle) {

	    return (angle % 360) + (angle < 0 ? 360 : 0);
	};

	var snapToGrid = function(value, gridSize) {

	    return gridSize * round(value / gridSize);
	};

	var toDeg = function(rad) {

	    return (180 * rad / PI) % 360;
	};

	var toRad = function(deg, over360) {

	    over360 = over360 || false;
	    deg = over360 ? deg : (deg % 360);
	    return deg * PI / 180;
	};

	// Return a random integer from the interval [min,max], inclusive.
	var random = function(min, max) {

	    if (max === undefined) {
	        // use first argument as max, min is 0
	        max = (min === undefined) ? 1 : min;
	        min = 0;

	    } else if (max < min) {
	        // switch max and min
	        var temp = min;
	        min = max;
	        max = temp;
	    }

	    return floor$1((Math.random() * (max - min + 1)) + min);
	};

	// @return the bearing (cardinal direction) of the line. For example N, W, or SE.

	var cos = Math.cos;
	var sin = Math.sin;
	var atan2 = Math.atan2;

	var bearing = function(p, q) {

	    var lat1 = toRad(p.y);
	    var lat2 = toRad(q.y);
	    var lon1 = p.x;
	    var lon2 = q.x;
	    var dLon = toRad(lon2 - lon1);
	    var y = sin(dLon) * cos(lat2);
	    var x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
	    var brng = toDeg(atan2(y, x));

	    var bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'];

	    var index = brng - 22.5;
	    if (index < 0)
	        { index += 360; }
	    index = parseInt(index / 45);

	    return bearings[index];
	};

	// @return {integer} length without sqrt
	// @note for applications where the exact length is not necessary (e.g. compare only)
	var squaredLength = function(start, end) {

	    var x0 = start.x;
	    var y0 = start.y;
	    var x1 = end.x;
	    var y1 = end.y;
	    return (x0 -= x1) * x0 + (y0 -= y1) * y0;
	};

	var length = function(start, end) {
	    return Math.sqrt(squaredLength(start, end));
	};

	/*
	    Point is the most basic object consisting of x/y coordinate.

	    Possible instantiations are:
	    * `Point(10, 20)`
	    * `new Point(10, 20)`
	    * `Point('10 20')`
	    * `Point(Point(10, 20))`
	*/

	var abs = Math.abs;
	var cos$1 = Math.cos;
	var sin$1 = Math.sin;
	var sqrt = Math.sqrt;
	var min$3 = Math.min;
	var max$1 = Math.max;
	var atan2$1 = Math.atan2;
	var round$1 = Math.round;
	var pow = Math.pow;
	var PI$1 = Math.PI;

	var Point = function(x, y) {

	    if (!(this instanceof Point)) {
	        return new Point(x, y);
	    }

	    if (typeof x === 'string') {
	        var xy = x.split(x.indexOf('@') === -1 ? ' ' : '@');
	        x = parseFloat(xy[0]);
	        y = parseFloat(xy[1]);

	    } else if (Object(x) === x) {
	        y = x.y;
	        x = x.x;
	    }

	    this.x = x === undefined ? 0 : x;
	    this.y = y === undefined ? 0 : y;
	};

	// Alternative constructor, from polar coordinates.
	// @param {number} Distance.
	// @param {number} Angle in radians.
	// @param {point} [optional] Origin.
	Point.fromPolar = function(distance, angle, origin) {

	    origin = new Point(origin);
	    var x = abs(distance * cos$1(angle));
	    var y = abs(distance * sin$1(angle));
	    var deg = normalizeAngle(toDeg(angle));

	    if (deg < 90) {
	        y = -y;

	    } else if (deg < 180) {
	        x = -x;
	        y = -y;

	    } else if (deg < 270) {
	        x = -x;
	    }

	    return new Point(origin.x + x, origin.y + y);
	};

	// Create a point with random coordinates that fall into the range `[x1, x2]` and `[y1, y2]`.
	Point.random = function(x1, x2, y1, y2) {

	    return new Point(random(x1, x2), random(y1, y2));
	};

	Point.prototype = {

	    chooseClosest: function(points) {

	        var n = points.length;
	        if (n === 1) { return new Point(points[0]); }
	        var closest = null;
	        var minSqrDistance = Infinity;
	        for (var i = 0; i < n; i++) {
	            var p = new Point(points[i]);
	            var sqrDistance = this.squaredDistance(p);
	            if (sqrDistance < minSqrDistance) {
	                closest = p;
	                minSqrDistance = sqrDistance;
	            }
	        }
	        return closest;
	    },

	    // If point lies outside rectangle `r`, return the nearest point on the boundary of rect `r`,
	    // otherwise return point itself.
	    // (see Squeak Smalltalk, Point>>adhereTo:)
	    adhereToRect: function(r) {

	        if (r.containsPoint(this)) {
	            return this;
	        }

	        this.x = min$3(max$1(this.x, r.x), r.x + r.width);
	        this.y = min$3(max$1(this.y, r.y), r.y + r.height);
	        return this;
	    },

	    // Compute the angle between vector from me to p1 and the vector from me to p2.
	    // ordering of points p1 and p2 is important!
	    // theta function's angle convention:
	    // returns angles between 0 and 180 when the angle is counterclockwise
	    // returns angles between 180 and 360 to convert clockwise angles into counterclockwise ones
	    // returns NaN if any of the points p1, p2 is coincident with this point
	    angleBetween: function(p1, p2) {

	        var angleBetween = (this.equals(p1) || this.equals(p2)) ? NaN : (this.theta(p2) - this.theta(p1));

	        if (angleBetween < 0) {
	            angleBetween += 360; // correction to keep angleBetween between 0 and 360
	        }

	        return angleBetween;
	    },

	    // Return the bearing between me and the given point.
	    bearing: function(point) {
	        return bearing(this, point);
	    },

	    // Returns change in angle from my previous position (-dx, -dy) to my new position
	    // relative to ref point.
	    changeInAngle: function(dx, dy, ref) {

	        // Revert the translation and measure the change in angle around x-axis.
	        return this.clone().offset(-dx, -dy).theta(ref) - this.theta(ref);
	    },

	    clone: function() {

	        return new Point(this);
	    },

	    // Returns the cross product of this point relative to two other points
	    // this point is the common point
	    // point p1 lies on the first vector, point p2 lies on the second vector
	    // watch out for the ordering of points p1 and p2!
	    // positive result indicates a clockwise ("right") turn from first to second vector
	    // negative result indicates a counterclockwise ("left") turn from first to second vector
	    // zero indicates that the first and second vector are collinear
	    // note that the above directions are reversed from the usual answer on the Internet
	    // that is because we are in a left-handed coord system (because the y-axis points downward)
	    cross: function(p1, p2) {

	        return (p1 && p2) ? (((p2.x - this.x) * (p1.y - this.y)) - ((p2.y - this.y) * (p1.x - this.x))) : NaN;
	    },

	    difference: function(dx, dy) {

	        if ((Object(dx) === dx)) {
	            dy = dx.y;
	            dx = dx.x;
	        }

	        return new Point(this.x - (dx || 0), this.y - (dy || 0));
	    },

	    // Returns distance between me and point `p`.
	    distance: function(p) {
	        return length(this, p);
	    },

	    // Returns the dot product of this point with given other point
	    dot: function(p) {

	        return p ? (this.x * p.x + this.y * p.y) : NaN;
	    },

	    equals: function(p) {

	        return !!p &&
	            this.x === p.x &&
	            this.y === p.y;
	    },

	    // Linear interpolation
	    lerp: function(p, t) {

	        var x = this.x;
	        var y = this.y;
	        return new Point((1 - t) * x + t * p.x, (1 - t) * y + t * p.y);
	    },

	    magnitude: function() {

	        return sqrt((this.x * this.x) + (this.y * this.y)) || 0.01;
	    },

	    // Returns a manhattan (taxi-cab) distance between me and point `p`.
	    manhattanDistance: function(p) {

	        return abs(p.x - this.x) + abs(p.y - this.y);
	    },

	    // Move point on line starting from ref ending at me by
	    // distance distance.
	    move: function(ref, distance) {

	        var theta = toRad((new Point(ref)).theta(this));
	        var offset = this.offset(cos$1(theta) * distance, -sin$1(theta) * distance);
	        return offset;
	    },

	    // Scales x and y such that the distance between the point and the origin (0,0) is equal to the given length.
	    normalize: function(length) {

	        var scale = (length || 1) / this.magnitude();
	        return this.scale(scale, scale);
	    },

	    // Offset me by the specified amount.
	    offset: function(dx, dy) {

	        if ((Object(dx) === dx)) {
	            dy = dx.y;
	            dx = dx.x;
	        }

	        this.x += dx || 0;
	        this.y += dy || 0;
	        return this;
	    },

	    // Returns a point that is the reflection of me with
	    // the center of inversion in ref point.
	    reflection: function(ref) {

	        return (new Point(ref)).move(this, this.distance(ref));
	    },

	    // Rotate point by angle around origin.
	    // Angle is flipped because this is a left-handed coord system (y-axis points downward).
	    rotate: function(origin, angle) {

	        if (angle === 0) { return this; }

	        origin = origin || new Point(0, 0);

	        angle = toRad(normalizeAngle(-angle));
	        var cosAngle = cos$1(angle);
	        var sinAngle = sin$1(angle);

	        var x = (cosAngle * (this.x - origin.x)) - (sinAngle * (this.y - origin.y)) + origin.x;
	        var y = (sinAngle * (this.x - origin.x)) + (cosAngle * (this.y - origin.y)) + origin.y;

	        this.x = x;
	        this.y = y;
	        return this;
	    },

	    round: function(precision) {

	        var f = 1; // case 0
	        if (precision) {
	            switch (precision) {
	                case 1: f = 10; break;
	                case 2: f = 100; break;
	                case 3: f = 1000; break;
	                default: f = pow(10, precision); break;
	            }
	        }

	        this.x = round$1(this.x * f) / f;
	        this.y = round$1(this.y * f) / f;
	        return this;
	    },

	    // Scale point with origin.
	    scale: function(sx, sy, origin) {

	        origin = (origin && new Point(origin)) || new Point(0, 0);
	        this.x = origin.x + sx * (this.x - origin.x);
	        this.y = origin.y + sy * (this.y - origin.y);
	        return this;
	    },

	    snapToGrid: function(gx, gy) {

	        this.x = snapToGrid(this.x, gx);
	        this.y = snapToGrid(this.y, gy || gx);
	        return this;
	    },

	    squaredDistance: function(p) {
	        return squaredLength(this, p);
	    },

	    // Compute the angle between me and `p` and the x axis.
	    // (cartesian-to-polar coordinates conversion)
	    // Return theta angle in degrees.
	    theta: function(p) {

	        p = new Point(p);

	        // Invert the y-axis.
	        var y = -(p.y - this.y);
	        var x = p.x - this.x;
	        var rad = atan2$1(y, x); // defined for all 0 corner cases

	        // Correction for III. and IV. quadrant.
	        if (rad < 0) {
	            rad = 2 * PI$1 + rad;
	        }

	        return 180 * rad / PI$1;
	    },

	    toJSON: function() {

	        return { x: this.x, y: this.y };
	    },

	    // Converts rectangular to polar coordinates.
	    // An origin can be specified, otherwise it's 0@0.
	    toPolar: function(o) {

	        o = (o && new Point(o)) || new Point(0, 0);
	        var x = this.x;
	        var y = this.y;
	        this.x = sqrt((x - o.x) * (x - o.x) + (y - o.y) * (y - o.y)); // r
	        this.y = toRad(o.theta(new Point(x, y)));
	        return this;
	    },

	    toString: function() {

	        return this.x + '@' + this.y;
	    },

	    serialize: function() {

	        return this.x + ',' + this.y;
	    },

	    update: function(x, y) {

	        if ((Object(x) === x)) {
	            y = x.y;
	            x = x.x;
	        }

	        this.x = x || 0;
	        this.y = y || 0;
	        return this;
	    },

	    // Compute the angle between the vector from 0,0 to me and the vector from 0,0 to p.
	    // Returns NaN if p is at 0,0.
	    vectorAngle: function(p) {

	        var zero = new Point(0, 0);
	        return zero.angleBetween(this, p);
	    }
	};

	Point.prototype.translate = Point.prototype.offset;

	// For backwards compatibility:
	var point = Point;

	var max$2 = Math.max;
	var min$4 = Math.min;

	var Line = function(p1, p2) {

	    if (!(this instanceof Line)) {
	        return new Line(p1, p2);
	    }

	    if (p1 instanceof Line) {
	        return new Line(p1.start, p1.end);
	    }

	    this.start = new Point(p1);
	    this.end = new Point(p2);
	};

	Line.prototype = {

	    // @returns the angle of incline of the line.
	    angle: function() {

	        var horizontalPoint = new Point(this.start.x + 1, this.start.y);
	        return this.start.angleBetween(this.end, horizontalPoint);
	    },

	    bbox: function() {

	        var left = min$4(this.start.x, this.end.x);
	        var top = min$4(this.start.y, this.end.y);
	        var right = max$2(this.start.x, this.end.x);
	        var bottom = max$2(this.start.y, this.end.y);

	        return new Rect(left, top, (right - left), (bottom - top));
	    },

	    // @return the bearing (cardinal direction) of the line. For example N, W, or SE.
	    // @returns {String} One of the following bearings : NE, E, SE, S, SW, W, NW, N.
	    bearing: function() {
	        return bearing(this.start, this.end);
	    },

	    clone: function() {

	        return new Line(this.start, this.end);
	    },

	    // @return {point} the closest point on the line to point `p`
	    closestPoint: function(p) {

	        return this.pointAt(this.closestPointNormalizedLength(p));
	    },

	    closestPointLength: function(p) {

	        return this.closestPointNormalizedLength(p) * this.length();
	    },

	    // @return {number} the normalized length of the closest point on the line to point `p`
	    closestPointNormalizedLength: function(p) {

	        var product = this.vector().dot((new Line(this.start, p)).vector());
	        var cpNormalizedLength = min$4(1, max$2(0, product / this.squaredLength()));

	        // cpNormalizedLength returns `NaN` if this line has zero length
	        // we can work with that - if `NaN`, return 0
	        if (cpNormalizedLength !== cpNormalizedLength) { return 0; } // condition evaluates to `true` if and only if cpNormalizedLength is `NaN`
	        // (`NaN` is the only value that is not equal to itself)

	        return cpNormalizedLength;
	    },

	    closestPointTangent: function(p) {

	        return this.tangentAt(this.closestPointNormalizedLength(p));
	    },

	    // Returns `true` if the point lies on the line.
	    containsPoint: function(p) {

	        var start = this.start;
	        var end = this.end;

	        if (start.cross(p, end) !== 0) { return false; }
	        // else: cross product of 0 indicates that this line and the vector to `p` are collinear

	        var length = this.length();
	        if ((new Line(start, p)).length() > length) { return false; }
	        if ((new Line(p, end)).length() > length) { return false; }
	        // else: `p` lies between start and end of the line

	        return true;
	    },

	    // Divides the line into two at requested `ratio` between 0 and 1.
	    divideAt: function(ratio) {

	        var dividerPoint = this.pointAt(ratio);

	        // return array with two lines
	        return [
	            new Line(this.start, dividerPoint),
	            new Line(dividerPoint, this.end)
	        ];
	    },

	    // Divides the line into two at requested `length`.
	    divideAtLength: function(length) {

	        var dividerPoint = this.pointAtLength(length);

	        // return array with two new lines
	        return [
	            new Line(this.start, dividerPoint),
	            new Line(dividerPoint, this.end)
	        ];
	    },

	    equals: function(l) {

	        return !!l &&
	            this.start.x === l.start.x &&
	            this.start.y === l.start.y &&
	            this.end.x === l.end.x &&
	            this.end.y === l.end.y;
	    },

	    // @return {point} Point where I'm intersecting a line.
	    // @return [point] Points where I'm intersecting a rectangle.
	    // @see Squeak Smalltalk, LineSegment>>intersectionWith:
	    intersect: function(shape, opt) {

	        if (shape && shape.intersectionWithLine) {
	            var intersection = shape.intersectionWithLine(this, opt);

	            // Backwards compatibility
	            if (intersection && (shape instanceof Line)) {
	                intersection = intersection[0];
	            }

	            return intersection;
	        }

	        return null;
	    },

	    intersectionWithLine: function(line) {

	        var pt1Dir = new Point(this.end.x - this.start.x, this.end.y - this.start.y);
	        var pt2Dir = new Point(line.end.x - line.start.x, line.end.y - line.start.y);
	        var det = (pt1Dir.x * pt2Dir.y) - (pt1Dir.y * pt2Dir.x);
	        var deltaPt = new Point(line.start.x - this.start.x, line.start.y - this.start.y);
	        var alpha = (deltaPt.x * pt2Dir.y) - (deltaPt.y * pt2Dir.x);
	        var beta = (deltaPt.x * pt1Dir.y) - (deltaPt.y * pt1Dir.x);

	        if (det === 0 || alpha * det < 0 || beta * det < 0) {
	            // No intersection found.
	            return null;
	        }

	        if (det > 0) {
	            if (alpha > det || beta > det) {
	                return null;
	            }

	        } else {
	            if (alpha < det || beta < det) {
	                return null;
	            }
	        }

	        return [new Point(
	            this.start.x + (alpha * pt1Dir.x / det),
	            this.start.y + (alpha * pt1Dir.y / det)
	        )];
	    },

	    isDifferentiable: function() {

	        return !this.start.equals(this.end);
	    },

	    // @return {double} length of the line
	    length: function() {
	        return length(this.start, this.end);
	    },

	    // @return {point} my midpoint
	    midpoint: function() {

	        return new Point(
	            (this.start.x + this.end.x) / 2,
	            (this.start.y + this.end.y) / 2
	        );
	    },

	    parallel: function(distance) {
	        var l = this.clone();
	        if (!this.isDifferentiable()) { return l; }
	        var start = l.start;
	        var end = l.end;
	        var eRef = start.clone().rotate(end, 270);
	        var sRef = end.clone().rotate(start, 90);
	        start.move(sRef, distance);
	        end.move(eRef, distance);
	        return l;
	    },

	    // @return {point} my point at 't' <0,1>
	    pointAt: function(t) {

	        var start = this.start;
	        var end = this.end;

	        if (t <= 0) { return start.clone(); }
	        if (t >= 1) { return end.clone(); }

	        return start.lerp(end, t);
	    },

	    pointAtLength: function(length) {

	        var start = this.start;
	        var end = this.end;

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        var lineLength = this.length();
	        if (length >= lineLength) { return (fromStart ? end.clone() : start.clone()); }

	        return this.pointAt((fromStart ? (length) : (lineLength - length)) / lineLength);
	    },

	    // @return {number} the offset of the point `p` from the line. + if the point `p` is on the right side of the line, - if on the left and 0 if on the line.
	    pointOffset: function(p) {

	        // Find the sign of the determinant of vectors (start,end), where p is the query point.
	        p = new Point(p);
	        var start = this.start;
	        var end = this.end;
	        var determinant = ((end.x - start.x) * (p.y - start.y) - (end.y - start.y) * (p.x - start.x));

	        return determinant / this.length();
	    },

	    rotate: function(origin, angle) {

	        this.start.rotate(origin, angle);
	        this.end.rotate(origin, angle);
	        return this;
	    },

	    round: function(precision) {

	        this.start.round(precision);
	        this.end.round(precision);
	        return this;
	    },

	    scale: function(sx, sy, origin) {

	        this.start.scale(sx, sy, origin);
	        this.end.scale(sx, sy, origin);
	        return this;
	    },

	    // @return {number} scale the line so that it has the requested length
	    setLength: function(length) {

	        var currentLength = this.length();
	        if (!currentLength) { return this; }

	        var scaleFactor = length / currentLength;
	        return this.scale(scaleFactor, scaleFactor, this.start);
	    },

	    // @return {integer} length without sqrt
	    // @note for applications where the exact length is not necessary (e.g. compare only)
	    squaredLength: function() {
	        return squaredLength(this.start, this.end);
	    },

	    tangentAt: function(t) {

	        if (!this.isDifferentiable()) { return null; }

	        var start = this.start;
	        var end = this.end;

	        var tangentStart = this.pointAt(t); // constrains `t` between 0 and 1

	        var tangentLine = new Line(start, end);
	        tangentLine.translate(tangentStart.x - start.x, tangentStart.y - start.y); // move so that tangent line starts at the point requested

	        return tangentLine;
	    },

	    tangentAtLength: function(length) {

	        if (!this.isDifferentiable()) { return null; }

	        var start = this.start;
	        var end = this.end;

	        var tangentStart = this.pointAtLength(length);

	        var tangentLine = new Line(start, end);
	        tangentLine.translate(tangentStart.x - start.x, tangentStart.y - start.y); // move so that tangent line starts at the point requested

	        return tangentLine;
	    },

	    toString: function() {

	        return this.start.toString() + ' ' + this.end.toString();
	    },

	    serialize: function() {

	        return this.start.serialize() + ' ' + this.end.serialize();
	    },

	    translate: function(tx, ty) {

	        this.start.translate(tx, ty);
	        this.end.translate(tx, ty);
	        return this;
	    },

	    // @return vector {point} of the line
	    vector: function() {

	        return new Point(this.end.x - this.start.x, this.end.y - this.start.y);
	    }
	};

	// For backwards compatibility:
	Line.prototype.intersection = Line.prototype.intersect;


	// For backwards compatibility:
	var line = Line;

	var sqrt$1 = Math.sqrt;
	var round$2 = Math.round;
	var pow$1 = Math.pow;

	var Ellipse = function(c, a, b) {

	    if (!(this instanceof Ellipse)) {
	        return new Ellipse(c, a, b);
	    }

	    if (c instanceof Ellipse) {
	        return new Ellipse(new Point(c.x, c.y), c.a, c.b);
	    }

	    c = new Point(c);
	    this.x = c.x;
	    this.y = c.y;
	    this.a = a;
	    this.b = b;
	};

	Ellipse.fromRect = function(rect) {

	    rect = new Rect(rect);
	    return new Ellipse(rect.center(), rect.width / 2, rect.height / 2);
	};

	Ellipse.prototype = {

	    bbox: function() {

	        return new Rect(this.x - this.a, this.y - this.b, 2 * this.a, 2 * this.b);
	    },

	    /**
	     * @returns {g.Point}
	     */
	    center: function() {

	        return new Point(this.x, this.y);
	    },

	    clone: function() {

	        return new Ellipse(this);
	    },

	    /**
	     * @param {g.Point} p
	     * @returns {boolean}
	     */
	    containsPoint: function(p) {

	        return this.normalizedDistance(p) <= 1;
	    },

	    equals: function(ellipse) {

	        return !!ellipse &&
	            ellipse.x === this.x &&
	            ellipse.y === this.y &&
	            ellipse.a === this.a &&
	            ellipse.b === this.b;
	    },

	    // inflate by dx and dy
	    // @param dx {delta_x} representing additional size to x
	    // @param dy {delta_y} representing additional size to y -
	    // dy param is not required -> in that case y is sized by dx
	    inflate: function(dx, dy) {
	        if (dx === undefined) {
	            dx = 0;
	        }

	        if (dy === undefined) {
	            dy = dx;
	        }

	        this.a += 2 * dx;
	        this.b += 2 * dy;

	        return this;
	    },

	    intersectionWithLine: function(line) {

	        var intersections = [];
	        var a1 = line.start;
	        var a2 = line.end;
	        var rx = this.a;
	        var ry = this.b;
	        var dir = line.vector();
	        var diff = a1.difference(new Point(this));
	        var mDir = new Point(dir.x / (rx * rx), dir.y / (ry * ry));
	        var mDiff = new Point(diff.x / (rx * rx), diff.y / (ry * ry));

	        var a = dir.dot(mDir);
	        var b = dir.dot(mDiff);
	        var c = diff.dot(mDiff) - 1.0;
	        var d = b * b - a * c;

	        if (d < 0) {
	            return null;
	        } else if (d > 0) {
	            var root = sqrt$1(d);
	            var ta = (-b - root) / a;
	            var tb = (-b + root) / a;

	            if ((ta < 0 || 1 < ta) && (tb < 0 || 1 < tb)) {
	                // if ((ta < 0 && tb < 0) || (ta > 1 && tb > 1)) outside else inside
	                return null;
	            } else {
	                if (0 <= ta && ta <= 1) { intersections.push(a1.lerp(a2, ta)); }
	                if (0 <= tb && tb <= 1) { intersections.push(a1.lerp(a2, tb)); }
	            }
	        } else {
	            var t = -b / a;
	            if (0 <= t && t <= 1) {
	                intersections.push(a1.lerp(a2, t));
	            } else {
	                // outside
	                return null;
	            }
	        }

	        return intersections;
	    },

	    // Find point on me where line from my center to
	    // point p intersects my boundary.
	    // @param {number} angle If angle is specified, intersection with rotated ellipse is computed.
	    intersectionWithLineFromCenterToPoint: function(p, angle) {

	        p = new Point(p);

	        if (angle) { p.rotate(new Point(this.x, this.y), angle); }

	        var dx = p.x - this.x;
	        var dy = p.y - this.y;
	        var result;

	        if (dx === 0) {
	            result = this.bbox().pointNearestToPoint(p);
	            if (angle) { return result.rotate(new Point(this.x, this.y), -angle); }
	            return result;
	        }

	        var m = dy / dx;
	        var mSquared = m * m;
	        var aSquared = this.a * this.a;
	        var bSquared = this.b * this.b;

	        var x = sqrt$1(1 / ((1 / aSquared) + (mSquared / bSquared)));
	        x = dx < 0 ? -x : x;

	        var y = m * x;
	        result = new Point(this.x + x, this.y + y);

	        if (angle) { return result.rotate(new Point(this.x, this.y), -angle); }
	        return result;
	    },

	    /**
	     * @param {g.Point} point
	     * @returns {number} result < 1 - inside ellipse, result == 1 - on ellipse boundary, result > 1 - outside
	     */
	    normalizedDistance: function(point) {

	        var x0 = point.x;
	        var y0 = point.y;
	        var a = this.a;
	        var b = this.b;
	        var x = this.x;
	        var y = this.y;

	        return ((x0 - x) * (x0 - x)) / (a * a) + ((y0 - y) * (y0 - y)) / (b * b);
	    },

	    round: function(precision) {

	        var f = 1; // case 0
	        if (precision) {
	            switch (precision) {
	                case 1: f = 10; break;
	                case 2: f = 100; break;
	                case 3: f = 1000; break;
	                default: f = pow$1(10, precision); break;
	            }
	        }

	        this.x = round$2(this.x * f) / f;
	        this.y = round$2(this.y * f) / f;
	        this.a = round$2(this.a * f) / f;
	        this.b = round$2(this.b * f) / f;
	        return this;
	    },

	    /** Compute angle between tangent and x axis
	     * @param {g.Point} p Point of tangency, it has to be on ellipse boundaries.
	     * @returns {number} angle between tangent and x axis
	     */
	    tangentTheta: function(p) {

	        var refPointDelta = 30;
	        var x0 = p.x;
	        var y0 = p.y;
	        var a = this.a;
	        var b = this.b;
	        var center = this.bbox().center();
	        var m = center.x;
	        var n = center.y;

	        var q1 = x0 > center.x + a / 2;
	        var q3 = x0 < center.x - a / 2;

	        var y, x;
	        if (q1 || q3) {
	            y = x0 > center.x ? y0 - refPointDelta : y0 + refPointDelta;
	            x = (a * a / (x0 - m)) - (a * a * (y0 - n) * (y - n)) / (b * b * (x0 - m)) + m;

	        } else {
	            x = y0 > center.y ? x0 + refPointDelta : x0 - refPointDelta;
	            y = (b * b / (y0 - n)) - (b * b * (x0 - m) * (x - m)) / (a * a * (y0 - n)) + n;
	        }

	        return (new Point(x, y)).theta(p);

	    },

	    toString: function() {

	        return (new Point(this.x, this.y)).toString() + ' ' + this.a + ' ' + this.b;
	    }
	};

	// For backwards compatibility:
	var ellipse = Ellipse;

	var abs$1 = Math.abs;
	var cos$2 = Math.cos;
	var sin$2 = Math.sin;
	var min$5 = Math.min;
	var max$3 = Math.max;
	var round$3 = Math.round;
	var pow$2 = Math.pow;

	var Rect = function(x, y, w, h) {

	    if (!(this instanceof Rect)) {
	        return new Rect(x, y, w, h);
	    }

	    if ((Object(x) === x)) {
	        y = x.y;
	        w = x.width;
	        h = x.height;
	        x = x.x;
	    }

	    this.x = x === undefined ? 0 : x;
	    this.y = y === undefined ? 0 : y;
	    this.width = w === undefined ? 0 : w;
	    this.height = h === undefined ? 0 : h;
	};

	Rect.fromEllipse = function(e) {

	    e = new Ellipse(e);
	    return new Rect(e.x - e.a, e.y - e.b, 2 * e.a, 2 * e.b);
	};

	Rect.fromPointUnion = function() {
	    var points = [], len = arguments.length;
	    while ( len-- ) points[ len ] = arguments[ len ];


	    if (points.length === 0) { return null; }

	    var p = new Point();
	    var minX, minY, maxX, maxY;
	    minX = minY = Infinity;
	    maxX = maxY = -Infinity;

	    for (var i = 0; i < points.length; i++) {
	        p.update(points[i]);
	        var x = p.x;
	        var y = p.y;

	        if (x < minX) { minX = x; }
	        if (x > maxX) { maxX = x; }
	        if (y < minY) { minY = y; }
	        if (y > maxY) { maxY = y; }
	    }

	    return new Rect(minX, minY, maxX - minX, maxY - minY);
	};

	Rect.fromRectUnion = function() {
	    var rects = [], len = arguments.length;
	    while ( len-- ) rects[ len ] = arguments[ len ];


	    if (rects.length === 0) { return null; }

	    var r = new Rect();
	    var minX, minY, maxX, maxY;
	    minX = minY = Infinity;
	    maxX = maxY = -Infinity;

	    for (var i = 0; i < rects.length; i++) {
	        r.update(rects[i]);
	        var x = r.x;
	        var y = r.y;
	        var mX = x + r.width;
	        var mY = y + r.height;

	        if (x < minX) { minX = x; }
	        if (mX > maxX) { maxX = mX; }
	        if (y < minY) { minY = y; }
	        if (mY > maxY) { maxY = mY; }
	    }

	    return new Rect(minX, minY, maxX - minX, maxY - minY);
	};

	Rect.prototype = {

	    // Find my bounding box when I'm rotated with the center of rotation in the center of me.
	    // @return r {rectangle} representing a bounding box
	    bbox: function(angle) {

	        if (!angle) { return this.clone(); }

	        var theta = toRad(angle);
	        var st = abs$1(sin$2(theta));
	        var ct = abs$1(cos$2(theta));
	        var w = this.width * ct + this.height * st;
	        var h = this.width * st + this.height * ct;
	        return new Rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h);
	    },

	    bottomLeft: function() {

	        return new Point(this.x, this.y + this.height);
	    },

	    bottomLine: function() {

	        return new Line(this.bottomLeft(), this.bottomRight());
	    },

	    bottomMiddle: function() {

	        return new Point(this.x + this.width / 2, this.y + this.height);
	    },

	    center: function() {

	        return new Point(this.x + this.width / 2, this.y + this.height / 2);
	    },

	    clone: function() {

	        return new Rect(this);
	    },

	    // @return {bool} true if point p is inside me.
	    containsPoint: function(p) {

	        p = new Point(p);
	        return p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height;
	    },

	    // @return {bool} true if rectangle `r` is inside me.
	    containsRect: function(r) {

	        var r0 = new Rect(this).normalize();
	        var r1 = new Rect(r).normalize();
	        var w0 = r0.width;
	        var h0 = r0.height;
	        var w1 = r1.width;
	        var h1 = r1.height;

	        if (!w0 || !h0 || !w1 || !h1) {
	            // At least one of the dimensions is 0
	            return false;
	        }

	        var x0 = r0.x;
	        var y0 = r0.y;
	        var x1 = r1.x;
	        var y1 = r1.y;

	        w1 += x1;
	        w0 += x0;
	        h1 += y1;
	        h0 += y0;

	        return x0 <= x1 && w1 <= w0 && y0 <= y1 && h1 <= h0;
	    },

	    corner: function() {

	        return new Point(this.x + this.width, this.y + this.height);
	    },

	    // @return {boolean} true if rectangles are equal.
	    equals: function(r) {

	        var mr = (new Rect(this)).normalize();
	        var nr = (new Rect(r)).normalize();
	        return mr.x === nr.x && mr.y === nr.y && mr.width === nr.width && mr.height === nr.height;
	    },

	    // inflate by dx and dy, recompute origin [x, y]
	    // @param dx {delta_x} representing additional size to x
	    // @param dy {delta_y} representing additional size to y -
	    // dy param is not required -> in that case y is sized by dx
	    inflate: function(dx, dy) {

	        if (dx === undefined) {
	            dx = 0;
	        }

	        if (dy === undefined) {
	            dy = dx;
	        }

	        this.x -= dx;
	        this.y -= dy;
	        this.width += 2 * dx;
	        this.height += 2 * dy;

	        return this;
	    },

	    // @return {rect} if rectangles intersect, {null} if not.
	    intersect: function(r) {

	        var myOrigin = this.origin();
	        var myCorner = this.corner();
	        var rOrigin = r.origin();
	        var rCorner = r.corner();

	        // No intersection found
	        if (rCorner.x <= myOrigin.x ||
	            rCorner.y <= myOrigin.y ||
	            rOrigin.x >= myCorner.x ||
	            rOrigin.y >= myCorner.y) { return null; }

	        var x = max$3(myOrigin.x, rOrigin.x);
	        var y = max$3(myOrigin.y, rOrigin.y);

	        return new Rect(x, y, min$5(myCorner.x, rCorner.x) - x, min$5(myCorner.y, rCorner.y) - y);
	    },

	    intersectionWithLine: function(line) {

	        var r = this;
	        var rectLines = [r.topLine(), r.rightLine(), r.bottomLine(), r.leftLine()];
	        var points = [];
	        var dedupeArr = [];
	        var pt, i;

	        var n = rectLines.length;
	        for (i = 0; i < n; i++) {

	            pt = line.intersect(rectLines[i]);
	            if (pt !== null && dedupeArr.indexOf(pt.toString()) < 0) {
	                points.push(pt);
	                dedupeArr.push(pt.toString());
	            }
	        }

	        return points.length > 0 ? points : null;
	    },

	    // Find point on my boundary where line starting
	    // from my center ending in point p intersects me.
	    // @param {number} angle If angle is specified, intersection with rotated rectangle is computed.
	    intersectionWithLineFromCenterToPoint: function(p, angle) {

	        p = new Point(p);
	        var center = new Point(this.x + this.width / 2, this.y + this.height / 2);
	        var result;

	        if (angle) { p.rotate(center, angle); }

	        // (clockwise, starting from the top side)
	        var sides = [
	            this.topLine(),
	            this.rightLine(),
	            this.bottomLine(),
	            this.leftLine()
	        ];
	        var connector = new Line(center, p);

	        for (var i = sides.length - 1; i >= 0; --i) {
	            var intersection = sides[i].intersection(connector);
	            if (intersection !== null) {
	                result = intersection;
	                break;
	            }
	        }
	        if (result && angle) { result.rotate(center, -angle); }
	        return result;
	    },

	    leftLine: function() {

	        return new Line(this.topLeft(), this.bottomLeft());
	    },

	    leftMiddle: function() {

	        return new Point(this.x, this.y + this.height / 2);
	    },

	    maxRectScaleToFit: function(rect, origin) {

	        rect = new Rect(rect);
	        origin || (origin = rect.center());

	        var sx1, sx2, sx3, sx4, sy1, sy2, sy3, sy4;
	        var ox = origin.x;
	        var oy = origin.y;

	        // Here we find the maximal possible scale for all corner points (for x and y axis) of the rectangle,
	        // so when the scale is applied the point is still inside the rectangle.

	        sx1 = sx2 = sx3 = sx4 = sy1 = sy2 = sy3 = sy4 = Infinity;

	        // Top Left
	        var p1 = rect.topLeft();
	        if (p1.x < ox) {
	            sx1 = (this.x - ox) / (p1.x - ox);
	        }
	        if (p1.y < oy) {
	            sy1 = (this.y - oy) / (p1.y - oy);
	        }
	        // Bottom Right
	        var p2 = rect.bottomRight();
	        if (p2.x > ox) {
	            sx2 = (this.x + this.width - ox) / (p2.x - ox);
	        }
	        if (p2.y > oy) {
	            sy2 = (this.y + this.height - oy) / (p2.y - oy);
	        }
	        // Top Right
	        var p3 = rect.topRight();
	        if (p3.x > ox) {
	            sx3 = (this.x + this.width - ox) / (p3.x - ox);
	        }
	        if (p3.y < oy) {
	            sy3 = (this.y - oy) / (p3.y - oy);
	        }
	        // Bottom Left
	        var p4 = rect.bottomLeft();
	        if (p4.x < ox) {
	            sx4 = (this.x - ox) / (p4.x - ox);
	        }
	        if (p4.y > oy) {
	            sy4 = (this.y + this.height - oy) / (p4.y - oy);
	        }

	        return {
	            sx: min$5(sx1, sx2, sx3, sx4),
	            sy: min$5(sy1, sy2, sy3, sy4)
	        };
	    },

	    maxRectUniformScaleToFit: function(rect, origin) {

	        var scale = this.maxRectScaleToFit(rect, origin);
	        return min$5(scale.sx, scale.sy);
	    },

	    // Move and expand me.
	    // @param r {rectangle} representing deltas
	    moveAndExpand: function(r) {

	        this.x += r.x || 0;
	        this.y += r.y || 0;
	        this.width += r.width || 0;
	        this.height += r.height || 0;
	        return this;
	    },

	    // Normalize the rectangle; i.e., make it so that it has a non-negative width and height.
	    // If width < 0 the function swaps the left and right corners,
	    // and it swaps the top and bottom corners if height < 0
	    // like in http://qt-project.org/doc/qt-4.8/qrectf.html#normalized
	    normalize: function() {

	        var newx = this.x;
	        var newy = this.y;
	        var newwidth = this.width;
	        var newheight = this.height;
	        if (this.width < 0) {
	            newx = this.x + this.width;
	            newwidth = -this.width;
	        }
	        if (this.height < 0) {
	            newy = this.y + this.height;
	            newheight = -this.height;
	        }
	        this.x = newx;
	        this.y = newy;
	        this.width = newwidth;
	        this.height = newheight;
	        return this;
	    },

	    // Offset me by the specified amount.
	    offset: function(dx, dy) {

	        // pretend that this is a point and call offset()
	        // rewrites x and y according to dx and dy
	        return Point.prototype.offset.call(this, dx, dy);
	    },

	    origin: function() {

	        return new Point(this.x, this.y);
	    },

	    // @return {point} a point on my boundary nearest to the given point.
	    // @see Squeak Smalltalk, Rectangle>>pointNearestTo:
	    pointNearestToPoint: function(point) {

	        point = new Point(point);
	        if (this.containsPoint(point)) {
	            var side = this.sideNearestToPoint(point);
	            switch (side) {
	                case 'right':
	                    return new Point(this.x + this.width, point.y);
	                case 'left':
	                    return new Point(this.x, point.y);
	                case 'bottom':
	                    return new Point(point.x, this.y + this.height);
	                case 'top':
	                    return new Point(point.x, this.y);
	            }
	        }
	        return point.adhereToRect(this);
	    },

	    rightLine: function() {

	        return new Line(this.topRight(), this.bottomRight());
	    },

	    rightMiddle: function() {

	        return new Point(this.x + this.width, this.y + this.height / 2);
	    },

	    round: function(precision) {

	        var f = 1; // case 0
	        if (precision) {
	            switch (precision) {
	                case 1: f = 10; break;
	                case 2: f = 100; break;
	                case 3: f = 1000; break;
	                default: f = pow$2(10, precision); break;
	            }
	        }

	        this.x = round$3(this.x * f) / f;
	        this.y = round$3(this.y * f) / f;
	        this.width = round$3(this.width * f) / f;
	        this.height = round$3(this.height * f) / f;
	        return this;
	    },

	    // Scale rectangle with origin.
	    scale: function(sx, sy, origin) {

	        origin = this.origin().scale(sx, sy, origin);
	        this.x = origin.x;
	        this.y = origin.y;
	        this.width *= sx;
	        this.height *= sy;
	        return this;
	    },

	    // @return {string} (left|right|top|bottom) side which is nearest to point
	    // @see Squeak Smalltalk, Rectangle>>sideNearestTo:
	    sideNearestToPoint: function(point) {

	        point = new Point(point);
	        var distToLeft = point.x - this.x;
	        var distToRight = (this.x + this.width) - point.x;
	        var distToTop = point.y - this.y;
	        var distToBottom = (this.y + this.height) - point.y;
	        var closest = distToLeft;
	        var side = 'left';

	        if (distToRight < closest) {
	            closest = distToRight;
	            side = 'right';
	        }
	        if (distToTop < closest) {
	            closest = distToTop;
	            side = 'top';
	        }
	        if (distToBottom < closest) {
	            // closest = distToBottom;
	            side = 'bottom';
	        }
	        return side;
	    },

	    snapToGrid: function(gx, gy) {

	        var origin = this.origin().snapToGrid(gx, gy);
	        var corner = this.corner().snapToGrid(gx, gy);
	        this.x = origin.x;
	        this.y = origin.y;
	        this.width = corner.x - origin.x;
	        this.height = corner.y - origin.y;
	        return this;
	    },

	    toJSON: function() {

	        return { x: this.x, y: this.y, width: this.width, height: this.height };
	    },

	    topLine: function() {

	        return new Line(this.topLeft(), this.topRight());
	    },

	    topMiddle: function() {

	        return new Point(this.x + this.width / 2, this.y);
	    },

	    topRight: function() {

	        return new Point(this.x + this.width, this.y);
	    },

	    toString: function() {

	        return this.origin().toString() + ' ' + this.corner().toString();
	    },

	    // @return {rect} representing the union of both rectangles.
	    union: function(rect) {

	        return Rect.fromRectUnion(this, rect);
	    },

	    update: function(x, y, w, h) {

	        if ((Object(x) === x)) {
	            y = x.y;
	            w = x.width;
	            h = x.height;
	            x = x.x;
	        }

	        this.x = x || 0;
	        this.y = y || 0;
	        this.width = w || 0;
	        this.height = h || 0;
	        return this;
	    }
	};

	Rect.prototype.bottomRight = Rect.prototype.corner;

	Rect.prototype.topLeft = Rect.prototype.origin;

	Rect.prototype.translate = Rect.prototype.offset;

	// For backwards compatibility:
	var rect = Rect;

	var abs$2 = Math.abs;

	var Polyline = function(points) {

	    if (!(this instanceof Polyline)) {
	        return new Polyline(points);
	    }

	    if (typeof points === 'string') {
	        return new Polyline.parse(points);
	    }

	    this.points = (Array.isArray(points) ? points.map(Point) : []);
	};

	Polyline.parse = function(svgString) {
	    svgString = svgString.trim();
	    if (svgString === '') { return new Polyline(); }

	    var points = [];

	    var coords = svgString.split(/\s*,\s*|\s+/);
	    var n = coords.length;
	    for (var i = 0; i < n; i += 2) {
	        points.push({ x: +coords[i], y: +coords[i + 1] });
	    }

	    return new Polyline(points);
	};

	Polyline.prototype = {

	    bbox: function() {

	        var x1 = Infinity;
	        var x2 = -Infinity;
	        var y1 = Infinity;
	        var y2 = -Infinity;

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return null; } // if points array is empty

	        for (var i = 0; i < numPoints; i++) {

	            var point = points[i];
	            var x = point.x;
	            var y = point.y;

	            if (x < x1) { x1 = x; }
	            if (x > x2) { x2 = x; }
	            if (y < y1) { y1 = y; }
	            if (y > y2) { y2 = y; }
	        }

	        return new Rect(x1, y1, x2 - x1, y2 - y1);
	    },

	    clone: function() {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return new Polyline(); } // if points array is empty

	        var newPoints = [];
	        for (var i = 0; i < numPoints; i++) {

	            var point = points[i].clone();
	            newPoints.push(point);
	        }

	        return new Polyline(newPoints);
	    },

	    closestPoint: function(p) {

	        var cpLength = this.closestPointLength(p);

	        return this.pointAtLength(cpLength);
	    },

	    closestPointLength: function(p) {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return 0; } // if points array is empty
	        if (numPoints === 1) { return 0; } // if there is only one point

	        var cpLength;
	        var minSqrDistance = Infinity;
	        var length = 0;
	        var n = numPoints - 1;
	        for (var i = 0; i < n; i++) {

	            var line = new Line(points[i], points[i + 1]);
	            var lineLength = line.length();

	            var cpNormalizedLength = line.closestPointNormalizedLength(p);
	            var cp = line.pointAt(cpNormalizedLength);

	            var sqrDistance = cp.squaredDistance(p);
	            if (sqrDistance < minSqrDistance) {
	                minSqrDistance = sqrDistance;
	                cpLength = length + (cpNormalizedLength * lineLength);
	            }

	            length += lineLength;
	        }

	        return cpLength;
	    },

	    closestPointNormalizedLength: function(p) {

	        var cpLength = this.closestPointLength(p);
	        if (cpLength === 0) { return 0; } // shortcut

	        var length = this.length();
	        if (length === 0) { return 0; } // prevents division by zero

	        return cpLength / length;
	    },

	    closestPointTangent: function(p) {

	        var cpLength = this.closestPointLength(p);

	        return this.tangentAtLength(cpLength);
	    },

	    // Returns `true` if the area surrounded by the polyline contains the point `p`.
	    // Implements the even-odd SVG algorithm (self-intersections are "outside").
	    // (Uses horizontal rays to the right of `p` to look for intersections.)
	    // Closes open polylines (always imagines a final closing segment).
	    containsPoint: function(p) {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return false; } // shortcut (this polyline has no points)

	        var x = p.x;
	        var y = p.y;

	        // initialize a final closing segment by creating one from last-first points on polyline
	        var startIndex = numPoints - 1; // start of current polyline segment
	        var endIndex = 0; // end of current polyline segment
	        var numIntersections = 0;
	        for (; endIndex < numPoints; endIndex++) {
	            var start = points[startIndex];
	            var end = points[endIndex];
	            if (p.equals(start)) { return true; } // shortcut (`p` is a point on polyline)

	            var segment = new Line(start, end); // current polyline segment
	            if (segment.containsPoint(p)) { return true; } // shortcut (`p` lies on a polyline segment)

	            // do we have an intersection?
	            if (((y <= start.y) && (y > end.y)) || ((y > start.y) && (y <= end.y))) {
	                // this conditional branch IS NOT entered when `segment` is collinear/coincident with `ray`
	                // (when `y === start.y === end.y`)
	                // this conditional branch IS entered when `segment` touches `ray` at only one point
	                // (e.g. when `y === start.y !== end.y`)
	                // since this branch is entered again for the following segment, the two touches cancel out

	                var xDifference = (((start.x - x) > (end.x - x)) ? (start.x - x) : (end.x - x));
	                if (xDifference >= 0) {
	                    // segment lies at least partially to the right of `p`
	                    var rayEnd = new Point((x + xDifference), y); // right
	                    var ray = new Line(p, rayEnd);

	                    if (segment.intersect(ray)) {
	                        // an intersection was detected to the right of `p`
	                        numIntersections++;
	                    }
	                } // else: `segment` lies completely to the left of `p` (i.e. no intersection to the right)
	            }

	            // move to check the next polyline segment
	            startIndex = endIndex;
	        }

	        // returns `true` for odd numbers of intersections (even-odd algorithm)
	        return ((numIntersections % 2) === 1);
	    },

	    // Returns a convex-hull polyline from this polyline.
	    // Implements the Graham scan (https://en.wikipedia.org/wiki/Graham_scan).
	    // Output polyline starts at the first element of the original polyline that is on the hull, then continues clockwise.
	    // Minimal polyline is found (only vertices of the hull are reported, no collinear points).
	    convexHull: function() {

	        var i;
	        var n;

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return new Polyline(); } // if points array is empty

	        // step 1: find the starting point - point with the lowest y (if equality, highest x)
	        var startPoint;
	        for (i = 0; i < numPoints; i++) {
	            if (startPoint === undefined) {
	                // if this is the first point we see, set it as start point
	                startPoint = points[i];

	            } else if (points[i].y < startPoint.y) {
	                // start point should have lowest y from all points
	                startPoint = points[i];

	            } else if ((points[i].y === startPoint.y) && (points[i].x > startPoint.x)) {
	                // if two points have the lowest y, choose the one that has highest x
	                // there are no points to the right of startPoint - no ambiguity about theta 0
	                // if there are several coincident start point candidates, first one is reported
	                startPoint = points[i];
	            }
	        }

	        // step 2: sort the list of points
	        // sorting by angle between line from startPoint to point and the x-axis (theta)

	        // step 2a: create the point records = [point, originalIndex, angle]
	        var sortedPointRecords = [];
	        for (i = 0; i < numPoints; i++) {

	            var angle = startPoint.theta(points[i]);
	            if (angle === 0) {
	                angle = 360; // give highest angle to start point
	                // the start point will end up at end of sorted list
	                // the start point will end up at beginning of hull points list
	            }

	            var entry = [points[i], i, angle];
	            sortedPointRecords.push(entry);
	        }

	        // step 2b: sort the list in place
	        sortedPointRecords.sort(function(record1, record2) {
	            // returning a negative number here sorts record1 before record2
	            // if first angle is smaller than second, first angle should come before second

	            var sortOutput = record1[2] - record2[2];  // negative if first angle smaller
	            if (sortOutput === 0) {
	                // if the two angles are equal, sort by originalIndex
	                sortOutput = record2[1] - record1[1]; // negative if first index larger
	                // coincident points will be sorted in reverse-numerical order
	                // so the coincident points with lower original index will be considered first
	            }

	            return sortOutput;
	        });

	        // step 2c: duplicate start record from the top of the stack to the bottom of the stack
	        if (sortedPointRecords.length > 2) {
	            var startPointRecord = sortedPointRecords[sortedPointRecords.length - 1];
	            sortedPointRecords.unshift(startPointRecord);
	        }

	        // step 3a: go through sorted points in order and find those with right turns
	        // we want to get our results in clockwise order
	        var insidePoints = {}; // dictionary of points with left turns - cannot be on the hull
	        var hullPointRecords = []; // stack of records with right turns - hull point candidates

	        var currentPointRecord;
	        var currentPoint;
	        var lastHullPointRecord;
	        var lastHullPoint;
	        var secondLastHullPointRecord;
	        var secondLastHullPoint;
	        while (sortedPointRecords.length !== 0) {

	            currentPointRecord = sortedPointRecords.pop();
	            currentPoint = currentPointRecord[0];

	            // check if point has already been discarded
	            // keys for insidePoints are stored in the form 'point.x@point.y@@originalIndex'
	            if (insidePoints.hasOwnProperty(currentPointRecord[0] + '@@' + currentPointRecord[1])) {
	                // this point had an incorrect turn at some previous iteration of this loop
	                // this disqualifies it from possibly being on the hull
	                continue;
	            }

	            var correctTurnFound = false;
	            while (!correctTurnFound) {

	                if (hullPointRecords.length < 2) {
	                    // not enough points for comparison, just add current point
	                    hullPointRecords.push(currentPointRecord);
	                    correctTurnFound = true;

	                } else {
	                    lastHullPointRecord = hullPointRecords.pop();
	                    lastHullPoint = lastHullPointRecord[0];
	                    secondLastHullPointRecord = hullPointRecords.pop();
	                    secondLastHullPoint = secondLastHullPointRecord[0];

	                    var crossProduct = secondLastHullPoint.cross(lastHullPoint, currentPoint);

	                    if (crossProduct < 0) {
	                        // found a right turn
	                        hullPointRecords.push(secondLastHullPointRecord);
	                        hullPointRecords.push(lastHullPointRecord);
	                        hullPointRecords.push(currentPointRecord);
	                        correctTurnFound = true;

	                    } else if (crossProduct === 0) {
	                        // the three points are collinear
	                        // three options:
	                        // there may be a 180 or 0 degree angle at lastHullPoint
	                        // or two of the three points are coincident
	                        var THRESHOLD = 1e-10; // we have to take rounding errors into account
	                        var angleBetween = lastHullPoint.angleBetween(secondLastHullPoint, currentPoint);
	                        if (abs$2(angleBetween - 180) < THRESHOLD) { // rouding around 180 to 180
	                            // if the cross product is 0 because the angle is 180 degrees
	                            // discard last hull point (add to insidePoints)
	                            //insidePoints.unshift(lastHullPoint);
	                            insidePoints[lastHullPointRecord[0] + '@@' + lastHullPointRecord[1]] = lastHullPoint;
	                            // reenter second-to-last hull point (will be last at next iter)
	                            hullPointRecords.push(secondLastHullPointRecord);
	                            // do not do anything with current point
	                            // correct turn not found

	                        } else if (lastHullPoint.equals(currentPoint) || secondLastHullPoint.equals(lastHullPoint)) {
	                            // if the cross product is 0 because two points are the same
	                            // discard last hull point (add to insidePoints)
	                            //insidePoints.unshift(lastHullPoint);
	                            insidePoints[lastHullPointRecord[0] + '@@' + lastHullPointRecord[1]] = lastHullPoint;
	                            // reenter second-to-last hull point (will be last at next iter)
	                            hullPointRecords.push(secondLastHullPointRecord);
	                            // do not do anything with current point
	                            // correct turn not found

	                        } else if (abs$2(((angleBetween + 1) % 360) - 1) < THRESHOLD) { // rounding around 0 and 360 to 0
	                            // if the cross product is 0 because the angle is 0 degrees
	                            // remove last hull point from hull BUT do not discard it
	                            // reenter second-to-last hull point (will be last at next iter)
	                            hullPointRecords.push(secondLastHullPointRecord);
	                            // put last hull point back into the sorted point records list
	                            sortedPointRecords.push(lastHullPointRecord);
	                            // we are switching the order of the 0deg and 180deg points
	                            // correct turn not found
	                        }

	                    } else {
	                        // found a left turn
	                        // discard last hull point (add to insidePoints)
	                        //insidePoints.unshift(lastHullPoint);
	                        insidePoints[lastHullPointRecord[0] + '@@' + lastHullPointRecord[1]] = lastHullPoint;
	                        // reenter second-to-last hull point (will be last at next iter of loop)
	                        hullPointRecords.push(secondLastHullPointRecord);
	                        // do not do anything with current point
	                        // correct turn not found
	                    }
	                }
	            }
	        }
	        // at this point, hullPointRecords contains the output points in clockwise order
	        // the points start with lowest-y,highest-x startPoint, and end at the same point

	        // step 3b: remove duplicated startPointRecord from the end of the array
	        if (hullPointRecords.length > 2) {
	            hullPointRecords.pop();
	        }

	        // step 4: find the lowest originalIndex record and put it at the beginning of hull
	        var lowestHullIndex; // the lowest originalIndex on the hull
	        var indexOfLowestHullIndexRecord = -1; // the index of the record with lowestHullIndex
	        n = hullPointRecords.length;
	        for (i = 0; i < n; i++) {

	            var currentHullIndex = hullPointRecords[i][1];

	            if (lowestHullIndex === undefined || currentHullIndex < lowestHullIndex) {
	                lowestHullIndex = currentHullIndex;
	                indexOfLowestHullIndexRecord = i;
	            }
	        }

	        var hullPointRecordsReordered = [];
	        if (indexOfLowestHullIndexRecord > 0) {
	            var newFirstChunk = hullPointRecords.slice(indexOfLowestHullIndexRecord);
	            var newSecondChunk = hullPointRecords.slice(0, indexOfLowestHullIndexRecord);
	            hullPointRecordsReordered = newFirstChunk.concat(newSecondChunk);

	        } else {
	            hullPointRecordsReordered = hullPointRecords;
	        }

	        var hullPoints = [];
	        n = hullPointRecordsReordered.length;
	        for (i = 0; i < n; i++) {
	            hullPoints.push(hullPointRecordsReordered[i][0]);
	        }

	        return new Polyline(hullPoints);
	    },

	    // Checks whether two polylines are exactly the same.
	    // If `p` is undefined or null, returns false.
	    equals: function(p) {

	        if (!p) { return false; }

	        var points = this.points;
	        var otherPoints = p.points;

	        var numPoints = points.length;
	        if (otherPoints.length !== numPoints) { return false; } // if the two polylines have different number of points, they cannot be equal

	        for (var i = 0; i < numPoints; i++) {

	            var point = points[i];
	            var otherPoint = p.points[i];

	            // as soon as an inequality is found in points, return false
	            if (!point.equals(otherPoint)) { return false; }
	        }

	        // if no inequality found in points, return true
	        return true;
	    },

	    intersectionWithLine: function(l) {
	        var line = new Line(l);
	        var intersections = [];
	        var points = this.points;
	        for (var i = 0, n = points.length - 1; i < n; i++) {
	            var a = points[i];
	            var b = points[i + 1];
	            var l2 = new Line(a, b);
	            var int = line.intersectionWithLine(l2);
	            if (int) { intersections.push(int[0]); }
	        }
	        return (intersections.length > 0) ? intersections : null;
	    },

	    isDifferentiable: function() {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return false; }

	        var n = numPoints - 1;
	        for (var i = 0; i < n; i++) {

	            var a = points[i];
	            var b = points[i + 1];
	            var line = new Line(a, b);

	            // as soon as a differentiable line is found between two points, return true
	            if (line.isDifferentiable()) { return true; }
	        }

	        // if no differentiable line is found between pairs of points, return false
	        return false;
	    },

	    length: function() {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return 0; } // if points array is empty

	        var length = 0;
	        var n = numPoints - 1;
	        for (var i = 0; i < n; i++) {
	            length += points[i].distance(points[i + 1]);
	        }

	        return length;
	    },

	    pointAt: function(ratio) {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return null; } // if points array is empty
	        if (numPoints === 1) { return points[0].clone(); } // if there is only one point

	        if (ratio <= 0) { return points[0].clone(); }
	        if (ratio >= 1) { return points[numPoints - 1].clone(); }

	        var polylineLength = this.length();
	        var length = polylineLength * ratio;

	        return this.pointAtLength(length);
	    },

	    pointAtLength: function(length) {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return null; } // if points array is empty
	        if (numPoints === 1) { return points[0].clone(); } // if there is only one point

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        var l = 0;
	        var n = numPoints - 1;
	        for (var i = 0; i < n; i++) {
	            var index = (fromStart ? i : (n - 1 - i));

	            var a = points[index];
	            var b = points[index + 1];
	            var line = new Line(a, b);
	            var d = a.distance(b);

	            if (length <= (l + d)) {
	                return line.pointAtLength((fromStart ? 1 : -1) * (length - l));
	            }

	            l += d;
	        }

	        // if length requested is higher than the length of the polyline, return last endpoint
	        var lastPoint = (fromStart ? points[numPoints - 1] : points[0]);
	        return lastPoint.clone();
	    },

	    round: function(precision) {

	        var points = this.points;
	        var numPoints = points.length;

	        for (var i = 0; i < numPoints; i++) {
	            points[i].round(precision);
	        }

	        return this;
	    },

	    scale: function(sx, sy, origin) {

	        var points = this.points;
	        var numPoints = points.length;

	        for (var i = 0; i < numPoints; i++) {
	            points[i].scale(sx, sy, origin);
	        }

	        return this;
	    },

	    simplify: function(opt) {
	        if ( opt === void 0 ) opt = {};


	        var points = this.points;
	        if (points.length < 3) { return this; } // we need at least 3 points

	        // TODO: we may also accept startIndex and endIndex to specify where to start and end simplification
	        var threshold = opt.threshold || 0; // = max distance of middle point from chord to be simplified

	        // start at the beginning of the polyline and go forward
	        var currentIndex = 0;
	        // we need at least one intermediate point (3 points) in every iteration
	        // as soon as that stops being true, we know we reached the end of the polyline
	        while (points[currentIndex + 2]) {
	            var firstIndex = currentIndex;
	            var middleIndex = (currentIndex + 1);
	            var lastIndex = (currentIndex + 2);

	            var firstPoint = points[firstIndex];
	            var middlePoint = points[middleIndex];
	            var lastPoint = points[lastIndex];

	            var chord = new Line(firstPoint, lastPoint); // = connection between first and last point
	            var closestPoint = chord.closestPoint(middlePoint); // = closest point on chord from middle point
	            var closestPointDistance = closestPoint.distance(middlePoint);
	            if (closestPointDistance <= threshold) {
	                // middle point is close enough to the chord = simplify
	                // 1) remove middle point:
	                points.splice(middleIndex, 1);
	                // 2) in next iteration, investigate the newly-created triplet of points
	                //    - do not change `currentIndex`
	                //    = (first point stays, point after removed point becomes middle point)
	            } else {
	                // middle point is far from the chord
	                // 1) preserve middle point
	                // 2) in next iteration, move `currentIndex` by one step:
	                currentIndex += 1;
	                //    = (point after first point becomes first point)
	            }
	        }

	        // `points` array was modified in-place
	        return this;
	    },

	    tangentAt: function(ratio) {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return null; } // if points array is empty
	        if (numPoints === 1) { return null; } // if there is only one point

	        if (ratio < 0) { ratio = 0; }
	        if (ratio > 1) { ratio = 1; }

	        var polylineLength = this.length();
	        var length = polylineLength * ratio;

	        return this.tangentAtLength(length);
	    },

	    tangentAtLength: function(length) {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return null; } // if points array is empty
	        if (numPoints === 1) { return null; } // if there is only one point

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        var lastValidLine; // differentiable (with a tangent)
	        var l = 0; // length so far
	        var n = numPoints - 1;
	        for (var i = 0; i < n; i++) {
	            var index = (fromStart ? i : (n - 1 - i));

	            var a = points[index];
	            var b = points[index + 1];
	            var line = new Line(a, b);
	            var d = a.distance(b);

	            if (line.isDifferentiable()) { // has a tangent line (line length is not 0)
	                if (length <= (l + d)) {
	                    return line.tangentAtLength((fromStart ? 1 : -1) * (length - l));
	                }

	                lastValidLine = line;
	            }

	            l += d;
	        }

	        // if length requested is higher than the length of the polyline, return last valid endpoint
	        if (lastValidLine) {
	            var ratio = (fromStart ? 1 : 0);
	            return lastValidLine.tangentAt(ratio);
	        }

	        // if no valid line, return null
	        return null;
	    },

	    toString: function() {

	        return this.points + '';
	    },

	    translate: function(tx, ty) {

	        var points = this.points;
	        var numPoints = points.length;

	        for (var i = 0; i < numPoints; i++) {
	            points[i].translate(tx, ty);
	        }

	        return this;
	    },

	    // Return svgString that can be used to recreate this line.
	    serialize: function() {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return ''; } // if points array is empty

	        var output = '';
	        for (var i = 0; i < numPoints; i++) {

	            var point = points[i];
	            output += point.x + ',' + point.y + ' ';
	        }

	        return output.trim();
	    }
	};

	Object.defineProperty(Polyline.prototype, 'start', {
	    // Getter for the first point of the polyline.

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return null; } // if points array is empty

	        return this.points[0];
	    },
	});

	Object.defineProperty(Polyline.prototype, 'end', {
	    // Getter for the last point of the polyline.

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        var points = this.points;
	        var numPoints = points.length;
	        if (numPoints === 0) { return null; } // if points array is empty

	        return this.points[numPoints - 1];
	    },
	});

	var abs$3 = Math.abs;
	var sqrt$2 = Math.sqrt;
	var min$6 = Math.min;
	var max$4 = Math.max;
	var pow$3 = Math.pow;

	var Curve = function(p1, p2, p3, p4) {

	    if (!(this instanceof Curve)) {
	        return new Curve(p1, p2, p3, p4);
	    }

	    if (p1 instanceof Curve) {
	        return new Curve(p1.start, p1.controlPoint1, p1.controlPoint2, p1.end);
	    }

	    this.start = new Point(p1);
	    this.controlPoint1 = new Point(p2);
	    this.controlPoint2 = new Point(p3);
	    this.end = new Point(p4);
	};

	// Curve passing through points.
	// Ported from C# implementation by Oleg V. Polikarpotchkin and Peter Lee (http://www.codeproject.com/KB/graphics/BezierSpline.aspx).
	// @param {array} points Array of points through which the smooth line will go.
	// @return {array} curves.
	Curve.throughPoints = (function() {

	    // Get open-ended Bezier Spline Control Points.
	    // @param knots Input Knot Bezier spline points (At least two points!).
	    // @param firstControlPoints Output First Control points. Array of knots.length - 1 length.
	    // @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
	    function getCurveControlPoints(knots) {

	        var firstControlPoints = [];
	        var secondControlPoints = [];
	        var n = knots.length - 1;
	        var i;

	        // Special case: Bezier curve should be a straight line.
	        if (n == 1) {
	            // 3P1 = 2P0 + P3
	            firstControlPoints[0] = new Point(
	                (2 * knots[0].x + knots[1].x) / 3,
	                (2 * knots[0].y + knots[1].y) / 3
	            );

	            // P2 = 2P1 – P0
	            secondControlPoints[0] = new Point(
	                2 * firstControlPoints[0].x - knots[0].x,
	                2 * firstControlPoints[0].y - knots[0].y
	            );

	            return [firstControlPoints, secondControlPoints];
	        }

	        // Calculate first Bezier control points.
	        // Right hand side vector.
	        var rhs = [];

	        // Set right hand side X values.
	        for (i = 1; i < n - 1; i++) {
	            rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
	        }

	        rhs[0] = knots[0].x + 2 * knots[1].x;
	        rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;

	        // Get first control points X-values.
	        var x = getFirstControlPoints(rhs);

	        // Set right hand side Y values.
	        for (i = 1; i < n - 1; ++i) {
	            rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
	        }

	        rhs[0] = knots[0].y + 2 * knots[1].y;
	        rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;

	        // Get first control points Y-values.
	        var y = getFirstControlPoints(rhs);

	        // Fill output arrays.
	        for (i = 0; i < n; i++) {
	            // First control point.
	            firstControlPoints.push(new Point(x[i], y[i]));

	            // Second control point.
	            if (i < n - 1) {
	                secondControlPoints.push(new Point(
	                    2 * knots [i + 1].x - x[i + 1],
	                    2 * knots[i + 1].y - y[i + 1]
	                ));

	            } else {
	                secondControlPoints.push(new Point(
	                    (knots[n].x + x[n - 1]) / 2,
	                    (knots[n].y + y[n - 1]) / 2
	                ));
	            }
	        }

	        return [firstControlPoints, secondControlPoints];
	    }

	    // Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points.
	    // @param rhs Right hand side vector.
	    // @return Solution vector.
	    function getFirstControlPoints(rhs) {

	        var n = rhs.length;
	        // `x` is a solution vector.
	        var x = [];
	        var tmp = [];
	        var b = 2.0;

	        x[0] = rhs[0] / b;

	        // Decomposition and forward substitution.
	        for (var i = 1; i < n; i++) {
	            tmp[i] = 1 / b;
	            b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
	            x[i] = (rhs[i] - x[i - 1]) / b;
	        }

	        for (i = 1; i < n; i++) {
	            // Backsubstitution.
	            x[n - i - 1] -= tmp[n - i] * x[n - i];
	        }

	        return x;
	    }

	    return function(points) {

	        if (!points || (Array.isArray(points) && points.length < 2)) {
	            throw new Error('At least 2 points are required');
	        }

	        var controlPoints = getCurveControlPoints(points);

	        var curves = [];
	        var n = controlPoints[0].length;
	        for (var i = 0; i < n; i++) {

	            var controlPoint1 = new Point(controlPoints[0][i].x, controlPoints[0][i].y);
	            var controlPoint2 = new Point(controlPoints[1][i].x, controlPoints[1][i].y);

	            curves.push(new Curve(points[i], controlPoint1, controlPoint2, points[i + 1]));
	        }

	        return curves;
	    };
	})();

	Curve.prototype = {

	    // Returns a bbox that tightly envelops the curve.
	    bbox: function() {

	        var start = this.start;
	        var controlPoint1 = this.controlPoint1;
	        var controlPoint2 = this.controlPoint2;
	        var end = this.end;

	        var x0 = start.x;
	        var y0 = start.y;
	        var x1 = controlPoint1.x;
	        var y1 = controlPoint1.y;
	        var x2 = controlPoint2.x;
	        var y2 = controlPoint2.y;
	        var x3 = end.x;
	        var y3 = end.y;

	        var points = new Array(); // local extremes
	        var tvalues = new Array(); // t values of local extremes
	        var bounds = [new Array(), new Array()];

	        var a, b, c, t;
	        var t1, t2;
	        var b2ac, sqrtb2ac;

	        for (var i = 0; i < 2; ++i) {

	            if (i === 0) {
	                b = 6 * x0 - 12 * x1 + 6 * x2;
	                a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
	                c = 3 * x1 - 3 * x0;

	            } else {
	                b = 6 * y0 - 12 * y1 + 6 * y2;
	                a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
	                c = 3 * y1 - 3 * y0;
	            }

	            if (abs$3(a) < 1e-12) { // Numerical robustness
	                if (abs$3(b) < 1e-12) { // Numerical robustness
	                    continue;
	                }

	                t = -c / b;
	                if ((0 < t) && (t < 1)) { tvalues.push(t); }

	                continue;
	            }

	            b2ac = b * b - 4 * c * a;
	            sqrtb2ac = sqrt$2(b2ac);

	            if (b2ac < 0) { continue; }

	            t1 = (-b + sqrtb2ac) / (2 * a);
	            if ((0 < t1) && (t1 < 1)) { tvalues.push(t1); }

	            t2 = (-b - sqrtb2ac) / (2 * a);
	            if ((0 < t2) && (t2 < 1)) { tvalues.push(t2); }
	        }

	        var j = tvalues.length;
	        var jlen = j;
	        var mt;
	        var x, y;

	        while (j--) {
	            t = tvalues[j];
	            mt = 1 - t;

	            x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
	            bounds[0][j] = x;

	            y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
	            bounds[1][j] = y;

	            points[j] = { X: x, Y: y };
	        }

	        tvalues[jlen] = 0;
	        tvalues[jlen + 1] = 1;

	        points[jlen] = { X: x0, Y: y0 };
	        points[jlen + 1] = { X: x3, Y: y3 };

	        bounds[0][jlen] = x0;
	        bounds[1][jlen] = y0;

	        bounds[0][jlen + 1] = x3;
	        bounds[1][jlen + 1] = y3;

	        tvalues.length = jlen + 2;
	        bounds[0].length = jlen + 2;
	        bounds[1].length = jlen + 2;
	        points.length = jlen + 2;

	        var left = min$6.apply(null, bounds[0]);
	        var top = min$6.apply(null, bounds[1]);
	        var right = max$4.apply(null, bounds[0]);
	        var bottom = max$4.apply(null, bounds[1]);

	        return new Rect(left, top, (right - left), (bottom - top));
	    },

	    clone: function() {

	        return new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
	    },

	    // Returns the point on the curve closest to point `p`
	    closestPoint: function(p, opt) {

	        return this.pointAtT(this.closestPointT(p, opt));
	    },

	    closestPointLength: function(p, opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
	        var localOpt = { precision: precision, subdivisions: subdivisions };

	        return this.lengthAtT(this.closestPointT(p, localOpt), localOpt);
	    },

	    closestPointNormalizedLength: function(p, opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
	        var localOpt = { precision: precision, subdivisions: subdivisions };

	        var cpLength = this.closestPointLength(p, localOpt);
	        if (!cpLength) { return 0; }

	        var length = this.length(localOpt);
	        if (length === 0) { return 0; }

	        return cpLength / length;
	    },

	    // Returns `t` of the point on the curve closest to point `p`
	    closestPointT: function(p, opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
	        // does not use localOpt

	        // identify the subdivision that contains the point:
	        var investigatedSubdivision;
	        var investigatedSubdivisionStartT; // assume that subdivisions are evenly spaced
	        var investigatedSubdivisionEndT;
	        var distFromStart; // distance of point from start of baseline
	        var distFromEnd; // distance of point from end of baseline
	        var chordLength; // distance between start and end of the subdivision
	        var minSumDist; // lowest observed sum of the two distances
	        var n = subdivisions.length;
	        var subdivisionSize = (n ? (1 / n) : 0);
	        for (var i = 0; i < n; i++) {

	            var currentSubdivision = subdivisions[i];

	            var startDist = currentSubdivision.start.distance(p);
	            var endDist = currentSubdivision.end.distance(p);
	            var sumDist = startDist + endDist;

	            // check that the point is closest to current subdivision and not any other
	            if (!minSumDist || (sumDist < minSumDist)) {
	                investigatedSubdivision = currentSubdivision;

	                investigatedSubdivisionStartT = i * subdivisionSize;
	                investigatedSubdivisionEndT = (i + 1) * subdivisionSize;

	                distFromStart = startDist;
	                distFromEnd = endDist;

	                chordLength = currentSubdivision.start.distance(currentSubdivision.end);

	                minSumDist = sumDist;
	            }
	        }

	        var precisionRatio = pow$3(10, -precision);

	        // recursively divide investigated subdivision:
	        // until distance between baselinePoint and closest path endpoint is within 10^(-precision)
	        // then return the closest endpoint of that final subdivision
	        while (true) {

	            // check if we have reached at least one required observed precision
	            // - calculated as: the difference in distances from point to start and end divided by the distance
	            // - note that this function is not monotonic = it doesn't converge stably but has "teeth"
	            // - the function decreases while one of the endpoints is fixed but "jumps" whenever we switch
	            // - this criterion works well for points lying far away from the curve
	            var startPrecisionRatio = (distFromStart ? (abs$3(distFromStart - distFromEnd) / distFromStart) : 0);
	            var endPrecisionRatio = (distFromEnd ? (abs$3(distFromStart - distFromEnd) / distFromEnd) : 0);
	            var hasRequiredPrecision = ((startPrecisionRatio < precisionRatio) || (endPrecisionRatio < precisionRatio));

	            // check if we have reached at least one required minimal distance
	            // - calculated as: the subdivision chord length multiplied by precisionRatio
	            // - calculation is relative so it will work for arbitrarily large/small curves and their subdivisions
	            // - this is a backup criterion that works well for points lying "almost at" the curve
	            var hasMinimalStartDistance = (distFromStart ? (distFromStart < (chordLength * precisionRatio)) : true);
	            var hasMinimalEndDistance = (distFromEnd ? (distFromEnd < (chordLength * precisionRatio)) : true);
	            var hasMinimalDistance = (hasMinimalStartDistance || hasMinimalEndDistance);

	            // do we stop now?
	            if (hasRequiredPrecision || hasMinimalDistance) {
	                return ((distFromStart <= distFromEnd) ? investigatedSubdivisionStartT : investigatedSubdivisionEndT);
	            }

	            // otherwise, set up for next iteration
	            var divided = investigatedSubdivision.divide(0.5);
	            subdivisionSize /= 2;

	            var startDist1 = divided[0].start.distance(p);
	            var endDist1 = divided[0].end.distance(p);
	            var sumDist1 = startDist1 + endDist1;

	            var startDist2 = divided[1].start.distance(p);
	            var endDist2 = divided[1].end.distance(p);
	            var sumDist2 = startDist2 + endDist2;

	            if (sumDist1 <= sumDist2) {
	                investigatedSubdivision = divided[0];

	                investigatedSubdivisionEndT -= subdivisionSize; // subdivisionSize was already halved

	                distFromStart = startDist1;
	                distFromEnd = endDist1;

	            } else {
	                investigatedSubdivision = divided[1];

	                investigatedSubdivisionStartT += subdivisionSize; // subdivisionSize was already halved

	                distFromStart = startDist2;
	                distFromEnd = endDist2;
	            }
	        }
	    },

	    closestPointTangent: function(p, opt) {

	        return this.tangentAtT(this.closestPointT(p, opt));
	    },

	    // Returns `true` if the area surrounded by the curve contains the point `p`.
	    // Implements the even-odd algorithm (self-intersections are "outside").
	    // Closes open curves (always imagines a closing segment).
	    // Precision may be adjusted by passing an `opt` object.
	    containsPoint: function(p, opt) {

	        var polyline = this.toPolyline(opt);
	        return polyline.containsPoint(p);
	    },

	    // Divides the curve into two at requested `ratio` between 0 and 1 with precision better than `opt.precision`; optionally using `opt.subdivisions` provided.
	    // For a function that uses `t`, use Curve.divideAtT().
	    divideAt: function(ratio, opt) {

	        if (ratio <= 0) { return this.divideAtT(0); }
	        if (ratio >= 1) { return this.divideAtT(1); }

	        var t = this.tAt(ratio, opt);

	        return this.divideAtT(t);
	    },

	    // Divides the curve into two at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
	    divideAtLength: function(length, opt) {

	        var t = this.tAtLength(length, opt);

	        return this.divideAtT(t);
	    },

	    // Divides the curve into two at point defined by `t` between 0 and 1.
	    // Using de Casteljau's algorithm (http://math.stackexchange.com/a/317867).
	    // Additional resource: https://pomax.github.io/bezierinfo/#decasteljau
	    divideAtT: function(t) {

	        var start = this.start;
	        var controlPoint1 = this.controlPoint1;
	        var controlPoint2 = this.controlPoint2;
	        var end = this.end;

	        // shortcuts for `t` values that are out of range
	        if (t <= 0) {
	            return [
	                new Curve(start, start, start, start),
	                new Curve(start, controlPoint1, controlPoint2, end)
	            ];
	        }

	        if (t >= 1) {
	            return [
	                new Curve(start, controlPoint1, controlPoint2, end),
	                new Curve(end, end, end, end)
	            ];
	        }

	        var dividerPoints = this.getSkeletonPoints(t);

	        var startControl1 = dividerPoints.startControlPoint1;
	        var startControl2 = dividerPoints.startControlPoint2;
	        var divider = dividerPoints.divider;
	        var dividerControl1 = dividerPoints.dividerControlPoint1;
	        var dividerControl2 = dividerPoints.dividerControlPoint2;

	        // return array with two new curves
	        return [
	            new Curve(start, startControl1, startControl2, divider),
	            new Curve(divider, dividerControl1, dividerControl2, end)
	        ];
	    },

	    // Returns the distance between the curve's start and end points.
	    endpointDistance: function() {

	        return this.start.distance(this.end);
	    },

	    // Checks whether two curves are exactly the same.
	    equals: function(c) {

	        return !!c &&
	            this.start.x === c.start.x &&
	            this.start.y === c.start.y &&
	            this.controlPoint1.x === c.controlPoint1.x &&
	            this.controlPoint1.y === c.controlPoint1.y &&
	            this.controlPoint2.x === c.controlPoint2.x &&
	            this.controlPoint2.y === c.controlPoint2.y &&
	            this.end.x === c.end.x &&
	            this.end.y === c.end.y;
	    },

	    // Returns five helper points necessary for curve division.
	    getSkeletonPoints: function(t) {

	        var start = this.start;
	        var control1 = this.controlPoint1;
	        var control2 = this.controlPoint2;
	        var end = this.end;

	        // shortcuts for `t` values that are out of range
	        if (t <= 0) {
	            return {
	                startControlPoint1: start.clone(),
	                startControlPoint2: start.clone(),
	                divider: start.clone(),
	                dividerControlPoint1: control1.clone(),
	                dividerControlPoint2: control2.clone()
	            };
	        }

	        if (t >= 1) {
	            return {
	                startControlPoint1: control1.clone(),
	                startControlPoint2: control2.clone(),
	                divider: end.clone(),
	                dividerControlPoint1: end.clone(),
	                dividerControlPoint2: end.clone()
	            };
	        }

	        var midpoint1 = (new Line(start, control1)).pointAt(t);
	        var midpoint2 = (new Line(control1, control2)).pointAt(t);
	        var midpoint3 = (new Line(control2, end)).pointAt(t);

	        var subControl1 = (new Line(midpoint1, midpoint2)).pointAt(t);
	        var subControl2 = (new Line(midpoint2, midpoint3)).pointAt(t);

	        var divider = (new Line(subControl1, subControl2)).pointAt(t);

	        var output = {
	            startControlPoint1: midpoint1,
	            startControlPoint2: subControl1,
	            divider: divider,
	            dividerControlPoint1: subControl2,
	            dividerControlPoint2: midpoint3
	        };

	        return output;
	    },

	    // Returns a list of curves whose flattened length is better than `opt.precision`.
	    // That is, observed difference in length between recursions is less than 10^(-3) = 0.001 = 0.1%
	    // (Observed difference is not real precision, but close enough as long as special cases are covered)
	    // (That is why skipping iteration 1 is important)
	    // As a rule of thumb, increasing `precision` by 1 requires two more division operations
	    // - Precision 0 (endpointDistance) - total of 2^0 - 1 = 0 operations (1 subdivision)
	    // - Precision 1 (<10% error) - total of 2^2 - 1 = 3 operations (4 subdivisions)
	    // - Precision 2 (<1% error) - total of 2^4 - 1 = 15 operations requires 4 division operations on all elements (15 operations total) (16 subdivisions)
	    // - Precision 3 (<0.1% error) - total of 2^6 - 1 = 63 operations - acceptable when drawing (64 subdivisions)
	    // - Precision 4 (<0.01% error) - total of 2^8 - 1 = 255 operations - high resolution, can be used to interpolate `t` (256 subdivisions)
	    // (Variation of 1 recursion worse or better is possible depending on the curve, doubling/halving the number of operations accordingly)
	    getSubdivisions: function(opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        // not using opt.subdivisions
	        // not using localOpt

	        var subdivisions = [new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end)];
	        if (precision === 0) { return subdivisions; }

	        var previousLength = this.endpointDistance();

	        var precisionRatio = pow$3(10, -precision);

	        // recursively divide curve at `t = 0.5`
	        // until the difference between observed length at subsequent iterations is lower than precision
	        var iteration = 0;
	        while (true) {
	            iteration += 1;

	            // divide all subdivisions
	            var newSubdivisions = [];
	            var numSubdivisions = subdivisions.length;
	            for (var i = 0; i < numSubdivisions; i++) {

	                var currentSubdivision = subdivisions[i];
	                var divided = currentSubdivision.divide(0.5); // dividing at t = 0.5 (not at middle length!)
	                newSubdivisions.push(divided[0], divided[1]);
	            }

	            // measure new length
	            var length = 0;
	            var numNewSubdivisions = newSubdivisions.length;
	            for (var j = 0; j < numNewSubdivisions; j++) {

	                var currentNewSubdivision = newSubdivisions[j];
	                length += currentNewSubdivision.endpointDistance();
	            }

	            // check if we have reached required observed precision
	            // sine-like curves may have the same observed length in iteration 0 and 1 - skip iteration 1
	            // not a problem for further iterations because cubic curves cannot have more than two local extrema
	            // (i.e. cubic curves cannot intersect the baseline more than once)
	            // therefore two subsequent iterations cannot produce sampling with equal length
	            var observedPrecisionRatio = ((length !== 0) ? ((length - previousLength) / length) : 0);
	            if (iteration > 1 && observedPrecisionRatio < precisionRatio) {
	                return newSubdivisions;
	            }

	            // otherwise, set up for next iteration
	            subdivisions = newSubdivisions;
	            previousLength = length;
	        }
	    },

	    isDifferentiable: function() {

	        var start = this.start;
	        var control1 = this.controlPoint1;
	        var control2 = this.controlPoint2;
	        var end = this.end;

	        return !(start.equals(control1) && control1.equals(control2) && control2.equals(end));
	    },

	    // Returns flattened length of the curve with precision better than `opt.precision`; or using `opt.subdivisions` provided.
	    length: function(opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSubdivisions() call
	        var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
	        // not using localOpt

	        var length = 0;
	        var n = subdivisions.length;
	        for (var i = 0; i < n; i++) {

	            var currentSubdivision = subdivisions[i];
	            length += currentSubdivision.endpointDistance();
	        }

	        return length;
	    },

	    // Returns distance along the curve up to `t` with precision better than requested `opt.precision`. (Not using `opt.subdivisions`.)
	    lengthAtT: function(t, opt) {

	        if (t <= 0) { return 0; }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        // not using opt.subdivisions
	        // not using localOpt

	        var subCurve = this.divide(t)[0];
	        var subCurveLength = subCurve.length({ precision: precision });

	        return subCurveLength;
	    },

	    // Returns point at requested `ratio` between 0 and 1 with precision better than `opt.precision`; optionally using `opt.subdivisions` provided.
	    // Mirrors Line.pointAt() function.
	    // For a function that tracks `t`, use Curve.pointAtT().
	    pointAt: function(ratio, opt) {

	        if (ratio <= 0) { return this.start.clone(); }
	        if (ratio >= 1) { return this.end.clone(); }

	        var t = this.tAt(ratio, opt);

	        return this.pointAtT(t);
	    },

	    // Returns point at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
	    pointAtLength: function(length, opt) {

	        var t = this.tAtLength(length, opt);

	        return this.pointAtT(t);
	    },

	    // Returns the point at provided `t` between 0 and 1.
	    // `t` does not track distance along curve as it does in Line objects.
	    // Non-linear relationship, speeds up and slows down as curve warps!
	    // For linear length-based solution, use Curve.pointAt().
	    pointAtT: function(t) {

	        if (t <= 0) { return this.start.clone(); }
	        if (t >= 1) { return this.end.clone(); }

	        return this.getSkeletonPoints(t).divider;
	    },

	    // Default precision
	    PRECISION: 3,

	    round: function(precision) {

	        this.start.round(precision);
	        this.controlPoint1.round(precision);
	        this.controlPoint2.round(precision);
	        this.end.round(precision);
	        return this;
	    },

	    scale: function(sx, sy, origin) {

	        this.start.scale(sx, sy, origin);
	        this.controlPoint1.scale(sx, sy, origin);
	        this.controlPoint2.scale(sx, sy, origin);
	        this.end.scale(sx, sy, origin);
	        return this;
	    },

	    // Returns a tangent line at requested `ratio` with precision better than requested `opt.precision`; or using `opt.subdivisions` provided.
	    tangentAt: function(ratio, opt) {

	        if (!this.isDifferentiable()) { return null; }

	        if (ratio < 0) { ratio = 0; }
	        else if (ratio > 1) { ratio = 1; }

	        var t = this.tAt(ratio, opt);

	        return this.tangentAtT(t);
	    },

	    // Returns a tangent line at requested `length` with precision better than requested `opt.precision`; or using `opt.subdivisions` provided.
	    tangentAtLength: function(length, opt) {

	        if (!this.isDifferentiable()) { return null; }

	        var t = this.tAtLength(length, opt);

	        return this.tangentAtT(t);
	    },

	    // Returns a tangent line at requested `t`.
	    tangentAtT: function(t) {

	        if (!this.isDifferentiable()) { return null; }

	        if (t < 0) { t = 0; }
	        else if (t > 1) { t = 1; }

	        var skeletonPoints = this.getSkeletonPoints(t);

	        var p1 = skeletonPoints.startControlPoint2;
	        var p2 = skeletonPoints.dividerControlPoint1;

	        var tangentStart = skeletonPoints.divider;

	        var tangentLine = new Line(p1, p2);
	        tangentLine.translate(tangentStart.x - p1.x, tangentStart.y - p1.y); // move so that tangent line starts at the point requested

	        return tangentLine;
	    },

	    // Returns `t` at requested `ratio` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
	    tAt: function(ratio, opt) {

	        if (ratio <= 0) { return 0; }
	        if (ratio >= 1) { return 1; }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
	        var localOpt = { precision: precision, subdivisions: subdivisions };

	        var curveLength = this.length(localOpt);
	        var length = curveLength * ratio;

	        return this.tAtLength(length, localOpt);
	    },

	    // Returns `t` at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
	    // Uses `precision` to approximate length within `precision` (always underestimates)
	    // Then uses a binary search to find the `t` of a subdivision endpoint that is close (within `precision`) to the `length`, if the curve was as long as approximated
	    // As a rule of thumb, increasing `precision` by 1 causes the algorithm to go 2^(precision - 1) deeper
	    // - Precision 0 (chooses one of the two endpoints) - 0 levels
	    // - Precision 1 (chooses one of 5 points, <10% error) - 1 level
	    // - Precision 2 (<1% error) - 3 levels
	    // - Precision 3 (<0.1% error) - 7 levels
	    // - Precision 4 (<0.01% error) - 15 levels
	    tAtLength: function(length, opt) {

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
	        var localOpt = { precision: precision, subdivisions: subdivisions };

	        // identify the subdivision that contains the point at requested `length`:
	        var investigatedSubdivision;
	        var investigatedSubdivisionStartT; // assume that subdivisions are evenly spaced
	        var investigatedSubdivisionEndT;
	        //var baseline; // straightened version of subdivision to investigate
	        //var baselinePoint; // point on the baseline that is the requested distance away from start
	        var baselinePointDistFromStart; // distance of baselinePoint from start of baseline
	        var baselinePointDistFromEnd; // distance of baselinePoint from end of baseline
	        var l = 0; // length so far
	        var n = subdivisions.length;
	        var subdivisionSize = 1 / n;
	        for (var i = 0; i < n; i++) {
	            var index = (fromStart ? i : (n - 1 - i));

	            var currentSubdivision = subdivisions[i];
	            var d = currentSubdivision.endpointDistance(); // length of current subdivision

	            if (length <= (l + d)) {
	                investigatedSubdivision = currentSubdivision;

	                investigatedSubdivisionStartT = index * subdivisionSize;
	                investigatedSubdivisionEndT = (index + 1) * subdivisionSize;

	                baselinePointDistFromStart = (fromStart ? (length - l) : ((d + l) - length));
	                baselinePointDistFromEnd = (fromStart ? ((d + l) - length) : (length - l));

	                break;
	            }

	            l += d;
	        }

	        if (!investigatedSubdivision) { return (fromStart ? 1 : 0); } // length requested is out of range - return maximum t
	        // note that precision affects what length is recorded
	        // (imprecise measurements underestimate length by up to 10^(-precision) of the precise length)
	        // e.g. at precision 1, the length may be underestimated by up to 10% and cause this function to return 1

	        var curveLength = this.length(localOpt);

	        var precisionRatio = pow$3(10, -precision);

	        // recursively divide investigated subdivision:
	        // until distance between baselinePoint and closest path endpoint is within 10^(-precision)
	        // then return the closest endpoint of that final subdivision
	        while (true) {

	            // check if we have reached required observed precision
	            var observedPrecisionRatio;

	            observedPrecisionRatio = ((curveLength !== 0) ? (baselinePointDistFromStart / curveLength) : 0);
	            if (observedPrecisionRatio < precisionRatio) { return investigatedSubdivisionStartT; }
	            observedPrecisionRatio = ((curveLength !== 0) ? (baselinePointDistFromEnd / curveLength) : 0);
	            if (observedPrecisionRatio < precisionRatio) { return investigatedSubdivisionEndT; }

	            // otherwise, set up for next iteration
	            var newBaselinePointDistFromStart;
	            var newBaselinePointDistFromEnd;

	            var divided = investigatedSubdivision.divide(0.5);
	            subdivisionSize /= 2;

	            var baseline1Length = divided[0].endpointDistance();
	            var baseline2Length = divided[1].endpointDistance();

	            if (baselinePointDistFromStart <= baseline1Length) { // point at requested length is inside divided[0]
	                investigatedSubdivision = divided[0];

	                investigatedSubdivisionEndT -= subdivisionSize; // sudivisionSize was already halved

	                newBaselinePointDistFromStart = baselinePointDistFromStart;
	                newBaselinePointDistFromEnd = baseline1Length - newBaselinePointDistFromStart;

	            } else { // point at requested length is inside divided[1]
	                investigatedSubdivision = divided[1];

	                investigatedSubdivisionStartT += subdivisionSize; // subdivisionSize was already halved

	                newBaselinePointDistFromStart = baselinePointDistFromStart - baseline1Length;
	                newBaselinePointDistFromEnd = baseline2Length - newBaselinePointDistFromStart;
	            }

	            baselinePointDistFromStart = newBaselinePointDistFromStart;
	            baselinePointDistFromEnd = newBaselinePointDistFromEnd;
	        }
	    },

	    // Returns an array of points that represents the curve when flattened, up to `opt.precision`; or using `opt.subdivisions` provided.
	    // Flattened length is no more than 10^(-precision) away from real curve length.
	    toPoints: function(opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSubdivisions() call
	        var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
	        // not using localOpt

	        var points = [subdivisions[0].start.clone()];
	        var n = subdivisions.length;
	        for (var i = 0; i < n; i++) {

	            var currentSubdivision = subdivisions[i];
	            points.push(currentSubdivision.end.clone());
	        }

	        return points;
	    },

	    // Returns a polyline that represents the curve when flattened, up to `opt.precision`; or using `opt.subdivisions` provided.
	    // Flattened length is no more than 10^(-precision) away from real curve length.
	    toPolyline: function(opt) {

	        return new Polyline(this.toPoints(opt));
	    },

	    toString: function() {

	        return this.start + ' ' + this.controlPoint1 + ' ' + this.controlPoint2 + ' ' + this.end;
	    },

	    translate: function(tx, ty) {

	        this.start.translate(tx, ty);
	        this.controlPoint1.translate(tx, ty);
	        this.controlPoint2.translate(tx, ty);
	        this.end.translate(tx, ty);
	        return this;
	    }
	};

	Curve.prototype.divide = Curve.prototype.divideAtT;

	// Accepts path data string, array of segments, array of Curves and/or Lines, or a Polyline.

	var Path = function(arg) {

	    if (!(this instanceof Path)) {
	        return new Path(arg);
	    }

	    if (typeof arg === 'string') { // create from a path data string
	        return new Path.parse(arg);
	    }

	    this.segments = [];

	    var i;
	    var n;

	    if (!arg) {
	        // don't do anything

	    } else if (Array.isArray(arg) && arg.length !== 0) { // if arg is a non-empty array
	        // flatten one level deep
	        // so we can chain arbitrary Path.createSegment results
	        arg = arg.reduce(function(acc, val) {
	            return acc.concat(val);
	        }, []);

	        n = arg.length;
	        if (arg[0].isSegment) { // create from an array of segments
	            for (i = 0; i < n; i++) {

	                var segment = arg[i];

	                this.appendSegment(segment);
	            }

	        } else { // create from an array of Curves and/or Lines
	            var previousObj = null;
	            for (i = 0; i < n; i++) {

	                var obj = arg[i];

	                if (!((obj instanceof Line) || (obj instanceof Curve))) {
	                    throw new Error('Cannot construct a path segment from the provided object.');
	                }

	                if (i === 0) { this.appendSegment(Path.createSegment('M', obj.start)); }

	                // if objects do not link up, moveto segments are inserted to cover the gaps
	                if (previousObj && !previousObj.end.equals(obj.start)) { this.appendSegment(Path.createSegment('M', obj.start)); }

	                if (obj instanceof Line) {
	                    this.appendSegment(Path.createSegment('L', obj.end));

	                } else if (obj instanceof Curve) {
	                    this.appendSegment(Path.createSegment('C', obj.controlPoint1, obj.controlPoint2, obj.end));
	                }

	                previousObj = obj;
	            }
	        }

	    } else if (arg.isSegment) { // create from a single segment
	        this.appendSegment(arg);

	    } else if (arg instanceof Line) { // create from a single Line
	        this.appendSegment(Path.createSegment('M', arg.start));
	        this.appendSegment(Path.createSegment('L', arg.end));

	    } else if (arg instanceof Curve) { // create from a single Curve
	        this.appendSegment(Path.createSegment('M', arg.start));
	        this.appendSegment(Path.createSegment('C', arg.controlPoint1, arg.controlPoint2, arg.end));

	    } else if (arg instanceof Polyline) { // create from a Polyline
	        if (!(arg.points && (arg.points.length !== 0))) { return; } // if Polyline has no points, leave Path empty

	        n = arg.points.length;
	        for (i = 0; i < n; i++) {

	            var point = arg.points[i];

	            if (i === 0) { this.appendSegment(Path.createSegment('M', point)); }
	            else { this.appendSegment(Path.createSegment('L', point)); }
	        }

	    } else { // unknown object
	        throw new Error('Cannot construct a path from the provided object.');
	    }
	};

	// More permissive than V.normalizePathData and Path.prototype.serialize.
	// Allows path data strings that do not start with a Moveto command (unlike SVG specification).
	// Does not require spaces between elements; commas are allowed, separators may be omitted when unambiguous (e.g. 'ZM10,10', 'L1.6.8', 'M100-200').
	// Allows for command argument chaining.
	// Throws an error if wrong number of arguments is provided with a command.
	// Throws an error if an unrecognized path command is provided (according to Path.segmentTypes). Only a subset of SVG commands is currently supported (L, C, M, Z).
	Path.parse = function(pathData) {

	    if (!pathData) { return new Path(); }

	    var path = new Path();

	    var commandRe = /(?:[a-zA-Z] *)(?:(?:-?\d+(?:\.\d+)?(?:e[-+]?\d+)? *,? *)|(?:-?\.\d+ *,? *))+|(?:[a-zA-Z] *)(?! |\d|-|\.)/g;
	    var commands = pathData.match(commandRe);

	    var numCommands = commands.length;
	    for (var i = 0; i < numCommands; i++) {

	        var command = commands[i];
	        var argRe = /(?:[a-zA-Z])|(?:(?:-?\d+(?:\.\d+)?(?:e[-+]?\d+)?))|(?:(?:-?\.\d+))/g;
	        var args = command.match(argRe);

	        var segment = Path.createSegment.apply(this, args); // args = [type, coordinate1, coordinate2...]
	        path.appendSegment(segment);
	    }

	    return path;
	};

	// Create a segment or an array of segments.
	// Accepts unlimited points/coords arguments after `type`.
	Path.createSegment = function(type) {
	    var arguments$1 = arguments;


	    if (!type) { throw new Error('Type must be provided.'); }

	    var segmentConstructor = Path.segmentTypes[type];
	    if (!segmentConstructor) { throw new Error(type + ' is not a recognized path segment type.'); }

	    var args = [];
	    var n = arguments.length;
	    for (var i = 1; i < n; i++) { // do not add first element (`type`) to args array
	        args.push(arguments$1[i]);
	    }

	    return applyToNew(segmentConstructor, args);
	};

	Path.prototype = {

	    // Accepts one segment or an array of segments as argument.
	    // Throws an error if argument is not a segment or an array of segments.
	    appendSegment: function(arg) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        // works even if path has no segments

	        var currentSegment;

	        var previousSegment = ((numSegments !== 0) ? segments[numSegments - 1] : null); // if we are appending to an empty path, previousSegment is null
	        var nextSegment = null;

	        if (!Array.isArray(arg)) { // arg is a segment
	            if (!arg || !arg.isSegment) { throw new Error('Segment required.'); }

	            currentSegment = this.prepareSegment(arg, previousSegment, nextSegment);
	            segments.push(currentSegment);

	        } else { // arg is an array of segments
	            // flatten one level deep
	            // so we can chain arbitrary Path.createSegment results
	            arg = arg.reduce(function(acc, val) {
	                return acc.concat(val);
	            }, []);

	            if (!arg[0].isSegment) { throw new Error('Segments required.'); }

	            var n = arg.length;
	            for (var i = 0; i < n; i++) {

	                var currentArg = arg[i];
	                currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment);
	                segments.push(currentSegment);
	                previousSegment = currentSegment;
	            }
	        }
	    },

	    // Returns the bbox of the path.
	    // If path has no segments, returns null.
	    // If path has only invisible segments, returns bbox of the end point of last segment.
	    bbox: function() {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        var bbox;
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            if (segment.isVisible) {
	                var segmentBBox = segment.bbox();
	                bbox = bbox ? bbox.union(segmentBBox) : segmentBBox;
	            }
	        }

	        if (bbox) { return bbox; }

	        // if the path has only invisible elements, return end point of last segment
	        var lastSegment = segments[numSegments - 1];
	        return new Rect(lastSegment.end.x, lastSegment.end.y, 0, 0);
	    },

	    // Returns a new path that is a clone of this path.
	    clone: function() {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        // works even if path has no segments

	        var path = new Path();
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i].clone();
	            path.appendSegment(segment);
	        }

	        return path;
	    },

	    closestPoint: function(p, opt) {

	        var t = this.closestPointT(p, opt);
	        if (!t) { return null; }

	        return this.pointAtT(t);
	    },

	    closestPointLength: function(p, opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };

	        var t = this.closestPointT(p, localOpt);
	        if (!t) { return 0; }

	        return this.lengthAtT(t, localOpt);
	    },

	    closestPointNormalizedLength: function(p, opt) {

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };

	        var cpLength = this.closestPointLength(p, localOpt);
	        if (cpLength === 0) { return 0; } // shortcut

	        var length = this.length(localOpt);
	        if (length === 0) { return 0; } // prevents division by zero

	        return cpLength / length;
	    },

	    // Private function.
	    closestPointT: function(p, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var closestPointT;
	        var minSquaredDistance = Infinity;
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            var subdivisions = segmentSubdivisions[i];

	            if (segment.isVisible) {
	                var segmentClosestPointT = segment.closestPointT(p, {
	                    precision: precision,
	                    subdivisions: subdivisions
	                });
	                var segmentClosestPoint = segment.pointAtT(segmentClosestPointT);
	                var squaredDistance = (new Line(segmentClosestPoint, p)).squaredLength();

	                if (squaredDistance < minSquaredDistance) {
	                    closestPointT = { segmentIndex: i, value: segmentClosestPointT };
	                    minSquaredDistance = squaredDistance;
	                }
	            }
	        }

	        if (closestPointT) { return closestPointT; }

	        // if no visible segment, return end of last segment
	        return { segmentIndex: numSegments - 1, value: 1 };
	    },

	    closestPointTangent: function(p, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var closestPointTangent;
	        var minSquaredDistance = Infinity;
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            var subdivisions = segmentSubdivisions[i];

	            if (segment.isDifferentiable()) {
	                var segmentClosestPointT = segment.closestPointT(p, {
	                    precision: precision,
	                    subdivisions: subdivisions
	                });
	                var segmentClosestPoint = segment.pointAtT(segmentClosestPointT);
	                var squaredDistance = (new Line(segmentClosestPoint, p)).squaredLength();

	                if (squaredDistance < minSquaredDistance) {
	                    closestPointTangent = segment.tangentAtT(segmentClosestPointT);
	                    minSquaredDistance = squaredDistance;
	                }
	            }
	        }

	        if (closestPointTangent) { return closestPointTangent; }

	        // if no valid segment, return null
	        return null;
	    },

	    // Returns `true` if the area surrounded by the path contains the point `p`.
	    // Implements the even-odd algorithm (self-intersections are "outside").
	    // Closes open paths (always imagines a final closing segment).
	    // Precision may be adjusted by passing an `opt` object.
	    containsPoint: function(p, opt) {

	        var polylines = this.toPolylines(opt);
	        if (!polylines) { return false; } // shortcut (this path has no polylines)

	        var numPolylines = polylines.length;

	        // how many component polylines does `p` lie within?
	        var numIntersections = 0;
	        for (var i = 0; i < numPolylines; i++) {
	            var polyline = polylines[i];
	            if (polyline.containsPoint(p)) {
	                // `p` lies within this polyline
	                numIntersections++;
	            }
	        }

	        // returns `true` for odd numbers of intersections (even-odd algorithm)
	        return ((numIntersections % 2) === 1);
	    },

	    // Divides the path into two at requested `ratio` between 0 and 1 with precision better than `opt.precision`; optionally using `opt.subdivisions` provided.
	    divideAt: function(ratio, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        if (ratio < 0) { ratio = 0; }
	        if (ratio > 1) { ratio = 1; }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };

	        var pathLength = this.length(localOpt);
	        var length = pathLength * ratio;

	        return this.divideAtLength(length, localOpt);
	    },

	    // Divides the path into two at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
	    divideAtLength: function(length, opt) {

	        var numSegments = this.segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var i;
	        var segment;

	        // identify the segment to divide:

	        var l = 0; // length so far
	        var divided;
	        var dividedSegmentIndex;
	        var lastValidSegment; // visible AND differentiable
	        var lastValidSegmentIndex;
	        var t;
	        for (i = 0; i < numSegments; i++) {
	            var index = (fromStart ? i : (numSegments - 1 - i));

	            segment = this.getSegment(index);
	            var subdivisions = segmentSubdivisions[index];
	            var d = segment.length({ precision: precision, subdivisions: subdivisions });

	            if (segment.isDifferentiable()) { // segment is not just a point
	                lastValidSegment = segment;
	                lastValidSegmentIndex = index;

	                if (length <= (l + d)) {
	                    dividedSegmentIndex = index;
	                    divided = segment.divideAtLength(((fromStart ? 1 : -1) * (length - l)), {
	                        precision: precision,
	                        subdivisions: subdivisions
	                    });
	                    break;
	                }
	            }

	            l += d;
	        }

	        if (!lastValidSegment) { // no valid segment found
	            return null;
	        }

	        // else: the path contains at least one valid segment

	        if (!divided) { // the desired length is greater than the length of the path
	            dividedSegmentIndex = lastValidSegmentIndex;
	            t = (fromStart ? 1 : 0);
	            divided = lastValidSegment.divideAtT(t);
	        }

	        // create a copy of this path and replace the identified segment with its two divided parts:

	        var pathCopy = this.clone();
	        pathCopy.replaceSegment(dividedSegmentIndex, divided);

	        var divisionStartIndex = dividedSegmentIndex;
	        var divisionMidIndex = dividedSegmentIndex + 1;
	        var divisionEndIndex = dividedSegmentIndex + 2;

	        // do not insert the part if it looks like a point
	        if (!divided[0].isDifferentiable()) {
	            pathCopy.removeSegment(divisionStartIndex);
	            divisionMidIndex -= 1;
	            divisionEndIndex -= 1;
	        }

	        // insert a Moveto segment to ensure secondPath will be valid:
	        var movetoEnd = pathCopy.getSegment(divisionMidIndex).start;
	        pathCopy.insertSegment(divisionMidIndex, Path.createSegment('M', movetoEnd));
	        divisionEndIndex += 1;

	        // do not insert the part if it looks like a point
	        if (!divided[1].isDifferentiable()) {
	            pathCopy.removeSegment(divisionEndIndex - 1);
	            divisionEndIndex -= 1;
	        }

	        // ensure that Closepath segments in secondPath will be assigned correct subpathStartSegment:

	        var secondPathSegmentIndexConversion = divisionEndIndex - divisionStartIndex - 1;
	        for (i = divisionEndIndex; i < pathCopy.segments.length; i++) {

	            var originalSegment = this.getSegment(i - secondPathSegmentIndexConversion);
	            segment = pathCopy.getSegment(i);

	            if ((segment.type === 'Z') && !originalSegment.subpathStartSegment.end.equals(segment.subpathStartSegment.end)) {
	                // pathCopy segment's subpathStartSegment is different from original segment's one
	                // convert this Closepath segment to a Lineto and replace it in pathCopy
	                var convertedSegment = Path.createSegment('L', originalSegment.end);
	                pathCopy.replaceSegment(i, convertedSegment);
	            }
	        }

	        // distribute pathCopy segments into two paths and return those:

	        var firstPath = new Path(pathCopy.segments.slice(0, divisionMidIndex));
	        var secondPath = new Path(pathCopy.segments.slice(divisionMidIndex));

	        return [firstPath, secondPath];
	    },

	    // Checks whether two paths are exactly the same.
	    // If `p` is undefined or null, returns false.
	    equals: function(p) {

	        if (!p) { return false; }

	        var segments = this.segments;
	        var otherSegments = p.segments;

	        var numSegments = segments.length;
	        if (otherSegments.length !== numSegments) { return false; } // if the two paths have different number of segments, they cannot be equal

	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            var otherSegment = otherSegments[i];

	            // as soon as an inequality is found in segments, return false
	            if ((segment.type !== otherSegment.type) || (!segment.equals(otherSegment))) { return false; }
	        }

	        // if no inequality found in segments, return true
	        return true;
	    },

	    // Accepts negative indices.
	    // Throws an error if path has no segments.
	    // Throws an error if index is out of range.
	    getSegment: function(index) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { throw new Error('Path has no segments.'); }

	        if (index < 0) { index = numSegments + index; } // convert negative indices to positive
	        if (index >= numSegments || index < 0) { throw new Error('Index out of range.'); }

	        return segments[index];
	    },

	    // Returns an array of segment subdivisions, with precision better than requested `opt.precision`.
	    getSegmentSubdivisions: function(opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        // works even if path has no segments

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        // not using opt.segmentSubdivisions
	        // not using localOpt

	        var segmentSubdivisions = [];
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            var subdivisions = segment.getSubdivisions({ precision: precision });
	            segmentSubdivisions.push(subdivisions);
	        }

	        return segmentSubdivisions;
	    },

	    // Returns an array of subpaths of this path.
	    // Invalid paths are validated first.
	    // Returns `[]` if path has no segments.
	    getSubpaths: function() {

	        var validatedPath = this.clone().validate();

	        var segments = validatedPath.segments;
	        var numSegments = segments.length;

	        var subpaths = [];
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            if (segment.isSubpathStart) {
	                // we encountered a subpath start segment
	                // create a new path for segment, and push it to list of subpaths
	                subpaths.push(new Path(segment));

	            } else {
	                // append current segment to the last subpath
	                subpaths[subpaths.length - 1].appendSegment(segment);
	            }
	        }

	        return subpaths;
	    },

	    // Insert `arg` at given `index`.
	    // `index = 0` means insert at the beginning.
	    // `index = segments.length` means insert at the end.
	    // Accepts negative indices, from `-1` to `-(segments.length + 1)`.
	    // Accepts one segment or an array of segments as argument.
	    // Throws an error if index is out of range.
	    // Throws an error if argument is not a segment or an array of segments.
	    insertSegment: function(index, arg) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        // works even if path has no segments

	        // note that these are incremented compared to getSegments()
	        // we can insert after last element (note that this changes the meaning of index -1)
	        if (index < 0) { index = numSegments + index + 1; } // convert negative indices to positive
	        if (index > numSegments || index < 0) { throw new Error('Index out of range.'); }

	        var currentSegment;

	        var previousSegment = null;
	        var nextSegment = null;

	        if (numSegments !== 0) {
	            if (index >= 1) {
	                previousSegment = segments[index - 1];
	                nextSegment = previousSegment.nextSegment; // if we are inserting at end, nextSegment is null

	            } else { // if index === 0
	                // previousSegment is null
	                nextSegment = segments[0];
	            }
	        }

	        if (!Array.isArray(arg)) {
	            if (!arg || !arg.isSegment) { throw new Error('Segment required.'); }

	            currentSegment = this.prepareSegment(arg, previousSegment, nextSegment);
	            segments.splice(index, 0, currentSegment);

	        } else {
	            // flatten one level deep
	            // so we can chain arbitrary Path.createSegment results
	            arg = arg.reduce(function(acc, val) {
	                return acc.concat(val);
	            }, []);

	            if (!arg[0].isSegment) { throw new Error('Segments required.'); }

	            var n = arg.length;
	            for (var i = 0; i < n; i++) {

	                var currentArg = arg[i];
	                currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment);
	                segments.splice((index + i), 0, currentSegment); // incrementing index to insert subsequent segments after inserted segments
	                previousSegment = currentSegment;
	            }
	        }
	    },

	    intersectionWithLine: function(line, opt) {

	        var intersection = null;
	        var polylines = this.toPolylines(opt);
	        if (!polylines) { return null; }
	        for (var i = 0, n = polylines.length; i < n; i++) {
	            var polyline = polylines[i];
	            var polylineIntersection = line.intersect(polyline);
	            if (polylineIntersection) {
	                intersection || (intersection = []);
	                if (Array.isArray(polylineIntersection)) {
	                    Array.prototype.push.apply(intersection, polylineIntersection);
	                } else {
	                    intersection.push(polylineIntersection);
	                }
	            }
	        }

	        return intersection;
	    },

	    isDifferentiable: function() {

	        var segments = this.segments;
	        var numSegments = segments.length;

	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            // as soon as a differentiable segment is found in segments, return true
	            if (segment.isDifferentiable()) { return true; }
	        }

	        // if no differentiable segment is found in segments, return false
	        return false;
	    },

	    // Checks whether current path segments are valid.
	    // Note that d is allowed to be empty - should disable rendering of the path.
	    isValid: function() {

	        var segments = this.segments;
	        var isValid = (segments.length === 0) || (segments[0].type === 'M'); // either empty or first segment is a Moveto
	        return isValid;
	    },

	    // Returns length of the path, with precision better than requested `opt.precision`; or using `opt.segmentSubdivisions` provided.
	    // If path has no segments, returns 0.
	    length: function(opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return 0; } // if segments is an empty array

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSegmentSubdivisions() call
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var length = 0;
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            var subdivisions = segmentSubdivisions[i];
	            length += segment.length({ subdivisions: subdivisions });
	        }

	        return length;
	    },

	    // Private function.
	    lengthAtT: function(t, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return 0; } // if segments is an empty array

	        var segmentIndex = t.segmentIndex;
	        if (segmentIndex < 0) { return 0; } // regardless of t.value

	        var tValue = t.value;
	        if (segmentIndex >= numSegments) {
	            segmentIndex = numSegments - 1;
	            tValue = 1;
	        } else if (tValue < 0) { tValue = 0; }
	        else if (tValue > 1) { tValue = 1; }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var subdivisions;
	        var length = 0;
	        for (var i = 0; i < segmentIndex; i++) {

	            var segment = segments[i];
	            subdivisions = segmentSubdivisions[i];
	            length += segment.length({ precisison: precision, subdivisions: subdivisions });
	        }

	        segment = segments[segmentIndex];
	        subdivisions = segmentSubdivisions[segmentIndex];
	        length += segment.lengthAtT(tValue, { precisison: precision, subdivisions: subdivisions });

	        return length;
	    },

	    // Returns point at requested `ratio` between 0 and 1, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
	    pointAt: function(ratio, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        if (ratio <= 0) { return this.start.clone(); }
	        if (ratio >= 1) { return this.end.clone(); }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };

	        var pathLength = this.length(localOpt);
	        var length = pathLength * ratio;

	        return this.pointAtLength(length, localOpt);
	    },

	    // Returns point at requested `length`, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
	    // Accepts negative length.
	    pointAtLength: function(length, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        if (length === 0) { return this.start.clone(); }

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var lastVisibleSegment;
	        var l = 0; // length so far
	        for (var i = 0; i < numSegments; i++) {
	            var index = (fromStart ? i : (numSegments - 1 - i));

	            var segment = segments[index];
	            var subdivisions = segmentSubdivisions[index];
	            var d = segment.length({ precision: precision, subdivisions: subdivisions });

	            if (segment.isVisible) {
	                if (length <= (l + d)) {
	                    return segment.pointAtLength(((fromStart ? 1 : -1) * (length - l)), {
	                        precision: precision,
	                        subdivisions: subdivisions
	                    });
	                }

	                lastVisibleSegment = segment;
	            }

	            l += d;
	        }

	        // if length requested is higher than the length of the path, return last visible segment endpoint
	        if (lastVisibleSegment) { return (fromStart ? lastVisibleSegment.end : lastVisibleSegment.start); }

	        // if no visible segment, return last segment end point (no matter if fromStart or no)
	        var lastSegment = segments[numSegments - 1];
	        return lastSegment.end.clone();
	    },

	    // Private function.
	    pointAtT: function(t) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        var segmentIndex = t.segmentIndex;
	        if (segmentIndex < 0) { return segments[0].pointAtT(0); }
	        if (segmentIndex >= numSegments) { return segments[numSegments - 1].pointAtT(1); }

	        var tValue = t.value;
	        if (tValue < 0) { tValue = 0; }
	        else if (tValue > 1) { tValue = 1; }

	        return segments[segmentIndex].pointAtT(tValue);
	    },

	    // Default precision
	    PRECISION: 3,

	    // Helper method for adding segments.
	    prepareSegment: function(segment, previousSegment, nextSegment) {

	        // insert after previous segment and before previous segment's next segment
	        segment.previousSegment = previousSegment;
	        segment.nextSegment = nextSegment;
	        if (previousSegment) { previousSegment.nextSegment = segment; }
	        if (nextSegment) { nextSegment.previousSegment = segment; }

	        var updateSubpathStart = segment;
	        if (segment.isSubpathStart) {
	            segment.subpathStartSegment = segment; // assign self as subpath start segment
	            updateSubpathStart = nextSegment; // start updating from next segment
	        }

	        // assign previous segment's subpath start (or self if it is a subpath start) to subsequent segments
	        if (updateSubpathStart) { this.updateSubpathStartSegment(updateSubpathStart); }

	        return segment;
	    },

	    // Remove the segment at `index`.
	    // Accepts negative indices, from `-1` to `-segments.length`.
	    // Throws an error if path has no segments.
	    // Throws an error if index is out of range.
	    removeSegment: function(index) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { throw new Error('Path has no segments.'); }

	        if (index < 0) { index = numSegments + index; } // convert negative indices to positive
	        if (index >= numSegments || index < 0) { throw new Error('Index out of range.'); }

	        var removedSegment = segments.splice(index, 1)[0];
	        var previousSegment = removedSegment.previousSegment;
	        var nextSegment = removedSegment.nextSegment;

	        // link the previous and next segments together (if present)
	        if (previousSegment) { previousSegment.nextSegment = nextSegment; } // may be null
	        if (nextSegment) { nextSegment.previousSegment = previousSegment; } // may be null

	        // if removed segment used to start a subpath, update all subsequent segments until another subpath start segment is reached
	        if (removedSegment.isSubpathStart && nextSegment) { this.updateSubpathStartSegment(nextSegment); }
	    },

	    // Replace the segment at `index` with `arg`.
	    // Accepts negative indices, from `-1` to `-segments.length`.
	    // Accepts one segment or an array of segments as argument.
	    // Throws an error if path has no segments.
	    // Throws an error if index is out of range.
	    // Throws an error if argument is not a segment or an array of segments.
	    replaceSegment: function(index, arg) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { throw new Error('Path has no segments.'); }

	        if (index < 0) { index = numSegments + index; } // convert negative indices to positive
	        if (index >= numSegments || index < 0) { throw new Error('Index out of range.'); }

	        var currentSegment;

	        var replacedSegment = segments[index];
	        var previousSegment = replacedSegment.previousSegment;
	        var nextSegment = replacedSegment.nextSegment;

	        var updateSubpathStart = replacedSegment.isSubpathStart; // boolean: is an update of subpath starts necessary?

	        if (!Array.isArray(arg)) {
	            if (!arg || !arg.isSegment) { throw new Error('Segment required.'); }

	            currentSegment = this.prepareSegment(arg, previousSegment, nextSegment);
	            segments.splice(index, 1, currentSegment); // directly replace

	            if (updateSubpathStart && currentSegment.isSubpathStart) { updateSubpathStart = false; } // already updated by `prepareSegment`

	        } else {
	            // flatten one level deep
	            // so we can chain arbitrary Path.createSegment results
	            arg = arg.reduce(function(acc, val) {
	                return acc.concat(val);
	            }, []);

	            if (!arg[0].isSegment) { throw new Error('Segments required.'); }

	            segments.splice(index, 1);

	            var n = arg.length;
	            for (var i = 0; i < n; i++) {

	                var currentArg = arg[i];
	                currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment);
	                segments.splice((index + i), 0, currentSegment); // incrementing index to insert subsequent segments after inserted segments
	                previousSegment = currentSegment;

	                if (updateSubpathStart && currentSegment.isSubpathStart) { updateSubpathStart = false; } // already updated by `prepareSegment`
	            }
	        }

	        // if replaced segment used to start a subpath and no new subpath start was added, update all subsequent segments until another subpath start segment is reached
	        if (updateSubpathStart && nextSegment) { this.updateSubpathStartSegment(nextSegment); }
	    },

	    round: function(precision) {

	        var segments = this.segments;
	        var numSegments = segments.length;

	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            segment.round(precision);
	        }

	        return this;
	    },

	    scale: function(sx, sy, origin) {

	        var segments = this.segments;
	        var numSegments = segments.length;

	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            segment.scale(sx, sy, origin);
	        }

	        return this;
	    },

	    segmentAt: function(ratio, opt) {

	        var index = this.segmentIndexAt(ratio, opt);
	        if (!index) { return null; }

	        return this.getSegment(index);
	    },

	    // Accepts negative length.
	    segmentAtLength: function(length, opt) {

	        var index = this.segmentIndexAtLength(length, opt);
	        if (!index) { return null; }

	        return this.getSegment(index);
	    },

	    segmentIndexAt: function(ratio, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        if (ratio < 0) { ratio = 0; }
	        if (ratio > 1) { ratio = 1; }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };

	        var pathLength = this.length(localOpt);
	        var length = pathLength * ratio;

	        return this.segmentIndexAtLength(length, localOpt);
	    },

	    // Accepts negative length.
	    segmentIndexAtLength: function(length, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var lastVisibleSegmentIndex = null;
	        var l = 0; // length so far
	        for (var i = 0; i < numSegments; i++) {
	            var index = (fromStart ? i : (numSegments - 1 - i));

	            var segment = segments[index];
	            var subdivisions = segmentSubdivisions[index];
	            var d = segment.length({ precision: precision, subdivisions: subdivisions });

	            if (segment.isVisible) {
	                if (length <= (l + d)) { return index; }
	                lastVisibleSegmentIndex = index;
	            }

	            l += d;
	        }

	        // if length requested is higher than the length of the path, return last visible segment index
	        // if no visible segment, return null
	        return lastVisibleSegmentIndex;
	    },

	    // Returns a string that can be used to reconstruct the path.
	    // Additional error checking compared to toString (must start with M segment).
	    serialize: function() {

	        if (!this.isValid()) { throw new Error('Invalid path segments.'); }

	        return this.toString();
	    },

	    // Returns tangent line at requested `ratio` between 0 and 1, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
	    tangentAt: function(ratio, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        if (ratio < 0) { ratio = 0; }
	        if (ratio > 1) { ratio = 1; }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };

	        var pathLength = this.length(localOpt);
	        var length = pathLength * ratio;

	        return this.tangentAtLength(length, localOpt);
	    },

	    // Returns tangent line at requested `length`, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
	    // Accepts negative length.
	    tangentAtLength: function(length, opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        var fromStart = true;
	        if (length < 0) {
	            fromStart = false; // negative lengths mean start calculation from end point
	            length = -length; // absolute value
	        }

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
	        // not using localOpt

	        var lastValidSegment; // visible AND differentiable (with a tangent)
	        var l = 0; // length so far
	        for (var i = 0; i < numSegments; i++) {
	            var index = (fromStart ? i : (numSegments - 1 - i));

	            var segment = segments[index];
	            var subdivisions = segmentSubdivisions[index];
	            var d = segment.length({ precision: precision, subdivisions: subdivisions });

	            if (segment.isDifferentiable()) {
	                if (length <= (l + d)) {
	                    return segment.tangentAtLength(((fromStart ? 1 : -1) * (length - l)), {
	                        precision: precision,
	                        subdivisions: subdivisions
	                    });
	                }

	                lastValidSegment = segment;
	            }

	            l += d;
	        }

	        // if length requested is higher than the length of the path, return tangent of endpoint of last valid segment
	        if (lastValidSegment) {
	            var t = (fromStart ? 1 : 0);
	            return lastValidSegment.tangentAtT(t);
	        }

	        // if no valid segment, return null
	        return null;
	    },

	    // Private function.
	    tangentAtT: function(t) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        var segmentIndex = t.segmentIndex;
	        if (segmentIndex < 0) { return segments[0].tangentAtT(0); }
	        if (segmentIndex >= numSegments) { return segments[numSegments - 1].tangentAtT(1); }

	        var tValue = t.value;
	        if (tValue < 0) { tValue = 0; }
	        else if (tValue > 1) { tValue = 1; }

	        return segments[segmentIndex].tangentAtT(tValue);
	    },

	    toPoints: function(opt) {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; } // if segments is an empty array

	        opt = opt || {};
	        var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
	        var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;

	        var points = [];
	        var partialPoints = [];
	        for (var i = 0; i < numSegments; i++) {
	            var segment = segments[i];
	            if (segment.isVisible) {
	                var currentSegmentSubdivisions = segmentSubdivisions[i];
	                if (currentSegmentSubdivisions.length > 0) {
	                    var subdivisionPoints = currentSegmentSubdivisions.map(function(curve) {
	                        return curve.start;
	                    });
	                    Array.prototype.push.apply(partialPoints, subdivisionPoints);
	                } else {
	                    partialPoints.push(segment.start);
	                }
	            } else if (partialPoints.length > 0) {
	                partialPoints.push(segments[i - 1].end);
	                points.push(partialPoints);
	                partialPoints = [];
	            }
	        }

	        if (partialPoints.length > 0) {
	            partialPoints.push(this.end);
	            points.push(partialPoints);
	        }
	        return points;
	    },

	    toPolylines: function(opt) {

	        var polylines = [];
	        var points = this.toPoints(opt);
	        if (!points) { return null; }
	        for (var i = 0, n = points.length; i < n; i++) {
	            polylines.push(new Polyline(points[i]));
	        }

	        return polylines;
	    },

	    toString: function() {

	        var segments = this.segments;
	        var numSegments = segments.length;

	        var pathData = '';
	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            pathData += segment.serialize() + ' ';
	        }

	        return pathData.trim();
	    },

	    translate: function(tx, ty) {

	        var segments = this.segments;
	        var numSegments = segments.length;

	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            segment.translate(tx, ty);
	        }

	        return this;
	    },

	    // Helper method for updating subpath start of segments, starting with the one provided.
	    updateSubpathStartSegment: function(segment) {

	        var previousSegment = segment.previousSegment; // may be null
	        while (segment && !segment.isSubpathStart) {

	            // assign previous segment's subpath start segment to this segment
	            if (previousSegment) { segment.subpathStartSegment = previousSegment.subpathStartSegment; } // may be null
	            else { segment.subpathStartSegment = null; } // if segment had no previous segment, assign null - creates an invalid path!

	            previousSegment = segment;
	            segment = segment.nextSegment; // move on to the segment after etc.
	        }
	    },

	    // If the path is not valid, insert M 0 0 at the beginning.
	    // Path with no segments is considered valid, so nothing is inserted.
	    validate: function() {

	        if (!this.isValid()) { this.insertSegment(0, Path.createSegment('M', 0, 0)); }
	        return this;
	    }
	};

	Object.defineProperty(Path.prototype, 'start', {
	    // Getter for the first visible endpoint of the path.

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; }

	        for (var i = 0; i < numSegments; i++) {

	            var segment = segments[i];
	            if (segment.isVisible) { return segment.start; }
	        }

	        // if no visible segment, return last segment end point
	        return segments[numSegments - 1].end;
	    }
	});

	Object.defineProperty(Path.prototype, 'end', {
	    // Getter for the last visible endpoint of the path.

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        var segments = this.segments;
	        var numSegments = segments.length;
	        if (numSegments === 0) { return null; }

	        for (var i = numSegments - 1; i >= 0; i--) {

	            var segment = segments[i];
	            if (segment.isVisible) { return segment.end; }
	        }

	        // if no visible segment, return last segment end point
	        return segments[numSegments - 1].end;
	    }
	});


	// Local helper function.
	// Use an array of arguments to call a constructor (function called with `new`).
	// Adapted from https://stackoverflow.com/a/8843181/2263595
	// It is not necessary to use this function if the arguments can be passed separately (i.e. if the number of arguments is limited).
	// - If that is the case, use `new constructor(arg1, arg2)`, for example.
	// It is not necessary to use this function if the function that needs an array of arguments is not supposed to be used as a constructor.
	// - If that is the case, use `f.apply(thisArg, [arg1, arg2...])`, for example.
	function applyToNew(constructor, argsArray) {
	    // The `new` keyword can only be applied to functions that take a limited number of arguments.
	    // - We can fake that with .bind().
	    // - It calls a function (`constructor`, here) with the arguments that were provided to it - effectively transforming an unlimited number of arguments into limited.
	    // - So `new (constructor.bind(thisArg, arg1, arg2...))`
	    // - `thisArg` can be anything (e.g. null) because `new` keyword resets context to the constructor object.
	    // We need to pass in a variable number of arguments to the bind() call.
	    // - We can use .apply().
	    // - So `new (constructor.bind.apply(constructor, [thisArg, arg1, arg2...]))`
	    // - `thisArg` can still be anything because `new` overwrites it.
	    // Finally, to make sure that constructor.bind overwriting is not a problem, we switch to `Function.prototype.bind`.
	    // - So, the final version is `new (Function.prototype.bind.apply(constructor, [thisArg, arg1, arg2...]))`

	    // The function expects `argsArray[0]` to be `thisArg`.
	    // - This means that whatever is sent as the first element will be ignored.
	    // - The constructor will only see arguments starting from argsArray[1].
	    // - So, a new dummy element is inserted at the start of the array.
	    argsArray.unshift(null);

	    return new (Function.prototype.bind.apply(constructor, argsArray));
	}

	// Local helper function.
	// Add properties from arguments on top of properties from `obj`.
	// This allows for rudimentary inheritance.
	// - The `obj` argument acts as parent.
	// - This function creates a new object that inherits all `obj` properties and adds/replaces those that are present in arguments.
	// - A high-level example: calling `extend(Vehicle, Car)` would be akin to declaring `class Car extends Vehicle`.
	function extend(obj) {
	    var arguments$1 = arguments;

	    // In JavaScript, the combination of a constructor function (e.g. `g.Line = function(...) {...}`) and prototype (e.g. `g.Line.prototype = {...}) is akin to a C++ class.
	    // - When inheritance is not necessary, we can leave it at that. (This would be akin to calling extend with only `obj`.)
	    // - But, what if we wanted the `g.Line` quasiclass to inherit from another quasiclass (let's call it `g.GeometryObject`) in JavaScript?
	    // - First, realize that both of those quasiclasses would still have their own separate constructor function.
	    // - So what we are actually saying is that we want the `g.Line` prototype to inherit from `g.GeometryObject` prototype.
	    // - This method provides a way to do exactly that.
	    // - It copies parent prototype's properties, then adds extra ones from child prototype/overrides parent prototype properties with child prototype properties.
	    // - Therefore, to continue with the example above:
	    //   - `g.Line.prototype = extend(g.GeometryObject.prototype, linePrototype)`
	    //   - Where `linePrototype` is a properties object that looks just like `g.Line.prototype` does right now.
	    //   - Then, `g.Line` would allow the programmer to access to all methods currently in `g.Line.Prototype`, plus any non-overridden methods from `g.GeometryObject.prototype`.
	    //   - In that aspect, `g.GeometryObject` would then act like the parent of `g.Line`.
	    // - Multiple inheritance is also possible, if multiple arguments are provided.
	    // - What if we wanted to add another level of abstraction between `g.GeometryObject` and `g.Line` (let's call it `g.LinearObject`)?
	    //   - `g.Line.prototype = extend(g.GeometryObject.prototype, g.LinearObject.prototype, linePrototype)`
	    //   - The ancestors are applied in order of appearance.
	    //   - That means that `g.Line` would have inherited from `g.LinearObject` that would have inherited from `g.GeometryObject`.
	    //   - Any number of ancestors may be provided.
	    // - Note that neither `obj` nor any of the arguments need to actually be prototypes of any JavaScript quasiclass, that was just a simplified explanation.
	    // - We can create a new object composed from the properties of any number of other objects (since they do not have a constructor, we can think of those as interfaces).
	    //   - `extend({ a: 1, b: 2 }, { b: 10, c: 20 }, { c: 100, d: 200 })` gives `{ a: 1, b: 10, c: 100, d: 200 }`.
	    //   - Basically, with this function, we can emulate the `extends` keyword as well as the `implements` keyword.
	    // - Therefore, both of the following are valid:
	    //   - `Lineto.prototype = extend(Line.prototype, segmentPrototype, linetoPrototype)`
	    //   - `Moveto.prototype = extend(segmentPrototype, movetoPrototype)`

	    var i;
	    var n;

	    var args = [];
	    n = arguments.length;
	    for (i = 1; i < n; i++) { // skip over obj
	        args.push(arguments$1[i]);
	    }

	    if (!obj) { throw new Error('Missing a parent object.'); }
	    var child = Object.create(obj);

	    n = args.length;
	    for (i = 0; i < n; i++) {

	        var src = args[i];

	        var inheritedProperty;
	        var key;
	        for (key in src) {

	            if (src.hasOwnProperty(key)) {
	                delete child[key]; // delete property inherited from parent
	                inheritedProperty = Object.getOwnPropertyDescriptor(src, key); // get new definition of property from src
	                Object.defineProperty(child, key, inheritedProperty); // re-add property with new definition (includes getter/setter methods)
	            }
	        }
	    }

	    return child;
	}

	// Path segment interface:
	var segmentPrototype = {

	    // virtual
	    bbox: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    clone: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    closestPoint: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    closestPointLength: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    closestPointNormalizedLength: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // Redirect calls to closestPointNormalizedLength() function if closestPointT() is not defined for segment.
	    closestPointT: function(p) {

	        if (this.closestPointNormalizedLength) { return this.closestPointNormalizedLength(p); }

	        throw new Error('Neither closestPointT() nor closestPointNormalizedLength() function is implemented.');
	    },

	    // virtual
	    closestPointTangent: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    divideAt: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    divideAtLength: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // Redirect calls to divideAt() function if divideAtT() is not defined for segment.
	    divideAtT: function(t) {

	        if (this.divideAt) { return this.divideAt(t); }

	        throw new Error('Neither divideAtT() nor divideAt() function is implemented.');
	    },

	    // virtual
	    equals: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    getSubdivisions: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    isDifferentiable: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    isSegment: true,

	    isSubpathStart: false, // true for Moveto segments

	    isVisible: true, // false for Moveto segments

	    // virtual
	    length: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // Return a fraction of result of length() function if lengthAtT() is not defined for segment.
	    lengthAtT: function(t) {

	        if (t <= 0) { return 0; }

	        var length = this.length();

	        if (t >= 1) { return length; }

	        return length * t;
	    },

	    nextSegment: null, // needed for subpath start segment updating

	    // virtual
	    pointAt: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    pointAtLength: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // Redirect calls to pointAt() function if pointAtT() is not defined for segment.
	    pointAtT: function(t) {

	        if (this.pointAt) { return this.pointAt(t); }

	        throw new Error('Neither pointAtT() nor pointAt() function is implemented.');
	    },

	    previousSegment: null, // needed to get segment start property

	    // virtual
	    round: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    subpathStartSegment: null, // needed to get Closepath segment end property

	    // virtual
	    scale: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    serialize: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    tangentAt: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    tangentAtLength: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // Redirect calls to tangentAt() function if tangentAtT() is not defined for segment.
	    tangentAtT: function(t) {

	        if (this.tangentAt) { return this.tangentAt(t); }

	        throw new Error('Neither tangentAtT() nor tangentAt() function is implemented.');
	    },

	    // virtual
	    toString: function() {

	        throw new Error('Declaration missing for virtual function.');
	    },

	    // virtual
	    translate: function() {

	        throw new Error('Declaration missing for virtual function.');
	    }
	};

	// usually directly assigned
	// getter for Closepath
	Object.defineProperty(segmentPrototype, 'end', {

	    configurable: true,

	    enumerable: true,

	    writable: true
	});

	// always a getter
	// always throws error for Moveto
	Object.defineProperty(segmentPrototype, 'start', {
	    // get a reference to the end point of previous segment

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        if (!this.previousSegment) { throw new Error('Missing previous segment. (This segment cannot be the first segment of a path; OR segment has not yet been added to a path.)'); }

	        return this.previousSegment.end;
	    }
	});

	// virtual
	Object.defineProperty(segmentPrototype, 'type', {

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        throw new Error('Bad segment declaration. No type specified.');
	    }
	});

	// Path segment implementations:
	var Lineto = function() {
	    var arguments$1 = arguments;


	    var args = [];
	    var n = arguments.length;
	    for (var i = 0; i < n; i++) {
	        args.push(arguments$1[i]);
	    }

	    if (!(this instanceof Lineto)) { // switching context of `this` to Lineto when called without `new`
	        return applyToNew(Lineto, args);
	    }

	    if (n === 0) {
	        throw new Error('Lineto constructor expects a line, 1 point, or 2 coordinates (none provided).');
	    }

	    var outputArray;

	    if (args[0] instanceof Line) { // lines provided
	        if (n === 1) {
	            this.end = args[0].end.clone();
	            return this;

	        } else {
	            throw new Error('Lineto constructor expects a line, 1 point, or 2 coordinates (' + n + ' lines provided).');
	        }

	    } else if (typeof args[0] === 'string' || typeof args[0] === 'number') { // coordinates provided
	        if (n === 2) {
	            this.end = new Point(+args[0], +args[1]);
	            return this;

	        } else if (n < 2) {
	            throw new Error('Lineto constructor expects a line, 1 point, or 2 coordinates (' + n + ' coordinates provided).');

	        } else { // this is a poly-line segment
	            var segmentCoords;
	            outputArray = [];
	            for (i = 0; i < n; i += 2) { // coords come in groups of two

	                segmentCoords = args.slice(i, i + 2); // will send one coord if args.length not divisible by 2
	                outputArray.push(applyToNew(Lineto, segmentCoords));
	            }
	            return outputArray;
	        }

	    } else { // points provided (needs to be last to also cover plain objects with x and y)
	        if (n === 1) {
	            this.end = new Point(args[0]);
	            return this;

	        } else { // this is a poly-line segment
	            var segmentPoint;
	            outputArray = [];
	            for (i = 0; i < n; i += 1) {

	                segmentPoint = args[i];
	                outputArray.push(new Lineto(segmentPoint));
	            }
	            return outputArray;
	        }
	    }
	};

	var linetoPrototype = {

	    clone: function() {

	        return new Lineto(this.end);
	    },

	    divideAt: function(ratio) {

	        var line = new Line(this.start, this.end);
	        var divided = line.divideAt(ratio);
	        return [
	            new Lineto(divided[0]),
	            new Lineto(divided[1])
	        ];
	    },

	    divideAtLength: function(length) {

	        var line = new Line(this.start, this.end);
	        var divided = line.divideAtLength(length);
	        return [
	            new Lineto(divided[0]),
	            new Lineto(divided[1])
	        ];
	    },

	    getSubdivisions: function() {

	        return [];
	    },

	    isDifferentiable: function() {

	        if (!this.previousSegment) { return false; }

	        return !this.start.equals(this.end);
	    },

	    round: function(precision) {

	        this.end.round(precision);
	        return this;
	    },

	    scale: function(sx, sy, origin) {

	        this.end.scale(sx, sy, origin);
	        return this;
	    },

	    serialize: function() {

	        var end = this.end;
	        return this.type + ' ' + end.x + ' ' + end.y;
	    },

	    toString: function() {

	        return this.type + ' ' + this.start + ' ' + this.end;
	    },

	    translate: function(tx, ty) {

	        this.end.translate(tx, ty);
	        return this;
	    }
	};

	Object.defineProperty(linetoPrototype, 'type', {

	    configurable: true,

	    enumerable: true,

	    value: 'L'
	});

	Lineto.prototype = extend(segmentPrototype, Line.prototype, linetoPrototype);

	var Curveto = function() {
	    var arguments$1 = arguments;


	    var args = [];
	    var n = arguments.length;
	    for (var i = 0; i < n; i++) {
	        args.push(arguments$1[i]);
	    }

	    if (!(this instanceof Curveto)) { // switching context of `this` to Curveto when called without `new`
	        return applyToNew(Curveto, args);
	    }

	    if (n === 0) {
	        throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (none provided).');
	    }

	    var outputArray;

	    if (args[0] instanceof Curve) { // curves provided
	        if (n === 1) {
	            this.controlPoint1 = args[0].controlPoint1.clone();
	            this.controlPoint2 = args[0].controlPoint2.clone();
	            this.end = args[0].end.clone();
	            return this;

	        } else {
	            throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (' + n + ' curves provided).');
	        }

	    } else if (typeof args[0] === 'string' || typeof args[0] === 'number') { // coordinates provided
	        if (n === 6) {
	            this.controlPoint1 = new Point(+args[0], +args[1]);
	            this.controlPoint2 = new Point(+args[2], +args[3]);
	            this.end = new Point(+args[4], +args[5]);
	            return this;

	        } else if (n < 6) {
	            throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (' + n + ' coordinates provided).');

	        } else { // this is a poly-bezier segment
	            var segmentCoords;
	            outputArray = [];
	            for (i = 0; i < n; i += 6) { // coords come in groups of six

	                segmentCoords = args.slice(i, i + 6); // will send fewer than six coords if args.length not divisible by 6
	                outputArray.push(applyToNew(Curveto, segmentCoords));
	            }
	            return outputArray;
	        }

	    } else { // points provided (needs to be last to also cover plain objects with x and y)
	        if (n === 3) {
	            this.controlPoint1 = new Point(args[0]);
	            this.controlPoint2 = new Point(args[1]);
	            this.end = new Point(args[2]);
	            return this;

	        } else if (n < 3) {
	            throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (' + n + ' points provided).');

	        } else { // this is a poly-bezier segment
	            var segmentPoints;
	            outputArray = [];
	            for (i = 0; i < n; i += 3) { // points come in groups of three

	                segmentPoints = args.slice(i, i + 3); // will send fewer than three points if args.length is not divisible by 3
	                outputArray.push(applyToNew(Curveto, segmentPoints));
	            }
	            return outputArray;
	        }
	    }
	};

	var curvetoPrototype = {

	    clone: function() {

	        return new Curveto(this.controlPoint1, this.controlPoint2, this.end);
	    },

	    divideAt: function(ratio, opt) {

	        var curve = new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
	        var divided = curve.divideAt(ratio, opt);
	        return [
	            new Curveto(divided[0]),
	            new Curveto(divided[1])
	        ];
	    },

	    divideAtLength: function(length, opt) {

	        var curve = new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
	        var divided = curve.divideAtLength(length, opt);
	        return [
	            new Curveto(divided[0]),
	            new Curveto(divided[1])
	        ];
	    },

	    divideAtT: function(t) {

	        var curve = new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
	        var divided = curve.divideAtT(t);
	        return [
	            new Curveto(divided[0]),
	            new Curveto(divided[1])
	        ];
	    },

	    isDifferentiable: function() {

	        if (!this.previousSegment) { return false; }

	        var start = this.start;
	        var control1 = this.controlPoint1;
	        var control2 = this.controlPoint2;
	        var end = this.end;

	        return !(start.equals(control1) && control1.equals(control2) && control2.equals(end));
	    },

	    round: function(precision) {

	        this.controlPoint1.round(precision);
	        this.controlPoint2.round(precision);
	        this.end.round(precision);
	        return this;
	    },

	    scale: function(sx, sy, origin) {

	        this.controlPoint1.scale(sx, sy, origin);
	        this.controlPoint2.scale(sx, sy, origin);
	        this.end.scale(sx, sy, origin);
	        return this;
	    },

	    serialize: function() {

	        var c1 = this.controlPoint1;
	        var c2 = this.controlPoint2;
	        var end = this.end;
	        return this.type + ' ' + c1.x + ' ' + c1.y + ' ' + c2.x + ' ' + c2.y + ' ' + end.x + ' ' + end.y;
	    },

	    toString: function() {

	        return this.type + ' ' + this.start + ' ' + this.controlPoint1 + ' ' + this.controlPoint2 + ' ' + this.end;
	    },

	    translate: function(tx, ty) {

	        this.controlPoint1.translate(tx, ty);
	        this.controlPoint2.translate(tx, ty);
	        this.end.translate(tx, ty);
	        return this;
	    }
	};

	Object.defineProperty(curvetoPrototype, 'type', {

	    configurable: true,

	    enumerable: true,

	    value: 'C'
	});

	Curveto.prototype = extend(segmentPrototype, Curve.prototype, curvetoPrototype);

	var Moveto = function() {
	    var arguments$1 = arguments;


	    var args = [];
	    var n = arguments.length;
	    for (var i = 0; i < n; i++) {
	        args.push(arguments$1[i]);
	    }

	    if (!(this instanceof Moveto)) { // switching context of `this` to Moveto when called without `new`
	        return applyToNew(Moveto, args);
	    }

	    if (n === 0) {
	        throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (none provided).');
	    }

	    var outputArray;

	    if (args[0] instanceof Line) { // lines provided
	        if (n === 1) {
	            this.end = args[0].end.clone();
	            return this;

	        } else {
	            throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (' + n + ' lines provided).');
	        }

	    } else if (args[0] instanceof Curve) { // curves provided
	        if (n === 1) {
	            this.end = args[0].end.clone();
	            return this;

	        } else {
	            throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (' + n + ' curves provided).');
	        }

	    } else if (typeof args[0] === 'string' || typeof args[0] === 'number') { // coordinates provided
	        if (n === 2) {
	            this.end = new Point(+args[0], +args[1]);
	            return this;

	        } else if (n < 2) {
	            throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (' + n + ' coordinates provided).');

	        } else { // this is a moveto-with-subsequent-poly-line segment
	            var segmentCoords;
	            outputArray = [];
	            for (i = 0; i < n; i += 2) { // coords come in groups of two

	                segmentCoords = args.slice(i, i + 2); // will send one coord if args.length not divisible by 2
	                if (i === 0) { outputArray.push(applyToNew(Moveto, segmentCoords)); }
	                else { outputArray.push(applyToNew(Lineto, segmentCoords)); }
	            }
	            return outputArray;
	        }

	    } else { // points provided (needs to be last to also cover plain objects with x and y)
	        if (n === 1) {
	            this.end = new Point(args[0]);
	            return this;

	        } else { // this is a moveto-with-subsequent-poly-line segment
	            var segmentPoint;
	            outputArray = [];
	            for (i = 0; i < n; i += 1) { // points come one by one

	                segmentPoint = args[i];
	                if (i === 0) { outputArray.push(new Moveto(segmentPoint)); }
	                else { outputArray.push(new Lineto(segmentPoint)); }
	            }
	            return outputArray;
	        }
	    }
	};

	var movetoPrototype = {

	    bbox: function() {

	        return null;
	    },

	    clone: function() {

	        return new Moveto(this.end);
	    },

	    closestPoint: function() {

	        return this.end.clone();
	    },

	    closestPointNormalizedLength: function() {

	        return 0;
	    },

	    closestPointLength: function() {

	        return 0;
	    },

	    closestPointT: function() {

	        return 1;
	    },

	    closestPointTangent: function() {

	        return null;
	    },

	    divideAt: function() {

	        return [
	            this.clone(),
	            this.clone()
	        ];
	    },

	    divideAtLength: function() {

	        return [
	            this.clone(),
	            this.clone()
	        ];
	    },

	    equals: function(m) {

	        return this.end.equals(m.end);
	    },

	    getSubdivisions: function() {

	        return [];
	    },

	    isDifferentiable: function() {

	        return false;
	    },

	    isSubpathStart: true,

	    isVisible: false,

	    length: function() {

	        return 0;
	    },

	    lengthAtT: function() {

	        return 0;
	    },

	    pointAt: function() {

	        return this.end.clone();
	    },

	    pointAtLength: function() {

	        return this.end.clone();
	    },

	    pointAtT: function() {

	        return this.end.clone();
	    },

	    round: function(precision) {

	        this.end.round(precision);
	        return this;
	    },

	    scale: function(sx, sy, origin) {

	        this.end.scale(sx, sy, origin);
	        return this;
	    },

	    serialize: function() {

	        var end = this.end;
	        return this.type + ' ' + end.x + ' ' + end.y;
	    },

	    tangentAt: function() {

	        return null;
	    },

	    tangentAtLength: function() {

	        return null;
	    },

	    tangentAtT: function() {

	        return null;
	    },

	    toString: function() {

	        return this.type + ' ' + this.end;
	    },

	    translate: function(tx, ty) {

	        this.end.translate(tx, ty);
	        return this;
	    }
	};

	Object.defineProperty(movetoPrototype, 'start', {

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        throw new Error('Illegal access. Moveto segments should not need a start property.');
	    }
	});

	Object.defineProperty(movetoPrototype, 'type', {

	    configurable: true,

	    enumerable: true,

	    value: 'M'
	});

	Moveto.prototype = extend(segmentPrototype, movetoPrototype); // does not inherit from any other geometry object

	var Closepath = function() {
	    var arguments$1 = arguments;


	    var args = [];
	    var n = arguments.length;
	    for (var i = 0; i < n; i++) {
	        args.push(arguments$1[i]);
	    }

	    if (!(this instanceof Closepath)) { // switching context of `this` to Closepath when called without `new`
	        return applyToNew(Closepath, args);
	    }

	    if (n > 0) {
	        throw new Error('Closepath constructor expects no arguments.');
	    }

	    return this;
	};

	var closepathPrototype = {

	    clone: function() {

	        return new Closepath();
	    },

	    divideAt: function(ratio) {

	        var line = new Line(this.start, this.end);
	        var divided = line.divideAt(ratio);
	        return [
	            // if we didn't actually cut into the segment, first divided part can stay as Z
	            (divided[1].isDifferentiable() ? new Lineto(divided[0]) : this.clone()),
	            new Lineto(divided[1])
	        ];
	    },

	    divideAtLength: function(length) {

	        var line = new Line(this.start, this.end);
	        var divided = line.divideAtLength(length);
	        return [
	            // if we didn't actually cut into the segment, first divided part can stay as Z
	            (divided[1].isDifferentiable() ? new Lineto(divided[0]) : this.clone()),
	            new Lineto(divided[1])
	        ];
	    },

	    getSubdivisions: function() {

	        return [];
	    },

	    isDifferentiable: function() {

	        if (!this.previousSegment || !this.subpathStartSegment) { return false; }

	        return !this.start.equals(this.end);
	    },

	    round: function() {

	        return this;
	    },

	    scale: function() {

	        return this;
	    },

	    serialize: function() {

	        return this.type;
	    },

	    toString: function() {

	        return this.type + ' ' + this.start + ' ' + this.end;
	    },

	    translate: function() {

	        return this;
	    }
	};

	Object.defineProperty(closepathPrototype, 'end', {
	    // get a reference to the end point of subpath start segment

	    configurable: true,

	    enumerable: true,

	    get: function() {

	        if (!this.subpathStartSegment) { throw new Error('Missing subpath start segment. (This segment needs a subpath start segment (e.g. Moveto); OR segment has not yet been added to a path.)'); }

	        return this.subpathStartSegment.end;
	    }
	});

	Object.defineProperty(closepathPrototype, 'type', {

	    configurable: true,

	    enumerable: true,

	    value: 'Z'
	});

	Closepath.prototype = extend(segmentPrototype, Line.prototype, closepathPrototype);

	var segmentTypes = Path.segmentTypes = {
	    L: Lineto,
	    C: Curveto,
	    M: Moveto,
	    Z: Closepath,
	    z: Closepath
	};

	Path.regexSupportedData = new RegExp('^[\\s\\d' + Object.keys(segmentTypes).join('') + ',.]*$');

	Path.isDataSupported = function(data) {

	    if (typeof data !== 'string') { return false; }
	    return this.regexSupportedData.test(data);
	};

	var bezier = {

	    // Cubic Bezier curve path through points.
	    // @deprecated
	    // @param {array} points Array of points through which the smooth line will go.
	    // @return {array} SVG Path commands as an array
	    curveThroughPoints: function(points) {

	        console.warn('deprecated');

	        return new Path(Curve.throughPoints(points)).serialize();
	    },

	    // Get open-ended Bezier Spline Control Points.
	    // @deprecated
	    // @param knots Input Knot Bezier spline points (At least two points!).
	    // @param firstControlPoints Output First Control points. Array of knots.length - 1 length.
	    // @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
	    getCurveControlPoints: function(knots) {

	        console.warn('deprecated');

	        var firstControlPoints = [];
	        var secondControlPoints = [];
	        var n = knots.length - 1;
	        var i;

	        // Special case: Bezier curve should be a straight line.
	        if (n == 1) {
	            // 3P1 = 2P0 + P3
	            firstControlPoints[0] = new Point(
	                (2 * knots[0].x + knots[1].x) / 3,
	                (2 * knots[0].y + knots[1].y) / 3
	            );

	            // P2 = 2P1 – P0
	            secondControlPoints[0] = new Point(
	                2 * firstControlPoints[0].x - knots[0].x,
	                2 * firstControlPoints[0].y - knots[0].y
	            );

	            return [firstControlPoints, secondControlPoints];
	        }

	        // Calculate first Bezier control points.
	        // Right hand side vector.
	        var rhs = [];

	        // Set right hand side X values.
	        for (i = 1; i < n - 1; i++) {
	            rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
	        }

	        rhs[0] = knots[0].x + 2 * knots[1].x;
	        rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;

	        // Get first control points X-values.
	        var x = this.getFirstControlPoints(rhs);

	        // Set right hand side Y values.
	        for (i = 1; i < n - 1; ++i) {
	            rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
	        }

	        rhs[0] = knots[0].y + 2 * knots[1].y;
	        rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;

	        // Get first control points Y-values.
	        var y = this.getFirstControlPoints(rhs);

	        // Fill output arrays.
	        for (i = 0; i < n; i++) {
	            // First control point.
	            firstControlPoints.push(new Point(x[i], y[i]));

	            // Second control point.
	            if (i < n - 1) {
	                secondControlPoints.push(new Point(
	                    2 * knots [i + 1].x - x[i + 1],
	                    2 * knots[i + 1].y - y[i + 1]
	                ));

	            } else {
	                secondControlPoints.push(new Point(
	                    (knots[n].x + x[n - 1]) / 2,
	                    (knots[n].y + y[n - 1]) / 2)
	                );
	            }
	        }

	        return [firstControlPoints, secondControlPoints];
	    },

	    // Divide a Bezier curve into two at point defined by value 't' <0,1>.
	    // Using deCasteljau algorithm. http://math.stackexchange.com/a/317867
	    // @deprecated
	    // @param control points (start, control start, control end, end)
	    // @return a function that accepts t and returns 2 curves.
	    getCurveDivider: function(p0, p1, p2, p3) {

	        console.warn('deprecated');

	        var curve = new Curve(p0, p1, p2, p3);

	        return function divideCurve(t) {

	            var divided = curve.divide(t);

	            return [{
	                p0: divided[0].start,
	                p1: divided[0].controlPoint1,
	                p2: divided[0].controlPoint2,
	                p3: divided[0].end
	            }, {
	                p0: divided[1].start,
	                p1: divided[1].controlPoint1,
	                p2: divided[1].controlPoint2,
	                p3: divided[1].end
	            }];
	        };
	    },

	    // Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points.
	    // @deprecated
	    // @param rhs Right hand side vector.
	    // @return Solution vector.
	    getFirstControlPoints: function(rhs) {

	        console.warn('deprecated');

	        var n = rhs.length;
	        // `x` is a solution vector.
	        var x = [];
	        var tmp = [];
	        var b = 2.0;

	        x[0] = rhs[0] / b;

	        // Decomposition and forward substitution.
	        for (var i = 1; i < n; i++) {
	            tmp[i] = 1 / b;
	            b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
	            x[i] = (rhs[i] - x[i - 1]) / b;
	        }

	        for (i = 1; i < n; i++) {
	            // Backsubstitution.
	            x[n - i - 1] -= tmp[n - i] * x[n - i];
	        }

	        return x;
	    },

	    // Solves an inversion problem -- Given the (x, y) coordinates of a point which lies on
	    // a parametric curve x = x(t)/w(t), y = y(t)/w(t), ﬁnd the parameter value t
	    // which corresponds to that point.
	    // @deprecated
	    // @param control points (start, control start, control end, end)
	    // @return a function that accepts a point and returns t.
	    getInversionSolver: function(p0, p1, p2, p3) {

	        console.warn('deprecated');

	        var curve = new Curve(p0, p1, p2, p3);

	        return function solveInversion(p) {

	            return curve.closestPointT(p);
	        };
	    }
	};

	// Geometry library.

	var g = ({
		scale: scale,
		normalizeAngle: normalizeAngle,
		snapToGrid: snapToGrid,
		toDeg: toDeg,
		toRad: toRad,
		random: random,
		bezier: bezier,
		Curve: Curve,
		Ellipse: Ellipse,
		ellipse: ellipse,
		Line: Line,
		line: line,
		Path: Path,
		Point: Point,
		point: point,
		Polyline: Polyline,
		Rect: Rect,
		rect: rect
	});

	// Vectorizer.

	var V = (function() {

	    var hasSvg = typeof window === 'object' &&
	        !!(
	            window.SVGAngle ||
	            document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1')
	        );

	    // SVG support is required.
	    if (!hasSvg) {

	        // Return a function that throws an error when it is used.
	        return function() {
	            throw new Error('SVG is required to use Vectorizer.');
	        };
	    }

	    // XML namespaces.
	    var ns = {
	        svg: 'http://www.w3.org/2000/svg',
	        xmlns: 'http://www.w3.org/2000/xmlns/',
	        xml: 'http://www.w3.org/XML/1998/namespace',
	        xlink: 'http://www.w3.org/1999/xlink',
	        xhtml: 'http://www.w3.org/1999/xhtml'
	    };

	    var SVGVersion = '1.1';

	    // Declare shorthands to the most used math functions.
	    var math = Math;
	    var PI = math.PI;
	    var atan2 = math.atan2;
	    var sqrt = math.sqrt;
	    var min = math.min;
	    var max = math.max;
	    var cos = math.cos;
	    var sin = math.sin;

	    var V = function(el, attrs, children) {

	        // This allows using V() without the new keyword.
	        if (!(this instanceof V)) {
	            return V.apply(Object.create(V.prototype), arguments);
	        }

	        if (!el) { return; }

	        if (V.isV(el)) {
	            el = el.node;
	        }

	        attrs = attrs || {};

	        if (V.isString(el)) {

	            if (el.toLowerCase() === 'svg') {

	                // Create a new SVG canvas.
	                el = V.createSvgDocument();

	            } else if (el[0] === '<') {

	                // Create element from an SVG string.
	                // Allows constructs of type: `document.appendChild(V('<rect></rect>').node)`.

	                var svgDoc = V.createSvgDocument(el);

	                // Note that `V()` might also return an array should the SVG string passed as
	                // the first argument contain more than one root element.
	                if (svgDoc.childNodes.length > 1) {

	                    // Map child nodes to `V`s.
	                    var arrayOfVels = [];
	                    var i, len;

	                    for (i = 0, len = svgDoc.childNodes.length; i < len; i++) {

	                        var childNode = svgDoc.childNodes[i];
	                        arrayOfVels.push(new V(document.importNode(childNode, true)));
	                    }

	                    return arrayOfVels;
	                }

	                el = document.importNode(svgDoc.firstChild, true);

	            } else {

	                el = document.createElementNS(ns.svg, el);
	            }

	            V.ensureId(el);
	        }

	        this.node = el;

	        this.setAttributes(attrs);

	        if (children) {
	            this.append(children);
	        }

	        return this;
	    };

	    var VPrototype = V.prototype;

	    Object.defineProperty(VPrototype, 'id', {
	        enumerable: true,
	        get: function() {
	            return this.node.id;
	        },
	        set: function(id) {
	            this.node.id = id;
	        }
	    });

	    /**
	     * @param {SVGGElement} toElem
	     * @returns {SVGMatrix}
	     */
	    VPrototype.getTransformToElement = function(target) {
	        var node = this.node;
	        if (V.isSVGGraphicsElement(target) && V.isSVGGraphicsElement(node)) {
	            var targetCTM = V.toNode(target).getScreenCTM();
	            var nodeCTM = node.getScreenCTM();
	            if (targetCTM && nodeCTM) {
	                return targetCTM.inverse().multiply(nodeCTM);
	            }
	        }
	        // Could not get actual transformation matrix
	        return V.createSVGMatrix();
	    };

	    /**
	     * @param {SVGMatrix} matrix
	     * @param {Object=} opt
	     * @returns {Vectorizer|SVGMatrix} Setter / Getter
	     */
	    VPrototype.transform = function(matrix, opt) {

	        var node = this.node;
	        if (V.isUndefined(matrix)) {
	            return V.transformStringToMatrix(this.attr('transform'));
	        }

	        if (opt && opt.absolute) {
	            return this.attr('transform', V.matrixToTransformString(matrix));
	        }

	        var svgTransform = V.createSVGTransform(matrix);
	        node.transform.baseVal.appendItem(svgTransform);
	        return this;
	    };

	    VPrototype.translate = function(tx, ty, opt) {

	        opt = opt || {};
	        ty = ty || 0;

	        var transformAttr = this.attr('transform') || '';
	        var transform = V.parseTransformString(transformAttr);
	        transformAttr = transform.value;
	        // Is it a getter?
	        if (V.isUndefined(tx)) {
	            return transform.translate;
	        }

	        transformAttr = transformAttr.replace(/translate\([^)]*\)/g, '').trim();

	        var newTx = opt.absolute ? tx : transform.translate.tx + tx;
	        var newTy = opt.absolute ? ty : transform.translate.ty + ty;
	        var newTranslate = 'translate(' + newTx + ',' + newTy + ')';

	        // Note that `translate()` is always the first transformation. This is
	        // usually the desired case.
	        this.attr('transform', (newTranslate + ' ' + transformAttr).trim());
	        return this;
	    };

	    VPrototype.rotate = function(angle, cx, cy, opt) {

	        opt = opt || {};

	        var transformAttr = this.attr('transform') || '';
	        var transform = V.parseTransformString(transformAttr);
	        transformAttr = transform.value;

	        // Is it a getter?
	        if (V.isUndefined(angle)) {
	            return transform.rotate;
	        }

	        transformAttr = transformAttr.replace(/rotate\([^)]*\)/g, '').trim();

	        angle %= 360;

	        var newAngle = opt.absolute ? angle : transform.rotate.angle + angle;
	        var newOrigin = (cx !== undefined && cy !== undefined) ? ',' + cx + ',' + cy : '';
	        var newRotate = 'rotate(' + newAngle + newOrigin + ')';

	        this.attr('transform', (transformAttr + ' ' + newRotate).trim());
	        return this;
	    };

	    // Note that `scale` as the only transformation does not combine with previous values.
	    VPrototype.scale = function(sx, sy) {

	        sy = V.isUndefined(sy) ? sx : sy;

	        var transformAttr = this.attr('transform') || '';
	        var transform = V.parseTransformString(transformAttr);
	        transformAttr = transform.value;

	        // Is it a getter?
	        if (V.isUndefined(sx)) {
	            return transform.scale;
	        }

	        transformAttr = transformAttr.replace(/scale\([^)]*\)/g, '').trim();

	        var newScale = 'scale(' + sx + ',' + sy + ')';

	        this.attr('transform', (transformAttr + ' ' + newScale).trim());
	        return this;
	    };

	    // Get SVGRect that contains coordinates and dimension of the real bounding box,
	    // i.e. after transformations are applied.
	    // If `target` is specified, bounding box will be computed relatively to `target` element.
	    VPrototype.bbox = function(withoutTransformations, target) {

	        var box;
	        var node = this.node;
	        var ownerSVGElement = node.ownerSVGElement;

	        // If the element is not in the live DOM, it does not have a bounding box defined and
	        // so fall back to 'zero' dimension element.
	        if (!ownerSVGElement) {
	            return new Rect(0, 0, 0, 0);
	        }

	        try {

	            box = node.getBBox();

	        } catch (e) {

	            // Fallback for IE.
	            box = {
	                x: node.clientLeft,
	                y: node.clientTop,
	                width: node.clientWidth,
	                height: node.clientHeight
	            };
	        }

	        if (withoutTransformations) {
	            return new Rect(box);
	        }

	        var matrix = this.getTransformToElement(target || ownerSVGElement);

	        return V.transformRect(box, matrix);
	    };

	    // Returns an SVGRect that contains coordinates and dimensions of the real bounding box,
	    // i.e. after transformations are applied.
	    // Fixes a browser implementation bug that returns incorrect bounding boxes for groups of svg elements.
	    // Takes an (Object) `opt` argument (optional) with the following attributes:
	    // (Object) `target` (optional): if not undefined, transform bounding boxes relative to `target`; if undefined, transform relative to this
	    // (Boolean) `recursive` (optional): if true, recursively enter all groups and get a union of element bounding boxes (svg bbox fix); if false or undefined, return result of native function this.node.getBBox();
	    VPrototype.getBBox = function(opt) {

	        var options = {};

	        var outputBBox;
	        var node = this.node;
	        var ownerSVGElement = node.ownerSVGElement;

	        // If the element is not in the live DOM, it does not have a bounding box defined and
	        // so fall back to 'zero' dimension element.
	        // If the element is not an SVGGraphicsElement, we could not measure the bounding box either
	        if (!ownerSVGElement || !V.isSVGGraphicsElement(node)) {
	            return new Rect(0, 0, 0, 0);
	        }

	        if (opt) {
	            if (opt.target) { // check if target exists
	                options.target = V.toNode(opt.target); // works for V objects, jquery objects, and node objects
	            }
	            if (opt.recursive) {
	                options.recursive = opt.recursive;
	            }
	        }

	        if (!options.recursive) {
	            try {
	                outputBBox = node.getBBox();
	            } catch (e) {
	                // Fallback for IE.
	                outputBBox = {
	                    x: node.clientLeft,
	                    y: node.clientTop,
	                    width: node.clientWidth,
	                    height: node.clientHeight
	                };
	            }

	            if (!options.target) {
	                // transform like this (that is, not at all)
	                return new Rect(outputBBox);
	            } else {
	                // transform like target
	                var matrix = this.getTransformToElement(options.target);
	                return V.transformRect(outputBBox, matrix);
	            }
	        } else { // if we want to calculate the bbox recursively
	            // browsers report correct bbox around svg elements (one that envelops the path lines tightly)
	            // but some browsers fail to report the same bbox when the elements are in a group (returning a looser bbox that also includes control points, like node.getClientRect())
	            // this happens even if we wrap a single svg element into a group!
	            // this option setting makes the function recursively enter all the groups from this and deeper, get bboxes of the elements inside, then return a union of those bboxes

	            var children = this.children();
	            var n = children.length;

	            if (n === 0) {
	                return this.getBBox({ target: options.target, recursive: false });
	            }

	            // recursion's initial pass-through setting:
	            // recursive passes-through just keep the target as whatever was set up here during the initial pass-through
	            if (!options.target) {
	                // transform children/descendants like this (their parent/ancestor)
	                options.target = this;
	            } // else transform children/descendants like target

	            for (var i = 0; i < n; i++) {
	                var currentChild = children[i];

	                var childBBox;

	                // if currentChild is not a group element, get its bbox with a nonrecursive call
	                if (currentChild.children().length === 0) {
	                    childBBox = currentChild.getBBox({ target: options.target, recursive: false });
	                } else {
	                    // if currentChild is a group element (determined by checking the number of children), enter it with a recursive call
	                    childBBox = currentChild.getBBox({ target: options.target, recursive: true });
	                }

	                if (!outputBBox) {
	                    // if this is the first iteration
	                    outputBBox = childBBox;
	                } else {
	                    // make a new bounding box rectangle that contains this child's bounding box and previous bounding box
	                    outputBBox = outputBBox.union(childBBox);
	                }
	            }

	            return outputBBox;
	        }
	    };

	    // Text() helpers

	    function createTextPathNode(attrs, vel) {
	        attrs || (attrs = {});
	        var textPathElement = V('textPath');
	        var d = attrs.d;
	        if (d && attrs['xlink:href'] === undefined) {
	            // If `opt.attrs` is a plain string, consider it to be directly the
	            // SVG path data for the text to go along (this is a shortcut).
	            // Otherwise if it is an object and contains the `d` property, then this is our path.
	            // Wrap the text in the SVG <textPath> element that points
	            // to a path defined by `opt.attrs` inside the `<defs>` element.
	            var linkedPath = V('path').attr('d', d).appendTo(vel.defs());
	            textPathElement.attr('xlink:href', '#' + linkedPath.id);
	        }
	        if (V.isObject(attrs)) {
	            // Set attributes on the `<textPath>`. The most important one
	            // is the `xlink:href` that points to our newly created `<path/>` element in `<defs/>`.
	            // Note that we also allow the following construct:
	            // `t.text('my text', { textPath: { 'xlink:href': '#my-other-path' } })`.
	            // In other words, one can completely skip the auto-creation of the path
	            // and use any other arbitrary path that is in the document.
	            textPathElement.attr(attrs);
	        }
	        return textPathElement.node;
	    }

	    function annotateTextLine(lineNode, lineAnnotations, opt) {
	        opt || (opt = {});
	        var includeAnnotationIndices = opt.includeAnnotationIndices;
	        var eol = opt.eol;
	        var lineHeight = opt.lineHeight;
	        var baseSize = opt.baseSize;
	        var maxFontSize = 0;
	        var fontMetrics = {};
	        var lastJ = lineAnnotations.length - 1;
	        for (var j = 0; j <= lastJ; j++) {
	            var annotation = lineAnnotations[j];
	            var fontSize = null;
	            if (V.isObject(annotation)) {
	                var annotationAttrs = annotation.attrs;
	                var vTSpan = V('tspan', annotationAttrs);
	                var tspanNode = vTSpan.node;
	                var t = annotation.t;
	                if (eol && j === lastJ) { t += eol; }
	                tspanNode.textContent = t;
	                // Per annotation className
	                var annotationClass = annotationAttrs['class'];
	                if (annotationClass) { vTSpan.addClass(annotationClass); }
	                // If `opt.includeAnnotationIndices` is `true`,
	                // set the list of indices of all the applied annotations
	                // in the `annotations` attribute. This list is a comma
	                // separated list of indices.
	                if (includeAnnotationIndices) { vTSpan.attr('annotations', annotation.annotations); }
	                // Check for max font size
	                fontSize = parseFloat(annotationAttrs['font-size']);
	                if (!isFinite(fontSize)) { fontSize = baseSize; }
	                if (fontSize && fontSize > maxFontSize) { maxFontSize = fontSize; }
	            } else {
	                if (eol && j === lastJ) { annotation += eol; }
	                tspanNode = document.createTextNode(annotation || ' ');
	                if (baseSize && baseSize > maxFontSize) { maxFontSize = baseSize; }
	            }
	            lineNode.appendChild(tspanNode);
	        }

	        if (maxFontSize) { fontMetrics.maxFontSize = maxFontSize; }
	        if (lineHeight) {
	            fontMetrics.lineHeight = lineHeight;
	        } else if (maxFontSize) {
	            fontMetrics.lineHeight = (maxFontSize * 1.2);
	        }
	        return fontMetrics;
	    }

	    var emRegex = /em$/;

	    function convertEmToPx(em, fontSize) {
	        var numerical = parseFloat(em);
	        if (emRegex.test(em)) { return numerical * fontSize; }
	        return numerical;
	    }

	    function calculateDY(alignment, linesMetrics, baseSizePx, lineHeight) {
	        if (!Array.isArray(linesMetrics)) { return 0; }
	        var n = linesMetrics.length;
	        if (!n) { return 0; }
	        var lineMetrics = linesMetrics[0];
	        var flMaxFont = convertEmToPx(lineMetrics.maxFontSize, baseSizePx) || baseSizePx;
	        var rLineHeights = 0;
	        var lineHeightPx = convertEmToPx(lineHeight, baseSizePx);
	        for (var i = 1; i < n; i++) {
	            lineMetrics = linesMetrics[i];
	            var iLineHeight = convertEmToPx(lineMetrics.lineHeight, baseSizePx) || lineHeightPx;
	            rLineHeights += iLineHeight;
	        }
	        var llMaxFont = convertEmToPx(lineMetrics.maxFontSize, baseSizePx) || baseSizePx;
	        var dy;
	        switch (alignment) {
	            case 'middle':
	                dy = (flMaxFont / 2) - (0.15 * llMaxFont) - (rLineHeights / 2);
	                break;
	            case 'bottom':
	                dy = -(0.25 * llMaxFont) - rLineHeights;
	                break;
	            default:
	            case 'top':
	                dy = (0.8 * flMaxFont);
	                break;
	        }
	        return dy;
	    }

	    VPrototype.text = function(content, opt) {

	        if (content && typeof content !== 'string') { throw new Error('Vectorizer: text() expects the first argument to be a string.'); }

	        // Replace all spaces with the Unicode No-break space (http://www.fileformat.info/info/unicode/char/a0/index.htm).
	        // IE would otherwise collapse all spaces into one.
	        content = V.sanitizeText(content);
	        opt || (opt = {});
	        // Should we allow the text to be selected?
	        var displayEmpty = opt.displayEmpty;
	        // End of Line character
	        var eol = opt.eol;
	        // Text along path
	        var textPath = opt.textPath;
	        // Vertical shift
	        var verticalAnchor = opt.textVerticalAnchor;
	        var namedVerticalAnchor = (verticalAnchor === 'middle' || verticalAnchor === 'bottom' || verticalAnchor === 'top');
	        // Horizontal shift applied to all the lines but the first.
	        var x = opt.x;
	        if (x === undefined) { x = this.attr('x') || 0; }
	        // Annotations
	        var iai = opt.includeAnnotationIndices;
	        var annotations = opt.annotations;
	        if (annotations && !V.isArray(annotations)) { annotations = [annotations]; }
	        // Shift all the <tspan> but first by one line (`1em`)
	        var defaultLineHeight = opt.lineHeight;
	        var autoLineHeight = (defaultLineHeight === 'auto');
	        var lineHeight = (autoLineHeight) ? '1.5em' : (defaultLineHeight || '1em');
	        // Clearing the element
	        this.empty();
	        this.attr({
	            // Preserve spaces. In other words, we do not want consecutive spaces to get collapsed to one.
	            'xml:space': 'preserve',
	            // An empty text gets rendered into the DOM in webkit-based browsers.
	            // In order to unify this behaviour across all browsers
	            // we rather hide the text element when it's empty.
	            'display': (content || displayEmpty) ? null : 'none'
	        });

	        // Set default font-size if none
	        var fontSize = parseFloat(this.attr('font-size'));
	        if (!fontSize) {
	            fontSize = 16;
	            if (namedVerticalAnchor || annotations) { this.attr('font-size', fontSize); }
	        }

	        var doc = document;
	        var containerNode;
	        if (textPath) {
	            // Now all the `<tspan>`s will be inside the `<textPath>`.
	            if (typeof textPath === 'string') { textPath = { d: textPath }; }
	            containerNode = createTextPathNode(textPath, this);
	        } else {
	            containerNode = doc.createDocumentFragment();
	        }
	        var offset = 0;
	        var lines = content.split('\n');
	        var linesMetrics = [];
	        var annotatedY;
	        for (var i = 0, lastI = lines.length - 1; i <= lastI; i++) {
	            var dy = lineHeight;
	            var lineClassName = 'v-line';
	            var lineNode = doc.createElementNS(ns.svg, 'tspan');
	            var line = lines[i];
	            var lineMetrics;
	            if (line) {
	                if (annotations) {
	                    // Find the *compacted* annotations for this line.
	                    var lineAnnotations = V.annotateString(line, annotations, {
	                        offset: -offset,
	                        includeAnnotationIndices: iai
	                    });
	                    lineMetrics = annotateTextLine(lineNode, lineAnnotations, {
	                        includeAnnotationIndices: iai,
	                        eol: (i !== lastI && eol),
	                        lineHeight: (autoLineHeight) ? null : lineHeight,
	                        baseSize: fontSize
	                    });
	                    // Get the line height based on the biggest font size in the annotations for this line.
	                    var iLineHeight = lineMetrics.lineHeight;
	                    if (iLineHeight && autoLineHeight && i !== 0) { dy = iLineHeight; }
	                    if (i === 0) { annotatedY = lineMetrics.maxFontSize * 0.8; }
	                } else {
	                    if (eol && i !== lastI) { line += eol; }
	                    lineNode.textContent = line;
	                }
	            } else {
	                // Make sure the textContent is never empty. If it is, add a dummy
	                // character and make it invisible, making the following lines correctly
	                // relatively positioned. `dy=1em` won't work with empty lines otherwise.
	                lineNode.textContent = '-';
	                lineClassName += ' v-empty-line';
	                // 'opacity' needs to be specified with fill, stroke. Opacity without specification
	                // is not applied in Firefox
	                var lineNodeStyle = lineNode.style;
	                lineNodeStyle.fillOpacity = 0;
	                lineNodeStyle.strokeOpacity = 0;
	                if (annotations) { lineMetrics = {}; }
	            }
	            if (lineMetrics) { linesMetrics.push(lineMetrics); }
	            if (i > 0) { lineNode.setAttribute('dy', dy); }
	            // Firefox requires 'x' to be set on the first line when inside a text path
	            if (i > 0 || textPath) { lineNode.setAttribute('x', x); }
	            lineNode.className.baseVal = lineClassName;
	            containerNode.appendChild(lineNode);
	            offset += line.length + 1;      // + 1 = newline character.
	        }
	        // Y Alignment calculation
	        if (namedVerticalAnchor) {
	            if (annotations) {
	                dy = calculateDY(verticalAnchor, linesMetrics, fontSize, lineHeight);
	            } else if (verticalAnchor === 'top') {
	                // A shortcut for top alignment. It does not depend on font-size nor line-height
	                dy = '0.8em';
	            } else {
	                var rh; // remaining height
	                if (lastI > 0) {
	                    rh = parseFloat(lineHeight) || 1;
	                    rh *= lastI;
	                    if (!emRegex.test(lineHeight)) { rh /= fontSize; }
	                } else {
	                    // Single-line text
	                    rh = 0;
	                }
	                switch (verticalAnchor) {
	                    case 'middle':
	                        dy = (0.3 - (rh / 2)) + 'em';
	                        break;
	                    case 'bottom':
	                        dy = (-rh - 0.3) + 'em';
	                        break;
	                }
	            }
	        } else {
	            if (verticalAnchor === 0) {
	                dy = '0em';
	            } else if (verticalAnchor) {
	                dy = verticalAnchor;
	            } else {
	                // No vertical anchor is defined
	                dy = 0;
	                // Backwards compatibility - we change the `y` attribute instead of `dy`.
	                if (this.attr('y') === null) { this.attr('y', annotatedY || '0.8em'); }
	            }
	        }
	        containerNode.firstChild.setAttribute('dy', dy);
	        // Appending lines to the element.
	        this.append(containerNode);
	        return this;
	    };

	    /**
	     * @public
	     * @param {string} name
	     * @returns {Vectorizer}
	     */
	    VPrototype.removeAttr = function(name) {

	        var qualifiedName = V.qualifyAttr(name);
	        var el = this.node;

	        if (qualifiedName.ns) {
	            if (el.hasAttributeNS(qualifiedName.ns, qualifiedName.local)) {
	                el.removeAttributeNS(qualifiedName.ns, qualifiedName.local);
	            }
	        } else if (el.hasAttribute(name)) {
	            el.removeAttribute(name);
	        }
	        return this;
	    };

	    VPrototype.attr = function(name, value) {

	        if (V.isUndefined(name)) {

	            // Return all attributes.
	            var attributes = this.node.attributes;
	            var attrs = {};

	            for (var i = 0; i < attributes.length; i++) {
	                attrs[attributes[i].name] = attributes[i].value;
	            }

	            return attrs;
	        }

	        if (V.isString(name) && V.isUndefined(value)) {
	            return this.node.getAttribute(name);
	        }

	        if (typeof name === 'object') {

	            for (var attrName in name) {
	                if (name.hasOwnProperty(attrName)) {
	                    this.setAttribute(attrName, name[attrName]);
	                }
	            }

	        } else {

	            this.setAttribute(name, value);
	        }

	        return this;
	    };

	    VPrototype.normalizePath = function() {

	        var tagName = this.tagName();
	        if (tagName === 'PATH') {
	            this.attr('d', V.normalizePathData(this.attr('d')));
	        }

	        return this;
	    };

	    VPrototype.remove = function() {

	        if (this.node.parentNode) {
	            this.node.parentNode.removeChild(this.node);
	        }

	        return this;
	    };

	    VPrototype.empty = function() {

	        while (this.node.firstChild) {
	            this.node.removeChild(this.node.firstChild);
	        }

	        return this;
	    };

	    /**
	     * @private
	     * @param {object} attrs
	     * @returns {Vectorizer}
	     */
	    VPrototype.setAttributes = function(attrs) {

	        for (var key in attrs) {
	            if (attrs.hasOwnProperty(key)) {
	                this.setAttribute(key, attrs[key]);
	            }
	        }

	        return this;
	    };

	    VPrototype.append = function(els) {

	        if (!V.isArray(els)) {
	            els = [els];
	        }

	        for (var i = 0, len = els.length; i < len; i++) {
	            this.node.appendChild(V.toNode(els[i])); // lgtm [js/xss-through-dom]
	        }

	        return this;
	    };

	    VPrototype.prepend = function(els) {

	        var child = this.node.firstChild;
	        return child ? V(child).before(els) : this.append(els);
	    };

	    VPrototype.before = function(els) {

	        var node = this.node;
	        var parent = node.parentNode;

	        if (parent) {

	            if (!V.isArray(els)) {
	                els = [els];
	            }

	            for (var i = 0, len = els.length; i < len; i++) {
	                parent.insertBefore(V.toNode(els[i]), node);
	            }
	        }

	        return this;
	    };

	    VPrototype.appendTo = function(node) {
	        V.toNode(node).appendChild(this.node); // lgtm [js/xss-through-dom]
	        return this;
	    };

	    VPrototype.svg = function() {

	        return this.node instanceof window.SVGSVGElement ? this : V(this.node.ownerSVGElement);
	    };

	    VPrototype.tagName = function() {

	        return this.node.tagName.toUpperCase();
	    };

	    VPrototype.defs = function() {
	        var context = this.svg() || this;
	        var defsNode = context.node.getElementsByTagName('defs')[0];
	        if (defsNode) { return V(defsNode); }
	        return V('defs').appendTo(context);
	    };

	    VPrototype.clone = function() {

	        var clone = V(this.node.cloneNode(true/* deep */));
	        // Note that clone inherits also ID. Therefore, we need to change it here.
	        clone.node.id = V.uniqueId();
	        return clone;
	    };

	    VPrototype.findOne = function(selector) {

	        var found = this.node.querySelector(selector);
	        return found ? V(found) : undefined;
	    };

	    VPrototype.find = function(selector) {

	        var vels = [];
	        var nodes = this.node.querySelectorAll(selector);

	        if (nodes) {

	            // Map DOM elements to `V`s.
	            for (var i = 0; i < nodes.length; i++) {
	                vels.push(V(nodes[i]));
	            }
	        }

	        return vels;
	    };

	    // Returns an array of V elements made from children of this.node.
	    VPrototype.children = function() {

	        var children = this.node.childNodes;

	        var outputArray = [];
	        for (var i = 0; i < children.length; i++) {
	            var currentChild = children[i];
	            if (currentChild.nodeType === 1) {
	                outputArray.push(V(children[i]));
	            }
	        }
	        return outputArray;
	    };

	    // Returns the V element from parentNode of this.node.
	    VPrototype.parent = function() {
	        return V(this.node.parentNode) || null;
	    },

	    // Find an index of an element inside its container.
	    VPrototype.index = function() {

	        var index = 0;
	        var node = this.node.previousSibling;

	        while (node) {
	            // nodeType 1 for ELEMENT_NODE
	            if (node.nodeType === 1) { index++; }
	            node = node.previousSibling;
	        }

	        return index;
	    };

	    VPrototype.findParentByClass = function(className, terminator) {

	        var ownerSVGElement = this.node.ownerSVGElement;
	        var node = this.node.parentNode;

	        while (node && node !== terminator && node !== ownerSVGElement) {

	            var vel = V(node);
	            if (vel.hasClass(className)) {
	                return vel;
	            }

	            node = node.parentNode;
	        }

	        return null;
	    };

	    // https://jsperf.com/get-common-parent
	    VPrototype.contains = function(el) {

	        var a = this.node;
	        var b = V.toNode(el);
	        var bup = b && b.parentNode;

	        return (a === bup) || !!(bup && bup.nodeType === 1 && (a.compareDocumentPosition(bup) & 16));
	    };

	    // Convert global point into the coordinate space of this element.
	    VPrototype.toLocalPoint = function(x, y) {

	        var svg = this.svg().node;

	        var p = svg.createSVGPoint();
	        p.x = x;
	        p.y = y;

	        try {

	            var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse());
	            var globalToLocalMatrix = this.getTransformToElement(svg).inverse();

	        } catch (e) {
	            // IE9 throws an exception in odd cases. (`Unexpected call to method or property access`)
	            // We have to make do with the original coordianates.
	            return p;
	        }

	        return globalPoint.matrixTransform(globalToLocalMatrix);
	    };

	    VPrototype.translateCenterToPoint = function(p) {

	        var bbox = this.getBBox({ target: this.svg() });
	        var center = bbox.center();

	        this.translate(p.x - center.x, p.y - center.y);
	        return this;
	    };

	    // Efficiently auto-orient an element. This basically implements the orient=auto attribute
	    // of markers. The easiest way of understanding on what this does is to imagine the element is an
	    // arrowhead. Calling this method on the arrowhead makes it point to the `position` point while
	    // being auto-oriented (properly rotated) towards the `reference` point.
	    // `target` is the element relative to which the transformations are applied. Usually a viewport.
	    VPrototype.translateAndAutoOrient = function(position, reference, target) {

	        position = new Point(position);
	        reference =  new Point(reference);
	        target || (target = this.svg());

	        // Clean-up previously set transformations except the scale. If we didn't clean up the
	        // previous transformations then they'd add up with the old ones. Scale is an exception as
	        // it doesn't add up, consider: `this.scale(2).scale(2).scale(2)`. The result is that the
	        // element is scaled by the factor 2, not 8.
	        var scale = this.scale();
	        this.attr('transform', '');
	        var bbox = this.getBBox({ target: target }).scale(scale.sx, scale.sy);

	        // 1. Translate to origin.
	        var translateToOrigin = V.createSVGTransform();
	        translateToOrigin.setTranslate(-bbox.x - bbox.width / 2, -bbox.y - bbox.height / 2);

	        // 2. Rotate around origin.
	        var rotateAroundOrigin = V.createSVGTransform();
	        var angle = position.angleBetween(reference, position.clone().offset(1, 0));
	        if (angle) { rotateAroundOrigin.setRotate(angle, 0, 0); }

	        // 3. Translate to the `position` + the offset (half my width) towards the `reference` point.
	        var translateFromOrigin = V.createSVGTransform();
	        var finalPosition = position.clone().move(reference, bbox.width / 2);
	        translateFromOrigin.setTranslate(2 * position.x - finalPosition.x, 2 * position.y - finalPosition.y);

	        // 4. Get the current transformation matrix of this node
	        var ctm = this.getTransformToElement(target);

	        // 5. Apply transformations and the scale
	        var transform = V.createSVGTransform();
	        transform.setMatrix(
	            translateFromOrigin.matrix.multiply(
	                rotateAroundOrigin.matrix.multiply(
	                    translateToOrigin.matrix.multiply(
	                        ctm.scale(scale.sx, scale.sy)))));

	        this.attr('transform', V.matrixToTransformString(transform.matrix));

	        return this;
	    };

	    VPrototype.animateAlongPath = function(attrs, path) {

	        path = V.toNode(path);

	        var id = V.ensureId(path);
	        var animateMotion = V('animateMotion', attrs);
	        var mpath = V('mpath', { 'xlink:href': '#' + id });

	        animateMotion.append(mpath);

	        this.append(animateMotion);
	        try {
	            animateMotion.node.beginElement();
	        } catch (e) {
	            // Fallback for IE 9.
	            // Run the animation programmatically if FakeSmile (`http://leunen.me/fakesmile/`) present
	            if (document.documentElement.getAttribute('smiling') === 'fake') {
	                /* global getTargets:true, Animator:true, animators:true id2anim:true */
	                // Register the animation. (See `https://answers.launchpad.net/smil/+question/203333`)
	                var animation = animateMotion.node;
	                animation.animators = [];

	                var animationID = animation.getAttribute('id');
	                if (animationID) { id2anim[animationID] = animation; }

	                var targets = getTargets(animation);
	                for (var i = 0, len = targets.length; i < len; i++) {
	                    var target = targets[i];
	                    var animator = new Animator(animation, target, i);
	                    animators.push(animator);
	                    animation.animators[i] = animator;
	                    animator.register();
	                }
	            }
	        }
	        return this;
	    };

	    VPrototype.hasClass = function(className) {

	        return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.node.getAttribute('class'));
	    };

	    VPrototype.addClass = function(className) {

	        if (className && !this.hasClass(className)) {
	            var prevClasses = this.node.getAttribute('class') || '';
	            this.node.setAttribute('class', (prevClasses + ' ' + className).trim());
	        }

	        return this;
	    };

	    VPrototype.removeClass = function(className) {

	        if (className && this.hasClass(className)) {
	            var newClasses = this.node.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
	            this.node.setAttribute('class', newClasses);
	        }

	        return this;
	    };

	    VPrototype.toggleClass = function(className, toAdd) {

	        var toRemove = V.isUndefined(toAdd) ? this.hasClass(className) : !toAdd;

	        if (toRemove) {
	            this.removeClass(className);
	        } else {
	            this.addClass(className);
	        }

	        return this;
	    };

	    // Interpolate path by discrete points. The precision of the sampling
	    // is controlled by `interval`. In other words, `sample()` will generate
	    // a point on the path starting at the beginning of the path going to the end
	    // every `interval` pixels.
	    // The sampler can be very useful for e.g. finding intersection between two
	    // paths (finding the two closest points from two samples).
	    VPrototype.sample = function(interval) {

	        interval = interval || 1;
	        var node = this.node;
	        var length = node.getTotalLength();
	        var samples = [];
	        var distance = 0;
	        var sample;
	        while (distance < length) {
	            sample = node.getPointAtLength(distance);
	            samples.push({ x: sample.x, y: sample.y, distance: distance });
	            distance += interval;
	        }
	        return samples;
	    };

	    VPrototype.convertToPath = function() {

	        var path = V('path');
	        path.attr(this.attr());
	        var d = this.convertToPathData();
	        if (d) {
	            path.attr('d', d);
	        }
	        return path;
	    };

	    VPrototype.convertToPathData = function() {

	        var tagName = this.tagName();

	        switch (tagName) {
	            case 'PATH':
	                return this.attr('d');
	            case 'LINE':
	                return V.convertLineToPathData(this.node);
	            case 'POLYGON':
	                return V.convertPolygonToPathData(this.node);
	            case 'POLYLINE':
	                return V.convertPolylineToPathData(this.node);
	            case 'ELLIPSE':
	                return V.convertEllipseToPathData(this.node);
	            case 'CIRCLE':
	                return V.convertCircleToPathData(this.node);
	            case 'RECT':
	                return V.convertRectToPathData(this.node);
	        }

	        throw new Error(tagName + ' cannot be converted to PATH.');
	    };

	    V.prototype.toGeometryShape = function() {
	        var x, y, width, height, cx, cy, r, rx, ry, points, d, x1, x2, y1, y2;
	        switch (this.tagName()) {

	            case 'RECT':
	                x = parseFloat(this.attr('x')) || 0;
	                y = parseFloat(this.attr('y')) || 0;
	                width = parseFloat(this.attr('width')) || 0;
	                height = parseFloat(this.attr('height')) || 0;
	                return new Rect(x, y, width, height);

	            case 'CIRCLE':
	                cx = parseFloat(this.attr('cx')) || 0;
	                cy = parseFloat(this.attr('cy')) || 0;
	                r = parseFloat(this.attr('r')) || 0;
	                return new Ellipse({ x: cx, y: cy }, r, r);

	            case 'ELLIPSE':
	                cx = parseFloat(this.attr('cx')) || 0;
	                cy = parseFloat(this.attr('cy')) || 0;
	                rx = parseFloat(this.attr('rx')) || 0;
	                ry = parseFloat(this.attr('ry')) || 0;
	                return new Ellipse({ x: cx, y: cy }, rx, ry);

	            case 'POLYLINE':
	                points = V.getPointsFromSvgNode(this);
	                return new Polyline(points);

	            case 'POLYGON':
	                points = V.getPointsFromSvgNode(this);
	                if (points.length > 1) { points.push(points[0]); }
	                return new Polyline(points);

	            case 'PATH':
	                d = this.attr('d');
	                if (!Path.isDataSupported(d)) { d = V.normalizePathData(d); }
	                return new Path(d);

	            case 'LINE':
	                x1 = parseFloat(this.attr('x1')) || 0;
	                y1 = parseFloat(this.attr('y1')) || 0;
	                x2 = parseFloat(this.attr('x2')) || 0;
	                y2 = parseFloat(this.attr('y2')) || 0;
	                return new Line({ x: x1, y: y1 }, { x: x2, y: y2 });
	        }

	        // Anything else is a rectangle
	        return this.getBBox();
	    };

	    // Find the intersection of a line starting in the center
	    // of the SVG `node` ending in the point `ref`.
	    // `target` is an SVG element to which `node`s transformations are relative to.
	    // Note that `ref` point must be in the coordinate system of the `target` for this function to work properly.
	    // Returns a point in the `target` coordinate system (the same system as `ref` is in) if
	    // an intersection is found. Returns `undefined` otherwise.
	    VPrototype.findIntersection = function(ref, target) {

	        var svg = this.svg().node;
	        target = target || svg;
	        var bbox = this.getBBox({ target: target });
	        var center = bbox.center();

	        if (!bbox.intersectionWithLineFromCenterToPoint(ref)) { return undefined; }

	        var spot;
	        var tagName = this.tagName();

	        // Little speed up optimization for `<rect>` element. We do not do conversion
	        // to path element and sampling but directly calculate the intersection through
	        // a transformed geometrical rectangle.
	        if (tagName === 'RECT') {

	            var gRect = new Rect(
	                parseFloat(this.attr('x') || 0),
	                parseFloat(this.attr('y') || 0),
	                parseFloat(this.attr('width')),
	                parseFloat(this.attr('height'))
	            );
	            // Get the rect transformation matrix with regards to the SVG document.
	            var rectMatrix = this.getTransformToElement(target);
	            // Decompose the matrix to find the rotation angle.
	            var rectMatrixComponents = V.decomposeMatrix(rectMatrix);
	            // Now we want to rotate the rectangle back so that we
	            // can use `intersectionWithLineFromCenterToPoint()` passing the angle as the second argument.
	            var resetRotation = svg.createSVGTransform();
	            resetRotation.setRotate(-rectMatrixComponents.rotation, center.x, center.y);
	            var rect = V.transformRect(gRect, resetRotation.matrix.multiply(rectMatrix));
	            spot = (new Rect(rect)).intersectionWithLineFromCenterToPoint(ref, rectMatrixComponents.rotation);

	        } else if (tagName === 'PATH' || tagName === 'POLYGON' || tagName === 'POLYLINE' || tagName === 'CIRCLE' || tagName === 'ELLIPSE') {

	            var pathNode = (tagName === 'PATH') ? this : this.convertToPath();
	            var samples = pathNode.sample();
	            var minDistance = Infinity;
	            var closestSamples = [];

	            var i, sample, gp, centerDistance, refDistance, distance;

	            for (i = 0; i < samples.length; i++) {

	                sample = samples[i];
	                // Convert the sample point in the local coordinate system to the global coordinate system.
	                gp = V.createSVGPoint(sample.x, sample.y);
	                gp = gp.matrixTransform(this.getTransformToElement(target));
	                sample = new Point(gp);
	                centerDistance = sample.distance(center);
	                // Penalize a higher distance to the reference point by 10%.
	                // This gives better results. This is due to
	                // inaccuracies introduced by rounding errors and getPointAtLength() returns.
	                refDistance = sample.distance(ref) * 1.1;
	                distance = centerDistance + refDistance;

	                if (distance < minDistance) {
	                    minDistance = distance;
	                    closestSamples = [{ sample: sample, refDistance: refDistance }];
	                } else if (distance < minDistance + 1) {
	                    closestSamples.push({ sample: sample, refDistance: refDistance });
	                }
	            }

	            closestSamples.sort(function(a, b) {
	                return a.refDistance - b.refDistance;
	            });

	            if (closestSamples[0]) {
	                spot = closestSamples[0].sample;
	            }
	        }

	        return spot;
	    };

	    /**
	     * @private
	     * @param {string} name
	     * @param {string} value
	     * @returns {Vectorizer}
	     */
	    VPrototype.setAttribute = function(name, value) {

	        var el = this.node;

	        if (value === null) {
	            this.removeAttr(name);
	            return this;
	        }

	        var qualifiedName = V.qualifyAttr(name);

	        if (qualifiedName.ns) {
	            // Attribute names can be namespaced. E.g. `image` elements
	            // have a `xlink:href` attribute to set the source of the image.
	            el.setAttributeNS(qualifiedName.ns, name, value);
	        } else if (name === 'id') {
	            el.id = value;
	        } else {
	            el.setAttribute(name, value);
	        }

	        return this;
	    };

	    // Create an SVG document element.
	    // If `content` is passed, it will be used as the SVG content of the `<svg>` root element.
	    V.createSvgDocument = function(content) {

	        if (content) {
	            var XMLString = "<svg xmlns=\"" + (ns.svg) + "\" xmlns:xlink=\"" + (ns.xlink) + "\" version=\"" + SVGVersion + "\">" + content + "</svg>";
	            var ref = V.parseXML(XMLString, { async: false });
	            var documentElement = ref.documentElement;
	            return documentElement;
	        }

	        var svg = document.createElementNS(ns.svg, 'svg');
	        svg.setAttributeNS(ns.xmlns, 'xmlns:xlink', ns.xlink);
	        svg.setAttribute('version', SVGVersion);
	        return svg;
	    };

	    V.createSVGStyle = function(stylesheet) {
	        var ref = V('style', { type: 'text/css' }, [
	            V.createCDATASection(stylesheet)
	        ]);
	        var node = ref.node;
	        return node;
	    },

	    V.createCDATASection = function(data) {
	        if ( data === void 0 ) data = '';

	        var xml = document.implementation.createDocument(null, 'xml', null);
	        return xml.createCDATASection(data);
	    };

	    V.idCounter = 0;

	    // A function returning a unique identifier for this client session with every call.
	    V.uniqueId = function() {

	        return 'v-' + (++V.idCounter);
	    };

	    V.toNode = function(el) {

	        return V.isV(el) ? el.node : (el.nodeName && el || el[0]);
	    };

	    V.ensureId = function(node) {

	        node = V.toNode(node);
	        return node.id || (node.id = V.uniqueId());
	    };

	    // Replace all spaces with the Unicode No-break space (http://www.fileformat.info/info/unicode/char/a0/index.htm).
	    // IE would otherwise collapse all spaces into one. This is used in the text() method but it is
	    // also exposed so that the programmer can use it in case he needs to. This is useful e.g. in tests
	    // when you want to compare the actual DOM text content without having to add the unicode character in
	    // the place of all spaces.
	    V.sanitizeText = function(text) {

	        return (text || '').replace(/ /g, '\u00A0');
	    };

	    V.isUndefined = function(value) {

	        return typeof value === 'undefined';
	    };

	    V.isString = function(value) {

	        return typeof value === 'string';
	    };

	    V.isObject = function(value) {

	        return value && (typeof value === 'object');
	    };

	    V.isArray = Array.isArray;

	    V.parseXML = function(data, opt) {

	        opt = opt || {};

	        var xml;

	        try {
	            var parser = new DOMParser();

	            if (!V.isUndefined(opt.async)) {
	                parser.async = opt.async;
	            }

	            xml = parser.parseFromString(data, 'text/xml');
	        } catch (error) {
	            xml = undefined;
	        }

	        if (!xml || xml.getElementsByTagName('parsererror').length) {
	            throw new Error('Invalid XML: ' + data);
	        }

	        return xml;
	    };

	    /**
	     * @param {string} name
	     * @returns {{ns: string|null, local: string}} namespace and attribute name
	     */
	    V.qualifyAttr = function(name) {

	        if (name.indexOf(':') !== -1) {
	            var combinedKey = name.split(':');
	            return {
	                ns: ns[combinedKey[0]],
	                local: combinedKey[1]
	            };
	        }

	        return {
	            ns: null,
	            local: name
	        };
	    };

	    V.transformRegex = /(\w+)\(([^,)]+),?([^)]+)?\)/gi;
	    V.transformSeparatorRegex = /[ ,]+/;
	    V.transformationListRegex = /^(\w+)\((.*)\)/;

	    V.transformStringToMatrix = function(transform) {

	        var transformationMatrix = V.createSVGMatrix();
	        var matches = transform && transform.match(V.transformRegex);
	        if (!matches) {
	            return transformationMatrix;
	        }

	        for (var i = 0, n = matches.length; i < n; i++) {
	            var transformationString = matches[i];

	            var transformationMatch = transformationString.match(V.transformationListRegex);
	            if (transformationMatch) {
	                var sx, sy, tx, ty, angle;
	                var ctm = V.createSVGMatrix();
	                var args = transformationMatch[2].split(V.transformSeparatorRegex);
	                switch (transformationMatch[1].toLowerCase()) {
	                    case 'scale':
	                        sx = parseFloat(args[0]);
	                        sy = (args[1] === undefined) ? sx : parseFloat(args[1]);
	                        ctm = ctm.scaleNonUniform(sx, sy);
	                        break;
	                    case 'translate':
	                        tx = parseFloat(args[0]);
	                        ty = parseFloat(args[1]);
	                        ctm = ctm.translate(tx, ty);
	                        break;
	                    case 'rotate':
	                        angle = parseFloat(args[0]);
	                        tx = parseFloat(args[1]) || 0;
	                        ty = parseFloat(args[2]) || 0;
	                        if (tx !== 0 || ty !== 0) {
	                            ctm = ctm.translate(tx, ty).rotate(angle).translate(-tx, -ty);
	                        } else {
	                            ctm = ctm.rotate(angle);
	                        }
	                        break;
	                    case 'skewx':
	                        angle = parseFloat(args[0]);
	                        ctm = ctm.skewX(angle);
	                        break;
	                    case 'skewy':
	                        angle = parseFloat(args[0]);
	                        ctm = ctm.skewY(angle);
	                        break;
	                    case 'matrix':
	                        ctm.a = parseFloat(args[0]);
	                        ctm.b = parseFloat(args[1]);
	                        ctm.c = parseFloat(args[2]);
	                        ctm.d = parseFloat(args[3]);
	                        ctm.e = parseFloat(args[4]);
	                        ctm.f = parseFloat(args[5]);
	                        break;
	                    default:
	                        continue;
	                }

	                transformationMatrix = transformationMatrix.multiply(ctm);
	            }

	        }
	        return transformationMatrix;
	    };

	    V.matrixToTransformString = function(matrix) {
	        matrix || (matrix = true);

	        return 'matrix(' +
	            (matrix.a !== undefined ? matrix.a : 1) + ',' +
	            (matrix.b !== undefined ? matrix.b : 0) + ',' +
	            (matrix.c !== undefined ? matrix.c : 0) + ',' +
	            (matrix.d !== undefined ? matrix.d : 1) + ',' +
	            (matrix.e !== undefined ? matrix.e : 0) + ',' +
	            (matrix.f !== undefined ? matrix.f : 0) +
	            ')';
	    };

	    V.parseTransformString = function(transform) {

	        var translate, rotate, scale;

	        if (transform) {

	            var separator = V.transformSeparatorRegex;

	            // Allow reading transform string with a single matrix
	            if (transform.trim().indexOf('matrix') >= 0) {

	                var matrix = V.transformStringToMatrix(transform);
	                var decomposedMatrix = V.decomposeMatrix(matrix);

	                translate = [decomposedMatrix.translateX, decomposedMatrix.translateY];
	                scale = [decomposedMatrix.scaleX, decomposedMatrix.scaleY];
	                rotate = [decomposedMatrix.rotation];

	                var transformations = [];
	                if (translate[0] !== 0 || translate[1] !== 0) {
	                    transformations.push('translate(' + translate + ')');
	                }
	                if (scale[0] !== 1 || scale[1] !== 1) {
	                    transformations.push('scale(' + scale + ')');
	                }
	                if (rotate[0] !== 0) {
	                    transformations.push('rotate(' + rotate + ')');
	                }
	                transform = transformations.join(' ');

	            } else {

	                var translateMatch = transform.match(/translate\((.*?)\)/);
	                if (translateMatch) {
	                    translate = translateMatch[1].split(separator);
	                }
	                var rotateMatch = transform.match(/rotate\((.*?)\)/);
	                if (rotateMatch) {
	                    rotate = rotateMatch[1].split(separator);
	                }
	                var scaleMatch = transform.match(/scale\((.*?)\)/);
	                if (scaleMatch) {
	                    scale = scaleMatch[1].split(separator);
	                }
	            }
	        }

	        var sx = (scale && scale[0]) ? parseFloat(scale[0]) : 1;

	        return {
	            value: transform,
	            translate: {
	                tx: (translate && translate[0]) ? parseInt(translate[0], 10) : 0,
	                ty: (translate && translate[1]) ? parseInt(translate[1], 10) : 0
	            },
	            rotate: {
	                angle: (rotate && rotate[0]) ? parseInt(rotate[0], 10) : 0,
	                cx: (rotate && rotate[1]) ? parseInt(rotate[1], 10) : undefined,
	                cy: (rotate && rotate[2]) ? parseInt(rotate[2], 10) : undefined
	            },
	            scale: {
	                sx: sx,
	                sy: (scale && scale[1]) ? parseFloat(scale[1]) : sx
	            }
	        };
	    };

	    V.deltaTransformPoint = function(matrix, point) {

	        var dx = point.x * matrix.a + point.y * matrix.c + 0;
	        var dy = point.x * matrix.b + point.y * matrix.d + 0;
	        return { x: dx, y: dy };
	    };

	    V.decomposeMatrix = function(matrix) {

	        // @see https://gist.github.com/2052247

	        // calculate delta transform point
	        var px = V.deltaTransformPoint(matrix, { x: 0, y: 1 });
	        var py = V.deltaTransformPoint(matrix, { x: 1, y: 0 });

	        // calculate skew
	        var skewX = ((180 / PI) * atan2(px.y, px.x) - 90);
	        var skewY = ((180 / PI) * atan2(py.y, py.x));

	        return {

	            translateX: matrix.e,
	            translateY: matrix.f,
	            scaleX: sqrt(matrix.a * matrix.a + matrix.b * matrix.b),
	            scaleY: sqrt(matrix.c * matrix.c + matrix.d * matrix.d),
	            skewX: skewX,
	            skewY: skewY,
	            rotation: skewX // rotation is the same as skew x
	        };
	    };

	    // Return the `scale` transformation from the following equation:
	    // `translate(tx, ty) . rotate(angle) . scale(sx, sy) === matrix(a,b,c,d,e,f)`
	    V.matrixToScale = function(matrix) {

	        var a, b, c, d;
	        if (matrix) {
	            a = V.isUndefined(matrix.a) ? 1 : matrix.a;
	            d = V.isUndefined(matrix.d) ? 1 : matrix.d;
	            b = matrix.b;
	            c = matrix.c;
	        } else {
	            a = d = 1;
	        }
	        return {
	            sx: b ? sqrt(a * a + b * b) : a,
	            sy: c ? sqrt(c * c + d * d) : d
	        };
	    };

	    // Return the `rotate` transformation from the following equation:
	    // `translate(tx, ty) . rotate(angle) . scale(sx, sy) === matrix(a,b,c,d,e,f)`
	    V.matrixToRotate = function(matrix) {

	        var p = { x: 0, y: 1 };
	        if (matrix) {
	            p = V.deltaTransformPoint(matrix, p);
	        }

	        return {
	            angle: normalizeAngle(toDeg(atan2(p.y, p.x)) - 90)
	        };
	    };

	    // Return the `translate` transformation from the following equation:
	    // `translate(tx, ty) . rotate(angle) . scale(sx, sy) === matrix(a,b,c,d,e,f)`
	    V.matrixToTranslate = function(matrix) {

	        return {
	            tx: (matrix && matrix.e) || 0,
	            ty: (matrix && matrix.f) || 0
	        };
	    };

	    V.isV = function(object) {

	        return object instanceof V;
	    };

	    // For backwards compatibility:
	    V.isVElement = V.isV;

	    // Element implements `getBBox()`, `getCTM()` and `getScreenCTM()`
	    // https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement
	    V.isSVGGraphicsElement = function(node) {
	        if (!node) { return false; }
	        node = V.toNode(node);
	        // IE/Edge does not implement SVGGraphicsElement interface, thus check for `getScreenCTM` below
	        return node instanceof SVGElement && typeof node.getScreenCTM === 'function';
	    };

	    var svgDocument = V('svg').node;

	    V.createSVGMatrix = function(matrix) {

	        var svgMatrix = svgDocument.createSVGMatrix();
	        for (var component in matrix) {
	            svgMatrix[component] = matrix[component];
	        }

	        return svgMatrix;
	    };

	    V.createSVGTransform = function(matrix) {

	        if (!V.isUndefined(matrix)) {

	            if (!(matrix instanceof SVGMatrix)) {
	                matrix = V.createSVGMatrix(matrix);
	            }

	            return svgDocument.createSVGTransformFromMatrix(matrix);
	        }

	        return svgDocument.createSVGTransform();
	    };

	    V.createSVGPoint = function(x, y) {

	        var p = svgDocument.createSVGPoint();
	        p.x = x;
	        p.y = y;
	        return p;
	    };

	    V.transformRect = function(r, matrix) {

	        var p = svgDocument.createSVGPoint();

	        p.x = r.x;
	        p.y = r.y;
	        var corner1 = p.matrixTransform(matrix);

	        p.x = r.x + r.width;
	        p.y = r.y;
	        var corner2 = p.matrixTransform(matrix);

	        p.x = r.x + r.width;
	        p.y = r.y + r.height;
	        var corner3 = p.matrixTransform(matrix);

	        p.x = r.x;
	        p.y = r.y + r.height;
	        var corner4 = p.matrixTransform(matrix);

	        var minX = min(corner1.x, corner2.x, corner3.x, corner4.x);
	        var maxX = max(corner1.x, corner2.x, corner3.x, corner4.x);
	        var minY = min(corner1.y, corner2.y, corner3.y, corner4.y);
	        var maxY = max(corner1.y, corner2.y, corner3.y, corner4.y);

	        return new Rect(minX, minY, maxX - minX, maxY - minY);
	    };

	    V.transformPoint = function(p, matrix) {

	        return new Point(V.createSVGPoint(p.x, p.y).matrixTransform(matrix));
	    };

	    V.transformLine = function(l, matrix) {

	        return new Line(
	            V.transformPoint(l.start, matrix),
	            V.transformPoint(l.end, matrix)
	        );
	    };

	    V.transformPolyline = function(p, matrix) {

	        var inPoints = (p instanceof Polyline) ? p.points : p;
	        if (!V.isArray(inPoints)) { inPoints = []; }
	        var outPoints = [];
	        for (var i = 0, n = inPoints.length; i < n; i++) { outPoints[i] = V.transformPoint(inPoints[i], matrix); }
	        return new Polyline(outPoints);
	    };

	    // Convert a style represented as string (e.g. `'fill="blue"; stroke="red"'`) to
	    // an object (`{ fill: 'blue', stroke: 'red' }`).
	    V.styleToObject = function(styleString) {
	        var ret = {};
	        var styles = styleString.split(';');
	        for (var i = 0; i < styles.length; i++) {
	            var style = styles[i];
	            var pair = style.split('=');
	            ret[pair[0].trim()] = pair[1].trim();
	        }
	        return ret;
	    };

	    // Inspired by d3.js https://github.com/mbostock/d3/blob/master/src/svg/arc.js
	    V.createSlicePathData = function(innerRadius, outerRadius, startAngle, endAngle) {

	        var svgArcMax = 2 * PI - 1e-6;
	        var r0 = innerRadius;
	        var r1 = outerRadius;
	        var a0 = startAngle;
	        var a1 = endAngle;
	        var da = (a1 < a0 && (da = a0, a0 = a1, a1 = da), a1 - a0);
	        var df = da < PI ? '0' : '1';
	        var c0 = cos(a0);
	        var s0 = sin(a0);
	        var c1 = cos(a1);
	        var s1 = sin(a1);

	        return (da >= svgArcMax)
	            ? (r0
	                ? 'M0,' + r1
	                + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + (-r1)
	                + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + r1
	                + 'M0,' + r0
	                + 'A' + r0 + ',' + r0 + ' 0 1,0 0,' + (-r0)
	                + 'A' + r0 + ',' + r0 + ' 0 1,0 0,' + r0
	                + 'Z'
	                : 'M0,' + r1
	                + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + (-r1)
	                + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + r1
	                + 'Z')
	            : (r0
	                ? 'M' + r1 * c0 + ',' + r1 * s0
	                + 'A' + r1 + ',' + r1 + ' 0 ' + df + ',1 ' + r1 * c1 + ',' + r1 * s1
	                + 'L' + r0 * c1 + ',' + r0 * s1
	                + 'A' + r0 + ',' + r0 + ' 0 ' + df + ',0 ' + r0 * c0 + ',' + r0 * s0
	                + 'Z'
	                : 'M' + r1 * c0 + ',' + r1 * s0
	                + 'A' + r1 + ',' + r1 + ' 0 ' + df + ',1 ' + r1 * c1 + ',' + r1 * s1
	                + 'L0,0'
	                + 'Z');
	    };

	    // Merge attributes from object `b` with attributes in object `a`.
	    // Note that this modifies the object `a`.
	    // Also important to note that attributes are merged but CSS classes are concatenated.
	    V.mergeAttrs = function(a, b) {

	        for (var attr in b) {

	            if (attr === 'class') {
	                // Concatenate classes.
	                a[attr] = a[attr] ? a[attr] + ' ' + b[attr] : b[attr];
	            } else if (attr === 'style') {
	                // `style` attribute can be an object.
	                if (V.isObject(a[attr]) && V.isObject(b[attr])) {
	                    // `style` stored in `a` is an object.
	                    a[attr] = V.mergeAttrs(a[attr], b[attr]);
	                } else if (V.isObject(a[attr])) {
	                    // `style` in `a` is an object but it's a string in `b`.
	                    // Convert the style represented as a string to an object in `b`.
	                    a[attr] = V.mergeAttrs(a[attr], V.styleToObject(b[attr]));
	                } else if (V.isObject(b[attr])) {
	                    // `style` in `a` is a string, in `b` it's an object.
	                    a[attr] = V.mergeAttrs(V.styleToObject(a[attr]), b[attr]);
	                } else {
	                    // Both styles are strings.
	                    a[attr] = V.mergeAttrs(V.styleToObject(a[attr]), V.styleToObject(b[attr]));
	                }
	            } else {
	                a[attr] = b[attr];
	            }
	        }

	        return a;
	    };

	    V.annotateString = function(t, annotations, opt) {

	        annotations = annotations || [];
	        opt = opt || {};

	        var offset = opt.offset || 0;
	        var compacted = [];
	        var batch;
	        var ret = [];
	        var item;
	        var prev;

	        for (var i = 0; i < t.length; i++) {

	            item = ret[i] = t[i];

	            for (var j = 0; j < annotations.length; j++) {

	                var annotation = annotations[j];
	                var start = annotation.start + offset;
	                var end = annotation.end + offset;

	                if (i >= start && i < end) {
	                    // Annotation applies.
	                    if (V.isObject(item)) {
	                        // There is more than one annotation to be applied => Merge attributes.
	                        item.attrs = V.mergeAttrs(V.mergeAttrs({}, item.attrs), annotation.attrs);
	                    } else {
	                        item = ret[i] = { t: t[i], attrs: annotation.attrs };
	                    }
	                    if (opt.includeAnnotationIndices) {
	                        (item.annotations || (item.annotations = [])).push(j);
	                    }
	                }
	            }

	            prev = ret[i - 1];

	            if (!prev) {

	                batch = item;

	            } else if (V.isObject(item) && V.isObject(prev)) {
	                // Both previous item and the current one are annotations. If the attributes
	                // didn't change, merge the text.
	                if (JSON.stringify(item.attrs) === JSON.stringify(prev.attrs)) {
	                    batch.t += item.t;
	                } else {
	                    compacted.push(batch);
	                    batch = item;
	                }

	            } else if (V.isObject(item)) {
	                // Previous item was a string, current item is an annotation.
	                compacted.push(batch);
	                batch = item;

	            } else if (V.isObject(prev)) {
	                // Previous item was an annotation, current item is a string.
	                compacted.push(batch);
	                batch = item;

	            } else {
	                // Both previous and current item are strings.
	                batch = (batch || '') + item;
	            }
	        }

	        if (batch) {
	            compacted.push(batch);
	        }

	        return compacted;
	    };

	    V.findAnnotationsAtIndex = function(annotations, index) {

	        var found = [];

	        if (annotations) {

	            annotations.forEach(function(annotation) {

	                if (annotation.start < index && index <= annotation.end) {
	                    found.push(annotation);
	                }
	            });
	        }

	        return found;
	    };

	    V.findAnnotationsBetweenIndexes = function(annotations, start, end) {

	        var found = [];

	        if (annotations) {

	            annotations.forEach(function(annotation) {

	                if ((start >= annotation.start && start < annotation.end) || (end > annotation.start && end <= annotation.end) || (annotation.start >= start && annotation.end < end)) {
	                    found.push(annotation);
	                }
	            });
	        }

	        return found;
	    };

	    // Shift all the text annotations after character `index` by `offset` positions.
	    V.shiftAnnotations = function(annotations, index, offset) {

	        if (annotations) {

	            annotations.forEach(function(annotation) {

	                if (annotation.start < index && annotation.end >= index) {
	                    annotation.end += offset;
	                } else if (annotation.start >= index) {
	                    annotation.start += offset;
	                    annotation.end += offset;
	                }
	            });
	        }

	        return annotations;
	    };

	    V.convertLineToPathData = function(line) {

	        line = V(line);
	        var d = [
	            'M', line.attr('x1'), line.attr('y1'),
	            'L', line.attr('x2'), line.attr('y2')
	        ].join(' ');
	        return d;
	    };

	    V.convertPolygonToPathData = function(polygon) {

	        var points = V.getPointsFromSvgNode(polygon);
	        if (points.length === 0) { return null; }

	        return V.svgPointsToPath(points) + ' Z';
	    };

	    V.convertPolylineToPathData = function(polyline) {

	        var points = V.getPointsFromSvgNode(polyline);
	        if (points.length === 0) { return null; }

	        return V.svgPointsToPath(points);
	    };

	    V.svgPointsToPath = function(points) {

	        for (var i = 0, n = points.length; i < n; i++) {
	            points[i] = points[i].x + ' ' + points[i].y;
	        }

	        return 'M ' + points.join(' L');
	    };

	    V.getPointsFromSvgNode = function(node) {

	        node = V.toNode(node);
	        var points = [];
	        var nodePoints = node.points;
	        if (nodePoints) {
	            for (var i = 0, n = nodePoints.numberOfItems; i < n; i++) {
	                points.push(nodePoints.getItem(i));
	            }
	        }

	        return points;
	    };

	    V.KAPPA = 0.551784;

	    V.convertCircleToPathData = function(circle) {

	        circle = V(circle);
	        var cx = parseFloat(circle.attr('cx')) || 0;
	        var cy = parseFloat(circle.attr('cy')) || 0;
	        var r = parseFloat(circle.attr('r'));
	        var cd = r * V.KAPPA; // Control distance.

	        var d = [
	            'M', cx, cy - r,    // Move to the first point.
	            'C', cx + cd, cy - r, cx + r, cy - cd, cx + r, cy, // I. Quadrant.
	            'C', cx + r, cy + cd, cx + cd, cy + r, cx, cy + r, // II. Quadrant.
	            'C', cx - cd, cy + r, cx - r, cy + cd, cx - r, cy, // III. Quadrant.
	            'C', cx - r, cy - cd, cx - cd, cy - r, cx, cy - r, // IV. Quadrant.
	            'Z'
	        ].join(' ');
	        return d;
	    };

	    V.convertEllipseToPathData = function(ellipse) {

	        ellipse = V(ellipse);
	        var cx = parseFloat(ellipse.attr('cx')) || 0;
	        var cy = parseFloat(ellipse.attr('cy')) || 0;
	        var rx = parseFloat(ellipse.attr('rx'));
	        var ry = parseFloat(ellipse.attr('ry')) || rx;
	        var cdx = rx * V.KAPPA; // Control distance x.
	        var cdy = ry * V.KAPPA; // Control distance y.

	        var d = [
	            'M', cx, cy - ry,    // Move to the first point.
	            'C', cx + cdx, cy - ry, cx + rx, cy - cdy, cx + rx, cy, // I. Quadrant.
	            'C', cx + rx, cy + cdy, cx + cdx, cy + ry, cx, cy + ry, // II. Quadrant.
	            'C', cx - cdx, cy + ry, cx - rx, cy + cdy, cx - rx, cy, // III. Quadrant.
	            'C', cx - rx, cy - cdy, cx - cdx, cy - ry, cx, cy - ry, // IV. Quadrant.
	            'Z'
	        ].join(' ');
	        return d;
	    };

	    V.convertRectToPathData = function(rect) {

	        rect = V(rect);

	        return V.rectToPath({
	            x: parseFloat(rect.attr('x')) || 0,
	            y: parseFloat(rect.attr('y')) || 0,
	            width: parseFloat(rect.attr('width')) || 0,
	            height: parseFloat(rect.attr('height')) || 0,
	            rx: parseFloat(rect.attr('rx')) || 0,
	            ry: parseFloat(rect.attr('ry')) || 0
	        });
	    };

	    // Convert a rectangle to SVG path commands. `r` is an object of the form:
	    // `{ x: [number], y: [number], width: [number], height: [number], top-ry: [number], top-ry: [number], bottom-rx: [number], bottom-ry: [number] }`,
	    // where `x, y, width, height` are the usual rectangle attributes and [top-/bottom-]rx/ry allows for
	    // specifying radius of the rectangle for all its sides (as opposed to the built-in SVG rectangle
	    // that has only `rx` and `ry` attributes).
	    V.rectToPath = function(r) {

	        var d;
	        var x = r.x;
	        var y = r.y;
	        var width = r.width;
	        var height = r.height;
	        var topRx = min(r.rx || r['top-rx'] || 0, width / 2);
	        var bottomRx = min(r.rx || r['bottom-rx'] || 0, width / 2);
	        var topRy = min(r.ry || r['top-ry'] || 0, height / 2);
	        var bottomRy = min(r.ry || r['bottom-ry'] || 0, height / 2);

	        if (topRx || bottomRx || topRy || bottomRy) {
	            d = [
	                'M', x, y + topRy,
	                'v', height - topRy - bottomRy,
	                'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, bottomRy,
	                'h', width - 2 * bottomRx,
	                'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, -bottomRy,
	                'v', -(height - bottomRy - topRy),
	                'a', topRx, topRy, 0, 0, 0, -topRx, -topRy,
	                'h', -(width - 2 * topRx),
	                'a', topRx, topRy, 0, 0, 0, -topRx, topRy,
	                'Z'
	            ];
	        } else {
	            d = [
	                'M', x, y,
	                'H', x + width,
	                'V', y + height,
	                'H', x,
	                'V', y,
	                'Z'
	            ];
	        }

	        return d.join(' ');
	    };

	    // Take a path data string
	    // Return a normalized path data string
	    // If data cannot be parsed, return 'M 0 0'
	    // Adapted from Rappid normalizePath polyfill
	    // Highly inspired by Raphael Library (www.raphael.com)
	    V.normalizePathData = (function() {

	        var spaces = '\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029';
	        var pathCommand = new RegExp('([a-z])[' + spaces + ',]*((-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?[' + spaces + ']*,?[' + spaces + ']*)+)', 'ig');
	        var pathValues = new RegExp('(-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?)[' + spaces + ']*,?[' + spaces + ']*', 'ig');

	        var math = Math;
	        var PI = math.PI;
	        var sin = math.sin;
	        var cos = math.cos;
	        var tan = math.tan;
	        var asin = math.asin;
	        var sqrt = math.sqrt;
	        var abs = math.abs;

	        function q2c(x1, y1, ax, ay, x2, y2) {

	            var _13 = 1 / 3;
	            var _23 = 2 / 3;
	            return [(_13 * x1) + (_23 * ax), (_13 * y1) + (_23 * ay), (_13 * x2) + (_23 * ax), (_13 * y2) + (_23 * ay), x2, y2];
	        }

	        function rotate(x, y, rad) {

	            var X = (x * cos(rad)) - (y * sin(rad));
	            var Y = (x * sin(rad)) + (y * cos(rad));
	            return { x: X, y: Y };
	        }

	        function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
	            // for more information of where this math came from visit:
	            // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
	            var _120 = (PI * 120) / 180;
	            var rad = (PI / 180) * (+angle || 0);
	            var res = [];
	            var xy;

	            if (!recursive) {
	                xy = rotate(x1, y1, -rad);
	                x1 = xy.x;
	                y1 = xy.y;

	                xy = rotate(x2, y2, -rad);
	                x2 = xy.x;
	                y2 = xy.y;

	                var x = (x1 - x2) / 2;
	                var y = (y1 - y2) / 2;
	                var h = ((x * x) / (rx * rx)) + ((y * y) / (ry * ry));

	                if (h > 1) {
	                    h = sqrt(h);
	                    rx = h * rx;
	                    ry = h * ry;
	                }

	                var rx2 = rx * rx;
	                var ry2 = ry * ry;

	                var k = ((large_arc_flag == sweep_flag) ? -1 : 1) * sqrt(abs(((rx2 * ry2) - (rx2 * y * y) - (ry2 * x * x)) / ((rx2 * y * y) + (ry2 * x * x))));

	                var cx = ((k * rx * y) / ry) + ((x1 + x2) / 2);
	                var cy = ((k * -ry * x) / rx) + ((y1 + y2) / 2);

	                var f1 = asin(((y1 - cy) / ry).toFixed(9));
	                var f2 = asin(((y2 - cy) / ry).toFixed(9));

	                f1 = ((x1 < cx) ? (PI - f1) : f1);
	                f2 = ((x2 < cx) ? (PI - f2) : f2);

	                if (f1 < 0) { f1 = (PI * 2) + f1; }
	                if (f2 < 0) { f2 = (PI * 2) + f2; }

	                if (sweep_flag && (f1 > f2)) { f1 = f1 - (PI * 2); }
	                if (!sweep_flag && (f2 > f1)) { f2 = f2 - (PI * 2); }

	            } else {
	                f1 = recursive[0];
	                f2 = recursive[1];
	                cx = recursive[2];
	                cy = recursive[3];
	            }

	            var df = f2 - f1;
	            if (abs(df) > _120) {
	                var f2old = f2;
	                var x2old = x2;
	                var y2old = y2;
	                f2 = f1 + (_120 * ((sweep_flag && (f2 > f1)) ? 1 : -1));
	                x2 = cx + (rx * cos(f2));
	                y2 = cy + (ry * sin(f2));
	                res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]);
	            }

	            df = f2 - f1;

	            var c1 = cos(f1);
	            var s1 = sin(f1);
	            var c2 = cos(f2);
	            var s2 = sin(f2);
	            var t = tan(df / 4);
	            var hx = (4 / 3) * (rx * t);
	            var hy = (4 / 3) * (ry * t);
	            var m1 = [x1, y1];
	            var m2 = [x1 + (hx * s1), y1 - (hy * c1)];
	            var m3 = [x2 + (hx * s2), y2 - (hy * c2)];
	            var m4 = [x2, y2];

	            m2[0] = (2 * m1[0]) - m2[0];
	            m2[1] = (2 * m1[1]) - m2[1];

	            if (recursive) {
	                return [m2, m3, m4].concat(res);
	            } else {
	                res = [m2, m3, m4].concat(res).join().split(',');
	                var newres = [];
	                var ii = res.length;
	                for (var i = 0; i < ii; i++) {
	                    newres[i] = (i % 2) ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x;
	                }
	                return newres;
	            }
	        }

	        function parsePathString(pathString) {

	            if (!pathString) { return null; }

	            var paramCounts = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0 };
	            var data = [];

	            String(pathString).replace(pathCommand, function(a, b, c) {

	                var params = [];
	                var name = b.toLowerCase();
	                c.replace(pathValues, function(a, b) {
	                    if (b) { params.push(+b); }
	                });

	                if ((name === 'm') && (params.length > 2)) {
	                    data.push([b].concat(params.splice(0, 2)));
	                    name = 'l';
	                    b = ((b === 'm') ? 'l' : 'L');
	                }

	                while (params.length >= paramCounts[name]) {
	                    data.push([b].concat(params.splice(0, paramCounts[name])));
	                    if (!paramCounts[name]) { break; }
	                }
	            });

	            return data;
	        }

	        function pathToAbsolute(pathArray) {

	            if (!Array.isArray(pathArray) || !Array.isArray(pathArray && pathArray[0])) { // rough assumption
	                pathArray = parsePathString(pathArray);
	            }

	            // if invalid string, return 'M 0 0'
	            if (!pathArray || !pathArray.length) { return [['M', 0, 0]]; }

	            var res = [];
	            var x = 0;
	            var y = 0;
	            var mx = 0;
	            var my = 0;
	            var start = 0;
	            var pa0;

	            var ii = pathArray.length;
	            for (var i = start; i < ii; i++) {

	                var r = [];
	                res.push(r);

	                var pa = pathArray[i];
	                pa0 = pa[0];

	                if (pa0 != pa0.toUpperCase()) {
	                    r[0] = pa0.toUpperCase();

	                    var jj;
	                    var j;
	                    switch (r[0]) {
	                        case 'A':
	                            r[1] = pa[1];
	                            r[2] = pa[2];
	                            r[3] = pa[3];
	                            r[4] = pa[4];
	                            r[5] = pa[5];
	                            r[6] = +pa[6] + x;
	                            r[7] = +pa[7] + y;
	                            break;

	                        case 'V':
	                            r[1] = +pa[1] + y;
	                            break;

	                        case 'H':
	                            r[1] = +pa[1] + x;
	                            break;

	                        case 'M':
	                            mx = +pa[1] + x;
	                            my = +pa[2] + y;

	                            jj = pa.length;
	                            for (j = 1; j < jj; j++) {
	                                r[j] = +pa[j] + ((j % 2) ? x : y);
	                            }
	                            break;

	                        default:
	                            jj = pa.length;
	                            for (j = 1; j < jj; j++) {
	                                r[j] = +pa[j] + ((j % 2) ? x : y);
	                            }
	                            break;
	                    }
	                } else {
	                    var kk = pa.length;
	                    for (var k = 0; k < kk; k++) {
	                        r[k] = pa[k];
	                    }
	                }

	                switch (r[0]) {
	                    case 'Z':
	                        x = +mx;
	                        y = +my;
	                        break;

	                    case 'H':
	                        x = r[1];
	                        break;

	                    case 'V':
	                        y = r[1];
	                        break;

	                    case 'M':
	                        mx = r[r.length - 2];
	                        my = r[r.length - 1];
	                        x = r[r.length - 2];
	                        y = r[r.length - 1];
	                        break;

	                    default:
	                        x = r[r.length - 2];
	                        y = r[r.length - 1];
	                        break;
	                }
	            }

	            return res;
	        }

	        function normalize(path) {

	            var p = pathToAbsolute(path);
	            var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null };

	            function processPath(path, d, pcom) {

	                var nx, ny;

	                if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; }

	                if (!(path[0] in { T: 1, Q: 1 })) {
	                    d.qx = null;
	                    d.qy = null;
	                }

	                switch (path[0]) {
	                    case 'M':
	                        d.X = path[1];
	                        d.Y = path[2];
	                        break;

	                    case 'A':
	                        if (parseFloat(path[1]) === 0 || parseFloat(path[2]) === 0) {
	                            // https://www.w3.org/TR/SVG/paths.html#ArcOutOfRangeParameters
	                            // "If either rx or ry is 0, then this arc is treated as a
	                            // straight line segment (a "lineto") joining the endpoints."
	                            path = ['L', path[6], path[7]];
	                        } else {
	                            path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1))));
	                        }
	                        break;

	                    case 'S':
	                        if (pcom === 'C' || pcom === 'S') { // In 'S' case we have to take into account, if the previous command is C/S.
	                            nx = (d.x * 2) - d.bx;          // And reflect the previous
	                            ny = (d.y * 2) - d.by;          // command's control point relative to the current point.
	                        } else {                            // or some else or nothing
	                            nx = d.x;
	                            ny = d.y;
	                        }
	                        path = ['C', nx, ny].concat(path.slice(1));
	                        break;

	                    case 'T':
	                        if (pcom === 'Q' || pcom === 'T') { // In 'T' case we have to take into account, if the previous command is Q/T.
	                            d.qx = (d.x * 2) - d.qx;        // And make a reflection similar
	                            d.qy = (d.y * 2) - d.qy;        // to case 'S'.
	                        } else {                            // or something else or nothing
	                            d.qx = d.x;
	                            d.qy = d.y;
	                        }
	                        path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
	                        break;

	                    case 'Q':
	                        d.qx = path[1];
	                        d.qy = path[2];
	                        path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
	                        break;

	                    case 'H':
	                        path = ['L'].concat(path[1], d.y);
	                        break;

	                    case 'V':
	                        path = ['L'].concat(d.x, path[1]);
	                        break;

	                    case 'L':
	                        break;

	                    case 'Z':
	                        break;
	                }

	                return path;
	            }

	            function fixArc(pp, i) {

	                if (pp[i].length > 7) {

	                    pp[i].shift();
	                    var pi = pp[i];

	                    while (pi.length) {
	                        pcoms[i] = 'A'; // if created multiple 'C's, their original seg is saved
	                        pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6)));
	                    }

	                    pp.splice(i, 1);
	                    ii = p.length;
	                }
	            }

	            var pcoms = []; // path commands of original path p
	            var pfirst = ''; // temporary holder for original path command
	            var pcom = ''; // holder for previous path command of original path

	            var ii = p.length;
	            for (var i = 0; i < ii; i++) {
	                if (p[i]) { pfirst = p[i][0]; } // save current path command

	                if (pfirst !== 'C') { // C is not saved yet, because it may be result of conversion
	                    pcoms[i] = pfirst; // Save current path command
	                    if (i > 0) { pcom = pcoms[i - 1]; } // Get previous path command pcom
	                }

	                p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath

	                if (pcoms[i] !== 'A' && pfirst === 'C') { pcoms[i] = 'C'; } // 'A' is the only command
	                // which may produce multiple 'C's
	                // so we have to make sure that 'C' is also 'C' in original path

	                fixArc(p, i); // fixArc adds also the right amount of 'A's to pcoms

	                var seg = p[i];
	                var seglen = seg.length;

	                attrs.x = seg[seglen - 2];
	                attrs.y = seg[seglen - 1];

	                attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x;
	                attrs.by = parseFloat(seg[seglen - 3]) || attrs.y;
	            }

	            // make sure normalized path data string starts with an M segment
	            if (!p[0][0] || p[0][0] !== 'M') {
	                p.unshift(['M', 0, 0]);
	            }

	            return p;
	        }

	        return function(pathData) {
	            return normalize(pathData).join(',').split(',').join(' ');
	        };
	    })();

	    V.namespace = ns;

	    V.g = g;

	    return V;

	})();

	var config = {
	    // When set to `true` the cell selectors could be defined as CSS selectors.
	    // If not, only JSON Markup selectors are taken into account.
	    // export let useCSSSelectors = true;
	    useCSSSelectors: true,
	    // The class name prefix config is for advanced use only.
	    // Be aware that if you change the prefix, the JointJS CSS will no longer function properly.
	    // export let classNamePrefix = 'joint-';
	    // export let defaultTheme = 'default';
	    classNamePrefix: 'joint-',
	    defaultTheme: 'default'
	};

	var addClassNamePrefix = function(className) {

	    if (!className) { return className; }

	    return className.toString().split(' ').map(function(_className) {

	        if (_className.substr(0, config.classNamePrefix.length) !== config.classNamePrefix) {
	            _className = config.classNamePrefix + _className;
	        }

	        return _className;

	    }).join(' ');
	};

	var removeClassNamePrefix = function(className) {

	    if (!className) { return className; }

	    return className.toString().split(' ').map(function(_className) {

	        if (_className.substr(0, config.classNamePrefix.length) === config.classNamePrefix) {
	            _className = _className.substr(config.classNamePrefix.length);
	        }

	        return _className;

	    }).join(' ');
	};

	var parseDOMJSON = function(json, namespace) {

	    var selectors = {};
	    var groupSelectors = {};
	    var svgNamespace = V.namespace.svg;

	    var ns = namespace || svgNamespace;
	    var fragment = document.createDocumentFragment();
	    var queue = [json, fragment, ns];
	    while (queue.length > 0) {
	        ns = queue.pop();
	        var parentNode = queue.pop();
	        var siblingsDef = queue.pop();
	        for (var i = 0, n = siblingsDef.length; i < n; i++) {
	            var nodeDef = siblingsDef[i];
	            // TagName
	            if (!nodeDef.hasOwnProperty('tagName')) { throw new Error('json-dom-parser: missing tagName'); }
	            var tagName = nodeDef.tagName;
	            // Namespace URI
	            if (nodeDef.hasOwnProperty('namespaceURI')) { ns = nodeDef.namespaceURI; }
	            var node = document.createElementNS(ns, tagName);
	            var svg = (ns === svgNamespace);

	            var wrapper = (svg) ? V : $;
	            // Attributes
	            var attributes = nodeDef.attributes;
	            if (attributes) { wrapper(node).attr(attributes); }
	            // Style
	            var style = nodeDef.style;
	            if (style) { $(node).css(style); }
	            // ClassName
	            if (nodeDef.hasOwnProperty('className')) {
	                var className = nodeDef.className;
	                if (svg) {
	                    node.className.baseVal = className;
	                } else {
	                    node.className = className;
	                }
	            }
	            // TextContent
	            if (nodeDef.hasOwnProperty('textContent')) {
	                node.textContent = nodeDef.textContent;
	            }
	            // Selector
	            if (nodeDef.hasOwnProperty('selector')) {
	                var nodeSelector = nodeDef.selector;
	                if (selectors[nodeSelector]) { throw new Error('json-dom-parser: selector must be unique'); }
	                selectors[nodeSelector] = node;
	                wrapper(node).attr('joint-selector', nodeSelector);
	            }
	            // Groups
	            if (nodeDef.hasOwnProperty('groupSelector')) {
	                var nodeGroups = nodeDef.groupSelector;
	                if (!Array.isArray(nodeGroups)) { nodeGroups = [nodeGroups]; }
	                for (var j = 0, m = nodeGroups.length; j < m; j++) {
	                    var nodeGroup = nodeGroups[j];
	                    var group = groupSelectors[nodeGroup];
	                    if (!group) { group = groupSelectors[nodeGroup] = []; }
	                    group.push(node);
	                }
	            }
	            parentNode.appendChild(node);
	            // Children
	            var childrenDef = nodeDef.children;
	            if (Array.isArray(childrenDef)) { queue.push(childrenDef, node, ns); }
	        }
	    }
	    return {
	        fragment: fragment,
	        selectors: selectors,
	        groupSelectors: groupSelectors
	    };
	};

	// Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/.
	var hashCode = function(str) {

	    var hash = 0;
	    if (str.length === 0) { return hash; }
	    for (var i = 0; i < str.length; i++) {
	        var c = str.charCodeAt(i);
	        hash = ((hash << 5) - hash) + c;
	        hash = hash & hash; // Convert to 32bit integer
	    }
	    return hash;
	};

	var getByPath = function(obj, path, delimiter) {

	    var keys = Array.isArray(path) ? path : path.split(delimiter || '/');
	    var key;
	    var i = 0;
	    var length = keys.length;
	    while (i < length) {
	        key = keys[i++];
	        if (Object(obj) === obj && key in obj) {
	            obj = obj[key];
	        } else {
	            return undefined;
	        }
	    }
	    return obj;
	};

	var isGetSafe = function(obj, key) {
	    // Prevent prototype pollution
	    // https://snyk.io/vuln/SNYK-JS-JSON8MERGEPATCH-1038399
	    if (typeof key !== 'string' && typeof key !== 'number') {
	        key = String(key);
	    }
	    if (key === 'constructor' && typeof obj[key] === 'function') {
	        return false;
	    }
	    if (key === '__proto__') {
	        return false;
	    }
	    return true;
	};

	var setByPath = function(obj, path, value, delimiter) {

	    var keys = Array.isArray(path) ? path : path.split(delimiter || '/');
	    var last = keys.length - 1;
	    var diver = obj;
	    var i = 0;

	    for (; i < last; i++) {
	        var key = keys[i];
	        if (!isGetSafe(diver, key)) { return obj; }
	        var value$1 = diver[key];
	        // diver creates an empty object if there is no nested object under such a key.
	        // This means that one can populate an empty nested object with setByPath().
	        diver = value$1 || (diver[key] = {});
	    }

	    diver[keys[last]] = value;

	    return obj;
	};

	var unsetByPath = function(obj, path, delimiter) {

	    var keys = Array.isArray(path) ? path : path.split(delimiter || '/');
	    var last = keys.length - 1;
	    var diver = obj;
	    var i = 0;

	    for (; i < last; i++) {
	        var key = keys[i];
	        if (!isGetSafe(diver, key)) { return obj; }
	        var value = diver[key];
	        if (!value) { return obj; }
	        diver = value;
	    }

	    delete diver[keys[last]];

	    return obj;
	};

	var flattenObject = function(obj, delim, stop) {

	    delim = delim || '/';
	    var ret = {};

	    for (var key in obj) {

	        if (!obj.hasOwnProperty(key)) { continue; }

	        var shouldGoDeeper = typeof obj[key] === 'object';
	        if (shouldGoDeeper && stop && stop(obj[key])) {
	            shouldGoDeeper = false;
	        }

	        if (shouldGoDeeper) {

	            var flatObject = flattenObject(obj[key], delim, stop);

	            for (var flatKey in flatObject) {
	                if (!flatObject.hasOwnProperty(flatKey)) { continue; }
	                ret[key + delim + flatKey] = flatObject[flatKey];
	            }

	        } else {

	            ret[key] = obj[key];
	        }
	    }

	    return ret;
	};

	var uuid = function() {

	    // credit: http://stackoverflow.com/posts/2117523/revisions

	    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	        var r = (Math.random() * 16) | 0;
	        var v = (c === 'x') ? r : (r & 0x3 | 0x8);
	        return v.toString(16);
	    });
	};

	// Generate global unique id for obj and store it as a property of the object.
	var guid = function(obj) {

	    guid.id = guid.id || 1;
	    obj.id = (obj.id === undefined ? 'j_' + guid.id++ : obj.id);
	    return obj.id;
	};

	var toKebabCase = function(string) {

	    return string.replace(/[A-Z]/g, '-$&').toLowerCase();
	};

	var normalizeEvent = function(evt) {

	    var normalizedEvent = evt;
	    var touchEvt = evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches[0];
	    if (touchEvt) {
	        for (var property in evt) {
	            // copy all the properties from the input event that are not
	            // defined on the touch event (functions included).
	            if (touchEvt[property] === undefined) {
	                touchEvt[property] = evt[property];
	            }
	        }
	        normalizedEvent = touchEvt;
	    }

	    // IE: evt.target could be set to SVGElementInstance for SVGUseElement
	    var target = normalizedEvent.target;
	    if (target) {
	        var useElement = target.correspondingUseElement;
	        if (useElement) { normalizedEvent.target = useElement; }
	    }

	    return normalizedEvent;
	};

	var nextFrame = (function() {

	    var raf;

	    if (typeof window !== 'undefined') {

	        raf = window.requestAnimationFrame ||
	            window.webkitRequestAnimationFrame ||
	            window.mozRequestAnimationFrame ||
	            window.oRequestAnimationFrame ||
	            window.msRequestAnimationFrame;
	    }

	    if (!raf) {

	        var lastTime = 0;

	        raf = function(callback) {

	            var currTime = new Date().getTime();
	            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
	            var id = setTimeout(function() {
	                callback(currTime + timeToCall);
	            }, timeToCall);

	            lastTime = currTime + timeToCall;

	            return id;
	        };
	    }

	    return function(callback, context) {
	        var rest = [], len = arguments.length - 2;
	        while ( len-- > 0 ) rest[ len ] = arguments[ len + 2 ];

	        return (context !== undefined)
	            ? raf(callback.bind.apply(callback, [ context ].concat( rest )))
	            : raf(callback);
	    };

	})();

	var cancelFrame = (function() {

	    var caf;
	    var client = typeof window != 'undefined';

	    if (client) {

	        caf = window.cancelAnimationFrame ||
	            window.webkitCancelAnimationFrame ||
	            window.webkitCancelRequestAnimationFrame ||
	            window.msCancelAnimationFrame ||
	            window.msCancelRequestAnimationFrame ||
	            window.oCancelAnimationFrame ||
	            window.oCancelRequestAnimationFrame ||
	            window.mozCancelAnimationFrame ||
	            window.mozCancelRequestAnimationFrame;
	    }

	    caf = caf || clearTimeout;

	    return client ? caf.bind(window) : caf;

	})();

	/**
	 * @deprecated
	 */
	var shapePerimeterConnectionPoint = function(linkView, view, magnet, reference) {

	    var bbox;
	    var spot;

	    if (!magnet) {

	        // There is no magnet, try to make the best guess what is the
	        // wrapping SVG element. This is because we want this "smart"
	        // connection points to work out of the box without the
	        // programmer to put magnet marks to any of the subelements.
	        // For example, we want the function to work on basic.Path elements
	        // without any special treatment of such elements.
	        // The code below guesses the wrapping element based on
	        // one simple assumption. The wrapping elemnet is the
	        // first child of the scalable group if such a group exists
	        // or the first child of the rotatable group if not.
	        // This makese sense because usually the wrapping element
	        // is below any other sub element in the shapes.
	        var scalable = view.$('.scalable')[0];
	        var rotatable = view.$('.rotatable')[0];

	        if (scalable && scalable.firstChild) {

	            magnet = scalable.firstChild;

	        } else if (rotatable && rotatable.firstChild) {

	            magnet = rotatable.firstChild;
	        }
	    }

	    if (magnet) {

	        spot = V(magnet).findIntersection(reference, linkView.paper.cells);
	        if (!spot) {
	            bbox = V(magnet).getBBox({ target: linkView.paper.cells });
	        }

	    } else {

	        bbox = view.model.getBBox();
	        spot = bbox.intersectionWithLineFromCenterToPoint(reference);
	    }
	    return spot || bbox.center();
	};

	var isPercentage = function(val) {

	    return isString(val) && val.slice(-1) === '%';
	};

	var parseCssNumeric = function(val, restrictUnits) {

	    function getUnit(validUnitExp) {

	        // one or more numbers, followed by
	        // any number of (
	        //  `.`, followed by
	        //  one or more numbers
	        // ), followed by
	        // `validUnitExp`, followed by
	        // end of string
	        var matches = new RegExp('(?:\\d+(?:\\.\\d+)*)(' + validUnitExp + ')$').exec(val);

	        if (!matches) { return null; }
	        return matches[1];
	    }

	    var number = parseFloat(val);

	    // if `val` cannot be parsed as a number, return `null`
	    if (Number.isNaN(number)) { return null; }

	    // else: we know `output.value`
	    var output = {};
	    output.value = number;

	    // determine the unit
	    var validUnitExp;
	    if (restrictUnits == null) {
	        // no restriction
	        // accept any unit, as well as no unit
	        validUnitExp = '[A-Za-z]*';

	    } else if (Array.isArray(restrictUnits)) {
	        // if this is an empty array, top restriction - return `null`
	        if (restrictUnits.length === 0) { return null; }

	        // else: restriction - an array of valid unit strings
	        validUnitExp = restrictUnits.join('|');

	    } else if (isString(restrictUnits)) {
	        // restriction - a single valid unit string
	        validUnitExp = restrictUnits;
	    }
	    var unit = getUnit(validUnitExp);

	    // if we found no matches for `restrictUnits`, return `null`
	    if (unit === null) { return null; }

	    // else: we know the unit
	    output.unit = unit;
	    return output;
	};

	var breakText = function(text, size, styles, opt) {
	    if ( styles === void 0 ) styles = {};
	    if ( opt === void 0 ) opt = {};


	    var width = size.width;
	    var height = size.height;

	    var svgDocument = opt.svgDocument || V('svg').node;
	    var textSpan = V('tspan').node;
	    var textElement = V('text').attr(styles).append(textSpan).node;
	    var textNode = document.createTextNode('');

	    // Prevent flickering
	    textElement.style.opacity = 0;
	    // Prevent FF from throwing an uncaught exception when `getBBox()`
	    // called on element that is not in the render tree (is not measurable).
	    // <tspan>.getComputedTextLength() returns always 0 in this case.
	    // Note that the `textElement` resp. `textSpan` can become hidden
	    // when it's appended to the DOM and a `display: none` CSS stylesheet
	    // rule gets applied.
	    textElement.style.display = 'block';
	    textSpan.style.display = 'block';

	    textSpan.appendChild(textNode);
	    svgDocument.appendChild(textElement); // lgtm [js/xss-through-dom]

	    if (!opt.svgDocument) {

	        document.body.appendChild(svgDocument);
	    }

	    var separator = opt.separator || ' ';
	    var eol = opt.eol || '\n';
	    var hyphen = opt.hyphen ? new RegExp(opt.hyphen) : /[^\w\d]/;
	    var maxLineCount = opt.maxLineCount;
	    if (!isNumber(maxLineCount)) { maxLineCount = Infinity; }

	    var words = text.split(separator);
	    var full = [];
	    var lines = [];
	    var p, h;
	    var lineHeight;

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

	        var word = words[i];

	        if (!word) { continue; }

	        var isEol = false;
	        if (eol && word.indexOf(eol) >= 0) {
	            // word contains end-of-line character
	            if (word.length > 1) {
	                // separate word and continue cycle
	                var eolWords = word.split(eol);
	                for (var j = 0, jl = eolWords.length - 1; j < jl; j++) {
	                    eolWords.splice(2 * j + 1, 0, eol);
	                }
	                words.splice.apply(words, [ i, 1 ].concat( eolWords.filter(function (word) { return word !== ''; }) ));
	                i--;
	                len = words.length;
	                continue;
	            } else {
	                // creates a new line
	                lines[++l] = '';
	                isEol = true;
	            }
	        }

	        if (!isEol) {
	            textNode.data = lines[l] ? lines[l] + ' ' + word : word;

	            if (textSpan.getComputedTextLength() <= width) {

	                // the current line fits
	                lines[l] = textNode.data;

	                if (p || h) {
	                // We were partitioning. Put rest of the word onto next line
	                    full[l++] = true;

	                    // cancel partitioning and splitting by hyphens
	                    p = 0;
	                    h = 0;
	                }

	            } else {

	                if (!lines[l] || p) {

	                    var partition = !!p;

	                    p = word.length - 1;

	                    if (partition || !p) {

	                        // word has only one character.
	                        if (!p) {

	                            if (!lines[l]) {

	                                // we won't fit this text within our rect
	                                lines = [];

	                                break;
	                            }

	                            // partitioning didn't help on the non-empty line
	                            // try again, but this time start with a new line

	                            // cancel partitions created
	                            words.splice(i, 2, word + words[i + 1]);

	                            // adjust word length
	                            len--;

	                            full[l++] = true;
	                            i--;

	                            continue;
	                        }

	                        // move last letter to the beginning of the next word
	                        words[i] = word.substring(0, p);
	                        words[i + 1] = word.substring(p) + (words[i + 1] === undefined ? '' : words[i + 1]);

	                    } else {

	                        if (h) {
	                        // cancel splitting and put the words together again
	                            words.splice(i, 2, words[i] + words[i + 1]);
	                            h = 0;
	                        } else {
	                            var hyphenIndex = word.search(hyphen);
	                            if (hyphenIndex > -1 && hyphenIndex !== word.length - 1 && hyphenIndex !== 0) {
	                                h = hyphenIndex + 1;
	                                p = 0;
	                            }

	                            // We initiate partitioning or splitting
	                            // split the long word into two words
	                            words.splice(i, 1, word.substring(0, h || p), word.substring(h|| p));
	                            // adjust words length
	                            len++;

	                        }

	                        if (l && !full[l - 1]) {
	                        // if the previous line is not full, try to fit max part of
	                        // the current word there
	                            l--;
	                        }
	                    }

	                    i--;

	                    continue;
	                }

	                l++;
	                i--;
	            }
	        }
	        var lastL = null;

	        if (lines.length > maxLineCount) {

	            lastL = maxLineCount - 1;

	        } else if (height !== undefined) {

	            // if size.height is defined we have to check whether the height of the entire
	            // text exceeds the rect height

	            if (lineHeight === undefined) {

	                var heightValue;

	                // use the same defaults as in V.prototype.text
	                if (styles.lineHeight === 'auto') {
	                    heightValue = { value: 1.5, unit: 'em' };
	                } else {
	                    heightValue = parseCssNumeric(styles.lineHeight, ['em']) || { value: 1, unit: 'em' };
	                }

	                lineHeight = heightValue.value;
	                if (heightValue.unit === 'em') {
	                    lineHeight *= textElement.getBBox().height;
	                }
	            }

	            if (lineHeight * lines.length > height) {

	                // remove overflowing lines
	                lastL = Math.floor(height / lineHeight) - 1;
	            }
	        }

	        if (lastL !== null) {

	            lines.splice(lastL + 1);

	            // add ellipsis
	            var ellipsis = opt.ellipsis;
	            if (!ellipsis || lastL < 0) { break; }
	            if (typeof ellipsis !== 'string') { ellipsis = '\u2026'; }

	            var lastLine = lines[lastL];
	            if (!lastLine && !isEol) { break; }
	            var k = lastLine.length;
	            var lastLineWithOmission, lastChar, separatorChar;
	            do {
	                lastChar = lastLine[k];
	                lastLineWithOmission = lastLine.substring(0, k);
	                if (!lastChar) {
	                    separatorChar = (typeof separator === 'string') ? separator : ' ';
	                    lastLineWithOmission += separatorChar;
	                } else if (lastChar.match(separator)) {
	                    lastLineWithOmission += lastChar;
	                }
	                lastLineWithOmission += ellipsis;
	                textNode.data = lastLineWithOmission;
	                if (textSpan.getComputedTextLength() <= width) {
	                    lines[lastL] = lastLineWithOmission;
	                    break;
	                }
	                k--;
	            } while (k >= 0);
	            break;
	        }
	    }

	    if (opt.svgDocument) {

	        // svg document was provided, remove the text element only
	        svgDocument.removeChild(textElement);

	    } else {

	        // clean svg document
	        document.body.removeChild(svgDocument);
	    }

	    return lines.join(eol);
	};

	// Sanitize HTML
	// Based on https://gist.github.com/ufologist/5a0da51b2b9ef1b861c30254172ac3c9
	// Parses a string into an array of DOM nodes.
	// Then outputs it back as a string.
	var sanitizeHTML = function(html) {

	    // Ignores tags that are invalid inside a <div> tag (e.g. <body>, <head>)

	    // If documentContext (second parameter) is not specified or given as `null` or `undefined`, a new document is used.
	    // Inline events will not execute when the HTML is parsed; this includes, for example, sending GET requests for images.

	    // If keepScripts (last parameter) is `false`, scripts are not executed.
	    var output = $($.parseHTML('<div>' + html + '</div>', null, false));

	    output.find('*').each(function() { // for all nodes
	        var currentNode = this;

	        $.each(currentNode.attributes, function() { // for all attributes in each node
	            var currentAttribute = this;

	            var attrName = currentAttribute.name;
	            var attrValue = currentAttribute.value;

	            // Remove attribute names that start with "on" (e.g. onload, onerror...).
	            // Remove attribute values that start with "javascript:" pseudo protocol (e.g. `href="javascript:alert(1)"`).
	            if (attrName.startsWith('on') || attrValue.startsWith('javascript:') || attrValue.startsWith('data:') || attrValue.startsWith('vbscript:')) {
	                $(currentNode).removeAttr(attrName);
	            }
	        });
	    });

	    return output.html();
	};

	// Download `blob` as file with `fileName`.
	// Does not work in IE9.
	var downloadBlob = function(blob, fileName) {

	    if (window.navigator.msSaveBlob) { // requires IE 10+
	        // pulls up a save dialog
	        window.navigator.msSaveBlob(blob, fileName);

	    } else { // other browsers
	        // downloads directly in Chrome and Safari

	        // presents a save/open dialog in Firefox
	        // Firefox bug: `from` field in save dialog always shows `from:blob:`
	        // https://bugzilla.mozilla.org/show_bug.cgi?id=1053327

	        var url = window.URL.createObjectURL(blob);
	        var link = document.createElement('a');

	        link.href = url;
	        link.download = fileName;
	        document.body.appendChild(link);

	        link.click();

	        document.body.removeChild(link);
	        window.URL.revokeObjectURL(url); // mark the url for garbage collection
	    }
	};

	// Download `dataUri` as file with `fileName`.
	// Does not work in IE9.
	var downloadDataUri = function(dataUri, fileName) {

	    var blob = dataUriToBlob(dataUri);
	    downloadBlob(blob, fileName);
	};

	// Convert an uri-encoded data component (possibly also base64-encoded) to a blob.
	var dataUriToBlob = function(dataUri) {

	    // first, make sure there are no newlines in the data uri
	    dataUri = dataUri.replace(/\s/g, '');
	    dataUri = decodeURIComponent(dataUri);

	    var firstCommaIndex = dataUri.indexOf(','); // split dataUri as `dataTypeString`,`data`

	    var dataTypeString = dataUri.slice(0, firstCommaIndex); // e.g. 'data:image/jpeg;base64'
	    var mimeString = dataTypeString.split(':')[1].split(';')[0]; // e.g. 'image/jpeg'

	    var data = dataUri.slice(firstCommaIndex + 1);
	    var decodedString;
	    if (dataTypeString.indexOf('base64') >= 0) { // data may be encoded in base64
	        decodedString = atob(data); // decode data
	    } else {
	        // convert the decoded string to UTF-8
	        decodedString = unescape(encodeURIComponent(data));
	    }
	    // write the bytes of the string to a typed array
	    var ia = new Uint8Array(decodedString.length);
	    for (var i = 0; i < decodedString.length; i++) {
	        ia[i] = decodedString.charCodeAt(i);
	    }

	    return new Blob([ia], { type: mimeString }); // return the typed array as Blob
	};

	// Read an image at `url` and return it as base64-encoded data uri.
	// The mime type of the image is inferred from the `url` file extension.
	// If data uri is provided as `url`, it is returned back unchanged.
	// `callback` is a method with `err` as first argument and `dataUri` as second argument.
	// Works with IE9.
	var imageToDataUri = function(url, callback) {

	    if (!url || url.substr(0, 'data:'.length) === 'data:') {
	        // No need to convert to data uri if it is already in data uri.

	        // This not only convenient but desired. For example,
	        // IE throws a security error if data:image/svg+xml is used to render
	        // an image to the canvas and an attempt is made to read out data uri.
	        // Now if our image is already in data uri, there is no need to render it to the canvas
	        // and so we can bypass this error.

	        // Keep the async nature of the function.
	        return setTimeout(function() {
	            callback(null, url);
	        }, 0);
	    }

	    // chrome, IE10+
	    var modernHandler = function(xhr, callback) {

	        if (xhr.status === 200) {

	            var reader = new FileReader();

	            reader.onload = function(evt) {
	                var dataUri = evt.target.result;
	                callback(null, dataUri);
	            };

	            reader.onerror = function() {
	                callback(new Error('Failed to load image ' + url));
	            };

	            reader.readAsDataURL(xhr.response);
	        } else {
	            callback(new Error('Failed to load image ' + url));
	        }
	    };

	    var legacyHandler = function(xhr, callback) {

	        var Uint8ToString = function(u8a) {
	            var CHUNK_SZ = 0x8000;
	            var c = [];
	            for (var i = 0; i < u8a.length; i += CHUNK_SZ) {
	                c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + CHUNK_SZ)));
	            }
	            return c.join('');
	        };

	        if (xhr.status === 200) {

	            var bytes = new Uint8Array(xhr.response);

	            var suffix = (url.split('.').pop()) || 'png';
	            var map = {
	                'svg': 'svg+xml'
	            };
	            var meta = 'data:image/' + (map[suffix] || suffix) + ';base64,';
	            var b64encoded = meta + btoa(Uint8ToString(bytes));
	            callback(null, b64encoded);
	        } else {
	            callback(new Error('Failed to load image ' + url));
	        }
	    };

	    var xhr = new XMLHttpRequest();

	    xhr.open('GET', url, true);
	    xhr.addEventListener('error', function() {
	        callback(new Error('Failed to load image ' + url));
	    });

	    xhr.responseType = window.FileReader ? 'blob' : 'arraybuffer';

	    xhr.addEventListener('load', function() {
	        if (window.FileReader) {
	            modernHandler(xhr, callback);
	        } else {
	            legacyHandler(xhr, callback);
	        }
	    });

	    xhr.send();
	};

	var getElementBBox = function(el) {

	    var $el = $(el);
	    if ($el.length === 0) {
	        throw new Error('Element not found');
	    }

	    var element = $el[0];
	    var doc = element.ownerDocument;
	    var clientBBox = element.getBoundingClientRect();

	    var strokeWidthX = 0;
	    var strokeWidthY = 0;

	    // Firefox correction
	    if (element.ownerSVGElement) {

	        var vel = V(element);
	        var bbox = vel.getBBox({ target: vel.svg() });

	        // if FF getBoundingClientRect includes stroke-width, getBBox doesn't.
	        // To unify this across all browsers we need to adjust the final bBox with `stroke-width` value.
	        strokeWidthX = (clientBBox.width - bbox.width);
	        strokeWidthY = (clientBBox.height - bbox.height);
	    }

	    return {
	        x: clientBBox.left + window.pageXOffset - doc.documentElement.offsetLeft + strokeWidthX / 2,
	        y: clientBBox.top + window.pageYOffset - doc.documentElement.offsetTop + strokeWidthY / 2,
	        width: clientBBox.width - strokeWidthX,
	        height: clientBBox.height - strokeWidthY
	    };
	};


	// Highly inspired by the jquery.sortElements plugin by Padolsey.
	// See http://james.padolsey.com/javascript/sorting-elements-with-jquery/.
	var sortElements = function(elements, comparator) {

	    var $elements = $(elements);
	    var placements = $elements.map(function() {

	        var sortElement = this;
	        var parentNode = sortElement.parentNode;
	        // Since the element itself will change position, we have
	        // to have some way of storing it's original position in
	        // the DOM. The easiest way is to have a 'flag' node:
	        var nextSibling = parentNode.insertBefore(document.createTextNode(''), sortElement.nextSibling);

	        return function() {

	            if (parentNode === this) {
	                throw new Error('You can\'t sort elements if any one is a descendant of another.');
	            }

	            // Insert before flag:
	            parentNode.insertBefore(this, nextSibling);
	            // Remove flag:
	            parentNode.removeChild(nextSibling);
	        };
	    });

	    return Array.prototype.sort.call($elements, comparator).each(function(i) {
	        placements[i].call(this);
	    });
	};

	// Sets attributes on the given element and its descendants based on the selector.
	// `attrs` object: { [SELECTOR1]: { attrs1 }, [SELECTOR2]: { attrs2}, ... } e.g. { 'input': { color : 'red' }}
	var setAttributesBySelector = function(element, attrs) {

	    var $element = $(element);

	    forIn(attrs, function(attrs, selector) {
	        var $elements = $element.find(selector).addBack().filter(selector);
	        // Make a special case for setting classes.
	        // We do not want to overwrite any existing class.
	        if (has$2(attrs, 'class')) {
	            $elements.addClass(attrs['class']);
	            attrs = omit(attrs, 'class');
	        }
	        $elements.attr(attrs);
	    });
	};

	// Return a new object with all four sides (top, right, bottom, left) in it.
	// Value of each side is taken from the given argument (either number or object).
	// Default value for a side is 0.
	// Examples:
	// normalizeSides(5) --> { top: 5, right: 5, bottom: 5, left: 5 }
	// normalizeSides({ horizontal: 5 }) --> { top: 0, right: 5, bottom: 0, left: 5 }
	// normalizeSides({ left: 5 }) --> { top: 0, right: 0, bottom: 0, left: 5 }
	// normalizeSides({ horizontal: 10, left: 5 }) --> { top: 0, right: 10, bottom: 0, left: 5 }
	// normalizeSides({ horizontal: 0, left: 5 }) --> { top: 0, right: 0, bottom: 0, left: 5 }
	var normalizeSides = function(box) {

	    if (Object(box) !== box) { // `box` is not an object
	        var val = 0; // `val` left as 0 if `box` cannot be understood as finite number
	        if (isFinite(box)) { val = +box; } // actually also accepts string numbers (e.g. '100')

	        return { top: val, right: val, bottom: val, left: val };
	    }

	    // `box` is an object
	    var top, right, bottom, left;
	    top = right = bottom = left = 0;

	    if (isFinite(box.vertical)) { top = bottom = +box.vertical; }
	    if (isFinite(box.horizontal)) { right = left = +box.horizontal; }

	    if (isFinite(box.top)) { top = +box.top; } // overwrite vertical
	    if (isFinite(box.right)) { right = +box.right; } // overwrite horizontal
	    if (isFinite(box.bottom)) { bottom = +box.bottom; } // overwrite vertical
	    if (isFinite(box.left)) { left = +box.left; } // overwrite horizontal

	    return { top: top, right: right, bottom: bottom, left: left };
	};

	var timing = {

	    linear: function(t) {
	        return t;
	    },

	    quad: function(t) {
	        return t * t;
	    },

	    cubic: function(t) {
	        return t * t * t;
	    },

	    inout: function(t) {
	        if (t <= 0) { return 0; }
	        if (t >= 1) { return 1; }
	        var t2 = t * t;
	        var t3 = t2 * t;
	        return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
	    },

	    exponential: function(t) {
	        return Math.pow(2, 10 * (t - 1));
	    },

	    bounce: function(t) {
	        for (var a = 0, b = 1; 1; a += b, b /= 2) {
	            if (t >= (7 - 4 * a) / 11) {
	                var q = (11 - 6 * a - 11 * t) / 4;
	                return -q * q + b * b;
	            }
	        }
	    },

	    reverse: function(f) {
	        return function(t) {
	            return 1 - f(1 - t);
	        };
	    },

	    reflect: function(f) {
	        return function(t) {
	            return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t)));
	        };
	    },

	    clamp: function(f, n, x) {
	        n = n || 0;
	        x = x || 1;
	        return function(t) {
	            var r = f(t);
	            return r < n ? n : r > x ? x : r;
	        };
	    },

	    back: function(s) {
	        if (!s) { s = 1.70158; }
	        return function(t) {
	            return t * t * ((s + 1) * t - s);
	        };
	    },

	    elastic: function(x) {
	        if (!x) { x = 1.5; }
	        return function(t) {
	            return Math.pow(2, 10 * (t - 1)) * Math.cos(20 * Math.PI * x / 3 * t);
	        };
	    }
	};

	var interpolate = {

	    number: function(a, b) {
	        var d = b - a;
	        return function(t) {
	            return a + d * t;
	        };
	    },

	    object: function(a, b) {
	        var s = Object.keys(a);
	        return function(t) {
	            var i, p;
	            var r = {};
	            for (i = s.length - 1; i != -1; i--) {
	                p = s[i];
	                r[p] = a[p] + (b[p] - a[p]) * t;
	            }
	            return r;
	        };
	    },

	    hexColor: function(a, b) {

	        var ca = parseInt(a.slice(1), 16);
	        var cb = parseInt(b.slice(1), 16);
	        var ra = ca & 0x0000ff;
	        var rd = (cb & 0x0000ff) - ra;
	        var ga = ca & 0x00ff00;
	        var gd = (cb & 0x00ff00) - ga;
	        var ba = ca & 0xff0000;
	        var bd = (cb & 0xff0000) - ba;

	        return function(t) {

	            var r = (ra + rd * t) & 0x000000ff;
	            var g = (ga + gd * t) & 0x0000ff00;
	            var b = (ba + bd * t) & 0x00ff0000;

	            return '#' + (1 << 24 | r | g | b).toString(16).slice(1);
	        };
	    },

	    unit: function(a, b) {

	        var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/;
	        var ma = r.exec(a);
	        var mb = r.exec(b);
	        var p = mb[1].indexOf('.');
	        var f = p > 0 ? mb[1].length - p - 1 : 0;
	        a = +ma[1];
	        var d = +mb[1] - a;
	        var u = ma[2];

	        return function(t) {
	            return (a + d * t).toFixed(f) + u;
	        };
	    }
	};

	// SVG filters.
	// (values in parentheses are default values)
	var filter = {

	    // `color` ... outline color ('blue')
	    // `width`... outline width (1)
	    // `opacity` ... outline opacity (1)
	    // `margin` ... gap between outline and the element (2)
	    outline: function(args) {

	        var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology in="SourceAlpha" result="morphedOuter" operator="dilate" radius="${outerRadius}" /><feMorphology in="SourceAlpha" result="morphedInner" operator="dilate" radius="${innerRadius}" /><feComposite result="morphedOuterColored" in="colored" in2="morphedOuter" operator="in"/><feComposite operator="xor" in="morphedOuterColored" in2="morphedInner" result="outline"/><feMerge><feMergeNode in="outline"/><feMergeNode in="SourceGraphic"/></feMerge></filter>';

	        var margin = Number.isFinite(args.margin) ? args.margin : 2;
	        var width = Number.isFinite(args.width) ? args.width : 1;

	        return template(tpl)({
	            color: args.color || 'blue',
	            opacity: Number.isFinite(args.opacity) ? args.opacity : 1,
	            outerRadius: margin + width,
	            innerRadius: margin
	        });
	    },

	    // `color` ... color ('red')
	    // `width`... width (1)
	    // `blur` ... blur (0)
	    // `opacity` ... opacity (1)
	    highlight: function(args) {

	        var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology result="morphed" in="SourceGraphic" operator="dilate" radius="${width}"/><feComposite result="composed" in="colored" in2="morphed" operator="in"/><feGaussianBlur result="blured" in="composed" stdDeviation="${blur}"/><feBlend in="SourceGraphic" in2="blured" mode="normal"/></filter>';

	        return template(tpl)({
	            color: args.color || 'red',
	            width: Number.isFinite(args.width) ? args.width : 1,
	            blur: Number.isFinite(args.blur) ? args.blur : 0,
	            opacity: Number.isFinite(args.opacity) ? args.opacity : 1
	        });
	    },

	    // `x` ... horizontal blur (2)
	    // `y` ... vertical blur (optional)
	    blur: function(args) {

	        var x = Number.isFinite(args.x) ? args.x : 2;

	        return template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>')({
	            stdDeviation: Number.isFinite(args.y) ? [x, args.y] : x
	        });
	    },

	    // `dx` ... horizontal shift (0)
	    // `dy` ... vertical shift (0)
	    // `blur` ... blur (4)
	    // `color` ... color ('black')
	    // `opacity` ... opacity (1)
	    dropShadow: function(args) {

	        var tpl = 'SVGFEDropShadowElement' in window
	            ? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>'
	            : '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>';

	        return template(tpl)({
	            dx: args.dx || 0,
	            dy: args.dy || 0,
	            opacity: Number.isFinite(args.opacity) ? args.opacity : 1,
	            color: args.color || 'black',
	            blur: Number.isFinite(args.blur) ? args.blur : 4
	        });
	    },

	    // `amount` ... the proportion of the conversion (1). A value of 1 (default) is completely grayscale. A value of 0 leaves the input unchanged.
	    grayscale: function(args) {

	        var amount = Number.isFinite(args.amount) ? args.amount : 1;

	        return template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>')({
	            a: 0.2126 + 0.7874 * (1 - amount),
	            b: 0.7152 - 0.7152 * (1 - amount),
	            c: 0.0722 - 0.0722 * (1 - amount),
	            d: 0.2126 - 0.2126 * (1 - amount),
	            e: 0.7152 + 0.2848 * (1 - amount),
	            f: 0.0722 - 0.0722 * (1 - amount),
	            g: 0.2126 - 0.2126 * (1 - amount),
	            h: 0.0722 + 0.9278 * (1 - amount)
	        });
	    },

	    // `amount` ... the proportion of the conversion (1). A value of 1 (default) is completely sepia. A value of 0 leaves the input unchanged.
	    sepia: function(args) {

	        var amount = Number.isFinite(args.amount) ? args.amount : 1;

	        return template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>')({
	            a: 0.393 + 0.607 * (1 - amount),
	            b: 0.769 - 0.769 * (1 - amount),
	            c: 0.189 - 0.189 * (1 - amount),
	            d: 0.349 - 0.349 * (1 - amount),
	            e: 0.686 + 0.314 * (1 - amount),
	            f: 0.168 - 0.168 * (1 - amount),
	            g: 0.272 - 0.272 * (1 - amount),
	            h: 0.534 - 0.534 * (1 - amount),
	            i: 0.131 + 0.869 * (1 - amount)
	        });
	    },

	    // `amount` ... the proportion of the conversion (1). A value of 0 is completely un-saturated. A value of 1 (default) leaves the input unchanged.
	    saturate: function(args) {

	        var amount = Number.isFinite(args.amount) ? args.amount : 1;

	        return template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>')({
	            amount: 1 - amount
	        });
	    },

	    // `angle` ...  the number of degrees around the color circle the input samples will be adjusted (0).
	    hueRotate: function(args) {

	        return template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>')({
	            angle: args.angle || 0
	        });
	    },

	    // `amount` ... the proportion of the conversion (1). A value of 1 (default) is completely inverted. A value of 0 leaves the input unchanged.
	    invert: function(args) {

	        var amount = Number.isFinite(args.amount) ? args.amount : 1;

	        return template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>')({
	            amount: amount,
	            amount2: 1 - amount
	        });
	    },

	    // `amount` ... proportion of the conversion (1). A value of 0 will create an image that is completely black. A value of 1 (default) leaves the input unchanged.
	    brightness: function(args) {

	        return template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>')({
	            amount: Number.isFinite(args.amount) ? args.amount : 1
	        });
	    },

	    // `amount` ... proportion of the conversion (1). A value of 0 will create an image that is completely black. A value of 1 (default) leaves the input unchanged.
	    contrast: function(args) {

	        var amount = Number.isFinite(args.amount) ? args.amount : 1;

	        return template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>')({
	            amount: amount,
	            amount2: .5 - amount / 2
	        });
	    }
	};

	var format = {

	    // Formatting numbers via the Python Format Specification Mini-language.
	    // See http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
	    // Heavilly inspired by the D3.js library implementation.
	    number: function(specifier, value, locale) {

	        locale = locale || {

	            currency: ['$', ''],
	            decimal: '.',
	            thousands: ',',
	            grouping: [3]
	        };

	        // See Python format specification mini-language: http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
	        // [[fill]align][sign][symbol][0][width][,][.precision][type]
	        var re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;

	        var match = re.exec(specifier);
	        var fill = match[1] || ' ';
	        var align = match[2] || '>';
	        var sign = match[3] || '';
	        var symbol = match[4] || '';
	        var zfill = match[5];
	        var width = +match[6];
	        var comma = match[7];
	        var precision = match[8];
	        var type = match[9];
	        var scale = 1;
	        var prefix = '';
	        var suffix = '';
	        var integer = false;

	        if (precision) { precision = +precision.substring(1); }

	        if (zfill || fill === '0' && align === '=') {
	            zfill = fill = '0';
	            align = '=';
	            if (comma) { width -= Math.floor((width - 1) / 4); }
	        }

	        switch (type) {
	            case 'n':
	                comma = true;
	                type = 'g';
	                break;
	            case '%':
	                scale = 100;
	                suffix = '%';
	                type = 'f';
	                break;
	            case 'p':
	                scale = 100;
	                suffix = '%';
	                type = 'r';
	                break;
	            case 'b':
	            case 'o':
	            case 'x':
	            case 'X':
	                if (symbol === '#') { prefix = '0' + type.toLowerCase(); }
	                break;
	            case 'c':
	            case 'd':
	                integer = true;
	                precision = 0;
	                break;
	            case 's':
	                scale = -1;
	                type = 'r';
	                break;
	        }

	        if (symbol === '$') {
	            prefix = locale.currency[0];
	            suffix = locale.currency[1];
	        }

	        // If no precision is specified for `'r'`, fallback to general notation.
	        if (type == 'r' && !precision) { type = 'g'; }

	        // Ensure that the requested precision is in the supported range.
	        if (precision != null) {
	            if (type == 'g') { precision = Math.max(1, Math.min(21, precision)); }
	            else if (type == 'e' || type == 'f') { precision = Math.max(0, Math.min(20, precision)); }
	        }

	        var zcomma = zfill && comma;

	        // Return the empty string for floats formatted as ints.
	        if (integer && (value % 1)) { return ''; }

	        // Convert negative to positive, and record the sign prefix.
	        var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, '-') : sign;

	        var fullSuffix = suffix;

	        // Apply the scale, computing it from the value's exponent for si format.
	        // Preserve the existing suffix, if any, such as the currency symbol.
	        if (scale < 0) {
	            var unit = this.prefix(value, precision);
	            value = unit.scale(value);
	            fullSuffix = unit.symbol + suffix;
	        } else {
	            value *= scale;
	        }

	        // Convert to the desired precision.
	        value = this.convert(type, value, precision);

	        // Break the value into the integer part (before) and decimal part (after).
	        var i = value.lastIndexOf('.');
	        var before = i < 0 ? value : value.substring(0, i);
	        var after = i < 0 ? '' : locale.decimal + value.substring(i + 1);

	        function formatGroup(value) {

	            var i = value.length;
	            var t = [];
	            var j = 0;
	            var g = locale.grouping[0];
	            while (i > 0 && g > 0) {
	                t.push(value.substring(i -= g, i + g));
	                g = locale.grouping[j = (j + 1) % locale.grouping.length];
	            }
	            return t.reverse().join(locale.thousands);
	        }

	        // If the fill character is not `'0'`, grouping is applied before padding.
	        if (!zfill && comma && locale.grouping) {

	            before = formatGroup(before);
	        }

	        var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length);
	        var padding = length < width ? new Array(length = width - length + 1).join(fill) : '';

	        // If the fill character is `'0'`, grouping is applied after padding.
	        if (zcomma) { before = formatGroup(padding + before); }

	        // Apply prefix.
	        negative += prefix;

	        // Rejoin integer and decimal parts.
	        value = before + after;

	        return (align === '<' ? negative + value + padding
	            : align === '>' ? padding + negative + value
	                : align === '^' ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length)
	                    : negative + (zcomma ? value : padding + value)) + fullSuffix;
	    },

	    // Formatting string via the Python Format string.
	    // See https://docs.python.org/2/library/string.html#format-string-syntax)
	    string: function(formatString, value) {

	        var fieldDelimiterIndex;
	        var fieldDelimiter = '{';
	        var endPlaceholder = false;
	        var formattedStringArray = [];

	        while ((fieldDelimiterIndex = formatString.indexOf(fieldDelimiter)) !== -1) {

	            var pieceFormattedString, formatSpec, fieldName;

	            pieceFormattedString = formatString.slice(0, fieldDelimiterIndex);

	            if (endPlaceholder) {
	                formatSpec = pieceFormattedString.split(':');
	                fieldName = formatSpec.shift().split('.');
	                pieceFormattedString = value;

	                for (var i = 0; i < fieldName.length; i++)
	                    { pieceFormattedString = pieceFormattedString[fieldName[i]]; }

	                if (formatSpec.length)
	                    { pieceFormattedString = this.number(formatSpec, pieceFormattedString); }
	            }

	            formattedStringArray.push(pieceFormattedString);

	            formatString = formatString.slice(fieldDelimiterIndex + 1);
	            endPlaceholder = !endPlaceholder;
	            fieldDelimiter = (endPlaceholder) ? '}' : '{';
	        }
	        formattedStringArray.push(formatString);

	        return formattedStringArray.join('');
	    },

	    convert: function(type, value, precision) {

	        switch (type) {
	            case 'b':
	                return value.toString(2);
	            case 'c':
	                return String.fromCharCode(value);
	            case 'o':
	                return value.toString(8);
	            case 'x':
	                return value.toString(16);
	            case 'X':
	                return value.toString(16).toUpperCase();
	            case 'g':
	                return value.toPrecision(precision);
	            case 'e':
	                return value.toExponential(precision);
	            case 'f':
	                return value.toFixed(precision);
	            case 'r':
	                return (value = this.round(value, this.precision(value, precision))).toFixed(Math.max(0, Math.min(20, this.precision(value * (1 + 1e-15), precision))));
	            default:
	                return value + '';
	        }
	    },

	    round: function(value, precision) {

	        return precision
	            ? Math.round(value * (precision = Math.pow(10, precision))) / precision
	            : Math.round(value);
	    },

	    precision: function(value, precision) {

	        return precision - (value ? Math.ceil(Math.log(value) / Math.LN10) : 1);
	    },

	    prefix: function(value, precision) {

	        var prefixes = ['y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'].map(function(d, i) {
	            var k = Math.pow(10, Math.abs(8 - i) * 3);
	            return {
	                scale: i > 8 ? function(d) {
	                    return d / k;
	                } : function(d) {
	                    return d * k;
	                },
	                symbol: d
	            };
	        });

	        var i = 0;
	        if (value) {
	            if (value < 0) { value *= -1; }
	            if (precision) { value = this.round(value, this.precision(value, precision)); }
	            i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
	            i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3));
	        }
	        return prefixes[8 + i / 3];
	    }
	};

	/*
	    Pre-compile the HTML to be used as a template.
	*/
	var template = function(html) {

	    /*
	        Must support the variation in templating syntax found here:
	        https://lodash.com/docs#template
	    */
	    var regex = /<%= ([^ ]+) %>|\$\{ ?([^{} ]+) ?\}|\{\{([^{} ]+)\}\}/g;

	    return function(data) {

	        data = data || {};

	        return html.replace(regex, function(match) {

	            var args = Array.from(arguments);
	            var attr = args.slice(1, 4).find(function(_attr) {
	                return !!_attr;
	            });

	            var attrArray = attr.split('.');
	            var value = data[attrArray.shift()];

	            while (value !== undefined && attrArray.length) {
	                value = value[attrArray.shift()];
	            }

	            return value !== undefined ? value : '';
	        });
	    };
	};

	/**
	 * @param {Element} el Element, which content is intent to display in full-screen mode, 'window.top.document.body' is default.
	 */
	var toggleFullScreen = function(el) {

	    var topDocument = window.top.document;
	    el = el || topDocument.body;

	    function prefixedResult(el, prop) {

	        var prefixes = ['webkit', 'moz', 'ms', 'o', ''];
	        for (var i = 0; i < prefixes.length; i++) {
	            var prefix = prefixes[i];
	            var propName = prefix ? (prefix + prop) : (prop.substr(0, 1).toLowerCase() + prop.substr(1));
	            if (el[propName] !== undefined) {
	                return isFunction(el[propName]) ? el[propName]() : el[propName];
	            }
	        }
	    }

	    if (prefixedResult(topDocument, 'FullscreenElement') || prefixedResult(topDocument, 'FullScreenElement')) {
	        prefixedResult(topDocument, 'ExitFullscreen') || // Spec.
	        prefixedResult(topDocument, 'CancelFullScreen'); // Firefox
	    } else {
	        prefixedResult(el, 'RequestFullscreen') || // Spec.
	        prefixedResult(el, 'RequestFullScreen'); // Firefox
	    }
	};

	// Deprecated
	// Copy all the properties to the first argument from the following arguments.
	// All the properties will be overwritten by the properties from the following
	// arguments. Inherited properties are ignored.
	var mixin = _.assign;

	// Deprecated
	// Copy all properties to the first argument from the following
	// arguments only in case if they don't exists in the first argument.
	// All the function propererties in the first argument will get
	// additional property base pointing to the extenders same named
	// property function's call method.
	var supplement = _.defaults;

	// Same as `mixin()` but deep version.
	var deepMixin = mixin;

	// Deprecated
	// Same as `supplement()` but deep version.
	var deepSupplement = _.defaultsDeep;

	// Replacements for deprecated functions
	var assign = _.assign;
	var defaults = _.defaults;
	// no better-named replacement for `deepMixin`
	var defaultsDeep = _.defaultsDeep;

	// Lodash 3 vs 4 incompatible
	var invoke = _.invokeMap || _.invoke;
	var sortedIndex = _.sortedIndexBy || _.sortedIndex;
	var uniq = _.uniqBy || _.uniq;

	var clone = _.clone;
	var cloneDeep = _.cloneDeep;
	var isEmpty = _.isEmpty;
	var isEqual = _.isEqual;
	var isFunction = _.isFunction;
	var isPlainObject = _.isPlainObject;
	var toArray = _.toArray;
	var debounce = _.debounce;
	var groupBy = _.groupBy;
	var sortBy = _.sortBy;
	var flattenDeep = _.flattenDeep;
	var without = _.without;
	var difference = _.difference;
	var intersection = _.intersection;
	var union = _.union;
	var has$2 = _.has;
	var result = _.result;
	var omit = _.omit;
	var pick = _.pick;
	var bindAll = _.bindAll;
	var forIn = _.forIn;
	var camelCase = _.camelCase;
	var uniqueId = _.uniqueId;

	var merge = function() {
	    if (_.mergeWith) {
	        var args = Array.from(arguments);
	        var last = args[args.length - 1];

	        var customizer = isFunction(last) ? last : noop;
	        args.push(function(a, b) {
	            var customResult = customizer(a, b);
	            if (customResult !== undefined) {
	                return customResult;
	            }

	            if (Array.isArray(a) && !Array.isArray(b)) {
	                return b;
	            }
	        });

	        return _.mergeWith.apply(this, args);
	    }
	    return _.merge.apply(this, arguments);
	};

	var isBoolean = function(value) {
	    var toString = Object.prototype.toString;
	    return value === true || value === false || (!!value && typeof value === 'object' && toString.call(value) === '[object Boolean]');
	};

	var isObject$1 = function(value) {
	    return !!value && (typeof value === 'object' || typeof value === 'function');
	};

	var isNumber = function(value) {
	    var toString = Object.prototype.toString;
	    return typeof value === 'number' || (!!value && typeof value === 'object' && toString.call(value) === '[object Number]');
	};

	var isString = function(value) {
	    var toString = Object.prototype.toString;
	    return typeof value === 'string' || (!!value && typeof value === 'object' && toString.call(value) === '[object String]');
	};

	var noop = function() {
	};

	// Clone `cells` returning an object that maps the original cell ID to the clone. The number
	// of clones is exactly the same as the `cells.length`.
	// This function simply clones all the `cells`. However, it also reconstructs
	// all the `source/target` and `parent/embed` references within the `cells`.
	// This is the main difference from the `cell.clone()` method. The
	// `cell.clone()` method works on one single cell only.
	// For example, for a graph: `A --- L ---> B`, `cloneCells([A, L, B])`
	// returns `[A2, L2, B2]` resulting to a graph: `A2 --- L2 ---> B2`, i.e.
	// the source and target of the link `L2` is changed to point to `A2` and `B2`.
	function cloneCells(cells) {

	    cells = uniq(cells);

	    // A map of the form [original cell ID] -> [clone] helping
	    // us to reconstruct references for source/target and parent/embeds.
	    // This is also the returned value.
	    var cloneMap = toArray(cells).reduce(function(map, cell) {
	        map[cell.id] = cell.clone();
	        return map;
	    }, {});

	    toArray(cells).forEach(function(cell) {

	        var clone = cloneMap[cell.id];
	        // assert(clone exists)

	        if (clone.isLink()) {
	            var source = clone.source();
	            var target = clone.target();
	            if (source.id && cloneMap[source.id]) {
	                // Source points to an element and the element is among the clones.
	                // => Update the source of the cloned link.
	                clone.prop('source/id', cloneMap[source.id].id);
	            }
	            if (target.id && cloneMap[target.id]) {
	                // Target points to an element and the element is among the clones.
	                // => Update the target of the cloned link.
	                clone.prop('target/id', cloneMap[target.id].id);
	            }
	        }

	        // Find the parent of the original cell
	        var parent = cell.get('parent');
	        if (parent && cloneMap[parent]) {
	            clone.set('parent', cloneMap[parent].id);
	        }

	        // Find the embeds of the original cell
	        var embeds = toArray(cell.get('embeds')).reduce(function(newEmbeds, embed) {
	            // Embedded cells that are not being cloned can not be carried
	            // over with other embedded cells.
	            if (cloneMap[embed]) {
	                newEmbeds.push(cloneMap[embed].id);
	            }
	            return newEmbeds;
	        }, []);

	        if (!isEmpty(embeds)) {
	            clone.set('embeds', embeds);
	        }
	    });

	    return cloneMap;
	}

	var props = {
	    width: 'w',
	    height: 'h',
	    minimum: 's',
	    maximum: 'l',
	    diagonal: 'd'
	};
	var propsList = Object.keys(props).map(function (key) { return props[key]; }).join('');
	var numberPattern = '[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?';
	var findSpacesRegex = /\s/g;
	var findExpressionsRegExp = /calc\(([^)]*)\)/g;
	var parseExpressionRegExp = new RegExp(("^(" + numberPattern + "\\*)?([" + propsList + "])([-+]" + numberPattern + ")?$"), 'g');

	function evalCalcExpression(expression, bbox) {
	    var match = parseExpressionRegExp.exec(expression.replace(findSpacesRegex, ''));
	    if (!match) { throw new Error(("Invalid calc() expression: " + expression)); }
	    parseExpressionRegExp.lastIndex = 0; // reset regex results for the next run
	    var multiply = match[1]; if ( multiply === void 0 ) multiply = 1;
	    var property = match[2];
	    var add = match[3]; if ( add === void 0 ) add = 0;
	    // Note: currently, we do not take x and y into account
	    var width = bbox.width;
	    var height = bbox.height;
	    var dimension = 0;
	    switch (property) {
	        case props.width: {
	            dimension = width;
	            break;
	        }
	        case props.height: {
	            dimension = height;
	            break;
	        }
	        case props.minimum: {
	            dimension = Math.min(height, width);
	            break;
	        }
	        case props.maximum: {
	            dimension = Math.max(height, width);
	            break;
	        }
	        case props.diagonal: {
	            dimension = Math.sqrt((height * height) + (width * width));
	            break;
	        }
	    }
	    return parseFloat(multiply) * dimension + parseFloat(add);
	}

	function isCalcAttribute(value) {
	    return typeof value === 'string' && value.includes('calc');
	}

	function evalCalcAttribute(value, refBBox) {
	    return value.replace(findExpressionsRegExp, function(_, expression) {
	        return evalCalcExpression(expression, refBBox);
	    });
	}

	function setWrapper(attrName, dimension) {
	    return function(value, refBBox) {
	        var isValuePercentage = isPercentage(value);
	        value = parseFloat(value);
	        if (isValuePercentage) {
	            value /= 100;
	        }

	        var attrs = {};
	        if (isFinite(value)) {
	            var attrValue = (isValuePercentage || value >= 0 && value <= 1)
	                ? value * refBBox[dimension]
	                : Math.max(value + refBBox[dimension], 0);
	            attrs[attrName] = attrValue;
	        }

	        return attrs;
	    };
	}

	function positionWrapper(axis, dimension, origin) {
	    return function(value, refBBox) {
	        var valuePercentage = isPercentage(value);
	        value = parseFloat(value);
	        if (valuePercentage) {
	            value /= 100;
	        }

	        var delta;
	        if (isFinite(value)) {
	            var refOrigin = refBBox[origin]();
	            if (valuePercentage || value > 0 && value < 1) {
	                delta = refOrigin[axis] + refBBox[dimension] * value;
	            } else {
	                delta = refOrigin[axis] + value;
	            }
	        }

	        var point = Point();
	        point[axis] = delta || 0;
	        return point;
	    };
	}

	function offsetWrapper(axis, dimension, corner) {
	    return function(value, nodeBBox) {
	        var delta;
	        if (value === 'middle') {
	            delta = nodeBBox[dimension] / 2;
	        } else if (value === corner) {
	            delta = nodeBBox[dimension];
	        } else if (isFinite(value)) {
	            // TODO: or not to do a breaking change?
	            delta = (value > -1 && value < 1) ? (-nodeBBox[dimension] * value) : -value;
	        } else if (isPercentage(value)) {
	            delta = nodeBBox[dimension] * parseFloat(value) / 100;
	        } else {
	            delta = 0;
	        }

	        var point = Point();
	        point[axis] = -(nodeBBox[axis] + delta);
	        return point;
	    };
	}

	function shapeWrapper(shapeConstructor, opt) {
	    var cacheName = 'joint-shape';
	    var resetOffset = opt && opt.resetOffset;
	    return function(value, refBBox, node) {
	        var $node = $(node);
	        var cache = $node.data(cacheName);
	        if (!cache || cache.value !== value) {
	            // only recalculate if value has changed
	            var cachedShape = shapeConstructor(value);
	            cache = {
	                value: value,
	                shape: cachedShape,
	                shapeBBox: cachedShape.bbox()
	            };
	            $node.data(cacheName, cache);
	        }

	        var shape = cache.shape.clone();
	        var shapeBBox = cache.shapeBBox.clone();
	        var shapeOrigin = shapeBBox.origin();
	        var refOrigin = refBBox.origin();

	        shapeBBox.x = refOrigin.x;
	        shapeBBox.y = refOrigin.y;

	        var fitScale = refBBox.maxRectScaleToFit(shapeBBox, refOrigin);
	        // `maxRectScaleToFit` can give Infinity if width or height is 0
	        var sx = (shapeBBox.width === 0 || refBBox.width === 0) ? 1 : fitScale.sx;
	        var sy = (shapeBBox.height === 0 || refBBox.height === 0) ? 1 : fitScale.sy;

	        shape.scale(sx, sy, shapeOrigin);
	        if (resetOffset) {
	            shape.translate(-shapeOrigin.x, -shapeOrigin.y);
	        }

	        return shape;
	    };
	}

	// `d` attribute for SVGPaths
	function dWrapper(opt) {
	    function pathConstructor(value) {
	        return new Path(V.normalizePathData(value));
	    }

	    var shape = shapeWrapper(pathConstructor, opt);
	    return function(value, refBBox, node) {
	        var path = shape(value, refBBox, node);
	        return {
	            d: path.serialize()
	        };
	    };
	}

	// `points` attribute for SVGPolylines and SVGPolygons
	function pointsWrapper(opt) {
	    var shape = shapeWrapper(Polyline, opt);
	    return function(value, refBBox, node) {
	        var polyline = shape(value, refBBox, node);
	        return {
	            points: polyline.serialize()
	        };
	    };
	}

	function atConnectionWrapper(method, opt) {
	    var zeroVector = new Point(1, 0);
	    return function(value) {
	        var p, angle;
	        var tangent = this[method](value);
	        if (tangent) {
	            angle = (opt.rotate) ? tangent.vector().vectorAngle(zeroVector) : 0;
	            p = tangent.start;
	        } else {
	            p = this.path.start;
	            angle = 0;
	        }
	        if (angle === 0) { return { transform: 'translate(' + p.x + ',' + p.y + ')' }; }
	        return { transform: 'translate(' + p.x + ',' + p.y + ') rotate(' + angle + ')' };
	    };
	}

	function isTextInUse(_value, _node, attrs) {
	    return (attrs.text !== undefined);
	}

	function isLinkView() {
	    return this.model.isLink();
	}

	function contextMarker(context) {
	    var marker = {};
	    // Stroke
	    // The context 'fill' is disregared here. The usual case is to use the marker with a connection
	    // (for which 'fill' attribute is set to 'none').
	    var stroke = context.stroke;
	    if (typeof stroke === 'string') {
	        marker['stroke'] = stroke;
	        marker['fill'] = stroke;
	    }
	    // Opacity
	    // Again the context 'fill-opacity' is ignored.
	    var strokeOpacity = context.strokeOpacity;
	    if (strokeOpacity === undefined) { strokeOpacity = context['stroke-opacity']; }
	    if (strokeOpacity === undefined) { strokeOpacity = context.opacity; }
	    if (strokeOpacity !== undefined) {
	        marker['stroke-opacity'] = strokeOpacity;
	        marker['fill-opacity'] = strokeOpacity;
	    }
	    return marker;
	}

	var attributesNS = {

	    xlinkHref: {
	        set: 'xlink:href'
	    },

	    xlinkShow: {
	        set: 'xlink:show'
	    },

	    xlinkRole: {
	        set: 'xlink:role'
	    },

	    xlinkType: {
	        set: 'xlink:type'
	    },

	    xlinkArcrole: {
	        set: 'xlink:arcrole'
	    },

	    xlinkTitle: {
	        set: 'xlink:title'
	    },

	    xlinkActuate: {
	        set: 'xlink:actuate'
	    },

	    xmlSpace: {
	        set: 'xml:space'
	    },

	    xmlBase: {
	        set: 'xml:base'
	    },

	    xmlLang: {
	        set: 'xml:lang'
	    },

	    preserveAspectRatio: {
	        set: 'preserveAspectRatio'
	    },

	    requiredExtension: {
	        set: 'requiredExtension'
	    },

	    requiredFeatures: {
	        set: 'requiredFeatures'
	    },

	    systemLanguage: {
	        set: 'systemLanguage'
	    },

	    externalResourcesRequired: {
	        set: 'externalResourceRequired'
	    },

	    filter: {
	        qualify: isPlainObject,
	        set: function(filter) {
	            return 'url(#' + this.paper.defineFilter(filter) + ')';
	        }
	    },

	    fill: {
	        qualify: isPlainObject,
	        set: function(fill) {
	            return 'url(#' + this.paper.defineGradient(fill) + ')';
	        }
	    },

	    stroke: {
	        qualify: isPlainObject,
	        set: function(stroke) {
	            return 'url(#' + this.paper.defineGradient(stroke) + ')';
	        }
	    },

	    sourceMarker: {
	        qualify: isPlainObject,
	        set: function(marker, refBBox, node, attrs) {
	            marker = assign(contextMarker(attrs), marker);
	            return { 'marker-start': 'url(#' + this.paper.defineMarker(marker) + ')' };
	        }
	    },

	    targetMarker: {
	        qualify: isPlainObject,
	        set: function(marker, refBBox, node, attrs) {
	            marker = assign(contextMarker(attrs), { 'transform': 'rotate(180)' }, marker);
	            return { 'marker-end': 'url(#' + this.paper.defineMarker(marker) + ')' };
	        }
	    },

	    vertexMarker: {
	        qualify: isPlainObject,
	        set: function(marker, refBBox, node, attrs) {
	            marker = assign(contextMarker(attrs), marker);
	            return { 'marker-mid': 'url(#' + this.paper.defineMarker(marker) + ')' };
	        }
	    },

	    text: {
	        qualify: function(_text, _node, attrs) {
	            return !attrs.textWrap || !isPlainObject(attrs.textWrap);
	        },
	        set: function(text, refBBox, node, attrs) {
	            var $node = $(node);
	            var cacheName = 'joint-text';
	            var cache = $node.data(cacheName);
	            var textAttrs = pick(attrs, 'lineHeight', 'annotations', 'textPath', 'x', 'textVerticalAnchor', 'eol', 'displayEmpty');
	            // eval `x` if using calc()
	            var x = textAttrs.x;
	            if (isCalcAttribute(x)) {
	                textAttrs.x = evalCalcAttribute(x, refBBox);
	            }
	            var fontSize = textAttrs.fontSize = attrs['font-size'] || attrs['fontSize'];
	            var textHash = JSON.stringify([text, textAttrs]);
	            // Update the text only if there was a change in the string
	            // or any of its attributes.
	            if (cache === undefined || cache !== textHash) {
	                // Chrome bug:
	                // Tspans positions defined as `em` are not updated
	                // when container `font-size` change.
	                if (fontSize) { node.setAttribute('font-size', fontSize); }
	                // Text Along Path Selector
	                var textPath = textAttrs.textPath;
	                if (isObject$1(textPath)) {
	                    var pathSelector = textPath.selector;
	                    if (typeof pathSelector === 'string') {
	                        var pathNode = this.findBySelector(pathSelector)[0];
	                        if (pathNode instanceof SVGPathElement) {
	                            textAttrs.textPath = assign({ 'xlink:href': '#' + pathNode.id }, textPath);
	                        }
	                    }
	                }
	                V(node).text('' + text, textAttrs);
	                $node.data(cacheName, textHash);
	            }
	        }
	    },

	    textWrap: {
	        qualify: isPlainObject,
	        set: function(value, refBBox, node, attrs) {
	            // option `width`
	            var width = value.width || 0;
	            if (isPercentage(width)) {
	                refBBox.width *= parseFloat(width) / 100;
	            } else if (width <= 0) {
	                refBBox.width += width;
	            } else {
	                refBBox.width = width;
	            }
	            // option `height`
	            var height = value.height || 0;
	            if (isPercentage(height)) {
	                refBBox.height *= parseFloat(height) / 100;
	            } else if (height <= 0) {
	                refBBox.height += height;
	            } else {
	                refBBox.height = height;
	            }
	            // option `text`
	            var wrappedText;
	            var text = value.text;
	            if (text === undefined) { text = attrs.text; }
	            if (text !== undefined) {
	                wrappedText = breakText('' + text, refBBox, {
	                    'font-weight': attrs['font-weight'] || attrs.fontWeight,
	                    'font-size': attrs['font-size'] || attrs.fontSize,
	                    'font-family': attrs['font-family'] || attrs.fontFamily,
	                    'lineHeight': attrs.lineHeight,
	                    'letter-spacing': 'letter-spacing' in attrs ? attrs['letter-spacing'] : attrs.letterSpacing
	                }, {
	                    // Provide an existing SVG Document here
	                    // instead of creating a temporary one over again.
	                    svgDocument: this.paper.svg,
	                    ellipsis: value.ellipsis,
	                    hyphen: value.hyphen,
	                    maxLineCount: value.maxLineCount
	                });
	            } else {
	                wrappedText = '';
	            }
	            attributesNS.text.set.call(this, wrappedText, refBBox, node, attrs);
	        }
	    },

	    title: {
	        qualify: function(title, node) {
	            // HTMLElement title is specified via an attribute (i.e. not an element)
	            return node instanceof SVGElement;
	        },
	        set: function(title, refBBox, node) {
	            var $node = $(node);
	            var cacheName = 'joint-title';
	            var cache = $node.data(cacheName);
	            if (cache === undefined || cache !== title) {
	                $node.data(cacheName, title);
	                // Generally <title> element should be the first child element of its parent.
	                var firstChild = node.firstChild;
	                if (firstChild && firstChild.tagName.toUpperCase() === 'TITLE') {
	                    // Update an existing title
	                    firstChild.textContent = title;
	                } else {
	                    // Create a new title
	                    var titleNode = document.createElementNS(node.namespaceURI, 'title');
	                    titleNode.textContent = title;
	                    node.insertBefore(titleNode, firstChild);
	                }
	            }
	        }
	    },

	    lineHeight: {
	        qualify: isTextInUse
	    },

	    textVerticalAnchor: {
	        qualify: isTextInUse
	    },

	    textPath: {
	        qualify: isTextInUse
	    },

	    annotations: {
	        qualify: isTextInUse
	    },

	    eol: {
	        qualify: isTextInUse
	    },

	    displayEmpty: {
	        qualify: isTextInUse
	    },

	    // `port` attribute contains the `id` of the port that the underlying magnet represents.
	    port: {
	        set: function(port) {
	            return (port === null || port.id === undefined) ? port : port.id;
	        }
	    },

	    // `style` attribute is special in the sense that it sets the CSS style of the subelement.
	    style: {
	        qualify: isPlainObject,
	        set: function(styles, refBBox, node) {
	            $(node).css(styles);
	        }
	    },

	    html: {
	        set: function(html, refBBox, node) {
	            $(node).html(html + '');
	        }
	    },

	    ref: {
	        // We do not set `ref` attribute directly on an element.
	        // The attribute itself does not qualify for relative positioning.
	    },

	    // if `refX` is in [0, 1] then `refX` is a fraction of bounding box width
	    // if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box
	    // otherwise, `refX` is the left coordinate of the bounding box

	    refX: {
	        position: positionWrapper('x', 'width', 'origin')
	    },

	    refY: {
	        position: positionWrapper('y', 'height', 'origin')
	    },

	    // `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom
	    // coordinate of the reference element.

	    refDx: {
	        position: positionWrapper('x', 'width', 'corner')
	    },

	    refDy: {
	        position: positionWrapper('y', 'height', 'corner')
	    },

	    // 'ref-width'/'ref-height' defines the width/height of the subelement relatively to
	    // the reference element size
	    // val in 0..1         ref-width = 0.75 sets the width to 75% of the ref. el. width
	    // val < 0 || val > 1  ref-height = -20 sets the height to the ref. el. height shorter by 20

	    refWidth: {
	        set: setWrapper('width', 'width')
	    },

	    refHeight: {
	        set: setWrapper('height', 'height')
	    },

	    refRx: {
	        set: setWrapper('rx', 'width')
	    },

	    refRy: {
	        set: setWrapper('ry', 'height')
	    },

	    refRInscribed: {
	        set: (function(attrName) {
	            var widthFn = setWrapper(attrName, 'width');
	            var heightFn = setWrapper(attrName, 'height');
	            return function(value, refBBox) {
	                var fn = (refBBox.height > refBBox.width) ? widthFn : heightFn;
	                return fn(value, refBBox);
	            };
	        })('r')
	    },

	    refRCircumscribed: {
	        set: function(value, refBBox) {
	            var isValuePercentage = isPercentage(value);
	            value = parseFloat(value);
	            if (isValuePercentage) {
	                value /= 100;
	            }

	            var diagonalLength = Math.sqrt((refBBox.height * refBBox.height) + (refBBox.width * refBBox.width));

	            var rValue;
	            if (isFinite(value)) {
	                if (isValuePercentage || value >= 0 && value <= 1) { rValue = value * diagonalLength; }
	                else { rValue = Math.max(value + diagonalLength, 0); }
	            }

	            return { r: rValue };
	        }
	    },

	    refCx: {
	        set: setWrapper('cx', 'width')
	    },

	    refCy: {
	        set: setWrapper('cy', 'height')
	    },

	    // `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate.
	    // `x-alignment` when set to `right` uses the x coordinate as referenced to the right of the bbox.

	    xAlignment: {
	        offset: offsetWrapper('x', 'width', 'right')
	    },

	    // `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate.
	    // `y-alignment` when set to `bottom` uses the y coordinate as referenced to the bottom of the bbox.

	    yAlignment: {
	        offset: offsetWrapper('y', 'height', 'bottom')
	    },

	    resetOffset: {
	        offset: function(val, nodeBBox) {
	            return (val)
	                ? { x: -nodeBBox.x, y: -nodeBBox.y }
	                : { x: 0, y: 0 };
	        }

	    },

	    refDResetOffset: {
	        set: dWrapper({ resetOffset: true })
	    },

	    refDKeepOffset: {
	        set: dWrapper({ resetOffset: false })
	    },

	    refPointsResetOffset: {
	        set: pointsWrapper({ resetOffset: true })
	    },

	    refPointsKeepOffset: {
	        set: pointsWrapper({ resetOffset: false })
	    },

	    // LinkView Attributes

	    connection: {
	        qualify: isLinkView,
	        set: function(ref) {
	            var stubs = ref.stubs; if ( stubs === void 0 ) stubs = 0;

	            var d;
	            if (isFinite(stubs) && stubs !== 0) {
	                var offset;
	                if (stubs < 0) {
	                    offset = (this.getConnectionLength() + stubs) / 2;
	                } else {
	                    offset = stubs;
	                }
	                var path = this.getConnection();
	                var sourceParts = path.divideAtLength(offset);
	                var targetParts = path.divideAtLength(-offset);
	                if (sourceParts && targetParts) {
	                    d = (sourceParts[0].serialize()) + " " + (targetParts[1].serialize());
	                }
	            }

	            return { d: d || this.getSerializedConnection() };
	        }
	    },

	    atConnectionLengthKeepGradient: {
	        qualify: isLinkView,
	        set: atConnectionWrapper('getTangentAtLength', { rotate: true })
	    },

	    atConnectionLengthIgnoreGradient: {
	        qualify: isLinkView,
	        set: atConnectionWrapper('getTangentAtLength', { rotate: false })
	    },

	    atConnectionRatioKeepGradient: {
	        qualify: isLinkView,
	        set: atConnectionWrapper('getTangentAtRatio', { rotate: true })
	    },

	    atConnectionRatioIgnoreGradient: {
	        qualify: isLinkView,
	        set: atConnectionWrapper('getTangentAtRatio', { rotate: false })
	    }
	};

	// Support `calc()` with the following SVG attributes
	[
	    'transform', // g
	    'd', // path
	    'points', // polyline / polygon
	    'width', 'height', // rect / image
	    'cx', 'cy', // circle / ellipse
	    'r', // circle
	    'rx', 'ry', // rect / ellipse
	    'x1', 'x2', 'y1', 'y2', // line
	    'x', 'y', // rect / text / image
	    'dx', 'dy' // text
	].forEach(function (attribute) {
	    attributesNS[attribute] = {
	        qualify: isCalcAttribute,
	        set: function setCalcAttribute(value, refBBox) {
	            var obj;

	            return ( obj = {}, obj[attribute] = evalCalcAttribute(value, refBBox), obj );
	        }
	    };
	});

	// Aliases
	attributesNS.refR = attributesNS.refRInscribed;
	attributesNS.refD = attributesNS.refDResetOffset;
	attributesNS.refPoints = attributesNS.refPointsResetOffset;
	attributesNS.atConnectionLength = attributesNS.atConnectionLengthKeepGradient;
	attributesNS.atConnectionRatio = attributesNS.atConnectionRatioKeepGradient;

	// This allows to combine both absolute and relative positioning
	// refX: 50%, refX2: 20
	attributesNS.refX2 = attributesNS.refX;
	attributesNS.refY2 = attributesNS.refY;
	attributesNS.refWidth2 = attributesNS.refWidth;
	attributesNS.refHeight2 = attributesNS.refHeight;

	// Aliases for backwards compatibility
	attributesNS['ref-x'] = attributesNS.refX;
	attributesNS['ref-y'] = attributesNS.refY;
	attributesNS['ref-dy'] = attributesNS.refDy;
	attributesNS['ref-dx'] = attributesNS.refDx;
	attributesNS['ref-width'] = attributesNS.refWidth;
	attributesNS['ref-height'] = attributesNS.refHeight;
	attributesNS['x-alignment'] = attributesNS.xAlignment;
	attributesNS['y-alignment'] = attributesNS.yAlignment;

	var attributes = attributesNS;

	// Cell base model.
	// --------------------------

	var Cell = Backbone.Model.extend({

	    // This is the same as Backbone.Model with the only difference that is uses util.merge
	    // instead of just _.extend. The reason is that we want to mixin attributes set in upper classes.
	    constructor: function(attributes, options) {

	        var defaults;
	        var attrs = attributes || {};
	        if (typeof this.preinitialize === 'function') {
	            // Check to support an older version of Backbone (prior v1.4)
	            this.preinitialize.apply(this, arguments);
	        }
	        this.cid = uniqueId('c');
	        this.attributes = {};
	        if (options && options.collection) { this.collection = options.collection; }
	        if (options && options.parse) { attrs = this.parse(attrs, options) || {}; }
	        if ((defaults = result(this, 'defaults'))) {
	            //<custom code>
	            // Replaced the call to _.defaults with util.merge.
	            attrs = merge({}, defaults, attrs);
	            //</custom code>
	        }
	        this.set(attrs, options);
	        this.changed = {};
	        this.initialize.apply(this, arguments);
	    },

	    translate: function(dx, dy, opt) {

	        throw new Error('Must define a translate() method.');
	    },

	    toJSON: function() {

	        var defaults = result(this.constructor.prototype, 'defaults');
	        var defaultAttrs = defaults.attrs || {};
	        var attrs = this.attributes.attrs;
	        var finalAttrs = {};

	        // Loop through all the attributes and
	        // omit the default attributes as they are implicitly reconstructible by the cell 'type'.
	        forIn(attrs, function(attr, selector) {

	            var defaultAttr = defaultAttrs[selector];

	            forIn(attr, function(value, name) {

	                // attr is mainly flat though it might have one more level (consider the `style` attribute).
	                // Check if the `value` is object and if yes, go one level deep.
	                if (isObject$1(value) && !Array.isArray(value)) {

	                    forIn(value, function(value2, name2) {

	                        if (!defaultAttr || !defaultAttr[name] || !isEqual(defaultAttr[name][name2], value2)) {

	                            finalAttrs[selector] = finalAttrs[selector] || {};
	                            (finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2;
	                        }
	                    });

	                } else if (!defaultAttr || !isEqual(defaultAttr[name], value)) {
	                    // `value` is not an object, default attribute for such a selector does not exist
	                    // or it is different than the attribute value set on the model.

	                    finalAttrs[selector] = finalAttrs[selector] || {};
	                    finalAttrs[selector][name] = value;
	                }
	            });
	        });

	        var attributes = cloneDeep(omit(this.attributes, 'attrs'));
	        attributes.attrs = finalAttrs;

	        return attributes;
	    },

	    initialize: function(options) {

	        if (!options || !options.id) {

	            this.set('id', this.generateId(), { silent: true });
	        }

	        this._transitionIds = {};

	        // Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes.
	        this.processPorts();
	        this.on('change:attrs', this.processPorts, this);
	    },

	    generateId: function() {
	        return uuid();
	    },

	    /**
	     * @deprecated
	     */
	    processPorts: function() {

	        // Whenever `attrs` changes, we extract ports from the `attrs` object and store it
	        // in a more accessible way. Also, if any port got removed and there were links that had `target`/`source`
	        // set to that port, we remove those links as well (to follow the same behaviour as
	        // with a removed element).

	        var previousPorts = this.ports;

	        // Collect ports from the `attrs` object.
	        var ports = {};
	        forIn(this.get('attrs'), function(attrs, selector) {

	            if (attrs && attrs.port) {

	                // `port` can either be directly an `id` or an object containing an `id` (and potentially other data).
	                if (attrs.port.id !== undefined) {
	                    ports[attrs.port.id] = attrs.port;
	                } else {
	                    ports[attrs.port] = { id: attrs.port };
	                }
	            }
	        });

	        // Collect ports that have been removed (compared to the previous ports) - if any.
	        // Use hash table for quick lookup.
	        var removedPorts = {};
	        forIn(previousPorts, function(port, id) {

	            if (!ports[id]) { removedPorts[id] = true; }
	        });

	        // Remove all the incoming/outgoing links that have source/target port set to any of the removed ports.
	        if (this.graph && !isEmpty(removedPorts)) {

	            var inboundLinks = this.graph.getConnectedLinks(this, { inbound: true });
	            inboundLinks.forEach(function(link) {

	                if (removedPorts[link.get('target').port]) { link.remove(); }
	            });

	            var outboundLinks = this.graph.getConnectedLinks(this, { outbound: true });
	            outboundLinks.forEach(function(link) {

	                if (removedPorts[link.get('source').port]) { link.remove(); }
	            });
	        }

	        // Update the `ports` object.
	        this.ports = ports;
	    },

	    remove: function(opt) {
	        if ( opt === void 0 ) opt = {};


	        // Store the graph in a variable because `this.graph` won't be accessible
	        // after `this.trigger('remove', ...)` down below.
	        var ref = this;
	        var graph = ref.graph;
	        var collection = ref.collection;
	        if (!graph) {
	            // The collection is a common Backbone collection (not the graph collection).
	            if (collection) { collection.remove(this, opt); }
	            return this;
	        }

	        graph.startBatch('remove');

	        // First, unembed this cell from its parent cell if there is one.
	        var parentCell = this.getParentCell();
	        if (parentCell) {
	            parentCell.unembed(this, opt);
	        }

	        // Remove also all the cells, which were embedded into this cell
	        var embeddedCells = this.getEmbeddedCells();
	        for (var i = 0, n = embeddedCells.length; i < n; i++) {
	            var embed = embeddedCells[i];
	            if (embed) {
	                embed.remove(opt);
	            }
	        }

	        this.trigger('remove', this, graph.attributes.cells, opt);

	        graph.stopBatch('remove');

	        return this;
	    },

	    toFront: function(opt) {

	        var graph = this.graph;
	        if (graph) {

	            opt = opt || {};

	            var z = graph.maxZIndex();

	            var cells;

	            if (opt.deep) {
	                cells = this.getEmbeddedCells({ deep: true, breadthFirst: opt.breadthFirst !== false });
	                cells.unshift(this);
	            } else {
	                cells = [this];
	            }

	            z = z - cells.length + 1;

	            var collection = graph.get('cells');
	            var shouldUpdate = (collection.indexOf(this) !== (collection.length - cells.length));
	            if (!shouldUpdate) {
	                shouldUpdate = cells.some(function(cell, index) {
	                    return cell.get('z') !== z + index;
	                });
	            }

	            if (shouldUpdate) {
	                this.startBatch('to-front');

	                z = z + cells.length;

	                cells.forEach(function(cell, index) {
	                    cell.set('z', z + index, opt);
	                });

	                this.stopBatch('to-front');
	            }
	        }

	        return this;
	    },

	    toBack: function(opt) {

	        var graph = this.graph;
	        if (graph) {

	            opt = opt || {};

	            var z = graph.minZIndex();

	            var cells;

	            if (opt.deep) {
	                cells = this.getEmbeddedCells({ deep: true, breadthFirst: opt.breadthFirst !== false });
	                cells.unshift(this);
	            } else {
	                cells = [this];
	            }

	            var collection = graph.get('cells');
	            var shouldUpdate = (collection.indexOf(this) !== 0);
	            if (!shouldUpdate) {
	                shouldUpdate = cells.some(function(cell, index) {
	                    return cell.get('z') !== z + index;
	                });
	            }

	            if (shouldUpdate) {
	                this.startBatch('to-back');

	                z -= cells.length;

	                cells.forEach(function(cell, index) {
	                    cell.set('z', z + index, opt);
	                });

	                this.stopBatch('to-back');
	            }
	        }

	        return this;
	    },

	    parent: function(parent, opt) {

	        // getter
	        if (parent === undefined) { return this.get('parent'); }
	        // setter
	        return this.set('parent', parent, opt);
	    },

	    embed: function(cell, opt) {

	        if (this === cell || this.isEmbeddedIn(cell)) {

	            throw new Error('Recursive embedding not allowed.');

	        } else {

	            this.startBatch('embed');

	            var embeds = assign([], this.get('embeds'));

	            // We keep all element ids after link ids.
	            embeds[cell.isLink() ? 'unshift' : 'push'](cell.id);

	            cell.parent(this.id, opt);
	            this.set('embeds', uniq(embeds), opt);

	            this.stopBatch('embed');
	        }

	        return this;
	    },

	    unembed: function(cell, opt) {

	        this.startBatch('unembed');

	        cell.unset('parent', opt);
	        this.set('embeds', without(this.get('embeds'), cell.id), opt);

	        this.stopBatch('unembed');

	        return this;
	    },

	    getParentCell: function() {

	        // unlike link.source/target, cell.parent stores id directly as a string
	        var parentId = this.parent();
	        var graph = this.graph;

	        return (parentId && graph && graph.getCell(parentId)) || null;
	    },

	    // Return an array of ancestor cells.
	    // The array is ordered from the parent of the cell
	    // to the most distant ancestor.
	    getAncestors: function() {

	        var ancestors = [];

	        if (!this.graph) {
	            return ancestors;
	        }

	        var parentCell = this.getParentCell();
	        while (parentCell) {
	            ancestors.push(parentCell);
	            parentCell = parentCell.getParentCell();
	        }

	        return ancestors;
	    },

	    getEmbeddedCells: function(opt) {

	        opt = opt || {};

	        // Cell models can only be retrieved when this element is part of a collection.
	        // There is no way this element knows about other cells otherwise.
	        // This also means that calling e.g. `translate()` on an element with embeds before
	        // adding it to a graph does not translate its embeds.
	        if (this.graph) {

	            var cells;

	            if (opt.deep) {

	                if (opt.breadthFirst) {

	                    // breadthFirst algorithm
	                    cells = [];
	                    var queue = this.getEmbeddedCells();

	                    while (queue.length > 0) {

	                        var parent = queue.shift();
	                        cells.push(parent);
	                        queue.push.apply(queue, parent.getEmbeddedCells());
	                    }

	                } else {

	                    // depthFirst algorithm
	                    cells = this.getEmbeddedCells();
	                    cells.forEach(function(cell) {
	                        cells.push.apply(cells, cell.getEmbeddedCells(opt));
	                    });
	                }

	            } else {

	                cells = toArray(this.get('embeds')).map(this.graph.getCell, this.graph);
	            }

	            return cells;
	        }
	        return [];
	    },

	    isEmbeddedIn: function(cell, opt) {

	        var cellId = isString(cell) ? cell : cell.id;
	        var parentId = this.parent();

	        opt = defaults({ deep: true }, opt);

	        // See getEmbeddedCells().
	        if (this.graph && opt.deep) {

	            while (parentId) {
	                if (parentId === cellId) {
	                    return true;
	                }
	                parentId = this.graph.getCell(parentId).parent();
	            }

	            return false;

	        } else {

	            // When this cell is not part of a collection check
	            // at least whether it's a direct child of given cell.
	            return parentId === cellId;
	        }
	    },

	    // Whether or not the cell is embedded in any other cell.
	    isEmbedded: function() {

	        return !!this.parent();
	    },

	    // Isolated cloning. Isolated cloning has two versions: shallow and deep (pass `{ deep: true }` in `opt`).
	    // Shallow cloning simply clones the cell and returns a new cell with different ID.
	    // Deep cloning clones the cell and all its embedded cells recursively.
	    clone: function(opt) {

	        opt = opt || {};

	        if (!opt.deep) {
	            // Shallow cloning.

	            var clone = Backbone.Model.prototype.clone.apply(this, arguments);
	            // We don't want the clone to have the same ID as the original.
	            clone.set('id', this.generateId());
	            // A shallow cloned element does not carry over the original embeds.
	            clone.unset('embeds');
	            // And can not be embedded in any cell
	            // as the clone is not part of the graph.
	            clone.unset('parent');

	            return clone;

	        } else {
	            // Deep cloning.

	            // For a deep clone, simply call `graph.cloneCells()` with the cell and all its embedded cells.
	            return toArray(cloneCells([this].concat(this.getEmbeddedCells({ deep: true }))));
	        }
	    },

	    // A convenient way to set nested properties.
	    // This method merges the properties you'd like to set with the ones
	    // stored in the cell and makes sure change events are properly triggered.
	    // You can either set a nested property with one object
	    // or use a property path.
	    // The most simple use case is:
	    // `cell.prop('name/first', 'John')` or
	    // `cell.prop({ name: { first: 'John' } })`.
	    // Nested arrays are supported too:
	    // `cell.prop('series/0/data/0/degree', 50)` or
	    // `cell.prop({ series: [ { data: [ { degree: 50 } ] } ] })`.
	    prop: function(props, value, opt) {

	        var delim = '/';
	        var _isString = isString(props);

	        if (_isString || Array.isArray(props)) {
	            // Get/set an attribute by a special path syntax that delimits
	            // nested objects by the colon character.

	            if (arguments.length > 1) {

	                var path;
	                var pathArray;

	                if (_isString) {
	                    path = props;
	                    pathArray = path.split('/');
	                } else {
	                    path = props.join(delim);
	                    pathArray = props.slice();
	                }

	                var property = pathArray[0];
	                var pathArrayLength = pathArray.length;

	                opt = opt || {};
	                opt.propertyPath = path;
	                opt.propertyValue = value;
	                opt.propertyPathArray = pathArray;

	                if (pathArrayLength === 1) {
	                    // Property is not nested. We can simply use `set()`.
	                    return this.set(property, value, opt);
	                }

	                var update = {};
	                // Initialize the nested object. Subobjects are either arrays or objects.
	                // An empty array is created if the sub-key is an integer. Otherwise, an empty object is created.
	                // Note that this imposes a limitation on object keys one can use with Inspector.
	                // Pure integer keys will cause issues and are therefore not allowed.
	                var initializer = update;
	                var prevProperty = property;

	                for (var i = 1; i < pathArrayLength; i++) {
	                    var pathItem = pathArray[i];
	                    var isArrayIndex = Number.isFinite(_isString ? Number(pathItem) : pathItem);
	                    initializer = initializer[prevProperty] = isArrayIndex ? [] : {};
	                    prevProperty = pathItem;
	                }

	                // Fill update with the `value` on `path`.
	                update = setByPath(update, pathArray, value, '/');

	                var baseAttributes = merge({}, this.attributes);
	                // if rewrite mode enabled, we replace value referenced by path with
	                // the new one (we don't merge).
	                opt.rewrite && unsetByPath(baseAttributes, path, '/');

	                // Merge update with the model attributes.
	                var attributes = merge(baseAttributes, update);
	                // Finally, set the property to the updated attributes.
	                return this.set(property, attributes[property], opt);

	            } else {

	                return getByPath(this.attributes, props, delim);
	            }
	        }

	        return this.set(merge({}, this.attributes, props), value);
	    },

	    // A convenient way to unset nested properties
	    removeProp: function(path, opt) {

	        opt = opt || {};

	        var pathArray = Array.isArray(path) ? path : path.split('/');

	        // Once a property is removed from the `attrs` attribute
	        // the cellView will recognize a `dirty` flag and re-render itself
	        // in order to remove the attribute from SVG element.
	        var property = pathArray[0];
	        if (property === 'attrs') { opt.dirty = true; }

	        if (pathArray.length === 1) {
	            // A top level property
	            return this.unset(path, opt);
	        }

	        // A nested property
	        var nestedPath = pathArray.slice(1);
	        var propertyValue = cloneDeep(this.get(property));

	        unsetByPath(propertyValue, nestedPath, '/');

	        return this.set(property, propertyValue, opt);
	    },

	    // A convenient way to set nested attributes.
	    attr: function(attrs, value, opt) {

	        var args = Array.from(arguments);
	        if (args.length === 0) {
	            return this.get('attrs');
	        }

	        if (Array.isArray(attrs)) {
	            args[0] = ['attrs'].concat(attrs);
	        } else if (isString(attrs)) {
	            // Get/set an attribute by a special path syntax that delimits
	            // nested objects by the colon character.
	            args[0] = 'attrs/' + attrs;

	        } else {

	            args[0] = { 'attrs' : attrs };
	        }

	        return this.prop.apply(this, args);
	    },

	    // A convenient way to unset nested attributes
	    removeAttr: function(path, opt) {

	        if (Array.isArray(path)) {

	            return this.removeProp(['attrs'].concat(path));
	        }

	        return this.removeProp('attrs/' + path, opt);
	    },

	    transition: function(path, value, opt, delim) {

	        delim = delim || '/';

	        var defaults = {
	            duration: 100,
	            delay: 10,
	            timingFunction: timing.linear,
	            valueFunction: interpolate.number
	        };

	        opt = assign(defaults, opt);

	        var firstFrameTime = 0;
	        var interpolatingFunction;

	        var setter = function(runtime) {

	            var id, progress, propertyValue;

	            firstFrameTime = firstFrameTime || runtime;
	            runtime -= firstFrameTime;
	            progress = runtime / opt.duration;

	            if (progress < 1) {
	                this._transitionIds[path] = id = nextFrame(setter);
	            } else {
	                progress = 1;
	                delete this._transitionIds[path];
	            }

	            propertyValue = interpolatingFunction(opt.timingFunction(progress));

	            opt.transitionId = id;

	            this.prop(path, propertyValue, opt);

	            if (!id) { this.trigger('transition:end', this, path); }

	        }.bind(this);

	        var initiator = function(callback) {

	            this.stopTransitions(path);

	            interpolatingFunction = opt.valueFunction(getByPath(this.attributes, path, delim), value);

	            this._transitionIds[path] = nextFrame(callback);

	            this.trigger('transition:start', this, path);

	        }.bind(this);

	        return setTimeout(initiator, opt.delay, setter);
	    },

	    getTransitions: function() {

	        return Object.keys(this._transitionIds);
	    },

	    stopTransitions: function(path, delim) {

	        delim = delim || '/';

	        var pathArray = path && path.split(delim);

	        Object.keys(this._transitionIds).filter(pathArray && function(key) {

	            return isEqual(pathArray, key.split(delim).slice(0, pathArray.length));

	        }).forEach(function(key) {

	            cancelFrame(this._transitionIds[key]);

	            delete this._transitionIds[key];

	            this.trigger('transition:end', this, key);

	        }, this);

	        return this;
	    },

	    // A shorcut making it easy to create constructs like the following:
	    // `var el = (new joint.shapes.basic.Rect).addTo(graph)`.
	    addTo: function(graph, opt) {

	        graph.addCell(this, opt);
	        return this;
	    },

	    // A shortcut for an equivalent call: `paper.findViewByModel(cell)`
	    // making it easy to create constructs like the following:
	    // `cell.findView(paper).highlight()`
	    findView: function(paper) {

	        return paper.findViewByModel(this);
	    },

	    isElement: function() {

	        return false;
	    },

	    isLink: function() {

	        return false;
	    },

	    startBatch: function(name, opt) {

	        if (this.graph) { this.graph.startBatch(name, assign({}, opt, { cell: this })); }
	        return this;
	    },

	    stopBatch: function(name, opt) {

	        if (this.graph) { this.graph.stopBatch(name, assign({}, opt, { cell: this })); }
	        return this;
	    },

	    getChangeFlag: function(attributes) {

	        var flag = 0;
	        if (!attributes) { return flag; }
	        for (var key in attributes) {
	            if (!attributes.hasOwnProperty(key) || !this.hasChanged(key)) { continue; }
	            flag |= attributes[key];
	        }
	        return flag;
	    },

	    angle: function() {

	        // To be overridden.
	        return 0;
	    },

	    position: function() {

	        // To be overridden.
	        return new Point(0, 0);
	    },

	    getPointFromConnectedLink: function() {

	        // To be overridden
	        return new Point();
	    },

	    getBBox: function() {

	        // To be overridden
	        return new Rect(0, 0, 0, 0);
	    }

	}, {

	    getAttributeDefinition: function(attrName) {

	        var defNS = this.attributes;
	        var globalDefNS = attributes;
	        return (defNS && defNS[attrName]) || globalDefNS[attrName];
	    },

	    define: function(type, defaults, protoProps, staticProps) {

	        protoProps = assign({
	            defaults: defaultsDeep({ type: type }, defaults, this.prototype.defaults)
	        }, protoProps);

	        var Cell = this.extend(protoProps, staticProps);
	        // es5 backward compatibility
	        /* global joint: true */
	        if (typeof joint !== 'undefined' && has$2(joint, 'shapes')) {
	            setByPath(joint.shapes, type, Cell, '.');
	        }
	        /* global joint: false */
	        return Cell;
	    }
	});

	var wrapWith = function(object, methods, wrapper) {

	    if (isString(wrapper)) {

	        if (!wrappers[wrapper]) {
	            throw new Error('Unknown wrapper: "' + wrapper + '"');
	        }

	        wrapper = wrappers[wrapper];
	    }

	    if (!isFunction(wrapper)) {
	        throw new Error('Wrapper must be a function.');
	    }

	    toArray(methods).forEach(function(method) {
	        object[method] = wrapper(object[method]);
	    });
	};

	var wrappers = {

	    cells: function(fn) {

	        return function() {

	            var args = Array.from(arguments);
	            var n = args.length;
	            var cells = n > 0 && args[0] || [];
	            var opt = n > 1 && args[n - 1] || {};

	            if (!Array.isArray(cells)) {

	                if (opt instanceof Cell) {
	                    cells = args;
	                } else if (cells instanceof Cell) {
	                    if (args.length > 1) {
	                        args.pop();
	                    }
	                    cells = args;
	                }
	            }

	            if (opt instanceof Cell) {
	                opt = {};
	            }

	            return fn.call(this, cells, opt);
	        };
	    }

	};



	var index = ({
		wrapWith: wrapWith,
		wrappers: wrappers,
		addClassNamePrefix: addClassNamePrefix,
		removeClassNamePrefix: removeClassNamePrefix,
		parseDOMJSON: parseDOMJSON,
		hashCode: hashCode,
		getByPath: getByPath,
		setByPath: setByPath,
		unsetByPath: unsetByPath,
		flattenObject: flattenObject,
		uuid: uuid,
		guid: guid,
		toKebabCase: toKebabCase,
		normalizeEvent: normalizeEvent,
		nextFrame: nextFrame,
		cancelFrame: cancelFrame,
		shapePerimeterConnectionPoint: shapePerimeterConnectionPoint,
		isPercentage: isPercentage,
		parseCssNumeric: parseCssNumeric,
		breakText: breakText,
		sanitizeHTML: sanitizeHTML,
		downloadBlob: downloadBlob,
		downloadDataUri: downloadDataUri,
		dataUriToBlob: dataUriToBlob,
		imageToDataUri: imageToDataUri,
		getElementBBox: getElementBBox,
		sortElements: sortElements,
		setAttributesBySelector: setAttributesBySelector,
		normalizeSides: normalizeSides,
		timing: timing,
		interpolate: interpolate,
		filter: filter,
		format: format,
		template: template,
		toggleFullScreen: toggleFullScreen,
		mixin: mixin,
		supplement: supplement,
		deepMixin: deepMixin,
		deepSupplement: deepSupplement,
		assign: assign,
		defaults: defaults,
		defaultsDeep: defaultsDeep,
		invoke: invoke,
		sortedIndex: sortedIndex,
		uniq: uniq,
		clone: clone,
		cloneDeep: cloneDeep,
		isEmpty: isEmpty,
		isEqual: isEqual,
		isFunction: isFunction,
		isPlainObject: isPlainObject,
		toArray: toArray,
		debounce: debounce,
		groupBy: groupBy,
		sortBy: sortBy,
		flattenDeep: flattenDeep,
		without: without,
		difference: difference,
		intersection: intersection,
		union: union,
		has: has$2,
		result: result,
		omit: omit,
		pick: pick,
		bindAll: bindAll,
		forIn: forIn,
		camelCase: camelCase,
		uniqueId: uniqueId,
		merge: merge,
		isBoolean: isBoolean,
		isObject: isObject$1,
		isNumber: isNumber,
		isString: isString,
		noop: noop,
		cloneCells: cloneCells
	});

	function portTransformAttrs(point, angle, opt) {

	    var trans = point.toJSON();

	    trans.angle = angle || 0;

	    return defaults({}, opt, trans);
	}

	function lineLayout(ports, p1, p2) {
	    return ports.map(function(port, index, ports) {
	        var p = this.pointAt(((index + 0.5) / ports.length));
	        // `dx`,`dy` per port offset option
	        if (port.dx || port.dy) {
	            p.offset(port.dx || 0, port.dy || 0);
	        }

	        return portTransformAttrs(p.round(), 0, port);
	    }, line(p1, p2));
	}

	function ellipseLayout(ports, elBBox, startAngle, stepFn) {

	    var center = elBBox.center();
	    var ratio = elBBox.width / elBBox.height;
	    var p1 = elBBox.topMiddle();

	    var ellipse = Ellipse.fromRect(elBBox);

	    return ports.map(function(port, index, ports) {

	        var angle = startAngle + stepFn(index, ports.length);
	        var p2 = p1.clone()
	            .rotate(center, -angle)
	            .scale(ratio, 1, center);

	        var theta = port.compensateRotation ? -ellipse.tangentTheta(p2) : 0;

	        // `dx`,`dy` per port offset option
	        if (port.dx || port.dy) {
	            p2.offset(port.dx || 0, port.dy || 0);
	        }

	        // `dr` delta radius option
	        if (port.dr) {
	            p2.move(center, port.dr);
	        }

	        return portTransformAttrs(p2.round(), theta, port);
	    });
	}

	// Creates a point stored in arguments
	function argPoint(bbox, args) {

	    var x = args.x;
	    if (isString(x)) {
	        x = parseFloat(x) / 100 * bbox.width;
	    }

	    var y = args.y;
	    if (isString(y)) {
	        y = parseFloat(y) / 100 * bbox.height;
	    }

	    return point(x || 0, y || 0);
	}


	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt opt Group options
	 * @returns {Array<g.Point>}
	 */
	var absolute = function(ports, elBBox, opt) {
	    //TODO v.talas angle
	    return ports.map(argPoint.bind(null, elBBox));
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt opt Group options
	 * @returns {Array<g.Point>}
	 */
	var fn = function(ports, elBBox, opt) {
	    return opt.fn(ports, elBBox, opt);
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt opt Group options
	 * @returns {Array<g.Point>}
	 */
	var line$1 = function(ports, elBBox, opt) {

	    var start = argPoint(elBBox, opt.start || elBBox.origin());
	    var end = argPoint(elBBox, opt.end || elBBox.corner());

	    return lineLayout(ports, start, end);
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt opt Group options
	 * @returns {Array<g.Point>}
	 */
	var left = function(ports, elBBox, opt) {
	    return lineLayout(ports, elBBox.origin(), elBBox.bottomLeft());
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt opt Group options
	 * @returns {Array<g.Point>}
	 */
	var right = function(ports, elBBox, opt) {
	    return lineLayout(ports, elBBox.topRight(), elBBox.corner());
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt opt Group options
	 * @returns {Array<g.Point>}
	 */
	var top = function(ports, elBBox, opt) {
	    return lineLayout(ports, elBBox.origin(), elBBox.topRight());
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt opt Group options
	 * @returns {Array<g.Point>}
	 */
	var bottom = function(ports, elBBox, opt) {
	    return lineLayout(ports, elBBox.bottomLeft(), elBBox.corner());
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt Group options
	 * @returns {Array<g.Point>}
	 */
	var ellipseSpread = function(ports, elBBox, opt) {

	    var startAngle = opt.startAngle || 0;
	    var stepAngle = opt.step || 360 / ports.length;

	    return ellipseLayout(ports, elBBox, startAngle, function(index) {
	        return index * stepAngle;
	    });
	};

	/**
	 * @param {Array<Object>} ports
	 * @param {g.Rect} elBBox
	 * @param {Object=} opt Group options
	 * @returns {Array<g.Point>}
	 */
	var ellipse$1 = function(ports, elBBox, opt) {

	    var startAngle = opt.startAngle || 0;
	    var stepAngle = opt.step || 20;

	    return ellipseLayout(ports, elBBox, startAngle, function(index, count) {
	        return (index + 0.5 - count / 2) * stepAngle;
	    });
	};

	var Port = ({
		absolute: absolute,
		fn: fn,
		line: line$1,
		left: left,
		right: right,
		top: top,
		bottom: bottom,
		ellipseSpread: ellipseSpread,
		ellipse: ellipse$1
	});

	function labelAttributes(opt1, opt2) {

	    return defaultsDeep({}, opt1, opt2, {
	        x: 0,
	        y: 0,
	        angle: 0,
	        attrs: {
	            '.': {
	                y: '0',
	                'text-anchor': 'start'
	            }
	        }
	    });
	}

	function outsideLayout(portPosition, elBBox, autoOrient, opt) {

	    opt = defaults({}, opt, { offset: 15 });
	    var angle = elBBox.center().theta(portPosition);
	    var x = getBBoxAngles(elBBox);

	    var tx, ty, y, textAnchor;
	    var offset = opt.offset;
	    var orientAngle = 0;

	    if (angle < x[1] || angle > x[2]) {
	        y = '.3em';
	        tx = offset;
	        ty = 0;
	        textAnchor = 'start';
	    } else if (angle < x[0]) {
	        y = '0';
	        tx = 0;
	        ty = -offset;
	        if (autoOrient) {
	            orientAngle = -90;
	            textAnchor = 'start';
	        } else {
	            textAnchor = 'middle';
	        }
	    } else if (angle < x[3]) {
	        y = '.3em';
	        tx = -offset;
	        ty = 0;
	        textAnchor = 'end';
	    } else {
	        y = '.6em';
	        tx = 0;
	        ty = offset;
	        if (autoOrient) {
	            orientAngle = 90;
	            textAnchor = 'start';
	        } else {
	            textAnchor = 'middle';
	        }
	    }

	    var round = Math.round;
	    return labelAttributes({
	        x: round(tx),
	        y: round(ty),
	        angle: orientAngle,
	        attrs: {
	            '.': {
	                y: y,
	                'text-anchor': textAnchor
	            }
	        }
	    });
	}

	function getBBoxAngles(elBBox) {

	    var center = elBBox.center();

	    var tl = center.theta(elBBox.origin());
	    var bl = center.theta(elBBox.bottomLeft());
	    var br = center.theta(elBBox.corner());
	    var tr = center.theta(elBBox.topRight());

	    return [tl, tr, br, bl];
	}

	function insideLayout(portPosition, elBBox, autoOrient, opt) {

	    var angle = elBBox.center().theta(portPosition);
	    opt = defaults({}, opt, { offset: 15 });

	    var tx, ty, y, textAnchor;
	    var offset = opt.offset;
	    var orientAngle = 0;

	    var bBoxAngles = getBBoxAngles(elBBox);

	    if (angle < bBoxAngles[1] || angle > bBoxAngles[2]) {
	        y = '.3em';
	        tx = -offset;
	        ty = 0;
	        textAnchor = 'end';
	    } else if (angle < bBoxAngles[0]) {
	        y = '.6em';
	        tx = 0;
	        ty = offset;
	        if (autoOrient) {
	            orientAngle = 90;
	            textAnchor = 'start';
	        } else {
	            textAnchor = 'middle';
	        }
	    } else if (angle < bBoxAngles[3]) {
	        y = '.3em';
	        tx = offset;
	        ty = 0;
	        textAnchor = 'start';
	    } else {
	        y = '0em';
	        tx = 0;
	        ty = -offset;
	        if (autoOrient) {
	            orientAngle = -90;
	            textAnchor = 'start';
	        } else {
	            textAnchor = 'middle';
	        }
	    }

	    var round = Math.round;
	    return labelAttributes({
	        x: round(tx),
	        y: round(ty),
	        angle: orientAngle,
	        attrs: {
	            '.': {
	                y: y,
	                'text-anchor': textAnchor
	            }
	        }
	    });
	}

	function radialLayout(portCenterOffset, autoOrient, opt) {

	    opt = defaults({}, opt, { offset: 20 });

	    var origin = point(0, 0);
	    var angle = -portCenterOffset.theta(origin);
	    var orientAngle = angle;
	    var offset = portCenterOffset.clone()
	        .move(origin, opt.offset)
	        .difference(portCenterOffset)
	        .round();

	    var y = '.3em';
	    var textAnchor;

	    if ((angle + 90) % 180 === 0) {
	        textAnchor = autoOrient ? 'end' : 'middle';
	        if (!autoOrient && angle === -270) {
	            y = '0em';
	        }
	    } else if (angle > -270 && angle < -90) {
	        textAnchor = 'start';
	        orientAngle = angle - 180;
	    } else {
	        textAnchor = 'end';
	    }

	    var round = Math.round;
	    return labelAttributes({
	        x: round(offset.x),
	        y: round(offset.y),
	        angle: autoOrient ? orientAngle : 0,
	        attrs: {
	            '.': {
	                y: y,
	                'text-anchor': textAnchor
	            }
	        }
	    });
	}

	var manual = function(portPosition, elBBox, opt) {
	    return labelAttributes(opt, elBBox);
	};

	var left$1 = function(portPosition, elBBox, opt) {
	    return labelAttributes(opt, { x: -15, attrs: { '.': { y: '.3em', 'text-anchor': 'end' }}});
	};

	var right$1 = function(portPosition, elBBox, opt) {
	    return labelAttributes(opt, { x: 15, attrs: { '.': { y: '.3em', 'text-anchor': 'start' }}});
	};

	var top$1 = function(portPosition, elBBox, opt) {
	    return labelAttributes(opt, { y: -15, attrs: { '.': { 'text-anchor': 'middle' }}});
	};

	var bottom$1 = function(portPosition, elBBox, opt) {
	    return labelAttributes(opt, { y: 15, attrs: { '.': { y: '.6em', 'text-anchor': 'middle' }}});
	};

	var outsideOriented = function(portPosition, elBBox, opt) {
	    return outsideLayout(portPosition, elBBox, true, opt);
	};

	var outside = function(portPosition, elBBox, opt) {
	    return outsideLayout(portPosition, elBBox, false, opt);
	};

	var insideOriented = function(portPosition, elBBox, opt) {
	    return insideLayout(portPosition, elBBox, true, opt);
	};

	var inside = function(portPosition, elBBox, opt) {
	    return insideLayout(portPosition, elBBox, false, opt);
	};

	var radial = function(portPosition, elBBox, opt) {
	    return radialLayout(portPosition.difference(elBBox.center()), false, opt);
	};

	var radialOriented = function(portPosition, elBBox, opt) {
	    return radialLayout(portPosition.difference(elBBox.center()), true, opt);
	};

	var PortLabel = ({
		manual: manual,
		left: left$1,
		right: right$1,
		top: top$1,
		bottom: bottom$1,
		outsideOriented: outsideOriented,
		outside: outside,
		insideOriented: insideOriented,
		inside: inside,
		radial: radial,
		radialOriented: radialOriented
	});

	// Link base model.
	// --------------------------

	var Link = Cell.extend({

	    // The default markup for links.
	    markup: [
	        '<path class="connection" stroke="black" d="M 0 0 0 0"/>',
	        '<path class="marker-source" fill="black" stroke="black" d="M 0 0 0 0"/>',
	        '<path class="marker-target" fill="black" stroke="black" d="M 0 0 0 0"/>',
	        '<path class="connection-wrap" d="M 0 0 0 0"/>',
	        '<g class="labels"/>',
	        '<g class="marker-vertices"/>',
	        '<g class="marker-arrowheads"/>',
	        '<g class="link-tools"/>'
	    ].join(''),

	    toolMarkup: [
	        '<g class="link-tool">',
	        '<g class="tool-remove" event="remove">',
	        '<circle r="11" />',
	        '<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z" />',
	        '<title>Remove link.</title>',
	        '</g>',
	        '<g class="tool-options" event="link:options">',
	        '<circle r="11" transform="translate(25)"/>',
	        '<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>',
	        '<title>Link options.</title>',
	        '</g>',
	        '</g>'
	    ].join(''),

	    doubleToolMarkup: undefined,

	    // The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`).
	    // Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for
	    // dragging vertices (changing their position). The latter is used for removing vertices.
	    vertexMarkup: [
	        '<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">',
	        '<circle class="marker-vertex" idx="<%= idx %>" r="10" />',
	        '<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>',
	        '<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',
	        '<title>Remove vertex.</title>',
	        '</path>',
	        '</g>'
	    ].join(''),

	    arrowheadMarkup: [
	        '<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">',
	        '<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />',
	        '</g>'
	    ].join(''),

	    // may be overwritten by user to change default label (its markup, attrs, position)
	    defaultLabel: undefined,

	    // deprecated
	    // may be overwritten by user to change default label markup
	    // lower priority than defaultLabel.markup
	    labelMarkup: undefined,

	    // private
	    _builtins: {
	        defaultLabel: {
	            // builtin default markup:
	            // used if neither defaultLabel.markup
	            // nor label.markup is set
	            markup: [
	                {
	                    tagName: 'rect',
	                    selector: 'rect' // faster than tagName CSS selector
	                }, {
	                    tagName: 'text',
	                    selector: 'text' // faster than tagName CSS selector
	                }
	            ],
	            // builtin default attributes:
	            // applied only if builtin default markup is used
	            attrs: {
	                text: {
	                    fill: '#000000',
	                    fontSize: 14,
	                    textAnchor: 'middle',
	                    yAlignment: 'middle',
	                    pointerEvents: 'none'
	                },
	                rect: {
	                    ref: 'text',
	                    fill: '#ffffff',
	                    rx: 3,
	                    ry: 3,
	                    refWidth: 1,
	                    refHeight: 1,
	                    refX: 0,
	                    refY: 0
	                }
	            },
	            // builtin default position:
	            // used if neither defaultLabel.position
	            // nor label.position is set
	            position: {
	                distance: 0.5
	            }
	        }
	    },

	    defaults: {
	        type: 'link',
	        source: {},
	        target: {}
	    },

	    isLink: function() {

	        return true;
	    },

	    disconnect: function(opt) {

	        return this.set({
	            source: { x: 0, y: 0 },
	            target: { x: 0, y: 0 }
	        }, opt);
	    },

	    source: function(source, args, opt) {

	        // getter
	        if (source === undefined) {
	            return clone(this.get('source'));
	        }

	        // setter
	        var setSource;
	        var setOpt;

	        // `source` is a cell
	        // take only its `id` and combine with `args`
	        var isCellProvided = source instanceof Cell;
	        if (isCellProvided) { // three arguments
	            setSource = clone(args) || {};
	            setSource.id = source.id;
	            setOpt = opt;
	            return this.set('source', setSource, setOpt);
	        }

	        // `source` is a point-like object
	        // for example, a g.Point
	        // take only its `x` and `y` and combine with `args`
	        var isPointProvided = !isPlainObject(source);
	        if (isPointProvided) { // three arguments
	            setSource = clone(args) || {};
	            setSource.x = source.x;
	            setSource.y = source.y;
	            setOpt = opt;
	            return this.set('source', setSource, setOpt);
	        }

	        // `source` is an object
	        // no checking
	        // two arguments
	        setSource = source;
	        setOpt = args;
	        return this.set('source', setSource, setOpt);
	    },

	    target: function(target, args, opt) {

	        // getter
	        if (target === undefined) {
	            return clone(this.get('target'));
	        }

	        // setter
	        var setTarget;
	        var setOpt;

	        // `target` is a cell
	        // take only its `id` argument and combine with `args`
	        var isCellProvided = target instanceof Cell;
	        if (isCellProvided) { // three arguments
	            setTarget = clone(args) || {};
	            setTarget.id = target.id;
	            setOpt = opt;
	            return this.set('target', setTarget, setOpt);
	        }

	        // `target` is a point-like object
	        // for example, a g.Point
	        // take only its `x` and `y` and combine with `args`
	        var isPointProvided = !isPlainObject(target);
	        if (isPointProvided) { // three arguments
	            setTarget = clone(args) || {};
	            setTarget.x = target.x;
	            setTarget.y = target.y;
	            setOpt = opt;
	            return this.set('target', setTarget, setOpt);
	        }

	        // `target` is an object
	        // no checking
	        // two arguments
	        setTarget = target;
	        setOpt = args;
	        return this.set('target', setTarget, setOpt);
	    },

	    router: function(name, args, opt) {

	        // getter
	        if (name === undefined) {
	            var router = this.get('router');
	            if (!router) {
	                if (this.get('manhattan')) { return { name: 'orthogonal' }; } // backwards compatibility
	                return null;
	            }
	            if (typeof router === 'object') { return clone(router); }
	            return router; // e.g. a function
	        }

	        // setter
	        var isRouterProvided = ((typeof name === 'object') || (typeof name === 'function'));
	        var localRouter = isRouterProvided ? name : { name: name, args: args };
	        var localOpt = isRouterProvided ? args : opt;

	        return this.set('router', localRouter, localOpt);
	    },

	    connector: function(name, args, opt) {

	        // getter
	        if (name === undefined) {
	            var connector = this.get('connector');
	            if (!connector) {
	                if (this.get('smooth')) { return { name: 'smooth' }; } // backwards compatibility
	                return null;
	            }
	            if (typeof connector === 'object') { return clone(connector); }
	            return connector; // e.g. a function
	        }

	        // setter
	        var isConnectorProvided = ((typeof name === 'object' || typeof name === 'function'));
	        var localConnector = isConnectorProvided ? name : { name: name, args: args };
	        var localOpt = isConnectorProvided ? args : opt;

	        return this.set('connector', localConnector, localOpt);
	    },

	    // Labels API

	    // A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter.
	    label: function(idx, label, opt) {

	        var labels = this.labels();

	        idx = (isFinite(idx) && idx !== null) ? (idx | 0) : 0;
	        if (idx < 0) { idx = labels.length + idx; }

	        // getter
	        if (arguments.length <= 1) { return this.prop(['labels', idx]); }
	        // setter
	        return this.prop(['labels', idx], label, opt);
	    },

	    labels: function(labels, opt) {

	        // getter
	        if (arguments.length === 0) {
	            labels = this.get('labels');
	            if (!Array.isArray(labels)) { return []; }
	            return labels.slice();
	        }
	        // setter
	        if (!Array.isArray(labels)) { labels = []; }
	        return this.set('labels', labels, opt);
	    },

	    insertLabel: function(idx, label, opt) {

	        if (!label) { throw new Error('dia.Link: no label provided'); }

	        var labels = this.labels();
	        var n = labels.length;
	        idx = (isFinite(idx) && idx !== null) ? (idx | 0) : n;
	        if (idx < 0) { idx = n + idx + 1; }

	        labels.splice(idx, 0, label);
	        return this.labels(labels, opt);
	    },

	    // convenience function
	    // add label to end of labels array
	    appendLabel: function(label, opt) {

	        return this.insertLabel(-1, label, opt);
	    },

	    removeLabel: function(idx, opt) {

	        var labels = this.labels();
	        idx = (isFinite(idx) && idx !== null) ? (idx | 0) : -1;

	        labels.splice(idx, 1);
	        return this.labels(labels, opt);
	    },

	    // Vertices API

	    vertex: function(idx, vertex, opt) {

	        var vertices = this.vertices();

	        idx = (isFinite(idx) && idx !== null) ? (idx | 0) : 0;
	        if (idx < 0) { idx = vertices.length + idx; }

	        // getter
	        if (arguments.length <= 1) { return this.prop(['vertices', idx]); }

	        // setter
	        var setVertex = this._normalizeVertex(vertex);
	        return this.prop(['vertices', idx], setVertex, opt);
	    },

	    vertices: function(vertices, opt) {

	        // getter
	        if (arguments.length === 0) {
	            vertices = this.get('vertices');
	            if (!Array.isArray(vertices)) { return []; }
	            return vertices.slice();
	        }

	        // setter
	        if (!Array.isArray(vertices)) { vertices = []; }
	        var setVertices = [];
	        for (var i = 0; i < vertices.length; i++) {
	            var vertex = vertices[i];
	            var setVertex = this._normalizeVertex(vertex);
	            setVertices.push(setVertex);
	        }
	        return this.set('vertices', setVertices, opt);
	    },

	    insertVertex: function(idx, vertex, opt) {

	        if (!vertex) { throw new Error('dia.Link: no vertex provided'); }

	        var vertices = this.vertices();
	        var n = vertices.length;
	        idx = (isFinite(idx) && idx !== null) ? (idx | 0) : n;
	        if (idx < 0) { idx = n + idx + 1; }

	        var setVertex = this._normalizeVertex(vertex);
	        vertices.splice(idx, 0, setVertex);
	        return this.vertices(vertices, opt);
	    },

	    removeVertex: function(idx, opt) {

	        var vertices = this.vertices();
	        idx = (isFinite(idx) && idx !== null) ? (idx | 0) : -1;

	        vertices.splice(idx, 1);
	        return this.vertices(vertices, opt);
	    },

	    _normalizeVertex: function(vertex) {

	        // is vertex a point-like object?
	        // for example, a g.Point
	        var isPointProvided = !isPlainObject(vertex);
	        if (isPointProvided) { return { x: vertex.x, y: vertex.y }; }

	        // else: return vertex unchanged
	        return vertex;
	    },

	    // Transformations

	    translate: function(tx, ty, opt) {

	        // enrich the option object
	        opt = opt || {};
	        opt.translateBy = opt.translateBy || this.id;
	        opt.tx = tx;
	        opt.ty = ty;

	        return this.applyToPoints(function(p) {
	            return { x: (p.x || 0) + tx, y: (p.y || 0) + ty };
	        }, opt);
	    },

	    scale: function(sx, sy, origin, opt) {

	        return this.applyToPoints(function(p) {
	            return Point(p).scale(sx, sy, origin).toJSON();
	        }, opt);
	    },

	    applyToPoints: function(fn, opt) {

	        if (!isFunction(fn)) {
	            throw new TypeError('dia.Link: applyToPoints expects its first parameter to be a function.');
	        }

	        var attrs = {};

	        var ref = this.attributes;
	        var source = ref.source;
	        var target = ref.target;
	        if (!source.id) {
	            attrs.source = fn(source);
	        }
	        if (!target.id) {
	            attrs.target = fn(target);
	        }

	        var vertices = this.vertices();
	        if (vertices.length > 0) {
	            attrs.vertices = vertices.map(fn);
	        }

	        return this.set(attrs, opt);
	    },

	    getSourcePoint: function() {
	        var sourceCell = this.getSourceCell();
	        if (!sourceCell) { return new Point(this.source()); }
	        return sourceCell.getPointFromConnectedLink(this, 'source');
	    },

	    getTargetPoint: function() {
	        var targetCell = this.getTargetCell();
	        if (!targetCell) { return new Point(this.target()); }
	        return targetCell.getPointFromConnectedLink(this, 'target');
	    },

	    getPointFromConnectedLink: function(/* link, endType */) {
	        return this.getPolyline().pointAt(0.5);
	    },

	    getPolyline: function() {
	        var points = [
	            this.getSourcePoint() ].concat( this.vertices().map(Point),
	            [this.getTargetPoint()]
	        );
	        return new Polyline(points);
	    },

	    getBBox: function() {
	        return this.getPolyline().bbox();
	    },

	    reparent: function(opt) {

	        var newParent;

	        if (this.graph) {

	            var source = this.getSourceElement();
	            var target = this.getTargetElement();
	            var prevParent = this.getParentCell();

	            if (source && target) {
	                if (source === target || source.isEmbeddedIn(target)) {
	                    newParent = target;
	                } else if (target.isEmbeddedIn(source)) {
	                    newParent = source;
	                } else {
	                    newParent = this.graph.getCommonAncestor(source, target);
	                }
	            }

	            if (prevParent && (!newParent || newParent.id !== prevParent.id)) {
	                // Unembed the link if source and target has no common ancestor
	                // or common ancestor changed
	                prevParent.unembed(this, opt);
	            }

	            if (newParent) {
	                newParent.embed(this, opt);
	            }
	        }

	        return newParent;
	    },

	    hasLoop: function(opt) {

	        opt = opt || {};

	        var ref = this.attributes;
	        var source = ref.source;
	        var target = ref.target;
	        var sourceId = source.id;
	        var targetId = target.id;

	        if (!sourceId || !targetId) {
	            // Link "pinned" to the paper does not have a loop.
	            return false;
	        }

	        var loop = sourceId === targetId;

	        // Note that there in the deep mode a link can have a loop,
	        // even if it connects only a parent and its embed.
	        // A loop "target equals source" is valid in both shallow and deep mode.
	        if (!loop && opt.deep && this.graph) {

	            var sourceElement = this.getSourceCell();
	            var targetElement = this.getTargetCell();

	            loop = sourceElement.isEmbeddedIn(targetElement) || targetElement.isEmbeddedIn(sourceElement);
	        }

	        return loop;
	    },

	    // unlike source(), this method returns null if source is a point
	    getSourceCell: function() {

	        var ref = this;
	        var graph = ref.graph;
	        var attributes = ref.attributes;
	        var source = attributes.source;
	        return (source && source.id && graph && graph.getCell(source.id)) || null;
	    },

	    getSourceElement: function() {
	        var cell = this;
	        var visited = {};
	        do {
	            if (visited[cell.id]) { return null; }
	            visited[cell.id] = true;
	            cell = cell.getSourceCell();
	        } while (cell && cell.isLink());
	        return cell;
	    },

	    // unlike target(), this method returns null if target is a point
	    getTargetCell: function() {

	        var ref = this;
	        var graph = ref.graph;
	        var attributes = ref.attributes;
	        var target = attributes.target;
	        return (target && target.id && graph && graph.getCell(target.id)) || null;
	    },

	    getTargetElement: function() {
	        var cell = this;
	        var visited = {};
	        do {
	            if (visited[cell.id]) { return null; }
	            visited[cell.id] = true;
	            cell = cell.getTargetCell();
	        } while (cell && cell.isLink());
	        return cell;
	    },

	    // Returns the common ancestor for the source element,
	    // target element and the link itself.
	    getRelationshipAncestor: function() {

	        var connectionAncestor;

	        if (this.graph) {

	            var cells = [
	                this,
	                this.getSourceElement(), // null if source is a point
	                this.getTargetElement() // null if target is a point
	            ].filter(function(item) {
	                return !!item;
	            });

	            connectionAncestor = this.graph.getCommonAncestor.apply(this.graph, cells);
	        }

	        return connectionAncestor || null;
	    },

	    // Is source, target and the link itself embedded in a given cell?
	    isRelationshipEmbeddedIn: function(cell) {

	        var cellId = (isString(cell) || isNumber(cell)) ? cell : cell.id;
	        var ancestor = this.getRelationshipAncestor();

	        return !!ancestor && (ancestor.id === cellId || ancestor.isEmbeddedIn(cellId));
	    },

	    // Get resolved default label.
	    _getDefaultLabel: function() {

	        var defaultLabel = this.get('defaultLabel') || this.defaultLabel || {};

	        var label = {};
	        label.markup = defaultLabel.markup || this.get('labelMarkup') || this.labelMarkup;
	        label.position = defaultLabel.position;
	        label.attrs = defaultLabel.attrs;
	        label.size = defaultLabel.size;

	        return label;
	    }
	}, {

	    endsEqual: function(a, b) {

	        var portsEqual = a.port === b.port || !a.port && !b.port;
	        return a.id === b.id && portsEqual;
	    }
	});

	var PortData = function(data) {

	    var clonedData = cloneDeep(data) || {};
	    this.ports = [];
	    this.groups = {};
	    this.portLayoutNamespace = Port;
	    this.portLabelLayoutNamespace = PortLabel;

	    this._init(clonedData);
	};

	PortData.prototype = {

	    getPorts: function() {
	        return this.ports;
	    },

	    getGroup: function(name) {
	        return this.groups[name] || {};
	    },

	    getPortsByGroup: function(groupName) {

	        return this.ports.filter(function(port) {
	            return port.group === groupName;
	        });
	    },

	    getGroupPortsMetrics: function(groupName, elBBox) {

	        var group = this.getGroup(groupName);
	        var ports = this.getPortsByGroup(groupName);

	        var groupPosition = group.position || {};
	        var groupPositionName = groupPosition.name;
	        var namespace = this.portLayoutNamespace;
	        if (!namespace[groupPositionName]) {
	            groupPositionName = 'left';
	        }

	        var groupArgs = groupPosition.args || {};
	        var portsArgs = ports.map(function(port) {
	            return port && port.position && port.position.args;
	        });
	        var groupPortTransformations = namespace[groupPositionName](portsArgs, elBBox, groupArgs);

	        var accumulator = {
	            ports: ports,
	            result: []
	        };

	        toArray(groupPortTransformations).reduce(function(res, portTransformation, index) {
	            var port = res.ports[index];
	            res.result.push({
	                portId: port.id,
	                portTransformation: portTransformation,
	                labelTransformation: this._getPortLabelLayout(port, Point(portTransformation), elBBox),
	                portAttrs: port.attrs,
	                portSize: port.size,
	                labelSize: port.label.size
	            });
	            return res;
	        }.bind(this), accumulator);

	        return accumulator.result;
	    },

	    _getPortLabelLayout: function(port, portPosition, elBBox) {

	        var namespace = this.portLabelLayoutNamespace;
	        var labelPosition = port.label.position.name || 'left';

	        if (namespace[labelPosition]) {
	            return namespace[labelPosition](portPosition, elBBox, port.label.position.args);
	        }

	        return null;
	    },

	    _init: function(data) {

	        // prepare groups
	        if (isObject$1(data.groups)) {
	            var groups = Object.keys(data.groups);
	            for (var i = 0, n = groups.length; i < n; i++) {
	                var key = groups[i];
	                this.groups[key] = this._evaluateGroup(data.groups[key]);
	            }
	        }

	        // prepare ports
	        var ports = toArray(data.items);
	        for (var j = 0, m = ports.length; j < m; j++) {
	            this.ports.push(this._evaluatePort(ports[j]));
	        }
	    },

	    _evaluateGroup: function(group) {

	        return merge(group, {
	            position: this._getPosition(group.position, true),
	            label: this._getLabel(group, true)
	        });
	    },

	    _evaluatePort: function(port) {

	        var evaluated = assign({}, port);

	        var group = this.getGroup(port.group);

	        evaluated.markup = evaluated.markup || group.markup;
	        evaluated.attrs = merge({}, group.attrs, evaluated.attrs);
	        evaluated.position = this._createPositionNode(group, evaluated);
	        evaluated.label = merge({}, group.label, this._getLabel(evaluated));
	        evaluated.z = this._getZIndex(group, evaluated);
	        evaluated.size = assign({}, group.size, evaluated.size);

	        return evaluated;
	    },

	    _getZIndex: function(group, port) {

	        if (isNumber(port.z)) {
	            return port.z;
	        }
	        if (isNumber(group.z) || group.z === 'auto') {
	            return group.z;
	        }
	        return 'auto';
	    },

	    _createPositionNode: function(group, port) {

	        return merge({
	            name: 'left',
	            args: {}
	        }, group.position, { args: port.args });
	    },

	    _getPosition: function(position, setDefault) {

	        var args = {};
	        var positionName;

	        if (isFunction(position)) {
	            positionName = 'fn';
	            args.fn = position;
	        } else if (isString(position)) {
	            positionName = position;
	        } else if (position === undefined) {
	            positionName = setDefault ? 'left' : null;
	        } else if (Array.isArray(position)) {
	            positionName = 'absolute';
	            args.x = position[0];
	            args.y = position[1];
	        } else if (isObject$1(position)) {
	            positionName = position.name;
	            assign(args, position.args);
	        }

	        var result = { args: args };

	        if (positionName) {
	            result.name = positionName;
	        }
	        return result;
	    },

	    _getLabel: function(item, setDefaults) {

	        var label = item.label || {};

	        var ret = label;
	        ret.position = this._getPosition(label.position, setDefaults);

	        return ret;
	    }
	};

	var elementPortPrototype = {

	    _initializePorts: function() {

	        this._createPortData();
	        this.on('change:ports', function() {

	            this._processRemovedPort();
	            this._createPortData();
	        }, this);
	    },

	    /**
	     * remove links tied wiht just removed element
	     * @private
	     */
	    _processRemovedPort: function() {

	        var current = this.get('ports') || {};
	        var currentItemsMap = {};

	        toArray(current.items).forEach(function(item) {
	            currentItemsMap[item.id] = true;
	        });

	        var previous = this.previous('ports') || {};
	        var removed = {};

	        toArray(previous.items).forEach(function(item) {
	            if (!currentItemsMap[item.id]) {
	                removed[item.id] = true;
	            }
	        });

	        var graph = this.graph;
	        if (graph && !isEmpty(removed)) {

	            var inboundLinks = graph.getConnectedLinks(this, { inbound: true });
	            inboundLinks.forEach(function(link) {

	                if (removed[link.get('target').port]) { link.remove(); }
	            });

	            var outboundLinks = graph.getConnectedLinks(this, { outbound: true });
	            outboundLinks.forEach(function(link) {

	                if (removed[link.get('source').port]) { link.remove(); }
	            });
	        }
	    },

	    /**
	     * @returns {boolean}
	     */
	    hasPorts: function() {

	        var ports = this.prop('ports/items');
	        return Array.isArray(ports) && ports.length > 0;
	    },

	    /**
	     * @param {string} id
	     * @returns {boolean}
	     */
	    hasPort: function(id) {

	        return this.getPortIndex(id) !== -1;
	    },

	    /**
	     * @returns {Array<object>}
	     */
	    getPorts: function() {

	        return cloneDeep(this.prop('ports/items')) || [];
	    },

	    /**
	     * @returns {Array<object>}
	     */
	    getGroupPorts: function(groupName) {
	        var groupPorts = toArray(this.prop(['ports','items'])).filter(function (port) { return port.group === groupName; });
	        return cloneDeep(groupPorts);
	    },

	    /**
	     * @param {string} id
	     * @returns {object}
	     */
	    getPort: function(id) {

	        return cloneDeep(toArray(this.prop('ports/items')).find(function(port) {
	            return port.id && port.id === id;
	        }));
	    },

	    /**
	     * @param {string} groupName
	     * @returns {Object<portId, {x: number, y: number, angle: number}>}
	     */
	    getPortsPositions: function(groupName) {

	        var portsMetrics = this._portSettingsData.getGroupPortsMetrics(groupName, Rect(this.size()));

	        return portsMetrics.reduce(function(positions, metrics) {
	            var transformation = metrics.portTransformation;
	            positions[metrics.portId] = {
	                x: transformation.x,
	                y: transformation.y,
	                angle: transformation.angle
	            };
	            return positions;
	        }, {});
	    },

	    /**
	     * @param {string|Port} port port id or port
	     * @returns {number} port index
	     */
	    getPortIndex: function(port) {

	        var id = isObject$1(port) ? port.id : port;

	        if (!this._isValidPortId(id)) {
	            return -1;
	        }

	        return toArray(this.prop('ports/items')).findIndex(function(item) {
	            return item.id === id;
	        });
	    },

	    /**
	     * @param {object} port
	     * @param {object} [opt]
	     * @returns {joint.dia.Element}
	     */
	    addPort: function(port, opt) {

	        if (!isObject$1(port) || Array.isArray(port)) {
	            throw new Error('Element: addPort requires an object.');
	        }

	        var ports = assign([], this.prop('ports/items'));
	        ports.push(port);
	        this.prop('ports/items', ports, opt);

	        return this;
	    },

	    /**
	     * @param {string|Port|number} before
	     * @param {object} port
	     * @param {object} [opt]
	     * @returns {joint.dia.Element}
	     */
	    insertPort: function(before, port, opt) {
	        var index$1 = (typeof before === 'number') ? before : this.getPortIndex(before);

	        if (!isObject$1(port) || Array.isArray(port)) {
	            throw new Error('dia.Element: insertPort requires an object.');
	        }

	        var ports = assign([], this.prop('ports/items'));
	        ports.splice(index$1, 0, port);
	        this.prop('ports/items', ports, opt);

	        return this;
	    },

	    /**
	     * @param {string} portId
	     * @param {string|object=} path
	     * @param {*=} value
	     * @param {object=} opt
	     * @returns {joint.dia.Element}
	     */
	    portProp: function(portId, path, value, opt) {

	        var index$1 = this.getPortIndex(portId);

	        if (index$1 === -1) {
	            throw new Error('Element: unable to find port with id ' + portId);
	        }

	        var args = Array.prototype.slice.call(arguments, 1);
	        if (Array.isArray(path)) {
	            args[0] = ['ports', 'items', index$1].concat(path);
	        } else if (isString(path)) {

	            // Get/set an attribute by a special path syntax that delimits
	            // nested objects by the colon character.
	            args[0] = ['ports/items/', index$1, '/', path].join('');

	        } else {

	            args = ['ports/items/' + index$1];
	            if (isPlainObject(path)) {
	                args.push(path);
	                args.push(value);
	            }
	        }

	        return this.prop.apply(this, args);
	    },

	    _validatePorts: function() {

	        var portsAttr = this.get('ports') || {};

	        var errorMessages = [];
	        portsAttr = portsAttr || {};
	        var ports = toArray(portsAttr.items);

	        ports.forEach(function(p) {

	            if (typeof p !== 'object') {
	                errorMessages.push('Element: invalid port ', p);
	            }

	            if (!this._isValidPortId(p.id)) {
	                p.id = this.generatePortId();
	            }
	        }, this);

	        if (uniq(ports, 'id').length !== ports.length) {
	            errorMessages.push('Element: found id duplicities in ports.');
	        }

	        return errorMessages;
	    },

	    generatePortId: function() {
	        return this.generateId();
	    },

	    /**
	     * @param {string} id port id
	     * @returns {boolean}
	     * @private
	     */
	    _isValidPortId: function(id) {

	        return id !== null && id !== undefined && !isObject$1(id);
	    },

	    addPorts: function(ports, opt) {

	        if (ports.length) {
	            this.prop('ports/items', assign([], this.prop('ports/items')).concat(ports), opt);
	        }

	        return this;
	    },

	    removePort: function(port, opt) {
	        var options = opt || {};
	        var index$1 = this.getPortIndex(port);
	        if (index$1 !== -1) {
	            var ports = assign([], this.prop(['ports', 'items']));
	            ports.splice(index$1, 1);
	            options.rewrite = true;
	            this.startBatch('port-remove');
	            this.prop(['ports', 'items'], ports, options);
	            this.stopBatch('port-remove');
	        }
	        return this;
	    },

	    removePorts: function(portsForRemoval, opt) {
	        var options, newPorts;
	        if (Array.isArray(portsForRemoval)) {
	            options = opt || {};
	            if (portsForRemoval.length === 0) { return this.this; }
	            var currentPorts = assign([], this.prop(['ports', 'items']));
	            newPorts = currentPorts.filter(function(cp) {
	                return !portsForRemoval.some(function(rp) {
	                    var rpId = isObject$1(rp) ? rp.id : rp;
	                    return cp.id === rpId;
	                });
	            });
	        } else {
	            options = portsForRemoval || {};
	            newPorts = [];
	        }
	        this.startBatch('port-remove');
	        options.rewrite = true;
	        this.prop(['ports', 'items'], newPorts, options);
	        this.stopBatch('port-remove');
	        return this;
	    },

	    /**
	     * @private
	     */
	    _createPortData: function() {

	        var err = this._validatePorts();

	        if (err.length > 0) {
	            this.set('ports', this.previous('ports'));
	            throw new Error(err.join(' '));
	        }

	        var prevPortData;

	        if (this._portSettingsData) {

	            prevPortData = this._portSettingsData.getPorts();
	        }

	        this._portSettingsData = new PortData(this.get('ports'));

	        var curPortData = this._portSettingsData.getPorts();

	        if (prevPortData) {

	            var added = curPortData.filter(function(item) {
	                if (!prevPortData.find(function(prevPort) {
	                    return prevPort.id === item.id;
	                })) {
	                    return item;
	                }
	            });

	            var removed = prevPortData.filter(function(item) {
	                if (!curPortData.find(function(curPort) {
	                    return curPort.id === item.id;
	                })) {
	                    return item;
	                }
	            });

	            if (removed.length > 0) {
	                this.trigger('ports:remove', this, removed);
	            }

	            if (added.length > 0) {
	                this.trigger('ports:add', this, added);
	            }
	        }
	    }
	};

	var elementViewPortPrototype = {

	    portContainerMarkup: 'g',
	    portMarkup: [{
	        tagName: 'circle',
	        selector: 'circle',
	        attributes: {
	            'r': 10,
	            'fill': '#FFFFFF',
	            'stroke': '#000000'
	        }
	    }],
	    portLabelMarkup: [{
	        tagName: 'text',
	        selector: 'text',
	        attributes: {
	            'fill': '#000000'
	        }
	    }],
	    /** @type {Object<string, {portElement: Vectorizer, portLabelElement: Vectorizer}>} */
	    _portElementsCache: null,

	    /**
	     * @private
	     */
	    _initializePorts: function() {
	        this._cleanPortsCache();
	    },

	    /**
	     * @typedef {Object} Port
	     *
	     * @property {string} id
	     * @property {Object} position
	     * @property {Object} label
	     * @property {Object} attrs
	     * @property {string} markup
	     * @property {string} group
	     */

	    /**
	     * @private
	     */
	    _refreshPorts: function() {

	        this._removePorts();
	        this._cleanPortsCache();
	        this._renderPorts();
	    },

	    _cleanPortsCache: function() {
	        this._portElementsCache = {};
	    },

	    /**
	     * @private
	     */
	    _renderPorts: function() {

	        // references to rendered elements without z-index
	        var elementReferences = [];
	        var elem = this._getContainerElement();

	        for (var i = 0, count = elem.node.childNodes.length; i < count; i++) {
	            elementReferences.push(elem.node.childNodes[i]);
	        }

	        var portsGropsByZ = groupBy(this.model._portSettingsData.getPorts(), 'z');
	        var withoutZKey = 'auto';

	        // render non-z first
	        toArray(portsGropsByZ[withoutZKey]).forEach(function(port) {
	            var portElement = this._getPortElement(port);
	            elem.append(portElement);
	            elementReferences.push(portElement);
	        }, this);

	        var groupNames = Object.keys(portsGropsByZ);
	        for (var k = 0; k < groupNames.length; k++) {
	            var groupName = groupNames[k];
	            if (groupName !== withoutZKey) {
	                var z = parseInt(groupName, 10);
	                this._appendPorts(portsGropsByZ[groupName], z, elementReferences);
	            }
	        }

	        this._updatePorts();
	    },

	    /**
	     * @returns {V}
	     * @private
	     */
	    _getContainerElement: function() {

	        return this.rotatableNode || this.vel;
	    },

	    /**
	     * @param {Array<Port>}ports
	     * @param {number} z
	     * @param refs
	     * @private
	     */
	    _appendPorts: function(ports, z, refs) {

	        var containerElement = this._getContainerElement();
	        var portElements = toArray(ports).map(this._getPortElement, this);

	        if (refs[z] || z < 0) {
	            V(refs[Math.max(z, 0)]).before(portElements);
	        } else {
	            containerElement.append(portElements);
	        }
	    },

	    /**
	     * Try to get element from cache,
	     * @param port
	     * @returns {*}
	     * @private
	     */
	    _getPortElement: function(port) {

	        if (this._portElementsCache[port.id]) {
	            return this._portElementsCache[port.id].portElement;
	        }
	        return this._createPortElement(port);
	    },

	    findPortNode: function(portId, selector) {
	        var portCache = this._portElementsCache[portId];
	        if (!portCache) { return null; }
	        var portRoot = portCache.portContentElement.node;
	        var portSelectors = portCache.portContentSelectors;
	        var ref = this.findBySelector(selector, portRoot, portSelectors);
	        var node = ref[0]; if ( node === void 0 ) node = null;
	        return node;
	    },

	    /**
	     * @private
	     */
	    _updatePorts: function() {

	        // layout ports without group
	        this._updatePortGroup(undefined);
	        // layout ports with explicit group
	        var groupsNames = Object.keys(this.model._portSettingsData.groups);
	        groupsNames.forEach(this._updatePortGroup, this);
	    },

	    /**
	     * @private
	     */
	    _removePorts: function() {
	        invoke(this._portElementsCache, 'portElement.remove');
	    },

	    /**
	     * @param {Port} port
	     * @returns {V}
	     * @private
	     */
	    _createPortElement: function(port) {

	        var portElement;
	        var labelElement;

	        var portContainerElement = V(this.portContainerMarkup).addClass('joint-port');

	        var portMarkup = this._getPortMarkup(port);
	        var portSelectors;
	        if (Array.isArray(portMarkup)) {
	            var portDoc = this.parseDOMJSON(portMarkup, portContainerElement.node);
	            var portFragment = portDoc.fragment;
	            if (portFragment.childNodes.length > 1) {
	                portElement = V('g').append(portFragment);
	            } else {
	                portElement = V(portFragment.firstChild);
	            }
	            portSelectors = portDoc.selectors;
	        } else {
	            portElement = V(portMarkup);
	            if (Array.isArray(portElement)) {
	                portElement = V('g').append(portElement);
	            }
	        }

	        if (!portElement) {
	            throw new Error('ElementView: Invalid port markup.');
	        }

	        portElement.attr({
	            'port': port.id,
	            'port-group': port.group
	        });

	        var labelMarkup = this._getPortLabelMarkup(port.label);
	        var labelSelectors;
	        if (Array.isArray(labelMarkup)) {
	            var labelDoc = this.parseDOMJSON(labelMarkup, portContainerElement.node);
	            var labelFragment = labelDoc.fragment;
	            if (labelFragment.childNodes.length > 1) {
	                labelElement = V('g').append(labelFragment);
	            } else {
	                labelElement = V(labelFragment.firstChild);
	            }
	            labelSelectors = labelDoc.selectors;
	        } else {
	            labelElement = V(labelMarkup);
	            if (Array.isArray(labelElement)) {
	                labelElement = V('g').append(labelElement);
	            }
	        }

	        if (!labelElement) {
	            throw new Error('ElementView: Invalid port label markup.');
	        }

	        var portContainerSelectors;
	        if (portSelectors && labelSelectors) {
	            for (var key in labelSelectors) {
	                if (portSelectors[key] && key !== this.selector) { throw new Error('ElementView: selectors within port must be unique.'); }
	            }
	            portContainerSelectors = assign({}, portSelectors, labelSelectors);
	        } else {
	            portContainerSelectors = portSelectors || labelSelectors;
	        }

	        portContainerElement.append([
	            portElement.addClass('joint-port-body'),
	            labelElement.addClass('joint-port-label')
	        ]);

	        this._portElementsCache[port.id] = {
	            portElement: portContainerElement,
	            portLabelElement: labelElement,
	            portSelectors: portContainerSelectors,
	            portLabelSelectors: labelSelectors,
	            portContentElement: portElement,
	            portContentSelectors: portSelectors
	        };

	        return portContainerElement;
	    },

	    /**
	     * @param {string=} groupName
	     * @private
	     */
	    _updatePortGroup: function(groupName) {

	        var elementBBox = Rect(this.model.size());
	        var portsMetrics = this.model._portSettingsData.getGroupPortsMetrics(groupName, elementBBox);

	        for (var i = 0, n = portsMetrics.length; i < n; i++) {
	            var metrics = portsMetrics[i];
	            var portId = metrics.portId;
	            var cached = this._portElementsCache[portId] || {};
	            var portTransformation = metrics.portTransformation;
	            this.applyPortTransform(cached.portElement, portTransformation);
	            this.updateDOMSubtreeAttributes(cached.portElement.node, metrics.portAttrs, {
	                rootBBox: new Rect(metrics.portSize),
	                selectors: cached.portSelectors
	            });

	            var labelTransformation = metrics.labelTransformation;
	            if (labelTransformation) {
	                this.applyPortTransform(cached.portLabelElement, labelTransformation, (-portTransformation.angle || 0));
	                this.updateDOMSubtreeAttributes(cached.portLabelElement.node, labelTransformation.attrs, {
	                    rootBBox: new Rect(metrics.labelSize),
	                    selectors: cached.portLabelSelectors
	                });
	            }
	        }
	    },

	    /**
	     * @param {Vectorizer} element
	     * @param {{dx:number, dy:number, angle: number, attrs: Object, x:number: y:number}} transformData
	     * @param {number=} initialAngle
	     * @constructor
	     */
	    applyPortTransform: function(element, transformData, initialAngle) {

	        var matrix = V.createSVGMatrix()
	            .rotate(initialAngle || 0)
	            .translate(transformData.x || 0, transformData.y || 0)
	            .rotate(transformData.angle || 0);

	        element.transform(matrix, { absolute: true });
	    },

	    /**
	     * @param {Port} port
	     * @returns {string}
	     * @private
	     */
	    _getPortMarkup: function(port) {

	        return port.markup || this.model.get('portMarkup') || this.model.portMarkup || this.portMarkup;
	    },

	    /**
	     * @param {Object} label
	     * @returns {string}
	     * @private
	     */
	    _getPortLabelMarkup: function(label) {

	        return label.markup || this.model.get('portLabelMarkup') || this.model.portLabelMarkup || this.portLabelMarkup;
	    }
	};

	// Element base model.
	// -----------------------------

	var Element$1 = Cell.extend({

	    defaults: {
	        position: { x: 0, y: 0 },
	        size: { width: 1, height: 1 },
	        angle: 0
	    },

	    initialize: function() {

	        this._initializePorts();
	        Cell.prototype.initialize.apply(this, arguments);
	    },

	    /**
	     * @abstract
	     */
	    _initializePorts: function() {
	        // implemented in ports.js
	    },

	    _refreshPorts: function() {
	        // implemented in ports.js
	    },

	    isElement: function() {

	        return true;
	    },

	    position: function(x, y, opt) {

	        var isSetter = isNumber(y);

	        opt = (isSetter ? opt : x) || {};

	        // option `parentRelative` for setting the position relative to the element's parent.
	        if (opt.parentRelative) {

	            // Getting the parent's position requires the collection.
	            // Cell.parent() holds cell id only.
	            if (!this.graph) { throw new Error('Element must be part of a graph.'); }

	            var parent = this.getParentCell();
	            var parentPosition = parent && !parent.isLink()
	                ? parent.get('position')
	                : { x: 0, y: 0 };
	        }

	        if (isSetter) {

	            if (opt.parentRelative) {
	                x += parentPosition.x;
	                y += parentPosition.y;
	            }

	            if (opt.deep) {
	                var currentPosition = this.get('position');
	                this.translate(x - currentPosition.x, y - currentPosition.y, opt);
	            } else {
	                this.set('position', { x: x, y: y }, opt);
	            }

	            return this;

	        } else { // Getter returns a geometry point.

	            var elementPosition = Point(this.get('position'));

	            return opt.parentRelative
	                ? elementPosition.difference(parentPosition)
	                : elementPosition;
	        }
	    },

	    translate: function(tx, ty, opt) {

	        tx = tx || 0;
	        ty = ty || 0;

	        if (tx === 0 && ty === 0) {
	            // Like nothing has happened.
	            return this;
	        }

	        opt = opt || {};
	        // Pass the initiator of the translation.
	        opt.translateBy = opt.translateBy || this.id;

	        var position = this.get('position') || { x: 0, y: 0 };
	        var ra = opt.restrictedArea;
	        if (ra && opt.translateBy === this.id) {

	            if (typeof ra === 'function') {

	                var newPosition = ra.call(this, position.x + tx, position.y + ty, opt);

	                tx = newPosition.x - position.x;
	                ty = newPosition.y - position.y;

	            } else  {
	                // We are restricting the translation for the element itself only. We get
	                // the bounding box of the element including all its embeds.
	                // All embeds have to be translated the exact same way as the element.
	                var bbox = this.getBBox({ deep: true });
	                //- - - - - - - - - - - - -> ra.x + ra.width
	                // - - - -> position.x      |
	                // -> bbox.x
	                //                ▓▓▓▓▓▓▓   |
	                //         ░░░░░░░▓▓▓▓▓▓▓
	                //         ░░░░░░░░░        |
	                //   ▓▓▓▓▓▓▓▓░░░░░░░
	                //   ▓▓▓▓▓▓▓▓               |
	                //   <-dx->                     | restricted area right border
	                //         <-width->        |   ░ translated element
	                //   <- - bbox.width - ->       ▓ embedded element
	                var dx = position.x - bbox.x;
	                var dy = position.y - bbox.y;
	                // Find the maximal/minimal coordinates that the element can be translated
	                // while complies the restrictions.
	                var x = Math.max(ra.x + dx, Math.min(ra.x + ra.width + dx - bbox.width, position.x + tx));
	                var y = Math.max(ra.y + dy, Math.min(ra.y + ra.height + dy - bbox.height, position.y + ty));
	                // recalculate the translation taking the restrictions into account.
	                tx = x - position.x;
	                ty = y - position.y;
	            }
	        }

	        var translatedPosition = {
	            x: position.x + tx,
	            y: position.y + ty
	        };

	        // To find out by how much an element was translated in event 'change:position' handlers.
	        opt.tx = tx;
	        opt.ty = ty;

	        if (opt.transition) {

	            if (!isObject$1(opt.transition)) { opt.transition = {}; }

	            this.transition('position', translatedPosition, assign({}, opt.transition, {
	                valueFunction: interpolate.object
	            }));

	            // Recursively call `translate()` on all the embeds cells.
	            invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt);

	        } else {

	            this.startBatch('translate', opt);
	            this.set('position', translatedPosition, opt);
	            invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt);
	            this.stopBatch('translate', opt);
	        }

	        return this;
	    },

	    size: function(width, height, opt) {

	        var currentSize = this.get('size');
	        // Getter
	        // () signature
	        if (width === undefined) {
	            return {
	                width: currentSize.width,
	                height: currentSize.height
	            };
	        }
	        // Setter
	        // (size, opt) signature
	        if (isObject$1(width)) {
	            opt = height;
	            height = isNumber(width.height) ? width.height : currentSize.height;
	            width = isNumber(width.width) ? width.width : currentSize.width;
	        }

	        return this.resize(width, height, opt);
	    },

	    resize: function(width, height, opt) {

	        opt = opt || {};

	        this.startBatch('resize', opt);

	        if (opt.direction) {

	            var currentSize = this.get('size');

	            switch (opt.direction) {

	                case 'left':
	                case 'right':
	                    // Don't change height when resizing horizontally.
	                    height = currentSize.height;
	                    break;

	                case 'top':
	                case 'bottom':
	                    // Don't change width when resizing vertically.
	                    width = currentSize.width;
	                    break;
	            }

	            // Get the angle and clamp its value between 0 and 360 degrees.
	            var angle = normalizeAngle(this.get('angle') || 0);

	            // This is a rectangle in size of the un-rotated element.
	            var bbox = this.getBBox();

	            var origin;

	            if (angle) {

	                var quadrant = {
	                    'top-right': 0,
	                    'right': 0,
	                    'top-left': 1,
	                    'top': 1,
	                    'bottom-left': 2,
	                    'left': 2,
	                    'bottom-right': 3,
	                    'bottom': 3
	                }[opt.direction];

	                if (opt.absolute) {

	                    // We are taking the element's rotation into account
	                    quadrant += Math.floor((angle + 45) / 90);
	                    quadrant %= 4;
	                }

	                // Pick the corner point on the element, which meant to stay on its place before and
	                // after the rotation.
	                var fixedPoint = bbox[['bottomLeft', 'corner', 'topRight', 'origin'][quadrant]]();

	                // Find  an image of the previous indent point. This is the position, where is the
	                // point actually located on the screen.
	                var imageFixedPoint = Point(fixedPoint).rotate(bbox.center(), -angle);

	                // Every point on the element rotates around a circle with the centre of rotation
	                // in the middle of the element while the whole element is being rotated. That means
	                // that the distance from a point in the corner of the element (supposed its always rect) to
	                // the center of the element doesn't change during the rotation and therefore it equals
	                // to a distance on un-rotated element.
	                // We can find the distance as DISTANCE = (ELEMENTWIDTH/2)^2 + (ELEMENTHEIGHT/2)^2)^0.5.
	                var radius = Math.sqrt((width * width) + (height * height)) / 2;

	                // Now we are looking for an angle between x-axis and the line starting at image of fixed point
	                // and ending at the center of the element. We call this angle `alpha`.

	                // The image of a fixed point is located in n-th quadrant. For each quadrant passed
	                // going anti-clockwise we have to add 90 degrees. Note that the first quadrant has index 0.
	                //
	                // 3 | 2
	                // --c-- Quadrant positions around the element's center `c`
	                // 0 | 1
	                //
	                var alpha = quadrant * Math.PI / 2;

	                // Add an angle between the beginning of the current quadrant (line parallel with x-axis or y-axis
	                // going through the center of the element) and line crossing the indent of the fixed point and the center
	                // of the element. This is the angle we need but on the un-rotated element.
	                alpha += Math.atan(quadrant % 2 == 0 ? height / width : width / height);

	                // Lastly we have to deduct the original angle the element was rotated by and that's it.
	                alpha -= toRad(angle);

	                // With this angle and distance we can easily calculate the centre of the un-rotated element.
	                // Note that fromPolar constructor accepts an angle in radians.
	                var center = Point.fromPolar(radius, alpha, imageFixedPoint);

	                // The top left corner on the un-rotated element has to be half a width on the left
	                // and half a height to the top from the center. This will be the origin of rectangle
	                // we were looking for.
	                origin = Point(center).offset(width / -2, height / -2);

	            } else {
	                // calculation for the origin Point when there is no rotation of the element
	                origin = bbox.topLeft();

	                switch (opt.direction) {
	                    case 'top':
	                    case 'top-right':
	                        origin.offset(0, bbox.height - height);
	                        break;
	                    case 'left':
	                    case 'bottom-left':
	                        origin.offset(bbox.width -width, 0);
	                        break;
	                    case 'top-left':
	                        origin.offset(bbox.width - width, bbox.height - height);
	                        break;
	                }
	            }

	            // Resize the element (before re-positioning it).
	            this.set('size', { width: width, height: height }, opt);

	            // Finally, re-position the element.
	            this.position(origin.x, origin.y, opt);

	        } else {

	            // Resize the element.
	            this.set('size', { width: width, height: height }, opt);
	        }

	        this.stopBatch('resize', opt);

	        return this;
	    },

	    scale: function(sx, sy, origin, opt) {

	        var scaledBBox = this.getBBox().scale(sx, sy, origin);
	        this.startBatch('scale', opt);
	        this.position(scaledBBox.x, scaledBBox.y, opt);
	        this.resize(scaledBBox.width, scaledBBox.height, opt);
	        this.stopBatch('scale');
	        return this;
	    },

	    fitEmbeds: function(opt) {
	        if ( opt === void 0 ) opt = {};


	        // Getting the children's size and position requires the collection.
	        // Cell.get('embeds') helds an array of cell ids only.
	        var ref = this;
	        var graph = ref.graph;
	        if (!graph) { throw new Error('Element must be part of a graph.'); }

	        var embeddedCells = this.getEmbeddedCells().filter(function (cell) { return cell.isElement(); });
	        if (embeddedCells.length === 0) { return this; }

	        this.startBatch('fit-embeds', opt);

	        if (opt.deep) {
	            // Recursively apply fitEmbeds on all embeds first.
	            invoke(embeddedCells, 'fitEmbeds', opt);
	        }

	        // Compute cell's size and position based on the children bbox
	        // and given padding.
	        var ref$1 = normalizeSides(opt.padding);
	        var left = ref$1.left;
	        var right = ref$1.right;
	        var top = ref$1.top;
	        var bottom = ref$1.bottom;
	        var ref$2 = graph.getCellsBBox(embeddedCells);
	        var x = ref$2.x;
	        var y = ref$2.y;
	        var width = ref$2.width;
	        var height = ref$2.height;
	        // Apply padding computed above to the bbox.
	        x -= left;
	        y -= top;
	        width += left + right;
	        height += bottom + top;

	        // Set new element dimensions finally.
	        this.set({
	            position: { x: x, y: y },
	            size: { width: width, height: height }
	        }, opt);

	        this.stopBatch('fit-embeds');

	        return this;
	    },

	    // Rotate element by `angle` degrees, optionally around `origin` point.
	    // If `origin` is not provided, it is considered to be the center of the element.
	    // If `absolute` is `true`, the `angle` is considered is absolute, i.e. it is not
	    // the difference from the previous angle.
	    rotate: function(angle, absolute, origin, opt) {

	        if (origin) {

	            var center = this.getBBox().center();
	            var size = this.get('size');
	            var position = this.get('position');
	            center.rotate(origin, this.get('angle') - angle);
	            var dx = center.x - size.width / 2 - position.x;
	            var dy = center.y - size.height / 2 - position.y;
	            this.startBatch('rotate', { angle: angle, absolute: absolute, origin: origin });
	            this.position(position.x + dx, position.y + dy, opt);
	            this.rotate(angle, absolute, null, opt);
	            this.stopBatch('rotate');

	        } else {

	            this.set('angle', absolute ? angle : (this.get('angle') + angle) % 360, opt);
	        }

	        return this;
	    },

	    angle: function() {
	        return normalizeAngle(this.get('angle') || 0);
	    },

	    getBBox: function(opt) {

	        opt = opt || {};

	        if (opt.deep && this.graph) {

	            // Get all the embedded elements using breadth first algorithm,
	            // that doesn't use recursion.
	            var elements = this.getEmbeddedCells({ deep: true, breadthFirst: true });
	            // Add the model itself.
	            elements.push(this);

	            return this.graph.getCellsBBox(elements);
	        }

	        var position = this.get('position');
	        var size = this.get('size');

	        return new Rect(position.x, position.y, size.width, size.height);
	    },

	    getPointFromConnectedLink: function(link, endType) {
	        // Center of the model
	        var bbox = this.getBBox();
	        var center = bbox.center();
	        // Center of a port
	        var endDef = link.get(endType);
	        if (!endDef) { return center; }
	        var portId = endDef.port;
	        if (!portId || !this.hasPort(portId)) { return center; }
	        var portGroup = this.portProp(portId, ['group']);
	        var portsPositions = this.getPortsPositions(portGroup);
	        var portCenter = new Point(portsPositions[portId]).offset(bbox.origin());
	        var angle = this.angle();
	        if (angle) { portCenter.rotate(center, -angle); }
	        return portCenter;
	    }
	});

	assign(Element$1.prototype, elementPortPrototype);

	var GraphCells = Backbone.Collection.extend({

	    initialize: function(models, opt) {

	        // Set the optional namespace where all model classes are defined.
	        if (opt.cellNamespace) {
	            this.cellNamespace = opt.cellNamespace;
	        } else {
	            /* global joint: true */
	            this.cellNamespace = typeof joint !== 'undefined' && has$2(joint, 'shapes') ? joint.shapes : null;
	            /* global joint: false */
	        }


	        this.graph = opt.graph;
	    },

	    model: function(attrs, opt) {

	        var collection = opt.collection;
	        var namespace = collection.cellNamespace;

	        // Find the model class in the namespace or use the default one.
	        var ModelClass = (attrs.type === 'link')
	            ? Link
	            : getByPath(namespace, attrs.type, '.') || Element$1;

	        var cell = new ModelClass(attrs, opt);
	        // Add a reference to the graph. It is necessary to do this here because this is the earliest place
	        // where a new model is created from a plain JS object. For other objects, see `joint.dia.Graph>>_prepareCell()`.
	        if (!opt.dry) {
	            cell.graph = collection.graph;
	        }

	        return cell;
	    },

	    // `comparator` makes it easy to sort cells based on their `z` index.
	    comparator: function(model) {

	        return model.get('z') || 0;
	    }
	});


	var Graph = Backbone.Model.extend({

	    initialize: function(attrs, opt) {

	        opt = opt || {};

	        // Passing `cellModel` function in the options object to graph allows for
	        // setting models based on attribute objects. This is especially handy
	        // when processing JSON graphs that are in a different than JointJS format.
	        var cells = new GraphCells([], {
	            model: opt.cellModel,
	            cellNamespace: opt.cellNamespace,
	            graph: this
	        });
	        Backbone.Model.prototype.set.call(this, 'cells', cells);

	        // Make all the events fired in the `cells` collection available.
	        // to the outside world.
	        cells.on('all', this.trigger, this);

	        // Backbone automatically doesn't trigger re-sort if models attributes are changed later when
	        // they're already in the collection. Therefore, we're triggering sort manually here.
	        this.on('change:z', this._sortOnChangeZ, this);

	        // `joint.dia.Graph` keeps an internal data structure (an adjacency list)
	        // for fast graph queries. All changes that affect the structure of the graph
	        // must be reflected in the `al` object. This object provides fast answers to
	        // questions such as "what are the neighbours of this node" or "what
	        // are the sibling links of this link".

	        // Outgoing edges per node. Note that we use a hash-table for the list
	        // of outgoing edges for a faster lookup.
	        // [nodeId] -> Object [edgeId] -> true
	        this._out = {};
	        // Ingoing edges per node.
	        // [nodeId] -> Object [edgeId] -> true
	        this._in = {};
	        // `_nodes` is useful for quick lookup of all the elements in the graph, without
	        // having to go through the whole cells array.
	        // [node ID] -> true
	        this._nodes = {};
	        // `_edges` is useful for quick lookup of all the links in the graph, without
	        // having to go through the whole cells array.
	        // [edgeId] -> true
	        this._edges = {};

	        this._batches = {};

	        cells.on('add', this._restructureOnAdd, this);
	        cells.on('remove', this._restructureOnRemove, this);
	        cells.on('reset', this._restructureOnReset, this);
	        cells.on('change:source', this._restructureOnChangeSource, this);
	        cells.on('change:target', this._restructureOnChangeTarget, this);
	        cells.on('remove', this._removeCell, this);
	    },

	    _sortOnChangeZ: function() {

	        this.get('cells').sort();
	    },

	    _restructureOnAdd: function(cell) {

	        if (cell.isLink()) {
	            this._edges[cell.id] = true;
	            var ref = cell.attributes;
	            var source = ref.source;
	            var target = ref.target;
	            if (source.id) {
	                (this._out[source.id] || (this._out[source.id] = {}))[cell.id] = true;
	            }
	            if (target.id) {
	                (this._in[target.id] || (this._in[target.id] = {}))[cell.id] = true;
	            }
	        } else {
	            this._nodes[cell.id] = true;
	        }
	    },

	    _restructureOnRemove: function(cell) {

	        if (cell.isLink()) {
	            delete this._edges[cell.id];
	            var ref = cell.attributes;
	            var source = ref.source;
	            var target = ref.target;
	            if (source.id && this._out[source.id] && this._out[source.id][cell.id]) {
	                delete this._out[source.id][cell.id];
	            }
	            if (target.id && this._in[target.id] && this._in[target.id][cell.id]) {
	                delete this._in[target.id][cell.id];
	            }
	        } else {
	            delete this._nodes[cell.id];
	        }
	    },

	    _restructureOnReset: function(cells) {

	        // Normalize into an array of cells. The original `cells` is GraphCells Backbone collection.
	        cells = cells.models;

	        this._out = {};
	        this._in = {};
	        this._nodes = {};
	        this._edges = {};

	        cells.forEach(this._restructureOnAdd, this);
	    },

	    _restructureOnChangeSource: function(link) {

	        var prevSource = link.previous('source');
	        if (prevSource.id && this._out[prevSource.id]) {
	            delete this._out[prevSource.id][link.id];
	        }
	        var source = link.attributes.source;
	        if (source.id) {
	            (this._out[source.id] || (this._out[source.id] = {}))[link.id] = true;
	        }
	    },

	    _restructureOnChangeTarget: function(link) {

	        var prevTarget = link.previous('target');
	        if (prevTarget.id && this._in[prevTarget.id]) {
	            delete this._in[prevTarget.id][link.id];
	        }
	        var target = link.get('target');
	        if (target.id) {
	            (this._in[target.id] || (this._in[target.id] = {}))[link.id] = true;
	        }
	    },

	    // Return all outbound edges for the node. Return value is an object
	    // of the form: [edgeId] -> true
	    getOutboundEdges: function(node) {

	        return (this._out && this._out[node]) || {};
	    },

	    // Return all inbound edges for the node. Return value is an object
	    // of the form: [edgeId] -> true
	    getInboundEdges: function(node) {

	        return (this._in && this._in[node]) || {};
	    },

	    toJSON: function() {

	        // Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections.
	        // It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitly.
	        var json = Backbone.Model.prototype.toJSON.apply(this, arguments);
	        json.cells = this.get('cells').toJSON();
	        return json;
	    },

	    fromJSON: function(json, opt) {

	        if (!json.cells) {

	            throw new Error('Graph JSON must contain cells array.');
	        }

	        return this.set(json, opt);
	    },

	    set: function(key, val, opt) {

	        var attrs;

	        // Handle both `key`, value and {key: value} style arguments.
	        if (typeof key === 'object') {
	            attrs = key;
	            opt = val;
	        } else {
	            (attrs = {})[key] = val;
	        }

	        // Make sure that `cells` attribute is handled separately via resetCells().
	        if (attrs.hasOwnProperty('cells')) {
	            this.resetCells(attrs.cells, opt);
	            attrs = omit(attrs, 'cells');
	        }

	        // The rest of the attributes are applied via original set method.
	        return Backbone.Model.prototype.set.call(this, attrs, opt);
	    },

	    clear: function(opt) {

	        opt = assign({}, opt, { clear: true });

	        var collection = this.get('cells');

	        if (collection.length === 0) { return this; }

	        this.startBatch('clear', opt);

	        // The elements come after the links.
	        var cells = collection.sortBy(function(cell) {
	            return cell.isLink() ? 1 : 2;
	        });

	        do {

	            // Remove all the cells one by one.
	            // Note that all the links are removed first, so it's
	            // safe to remove the elements without removing the connected
	            // links first.
	            cells.shift().remove(opt);

	        } while (cells.length > 0);

	        this.stopBatch('clear');

	        return this;
	    },

	    _prepareCell: function(cell, opt) {

	        var attrs;
	        if (cell instanceof Backbone.Model) {
	            attrs = cell.attributes;
	            if (!cell.graph && (!opt || !opt.dry)) {
	                // An element can not be member of more than one graph.
	                // A cell stops being the member of the graph after it's explicitly removed.
	                cell.graph = this;
	            }
	        } else {
	            // In case we're dealing with a plain JS object, we have to set the reference
	            // to the `graph` right after the actual model is created. This happens in the `model()` function
	            // of `joint.dia.GraphCells`.
	            attrs = cell;
	        }

	        if (!isString(attrs.type)) {
	            throw new TypeError('dia.Graph: cell type must be a string.');
	        }

	        return cell;
	    },

	    minZIndex: function() {

	        var firstCell = this.get('cells').first();
	        return firstCell ? (firstCell.get('z') || 0) : 0;
	    },

	    maxZIndex: function() {

	        var lastCell = this.get('cells').last();
	        return lastCell ? (lastCell.get('z') || 0) : 0;
	    },

	    addCell: function(cell, opt) {

	        if (Array.isArray(cell)) {

	            return this.addCells(cell, opt);
	        }

	        if (cell instanceof Backbone.Model) {

	            if (!cell.has('z')) {
	                cell.set('z', this.maxZIndex() + 1);
	            }

	        } else if (cell.z === undefined) {

	            cell.z = this.maxZIndex() + 1;
	        }

	        this.get('cells').add(this._prepareCell(cell, opt), opt || {});

	        return this;
	    },

	    addCells: function(cells, opt) {

	        if (cells.length === 0) { return this; }

	        cells = flattenDeep(cells);
	        opt.maxPosition = opt.position = cells.length - 1;

	        this.startBatch('add', opt);
	        cells.forEach(function(cell) {
	            this.addCell(cell, opt);
	            opt.position--;
	        }, this);
	        this.stopBatch('add', opt);

	        return this;
	    },

	    // When adding a lot of cells, it is much more efficient to
	    // reset the entire cells collection in one go.
	    // Useful for bulk operations and optimizations.
	    resetCells: function(cells, opt) {

	        var preparedCells = toArray(cells).map(function(cell) {
	            return this._prepareCell(cell, opt);
	        }, this);
	        this.get('cells').reset(preparedCells, opt);

	        return this;
	    },

	    removeCells: function(cells, opt) {

	        if (cells.length) {

	            this.startBatch('remove');
	            invoke(cells, 'remove', opt);
	            this.stopBatch('remove');
	        }

	        return this;
	    },

	    _removeCell: function(cell, collection, options) {

	        options = options || {};

	        if (!options.clear) {
	            // Applications might provide a `disconnectLinks` option set to `true` in order to
	            // disconnect links when a cell is removed rather then removing them. The default
	            // is to remove all the associated links.
	            if (options.disconnectLinks) {

	                this.disconnectLinks(cell, options);

	            } else {

	                this.removeLinks(cell, options);
	            }
	        }
	        // Silently remove the cell from the cells collection. Silently, because
	        // `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is
	        // then propagated to the graph model. If we didn't remove the cell silently, two `remove` events
	        // would be triggered on the graph model.
	        this.get('cells').remove(cell, { silent: true });

	        if (cell.graph === this) {
	            // Remove the element graph reference only if the cell is the member of this graph.
	            cell.graph = null;
	        }
	    },

	    // Get a cell by `id`.
	    getCell: function(id) {

	        return this.get('cells').get(id);
	    },

	    getCells: function() {

	        return this.get('cells').toArray();
	    },

	    getElements: function() {

	        return this.get('cells').filter(function (cell) { return cell.isElement(); });
	    },

	    getLinks: function() {

	        return this.get('cells').filter(function (cell) { return cell.isLink(); });
	    },

	    getFirstCell: function() {

	        return this.get('cells').first();
	    },

	    getLastCell: function() {

	        return this.get('cells').last();
	    },

	    // Get all inbound and outbound links connected to the cell `model`.
	    getConnectedLinks: function(model, opt) {

	        opt = opt || {};

	        var indirect = opt.indirect;
	        var inbound = opt.inbound;
	        var outbound = opt.outbound;
	        if ((inbound === undefined) && (outbound === undefined)) {
	            inbound = outbound = true;
	        }

	        // the final array of connected link models
	        var links = [];
	        // a hash table of connected edges of the form: [edgeId] -> true
	        // used for quick lookups to check if we already added a link
	        var edges = {};

	        if (outbound) {
	            addOutbounds(this, model);
	        }
	        if (inbound) {
	            addInbounds(this, model);
	        }

	        function addOutbounds(graph, model) {
	            forIn(graph.getOutboundEdges(model.id), function(_, edge) {
	                // skip links that were already added
	                // (those must be self-loop links)
	                // (because they are inbound and outbound edges of the same two elements)
	                if (edges[edge]) { return; }
	                var link = graph.getCell(edge);
	                links.push(link);
	                edges[edge] = true;
	                if (indirect) {
	                    if (inbound) { addInbounds(graph, link); }
	                    if (outbound) { addOutbounds(graph, link); }
	                }
	            }.bind(graph));
	            if (indirect && model.isLink()) {
	                var outCell = model.getTargetCell();
	                if (outCell && outCell.isLink()) {
	                    if (!edges[outCell.id]) {
	                        links.push(outCell);
	                        addOutbounds(graph, outCell);
	                    }
	                }
	            }
	        }

	        function addInbounds(graph, model) {
	            forIn(graph.getInboundEdges(model.id), function(_, edge) {
	                // skip links that were already added
	                // (those must be self-loop links)
	                // (because they are inbound and outbound edges of the same two elements)
	                if (edges[edge]) { return; }
	                var link = graph.getCell(edge);
	                links.push(link);
	                edges[edge] = true;
	                if (indirect) {
	                    if (inbound) { addInbounds(graph, link); }
	                    if (outbound) { addOutbounds(graph, link); }
	                }
	            }.bind(graph));
	            if (indirect && model.isLink()) {
	                var inCell = model.getSourceCell();
	                if (inCell && inCell.isLink()) {
	                    if (!edges[inCell.id]) {
	                        links.push(inCell);
	                        addInbounds(graph, inCell);
	                    }
	                }
	            }
	        }

	        // if `deep` option is `true`, check also all the links that are connected to any of the descendant cells
	        if (opt.deep) {

	            var embeddedCells = model.getEmbeddedCells({ deep: true });

	            // in the first round, we collect all the embedded elements
	            var embeddedElements = {};
	            embeddedCells.forEach(function(cell) {
	                if (cell.isElement()) {
	                    embeddedElements[cell.id] = true;
	                }
	            });

	            embeddedCells.forEach(function(cell) {
	                if (cell.isLink()) { return; }
	                if (outbound) {
	                    forIn(this.getOutboundEdges(cell.id), function(exists, edge) {
	                        if (!edges[edge]) {
	                            var edgeCell = this.getCell(edge);
	                            var ref = edgeCell.attributes;
	                            var source = ref.source;
	                            var target = ref.target;
	                            var sourceId = source.id;
	                            var targetId = target.id;

	                            // if `includeEnclosed` option is falsy, skip enclosed links
	                            if (!opt.includeEnclosed
	                                && (sourceId && embeddedElements[sourceId])
	                                && (targetId && embeddedElements[targetId])) {
	                                return;
	                            }

	                            links.push(this.getCell(edge));
	                            edges[edge] = true;
	                        }
	                    }.bind(this));
	                }
	                if (inbound) {
	                    forIn(this.getInboundEdges(cell.id), function(exists, edge) {
	                        if (!edges[edge]) {
	                            var edgeCell = this.getCell(edge);
	                            var ref = edgeCell.attributes;
	                            var source = ref.source;
	                            var target = ref.target;
	                            var sourceId = source.id;
	                            var targetId = target.id;

	                            // if `includeEnclosed` option is falsy, skip enclosed links
	                            if (!opt.includeEnclosed
	                                && (sourceId && embeddedElements[sourceId])
	                                && (targetId && embeddedElements[targetId])) {
	                                return;
	                            }

	                            links.push(this.getCell(edge));
	                            edges[edge] = true;
	                        }
	                    }.bind(this));
	                }
	            }, this);
	        }

	        return links;
	    },

	    getNeighbors: function(model, opt) {

	        opt || (opt = {});

	        var inbound = opt.inbound;
	        var outbound = opt.outbound;
	        if (inbound === undefined && outbound === undefined) {
	            inbound = outbound = true;
	        }

	        var neighbors = this.getConnectedLinks(model, opt).reduce(function(res, link) {

	            var ref = link.attributes;
	            var source = ref.source;
	            var target = ref.target;
	            var loop = link.hasLoop(opt);

	            // Discard if it is a point, or if the neighbor was already added.
	            if (inbound && has$2(source, 'id') && !res[source.id]) {

	                var sourceElement = this.getCell(source.id);
	                if (sourceElement.isElement()) {
	                    if (loop || (sourceElement && sourceElement !== model && (!opt.deep || !sourceElement.isEmbeddedIn(model)))) {
	                        res[source.id] = sourceElement;
	                    }
	                }
	            }

	            // Discard if it is a point, or if the neighbor was already added.
	            if (outbound && has$2(target, 'id') && !res[target.id]) {

	                var targetElement = this.getCell(target.id);
	                if (targetElement.isElement()) {
	                    if (loop || (targetElement && targetElement !== model && (!opt.deep || !targetElement.isEmbeddedIn(model)))) {
	                        res[target.id] = targetElement;
	                    }
	                }
	            }

	            return res;
	        }.bind(this), {});

	        if (model.isLink()) {
	            if (inbound) {
	                var sourceCell = model.getSourceCell();
	                if (sourceCell && sourceCell.isElement() && !neighbors[sourceCell.id]) {
	                    neighbors[sourceCell.id] = sourceCell;
	                }
	            }
	            if (outbound) {
	                var targetCell = model.getTargetCell();
	                if (targetCell && targetCell.isElement() && !neighbors[targetCell.id]) {
	                    neighbors[targetCell.id] = targetCell;
	                }
	            }
	        }

	        return toArray(neighbors);
	    },

	    getCommonAncestor: function(/* cells */) {

	        var cellsAncestors = Array.from(arguments).map(function(cell) {

	            var ancestors = [];
	            var parentId = cell.get('parent');

	            while (parentId) {

	                ancestors.push(parentId);
	                parentId = this.getCell(parentId).get('parent');
	            }

	            return ancestors;

	        }, this);

	        cellsAncestors = cellsAncestors.sort(function(a, b) {
	            return a.length - b.length;
	        });

	        var commonAncestor = toArray(cellsAncestors.shift()).find(function(ancestor) {
	            return cellsAncestors.every(function(cellAncestors) {
	                return cellAncestors.includes(ancestor);
	            });
	        });

	        return this.getCell(commonAncestor);
	    },

	    // Find the whole branch starting at `element`.
	    // If `opt.deep` is `true`, take into account embedded elements too.
	    // If `opt.breadthFirst` is `true`, use the Breadth-first search algorithm, otherwise use Depth-first search.
	    getSuccessors: function(element, opt) {

	        opt = opt || {};
	        var res = [];
	        // Modify the options so that it includes the `outbound` neighbors only. In other words, search forwards.
	        this.search(element, function(el) {
	            if (el !== element) {
	                res.push(el);
	            }
	        }, assign({}, opt, { outbound: true }));
	        return res;
	    },

	    cloneCells: cloneCells,
	    // Clone the whole subgraph (including all the connected links whose source/target is in the subgraph).
	    // If `opt.deep` is `true`, also take into account all the embedded cells of all the subgraph cells.
	    // Return a map of the form: [original cell ID] -> [clone].
	    cloneSubgraph: function(cells, opt) {

	        var subgraph = this.getSubgraph(cells, opt);
	        return this.cloneCells(subgraph);
	    },

	    // Return `cells` and all the connected links that connect cells in the `cells` array.
	    // If `opt.deep` is `true`, return all the cells including all their embedded cells
	    // and all the links that connect any of the returned cells.
	    // For example, for a single shallow element, the result is that very same element.
	    // For two elements connected with a link: `A --- L ---> B`, the result for
	    // `getSubgraph([A, B])` is `[A, L, B]`. The same goes for `getSubgraph([L])`, the result is again `[A, L, B]`.
	    getSubgraph: function(cells, opt) {

	        opt = opt || {};

	        var subgraph = [];
	        // `cellMap` is used for a quick lookup of existence of a cell in the `cells` array.
	        var cellMap = {};
	        var elements = [];
	        var links = [];

	        toArray(cells).forEach(function(cell) {
	            if (!cellMap[cell.id]) {
	                subgraph.push(cell);
	                cellMap[cell.id] = cell;
	                if (cell.isLink()) {
	                    links.push(cell);
	                } else {
	                    elements.push(cell);
	                }
	            }

	            if (opt.deep) {
	                var embeds = cell.getEmbeddedCells({ deep: true });
	                embeds.forEach(function(embed) {
	                    if (!cellMap[embed.id]) {
	                        subgraph.push(embed);
	                        cellMap[embed.id] = embed;
	                        if (embed.isLink()) {
	                            links.push(embed);
	                        } else {
	                            elements.push(embed);
	                        }
	                    }
	                });
	            }
	        });

	        links.forEach(function(link) {
	            // For links, return their source & target (if they are elements - not points).
	            var ref = link.attributes;
	            var source = ref.source;
	            var target = ref.target;
	            if (source.id && !cellMap[source.id]) {
	                var sourceElement = this.getCell(source.id);
	                subgraph.push(sourceElement);
	                cellMap[sourceElement.id] = sourceElement;
	                elements.push(sourceElement);
	            }
	            if (target.id && !cellMap[target.id]) {
	                var targetElement = this.getCell(target.id);
	                subgraph.push(this.getCell(target.id));
	                cellMap[targetElement.id] = targetElement;
	                elements.push(targetElement);
	            }
	        }, this);

	        elements.forEach(function(element) {
	            // For elements, include their connected links if their source/target is in the subgraph;
	            var links = this.getConnectedLinks(element, opt);
	            links.forEach(function(link) {
	                var ref = link.attributes;
	                var source = ref.source;
	                var target = ref.target;
	                if (!cellMap[link.id] && source.id && cellMap[source.id] && target.id && cellMap[target.id]) {
	                    subgraph.push(link);
	                    cellMap[link.id] = link;
	                }
	            });
	        }, this);

	        return subgraph;
	    },

	    // Find all the predecessors of `element`. This is a reverse operation of `getSuccessors()`.
	    // If `opt.deep` is `true`, take into account embedded elements too.
	    // If `opt.breadthFirst` is `true`, use the Breadth-first search algorithm, otherwise use Depth-first search.
	    getPredecessors: function(element, opt) {

	        opt = opt || {};
	        var res = [];
	        // Modify the options so that it includes the `inbound` neighbors only. In other words, search backwards.
	        this.search(element, function(el) {
	            if (el !== element) {
	                res.push(el);
	            }
	        }, assign({}, opt, { inbound: true }));
	        return res;
	    },

	    // Perform search on the graph.
	    // If `opt.breadthFirst` is `true`, use the Breadth-first Search algorithm, otherwise use Depth-first search.
	    // By setting `opt.inbound` to `true`, you can reverse the direction of the search.
	    // If `opt.deep` is `true`, take into account embedded elements too.
	    // `iteratee` is a function of the form `function(element) {}`.
	    // If `iteratee` explicitly returns `false`, the searching stops.
	    search: function(element, iteratee, opt) {

	        opt = opt || {};
	        if (opt.breadthFirst) {
	            this.bfs(element, iteratee, opt);
	        } else {
	            this.dfs(element, iteratee, opt);
	        }
	    },

	    // Breadth-first search.
	    // If `opt.deep` is `true`, take into account embedded elements too.
	    // If `opt.inbound` is `true`, reverse the search direction (it's like reversing all the link directions).
	    // `iteratee` is a function of the form `function(element, distance) {}`.
	    // where `element` is the currently visited element and `distance` is the distance of that element
	    // from the root `element` passed the `bfs()`, i.e. the element we started the search from.
	    // Note that the `distance` is not the shortest or longest distance, it is simply the number of levels
	    // crossed till we visited the `element` for the first time. It is especially useful for tree graphs.
	    // If `iteratee` explicitly returns `false`, the searching stops.
	    bfs: function(element, iteratee, opt) {
	        if ( opt === void 0 ) opt = {};


	        var visited = {};
	        var distance = {};
	        var queue = [];

	        queue.push(element);
	        distance[element.id] = 0;

	        while (queue.length > 0) {
	            var next = queue.shift();
	            if (visited[next.id]) { continue; }
	            visited[next.id] = true;
	            if (iteratee.call(this, next, distance[next.id]) === false) { continue; }
	            var neighbors = this.getNeighbors(next, opt);
	            for (var i = 0, n = neighbors.length; i < n; i++) {
	                var neighbor = neighbors[i];
	                distance[neighbor.id] = distance[next.id] + 1;
	                queue.push(neighbor);
	            }
	        }
	    },

	    // Depth-first search.
	    // If `opt.deep` is `true`, take into account embedded elements too.
	    // If `opt.inbound` is `true`, reverse the search direction (it's like reversing all the link directions).
	    // `iteratee` is a function of the form `function(element, distance) {}`.
	    // If `iteratee` explicitly returns `false`, the search stops.
	    dfs: function(element, iteratee, opt) {
	        if ( opt === void 0 ) opt = {};


	        var visited = {};
	        var distance = {};
	        var queue = [];

	        queue.push(element);
	        distance[element.id] = 0;

	        while (queue.length > 0) {
	            var next = queue.pop();
	            if (visited[next.id]) { continue; }
	            visited[next.id] = true;
	            if (iteratee.call(this, next, distance[next.id]) === false) { continue; }
	            var neighbors = this.getNeighbors(next, opt);
	            var lastIndex = queue.length;
	            for (var i = 0, n = neighbors.length; i < n; i++) {
	                var neighbor = neighbors[i];
	                distance[neighbor.id] = distance[next.id] + 1;
	                queue.splice(lastIndex, 0, neighbor);
	            }
	        }
	    },

	    // Get all the roots of the graph. Time complexity: O(|V|).
	    getSources: function() {

	        var sources = [];
	        forIn(this._nodes, function(exists, node) {
	            if (!this._in[node] || isEmpty(this._in[node])) {
	                sources.push(this.getCell(node));
	            }
	        }.bind(this));
	        return sources;
	    },

	    // Get all the leafs of the graph. Time complexity: O(|V|).
	    getSinks: function() {

	        var sinks = [];
	        forIn(this._nodes, function(exists, node) {
	            if (!this._out[node] || isEmpty(this._out[node])) {
	                sinks.push(this.getCell(node));
	            }
	        }.bind(this));
	        return sinks;
	    },

	    // Return `true` if `element` is a root. Time complexity: O(1).
	    isSource: function(element) {

	        return !this._in[element.id] || isEmpty(this._in[element.id]);
	    },

	    // Return `true` if `element` is a leaf. Time complexity: O(1).
	    isSink: function(element) {

	        return !this._out[element.id] || isEmpty(this._out[element.id]);
	    },

	    // Return `true` is `elementB` is a successor of `elementA`. Return `false` otherwise.
	    isSuccessor: function(elementA, elementB) {

	        var isSuccessor = false;
	        this.search(elementA, function(element) {
	            if (element === elementB && element !== elementA) {
	                isSuccessor = true;
	                return false;
	            }
	        }, { outbound: true });
	        return isSuccessor;
	    },

	    // Return `true` is `elementB` is a predecessor of `elementA`. Return `false` otherwise.
	    isPredecessor: function(elementA, elementB) {

	        var isPredecessor = false;
	        this.search(elementA, function(element) {
	            if (element === elementB && element !== elementA) {
	                isPredecessor = true;
	                return false;
	            }
	        }, { inbound: true });
	        return isPredecessor;
	    },

	    // Return `true` is `elementB` is a neighbor of `elementA`. Return `false` otherwise.
	    // `opt.deep` controls whether to take into account embedded elements as well. See `getNeighbors()`
	    // for more details.
	    // If `opt.outbound` is set to `true`, return `true` only if `elementB` is a successor neighbor.
	    // Similarly, if `opt.inbound` is set to `true`, return `true` only if `elementB` is a predecessor neighbor.
	    isNeighbor: function(elementA, elementB, opt) {

	        opt = opt || {};

	        var inbound = opt.inbound;
	        var outbound = opt.outbound;
	        if ((inbound === undefined) && (outbound === undefined)) {
	            inbound = outbound = true;
	        }

	        var isNeighbor = false;

	        this.getConnectedLinks(elementA, opt).forEach(function(link) {

	            var ref = link.attributes;
	            var source = ref.source;
	            var target = ref.target;

	            // Discard if it is a point.
	            if (inbound && has$2(source, 'id') && (source.id === elementB.id)) {
	                isNeighbor = true;
	                return false;
	            }

	            // Discard if it is a point, or if the neighbor was already added.
	            if (outbound && has$2(target, 'id') && (target.id === elementB.id)) {
	                isNeighbor = true;
	                return false;
	            }
	        });

	        return isNeighbor;
	    },

	    // Disconnect links connected to the cell `model`.
	    disconnectLinks: function(model, opt) {

	        this.getConnectedLinks(model).forEach(function(link) {

	            link.set((link.attributes.source.id === model.id ? 'source' : 'target'), { x: 0, y: 0 }, opt);
	        });
	    },

	    // Remove links connected to the cell `model` completely.
	    removeLinks: function(model, opt) {

	        invoke(this.getConnectedLinks(model), 'remove', opt);
	    },

	    // Find all elements at given point
	    findModelsFromPoint: function(p) {

	        return this.getElements().filter(function(el) {
	            return el.getBBox().containsPoint(p);
	        });
	    },

	    // Find all elements in given area
	    findModelsInArea: function(rect$1, opt) {

	        rect$1 = rect(rect$1);
	        opt = defaults(opt || {}, { strict: false });

	        var method = opt.strict ? 'containsRect' : 'intersect';

	        return this.getElements().filter(function(el) {
	            return rect$1[method](el.getBBox());
	        });
	    },

	    // Find all elements under the given element.
	    findModelsUnderElement: function(element, opt) {

	        opt = defaults(opt || {}, { searchBy: 'bbox' });

	        var bbox = element.getBBox();
	        var elements = (opt.searchBy === 'bbox')
	            ? this.findModelsInArea(bbox)
	            : this.findModelsFromPoint(bbox[opt.searchBy]());

	        // don't account element itself or any of its descendants
	        return elements.filter(function(el) {
	            return element.id !== el.id && !el.isEmbeddedIn(element);
	        });
	    },


	    // Return bounding box of all elements.
	    getBBox: function() {

	        return this.getCellsBBox(this.getCells());
	    },

	    // Return the bounding box of all cells in array provided.
	    getCellsBBox: function(cells, opt) {
	        opt || (opt = {});
	        return toArray(cells).reduce(function(memo, cell) {
	            var rect = cell.getBBox(opt);
	            if (!rect) { return memo; }
	            var angle = cell.angle();
	            if (angle) { rect = rect.bbox(angle); }
	            if (memo) {
	                return memo.union(rect);
	            }
	            return rect;
	        }, null);
	    },

	    translate: function(dx, dy, opt) {

	        // Don't translate cells that are embedded in any other cell.
	        var cells = this.getCells().filter(function(cell) {
	            return !cell.isEmbedded();
	        });

	        invoke(cells, 'translate', dx, dy, opt);

	        return this;
	    },

	    resize: function(width, height, opt) {

	        return this.resizeCells(width, height, this.getCells(), opt);
	    },

	    resizeCells: function(width, height, cells, opt) {

	        // `getBBox` method returns `null` if no elements provided.
	        // i.e. cells can be an array of links
	        var bbox = this.getCellsBBox(cells);
	        if (bbox) {
	            var sx = Math.max(width / bbox.width, 0);
	            var sy = Math.max(height / bbox.height, 0);
	            invoke(cells, 'scale', sx, sy, bbox.origin(), opt);
	        }

	        return this;
	    },

	    startBatch: function(name, data) {

	        data = data || {};
	        this._batches[name] = (this._batches[name] || 0) + 1;

	        return this.trigger('batch:start', assign({}, data, { batchName: name }));
	    },

	    stopBatch: function(name, data) {

	        data = data || {};
	        this._batches[name] = (this._batches[name] || 0) - 1;

	        return this.trigger('batch:stop', assign({}, data, { batchName: name }));
	    },

	    hasActiveBatch: function(name) {

	        var batches = this._batches;
	        var names;

	        if (arguments.length === 0) {
	            names = Object.keys(batches);
	        } else if (Array.isArray(name)) {
	            names = name;
	        } else {
	            names = [name];
	        }

	        return names.some(function (batch) { return batches[batch] > 0; });
	    }

	}, {

	    validations: {

	        multiLinks: function(graph, link) {

	            // Do not allow multiple links to have the same source and target.
	            var ref = link.attributes;
	            var source = ref.source;
	            var target = ref.target;

	            if (source.id && target.id) {

	                var sourceModel = link.getSourceCell();
	                if (sourceModel) {

	                    var connectedLinks = graph.getConnectedLinks(sourceModel, { outbound: true });
	                    var sameLinks = connectedLinks.filter(function(_link) {

	                        var ref = _link.attributes;
	                        var _source = ref.source;
	                        var _target = ref.target;
	                        return _source && _source.id === source.id &&
	                            (!_source.port || (_source.port === source.port)) &&
	                            _target && _target.id === target.id &&
	                            (!_target.port || (_target.port === target.port));

	                    });

	                    if (sameLinks.length > 1) {
	                        return false;
	                    }
	                }
	            }

	            return true;
	        },

	        linkPinning: function(_graph, link) {
	            var ref = link.attributes;
	            var source = ref.source;
	            var target = ref.target;
	            return source.id && target.id;
	        }
	    }

	});

	wrapWith(Graph.prototype, ['resetCells', 'addCells', 'removeCells'], wrappers.cells);

	var views = {};

	var View = Backbone.View.extend({

	    options: {},
	    theme: null,
	    themeClassNamePrefix: addClassNamePrefix('theme-'),
	    requireSetThemeOverride: false,
	    defaultTheme: config.defaultTheme,
	    children: null,
	    childNodes: null,

	    DETACHABLE: true,
	    UPDATE_PRIORITY: 2,
	    FLAG_INSERT: 1<<30,
	    FLAG_REMOVE: 1<<29,

	    constructor: function(options) {

	        this.requireSetThemeOverride = options && !!options.theme;
	        this.options = assign({}, this.options, options);

	        Backbone.View.call(this, options);
	    },

	    initialize: function() {

	        views[this.cid] = this;

	        this.setTheme(this.options.theme || this.defaultTheme);
	        this.init();
	    },

	    unmount: function() {
	        if (this.svgElement) {
	            this.vel.remove();
	        } else {
	            this.$el.remove();
	        }
	    },

	    renderChildren: function(children) {
	        children || (children = result(this, 'children'));
	        if (children) {
	            var isSVG = this.svgElement;
	            var namespace = V.namespace[isSVG ? 'svg' : 'xhtml'];
	            var doc = parseDOMJSON(children, namespace);
	            (isSVG ? this.vel : this.$el).empty().append(doc.fragment);
	            this.childNodes = doc.selectors;
	        }
	        return this;
	    },

	    findAttribute: function(attributeName, node) {

	        var currentNode = node;

	        while (currentNode && currentNode.nodeType === 1) {
	            var attributeValue = currentNode.getAttribute(attributeName);
	            // attribute found
	            if (attributeValue) { return attributeValue; }
	            // do not climb up the DOM
	            if (currentNode === this.el) { return null; }
	            // try parent node
	            currentNode = currentNode.parentNode;
	        }

	        return null;
	    },

	    // Override the Backbone `_ensureElement()` method in order to create an
	    // svg element (e.g., `<g>`) node that wraps all the nodes of the Cell view.
	    // Expose class name setter as a separate method.
	    _ensureElement: function() {
	        if (!this.el) {
	            var tagName = result(this, 'tagName');
	            var attrs = assign({}, result(this, 'attributes'));
	            var style = assign({}, result(this, 'style'));
	            if (this.id) { attrs.id = result(this, 'id'); }
	            this.setElement(this._createElement(tagName));
	            this._setAttributes(attrs);
	            this._setStyle(style);
	        } else {
	            this.setElement(result(this, 'el'));
	        }
	        this._ensureElClassName();
	    },

	    _setAttributes: function(attrs) {
	        if (this.svgElement) {
	            this.vel.attr(attrs);
	        } else {
	            this.$el.attr(attrs);
	        }
	    },

	    _setStyle: function(style) {
	        this.$el.css(style);
	    },

	    _createElement: function(tagName) {
	        if (this.svgElement) {
	            return document.createElementNS(V.namespace.svg, tagName);
	        } else {
	            return document.createElement(tagName);
	        }
	    },

	    // Utilize an alternative DOM manipulation API by
	    // adding an element reference wrapped in Vectorizer.
	    _setElement: function(el) {
	        this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
	        this.el = this.$el[0];
	        if (this.svgElement) { this.vel = V(this.el); }
	    },

	    _ensureElClassName: function() {
	        var className = result(this, 'className');
	        if (!className) { return; }
	        var prefixedClassName = addClassNamePrefix(className);
	        // Note: className removal here kept for backwards compatibility only
	        if (this.svgElement) {
	            this.vel.removeClass(className).addClass(prefixedClassName);
	        } else {
	            this.$el.removeClass(className).addClass(prefixedClassName);
	        }
	    },

	    init: function() {
	        // Intentionally empty.
	        // This method is meant to be overridden.
	    },

	    onRender: function() {
	        // Intentionally empty.
	        // This method is meant to be overridden.
	    },

	    confirmUpdate: function() {
	        // Intentionally empty.
	        // This method is meant to be overridden.
	        return 0;
	    },

	    setTheme: function(theme, opt) {

	        opt = opt || {};

	        // Theme is already set, override is required, and override has not been set.
	        // Don't set the theme.
	        if (this.theme && this.requireSetThemeOverride && !opt.override) {
	            return this;
	        }

	        this.removeThemeClassName();
	        this.addThemeClassName(theme);
	        this.onSetTheme(this.theme/* oldTheme */, theme/* newTheme */);
	        this.theme = theme;

	        return this;
	    },

	    addThemeClassName: function(theme) {

	        theme = theme || this.theme;

	        var className = this.themeClassNamePrefix + theme;

	        if (this.svgElement) {
	            this.vel.addClass(className);
	        } else {
	            this.$el.addClass(className);
	        }

	        return this;
	    },

	    removeThemeClassName: function(theme) {

	        theme = theme || this.theme;

	        var className = this.themeClassNamePrefix + theme;

	        if (this.svgElement) {
	            this.vel.removeClass(className);
	        } else {
	            this.$el.removeClass(className);
	        }

	        return this;
	    },

	    onSetTheme: function(oldTheme, newTheme) {
	        // Intentionally empty.
	        // This method is meant to be overridden.
	    },

	    remove: function() {

	        this.onRemove();
	        this.undelegateDocumentEvents();

	        views[this.cid] = null;

	        Backbone.View.prototype.remove.apply(this, arguments);

	        return this;
	    },

	    onRemove: function() {
	        // Intentionally empty.
	        // This method is meant to be overridden.
	    },

	    getEventNamespace: function() {
	        // Returns a per-session unique namespace
	        return '.joint-event-ns-' + this.cid;
	    },

	    delegateElementEvents: function(element, events, data) {
	        if (!events) { return this; }
	        data || (data = {});
	        var eventNS = this.getEventNamespace();
	        for (var eventName in events) {
	            var method = events[eventName];
	            if (typeof method !== 'function') { method = this[method]; }
	            if (!method) { continue; }
	            $(element).on(eventName + eventNS, data, method.bind(this));
	        }
	        return this;
	    },

	    undelegateElementEvents: function(element) {
	        $(element).off(this.getEventNamespace());
	        return this;
	    },

	    delegateDocumentEvents: function(events, data) {
	        events || (events = result(this, 'documentEvents'));
	        return this.delegateElementEvents(document, events, data);
	    },

	    undelegateDocumentEvents: function() {
	        return this.undelegateElementEvents(document);
	    },

	    eventData: function(evt, data) {
	        if (!evt) { throw new Error('eventData(): event object required.'); }
	        var currentData = evt.data;
	        var key = '__' + this.cid + '__';
	        if (data === undefined) {
	            if (!currentData) { return {}; }
	            return currentData[key] || {};
	        }
	        currentData || (currentData = evt.data = {});
	        currentData[key] || (currentData[key] = {});
	        assign(currentData[key], data);
	        return this;
	    },

	    stopPropagation: function(evt) {
	        this.eventData(evt, { propagationStopped: true });
	        return this;
	    },

	    isPropagationStopped: function(evt) {
	        return !!this.eventData(evt).propagationStopped;
	    }

	}, {

	    extend: function() {

	        var args = Array.from(arguments);

	        // Deep clone the prototype and static properties objects.
	        // This prevents unexpected behavior where some properties are overwritten outside of this function.
	        var protoProps = args[0] && assign({}, args[0]) || {};
	        var staticProps = args[1] && assign({}, args[1]) || {};

	        // Need the real render method so that we can wrap it and call it later.
	        var renderFn = protoProps.render || (this.prototype && this.prototype.render) || null;

	        /*
	            Wrap the real render method so that:
	                .. `onRender` is always called.
	                .. `this` is always returned.
	        */
	        protoProps.render = function() {

	            if (typeof renderFn === 'function') {
	                // Call the original render method.
	                renderFn.apply(this, arguments);
	            }

	            if (this.render.__render__ === renderFn) {
	                // Should always call onRender() method.
	                // Should call it only once when renderFn is actual prototype method i.e. not the wrapper
	                this.onRender();
	            }

	            // Should always return itself.
	            return this;
	        };

	        protoProps.render.__render__ = renderFn;

	        return Backbone.View.extend.call(this, protoProps, staticProps);
	    }
	});

	var index$1 = ({
		views: views,
		View: View
	});

	function toArray$1(obj) {
	    if (!obj) { return []; }
	    if (Array.isArray(obj)) { return obj; }
	    return [obj];
	}

	var HighlighterView = View.extend({

	    tagName: 'g',
	    svgElement: true,
	    className: 'highlight',

	    HIGHLIGHT_FLAG: 1,
	    UPDATE_PRIORITY: 3,
	    DETACHABLE: false,
	    UPDATABLE: true,
	    MOUNTABLE: true,

	    cellView: null,
	    nodeSelector: null,
	    node: null,
	    updateRequested: false,
	    transformGroup: null,

	    requestUpdate: function requestUpdate(cellView, nodeSelector) {
	        var paper = cellView.paper;
	        this.cellView = cellView;
	        this.nodeSelector = nodeSelector;
	        if (paper) {
	            this.updateRequested = true;
	            paper.requestViewUpdate(this, this.HIGHLIGHT_FLAG, this.UPDATE_PRIORITY);
	        }
	    },

	    confirmUpdate: function confirmUpdate() {
	        // The cellView is now rendered/updated since it has a higher update priority.
	        this.updateRequested = false;
	        var ref = this;
	        var cellView = ref.cellView;
	        var nodeSelector = ref.nodeSelector;
	        this.update(cellView, nodeSelector);
	        this.mount();
	        this.transform();
	        return 0;
	    },

	    findNode: function findNode(cellView, nodeSelector) {
	        var assign, assign$1;

	        if ( nodeSelector === void 0 ) nodeSelector = null;
	        var el;
	        if (typeof nodeSelector === 'string') {
	            (assign = cellView.findBySelector(nodeSelector), el = assign[0]);
	        } else if (isPlainObject(nodeSelector)) {
	            var isLink = cellView.model.isLink();
	            var label = nodeSelector.label; if ( label === void 0 ) label = null;
	            var port = nodeSelector.port;
	            var selector = nodeSelector.selector;
	            if (isLink && label !== null) {
	                // Link Label Selector
	                el = cellView.findLabelNode(label, selector);
	            } else if (!isLink && port) {
	                // Element Port Selector
	                el = cellView.findPortNode(port, selector);
	            } else {
	                // Cell Selector
	                (assign$1 = cellView.findBySelector(selector), el = assign$1[0]);
	            }
	        } else if (nodeSelector) {
	            el = V.toNode(nodeSelector);
	            if (!(el instanceof SVGElement)) { el = null; }
	        }
	        return el ? el : null;
	    },

	    mount: function mount() {
	        var ref = this;
	        var MOUNTABLE = ref.MOUNTABLE;
	        var cellView = ref.cellView;
	        var el = ref.el;
	        var options = ref.options;
	        var transformGroup = ref.transformGroup;
	        if (!MOUNTABLE || transformGroup) { return; }
	        var cellViewRoot = cellView.vel;
	        var paper = cellView.paper;
	        var layerName = options.layer;
	        if (layerName) {
	            this.transformGroup = V('g')
	                .addClass('highlight-transform')
	                .append(el)
	                .appendTo(paper.getLayerNode(layerName));
	        } else {
	            // TODO: prepend vs append
	            if (!el.parentNode || el.nextSibling) {
	                // Not appended yet or not the last child
	                cellViewRoot.append(el);
	            }
	        }
	    },

	    unmount: function unmount() {
	        var ref = this;
	        var MOUNTABLE = ref.MOUNTABLE;
	        var transformGroup = ref.transformGroup;
	        var vel = ref.vel;
	        if (!MOUNTABLE) { return; }
	        if (transformGroup) {
	            this.transformGroup = null;
	            transformGroup.remove();
	        } else {
	            vel.remove();
	        }
	    },

	    transform: function transform() {
	        var ref = this;
	        var transformGroup = ref.transformGroup;
	        var cellView = ref.cellView;
	        var updateRequested = ref.updateRequested;
	        if (!transformGroup || cellView.model.isLink() || updateRequested) { return; }
	        var translateMatrix = cellView.getRootTranslateMatrix();
	        var rotateMatrix = cellView.getRootRotateMatrix();
	        var transformMatrix = translateMatrix.multiply(rotateMatrix);
	        transformGroup.attr('transform', V.matrixToTransformString(transformMatrix));
	    },

	    update: function update() {
	        var ref = this;
	        var prevNode = ref.node;
	        var cellView = ref.cellView;
	        var nodeSelector = ref.nodeSelector;
	        var updateRequested = ref.updateRequested;
	        var id = ref.id;
	        if (updateRequested) { return; }
	        var node = this.node = this.findNode(cellView, nodeSelector);
	        if (prevNode) {
	            this.unhighlight(cellView, prevNode);
	        }
	        if (node) {
	            this.highlight(cellView, node);
	            this.mount();
	        } else {
	            this.unmount();
	            cellView.notify('cell:highlight:invalid', id, this);
	        }
	    },

	    onRemove: function onRemove() {
	        var ref = this;
	        var node = ref.node;
	        var cellView = ref.cellView;
	        var id = ref.id;
	        var constructor = ref.constructor;
	        if (node) {
	            this.unhighlight(cellView, node);
	        }
	        this.unmount();
	        constructor._removeRef(cellView, id);
	    },

	    highlight: function highlight(_cellView, _node) {
	        // to be overridden
	    },

	    unhighlight: function unhighlight(_cellView, _node) {
	        // to be overridden
	    }

	}, {

	    _views: {},

	    // Used internally by CellView highlight()
	    highlight: function(cellView, node, opt) {
	        var id = this.uniqueId(node, opt);
	        this.add(cellView, node, id, opt);
	    },

	    // Used internally by CellView unhighlight()
	    unhighlight: function(cellView, node, opt) {
	        var id = this.uniqueId(node, opt);
	        this.remove(cellView, id);
	    },

	    get: function get(cellView, id) {
	        if ( id === void 0 ) id = null;

	        var cid = cellView.cid;
	        var ref$2 = this;
	        var _views = ref$2._views;
	        var refs = _views[cid];
	        if (id === null) {
	            // all highlighters
	            var views = [];
	            if (!refs) { return views; }
	            for (var hid in refs) {
	                var ref = refs[hid];
	                if (ref instanceof this) {
	                    views.push(ref);
	                }
	            }
	            return views;
	        } else {
	            // single highlighter
	            if (!refs) { return null; }
	            if (id in refs) {
	                var ref$1 = refs[id];
	                if (ref$1 instanceof this) { return ref$1; }
	            }
	            return null;
	        }
	    },

	    add: function add(cellView, nodeSelector, id, opt) {
	        if ( opt === void 0 ) opt = {};

	        if (!id) { throw new Error('dia.HighlighterView: An ID required.'); }
	        // Search the existing view amongst all the highlighters
	        var previousView = HighlighterView.get(cellView, id);
	        if (previousView) { previousView.remove(); }
	        var view = new this(opt);
	        view.id = id;
	        this._addRef(cellView, id, view);
	        view.requestUpdate(cellView, nodeSelector);
	        return view;
	    },

	    _addRef: function _addRef(cellView, id, view) {
	        var cid = cellView.cid;
	        var ref = this;
	        var _views = ref._views;
	        var refs = _views[cid];
	        if (!refs) { refs = _views[cid] = {}; }
	        refs[id] = view;
	    },

	    _removeRef: function _removeRef(cellView, id) {
	        var cid = cellView.cid;
	        var ref = this;
	        var _views = ref._views;
	        var refs = _views[cid];
	        if (!refs) { return; }
	        if (id) { delete refs[id]; }
	        for (var _ in refs) { return; }
	        delete _views[cid];
	    },

	    remove: function remove(cellView, id) {
	        if ( id === void 0 ) id = null;

	        toArray$1(this.get(cellView, id)).forEach(function (view) {
	            view.remove();
	        });
	    },

	    update: function update(cellView, id, dirty) {
	        if ( id === void 0 ) id = null;
	        if ( dirty === void 0 ) dirty = false;

	        toArray$1(this.get(cellView, id)).forEach(function (view) {
	            if (dirty || view.UPDATABLE) { view.update(); }
	        });
	    },

	    transform: function transform(cellView, id) {
	        if ( id === void 0 ) id = null;

	        toArray$1(this.get(cellView, id)).forEach(function (view) {
	            if (view.UPDATABLE) { view.transform(); }
	        });
	    },

	    uniqueId: function uniqueId(node, opt) {
	        if ( opt === void 0 ) opt = '';

	        return V.ensureId(node) + JSON.stringify(opt);
	    }

	});

	var HighlightingTypes = {
	    DEFAULT: 'default',
	    EMBEDDING: 'embedding',
	    CONNECTING: 'connecting',
	    MAGNET_AVAILABILITY: 'magnetAvailability',
	    ELEMENT_AVAILABILITY: 'elementAvailability'
	};

	// CellView base view and controller.
	// --------------------------------------------

	// This is the base view and controller for `ElementView` and `LinkView`.
	var CellView = View.extend({

	    tagName: 'g',

	    svgElement: true,

	    selector: 'root',

	    metrics: null,

	    className: function() {

	        var classNames = ['cell'];
	        var type = this.model.get('type');

	        if (type) {

	            type.toLowerCase().split('.').forEach(function(value, index, list) {
	                classNames.push('type-' + list.slice(0, index + 1).join('-'));
	            });
	        }

	        return classNames.join(' ');
	    },

	    _presentationAttributes: null,
	    _flags: null,

	    setFlags: function() {
	        var flags = {};
	        var attributes = {};
	        var shift = 0;
	        var i, n, label;
	        var presentationAttributes = result(this, 'presentationAttributes');
	        for (var attribute in presentationAttributes) {
	            if (!presentationAttributes.hasOwnProperty(attribute)) { continue; }
	            var labels = presentationAttributes[attribute];
	            if (!Array.isArray(labels)) { labels = [labels]; }
	            for (i = 0, n = labels.length; i < n; i++) {
	                label = labels[i];
	                var flag = flags[label];
	                if (!flag) {
	                    flag = flags[label] = 1<<(shift++);
	                }
	                attributes[attribute] |= flag;
	            }
	        }
	        var initFlag = result(this, 'initFlag');
	        if (!Array.isArray(initFlag)) { initFlag = [initFlag]; }
	        for (i = 0, n = initFlag.length; i < n; i++) {
	            label = initFlag[i];
	            if (!flags[label]) { flags[label] = 1<<(shift++); }
	        }

	        // 26 - 30 are reserved for paper flags
	        // 31+ overflows maximal number
	        if (shift > 25) { throw new Error('dia.CellView: Maximum number of flags exceeded.'); }

	        this._flags = flags;
	        this._presentationAttributes = attributes;
	    },

	    hasFlag: function(flag, label) {
	        return flag & this.getFlag(label);
	    },

	    removeFlag: function(flag, label) {
	        return flag ^ (flag & this.getFlag(label));
	    },

	    getFlag: function(label) {
	        var flags = this._flags;
	        if (!flags) { return 0; }
	        var flag = 0;
	        if (Array.isArray(label)) {
	            for (var i = 0, n = label.length; i < n; i++) { flag |= flags[label[i]]; }
	        } else {
	            flag |= flags[label];
	        }
	        return flag;
	    },

	    attributes: function() {
	        var cell = this.model;
	        return {
	            'model-id': cell.id,
	            'data-type': cell.attributes.type
	        };
	    },

	    constructor: function(options) {

	        // Make sure a global unique id is assigned to this view. Store this id also to the properties object.
	        // The global unique id makes sure that the same view can be rendered on e.g. different machines and
	        // still be associated to the same object among all those clients. This is necessary for real-time
	        // collaboration mechanism.
	        options.id = options.id || guid(this);

	        View.call(this, options);
	    },

	    initialize: function() {

	        this.setFlags();

	        View.prototype.initialize.apply(this, arguments);

	        this.cleanNodesCache();

	        // Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree.
	        this.$el.data('view', this);

	        this.startListening();
	    },

	    startListening: function() {
	        this.listenTo(this.model, 'change', this.onAttributesChange);
	    },

	    onAttributesChange: function(model, opt) {
	        var flag = model.getChangeFlag(this._presentationAttributes);
	        if (opt.updateHandled || !flag) { return; }
	        if (opt.dirty && this.hasFlag(flag, 'UPDATE')) { flag |= this.getFlag('RENDER'); }
	        // TODO: tool changes does not need to be sync
	        // Fix Segments tools
	        if (opt.tool) { opt.async = false; }
	        this.requestUpdate(flag, opt);
	    },

	    requestUpdate: function(flags, opt) {
	        var ref = this;
	        var paper = ref.paper;
	        if (paper && flags > 0) {
	            paper.requestViewUpdate(this, flags, this.UPDATE_PRIORITY, opt);
	        }
	    },

	    parseDOMJSON: function(markup, root) {

	        var doc = parseDOMJSON(markup);
	        var selectors = doc.selectors;
	        var groups = doc.groupSelectors;
	        for (var group in groups) {
	            if (selectors[group]) { throw new Error('dia.CellView: ambiguous group selector'); }
	            selectors[group] = groups[group];
	        }
	        if (root) {
	            var rootSelector = this.selector;
	            if (selectors[rootSelector]) { throw new Error('dia.CellView: ambiguous root selector.'); }
	            selectors[rootSelector] = root;
	        }
	        return { fragment: doc.fragment, selectors: selectors };
	    },

	    // Return `true` if cell link is allowed to perform a certain UI `feature`.
	    // Example: `can('vertexMove')`, `can('labelMove')`.
	    can: function(feature) {

	        var interactive = isFunction(this.options.interactive)
	            ? this.options.interactive(this)
	            : this.options.interactive;

	        return (isObject$1(interactive) && interactive[feature] !== false) ||
	            (isBoolean(interactive) && interactive !== false);
	    },

	    findBySelector: function(selector, root, selectors) {

	        root || (root = this.el);
	        selectors || (selectors = this.selectors);

	        // These are either descendants of `this.$el` of `this.$el` itself.
	        // `.` is a special selector used to select the wrapping `<g>` element.
	        if (!selector || selector === '.') { return [root]; }
	        if (selectors) {
	            var nodes = selectors[selector];
	            if (nodes) {
	                if (Array.isArray(nodes)) { return nodes; }
	                return [nodes];
	            }
	        }

	        // Maintaining backwards compatibility
	        // e.g. `circle:first` would fail with querySelector() call
	        if (config.useCSSSelectors) { return $(root).find(selector).toArray(); }

	        return [];
	    },

	    notify: function(eventName) {

	        if (this.paper) {

	            var args = Array.prototype.slice.call(arguments, 1);

	            // Trigger the event on both the element itself and also on the paper.
	            this.trigger.apply(this, [eventName].concat(args));

	            // Paper event handlers receive the view object as the first argument.
	            this.paper.trigger.apply(this.paper, [eventName, this].concat(args));
	        }
	    },

	    getBBox: function(opt) {

	        var bbox;
	        if (opt && opt.useModelGeometry) {
	            var model = this.model;
	            bbox = model.getBBox().bbox(model.angle());
	        } else {
	            bbox = this.getNodeBBox(this.el);
	        }

	        return this.paper.localToPaperRect(bbox);
	    },

	    getNodeBBox: function(magnet) {

	        var rect = this.getNodeBoundingRect(magnet);
	        var magnetMatrix = this.getNodeMatrix(magnet);
	        var translateMatrix = this.getRootTranslateMatrix();
	        var rotateMatrix = this.getRootRotateMatrix();
	        return V.transformRect(rect, translateMatrix.multiply(rotateMatrix).multiply(magnetMatrix));
	    },

	    getNodeUnrotatedBBox: function(magnet) {

	        var rect = this.getNodeBoundingRect(magnet);
	        var magnetMatrix = this.getNodeMatrix(magnet);
	        var translateMatrix = this.getRootTranslateMatrix();
	        return V.transformRect(rect, translateMatrix.multiply(magnetMatrix));
	    },

	    getRootTranslateMatrix: function() {

	        var model = this.model;
	        var position = model.position();
	        var mt = V.createSVGMatrix().translate(position.x, position.y);
	        return mt;
	    },

	    getRootRotateMatrix: function() {

	        var mr = V.createSVGMatrix();
	        var model = this.model;
	        var angle = model.angle();
	        if (angle) {
	            var bbox = model.getBBox();
	            var cx = bbox.width / 2;
	            var cy = bbox.height / 2;
	            mr = mr.translate(cx, cy).rotate(angle).translate(-cx, -cy);
	        }
	        return mr;
	    },

	    _notifyHighlight: function(eventName, el, opt) {
	        var assign, assign$1;

	        if ( opt === void 0 ) opt = {};
	        var ref = this;
	        var rootNode = ref.el;
	        var node;
	        if (typeof el === 'string') {
	            (assign = this.findBySelector(el), node = assign[0], node = node === void 0 ? rootNode : node);
	        } else {
	            (assign$1 = this.$(el), node = assign$1[0], node = node === void 0 ? rootNode : node);
	        }
	        // set partial flag if the highlighted element is not the entire view.
	        opt.partial = (node !== rootNode);
	        // translate type flag into a type string
	        if (opt.type === undefined) {
	            var type;
	            switch (true) {
	                case opt.embedding:
	                    type = HighlightingTypes.EMBEDDING;
	                    break;
	                case opt.connecting:
	                    type = HighlightingTypes.CONNECTING;
	                    break;
	                case opt.magnetAvailability:
	                    type = HighlightingTypes.MAGNET_AVAILABILITY;
	                    break;
	                case opt.elementAvailability:
	                    type = HighlightingTypes.ELEMENT_AVAILABILITY;
	                    break;
	                default:
	                    type = HighlightingTypes.DEFAULT;
	                    break;
	            }
	            opt.type = type;
	        }
	        this.notify(eventName, node, opt);
	        return this;
	    },

	    highlight: function(el, opt) {
	        return this._notifyHighlight('cell:highlight', el, opt);
	    },

	    unhighlight: function(el, opt) {
	        if ( opt === void 0 ) opt = {};

	        return this._notifyHighlight('cell:unhighlight', el, opt);
	    },

	    // Find the closest element that has the `magnet` attribute set to `true`. If there was not such
	    // an element found, return the root element of the cell view.
	    findMagnet: function(el) {

	        var root = this.el;
	        var magnet = this.$(el)[0];
	        if (!magnet) {
	            magnet = root;
	        }

	        do {
	            var magnetAttribute = magnet.getAttribute('magnet');
	            var isMagnetRoot = (magnet === root);
	            if ((magnetAttribute || isMagnetRoot) && magnetAttribute !== 'false') {
	                return magnet;
	            }
	            if (isMagnetRoot) {
	                // If the overall cell has set `magnet === false`, then return `undefined` to
	                // announce there is no magnet found for this cell.
	                // This is especially useful to set on cells that have 'ports'. In this case,
	                // only the ports have set `magnet === true` and the overall element has `magnet === false`.
	                return undefined;
	            }
	            magnet = magnet.parentNode;
	        } while (magnet);

	        return undefined;
	    },

	    findProxyNode: function(el, type) {
	        el || (el = this.el);
	        var nodeSelector = el.getAttribute((type + "-selector"));
	        if (nodeSelector) {
	            var ref = this.findBySelector(nodeSelector);
	            var proxyNode = ref[0];
	            if (proxyNode) { return proxyNode; }
	        }
	        return el;
	    },

	    // Construct a unique selector for the `el` element within this view.
	    // `prevSelector` is being collected through the recursive call.
	    // No value for `prevSelector` is expected when using this method.
	    getSelector: function(el, prevSelector) {

	        var selector;

	        if (el === this.el) {
	            if (typeof prevSelector === 'string') { selector = '> ' + prevSelector; }
	            return selector;
	        }

	        if (el) {

	            var nthChild = V(el).index() + 1;
	            selector = el.tagName + ':nth-child(' + nthChild + ')';

	            if (prevSelector) {
	                selector += ' > ' + prevSelector;
	            }

	            selector = this.getSelector(el.parentNode, selector);
	        }

	        return selector;
	    },

	    addLinkFromMagnet: function(magnet, x, y) {

	        var paper = this.paper;
	        var graph = paper.model;

	        var link = paper.getDefaultLink(this, magnet);
	        link.set({
	            source: this.getLinkEnd(magnet, x, y, link, 'source'),
	            target: { x: x, y: y }
	        }).addTo(graph, {
	            async: false,
	            ui: true
	        });

	        return link.findView(paper);
	    },

	    getLinkEnd: function(magnet) {
	        var ref;

	        var args = [], len = arguments.length - 1;
	        while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];

	        var model = this.model;
	        var id = model.id;
	        var port = this.findAttribute('port', magnet);
	        // Find a unique `selector` of the element under pointer that is a magnet.
	        var selector = magnet.getAttribute('joint-selector');

	        var end = { id: id };
	        if (selector != null) { end.magnet = selector; }
	        if (port != null) {
	            end.port = port;
	            if (!model.hasPort(port) && !selector) {
	                // port created via the `port` attribute (not API)
	                end.selector = this.getSelector(magnet);
	            }
	        } else if (selector == null && this.el !== magnet) {
	            end.selector = this.getSelector(magnet);
	        }

	        return (ref = this).customizeLinkEnd.apply(ref, [ end, magnet ].concat( args ));
	    },

	    customizeLinkEnd: function(end, magnet, x, y, link, endType) {
	        var ref = this;
	        var paper = ref.paper;
	        var ref$1 = paper.options;
	        var connectionStrategy = ref$1.connectionStrategy;
	        if (typeof connectionStrategy === 'function') {
	            var strategy = connectionStrategy.call(paper, end, this, magnet, new Point(x, y), link, endType, paper);
	            if (strategy) { return strategy; }
	        }
	        return end;
	    },

	    getMagnetFromLinkEnd: function(end) {

	        var root = this.el;
	        var port = end.port;
	        var selector = end.magnet;
	        var model = this.model;
	        var magnet;
	        if (port != null && model.isElement() && model.hasPort(port)) {
	            magnet = this.findPortNode(port, selector) || root;
	        } else {
	            if (!selector) { selector = end.selector; }
	            if (!selector && port != null) {
	                // link end has only `id` and `port` property referencing
	                // a port created via the `port` attribute (not API).
	                selector = '[port="' + port + '"]';
	            }
	            magnet = this.findBySelector(selector, root, this.selectors)[0];
	        }

	        return this.findProxyNode(magnet, 'magnet');
	    },

	    dragLinkStart: function(evt, magnet, x, y) {
	        this.model.startBatch('add-link');
	        var linkView = this.addLinkFromMagnet(magnet, x, y);
	        // backwards compatibility events
	        linkView.notifyPointerdown(evt, x, y);
	        linkView.eventData(evt, linkView.startArrowheadMove('target', { whenNotAllowed: 'remove' }));
	        this.eventData(evt, { linkView: linkView });
	    },

	    dragLink: function(evt, x, y) {
	        var data = this.eventData(evt);
	        var linkView = data.linkView;
	        if (linkView) {
	            linkView.pointermove(evt, x, y);
	        } else {
	            var paper = this.paper;
	            var magnetThreshold = paper.options.magnetThreshold;
	            var currentTarget = this.getEventTarget(evt);
	            var targetMagnet = data.targetMagnet;
	            if (magnetThreshold === 'onleave') {
	                // magnetThreshold when the pointer leaves the magnet
	                if (targetMagnet === currentTarget || V(targetMagnet).contains(currentTarget)) { return; }
	            } else {
	                // magnetThreshold defined as a number of movements
	                if (paper.eventData(evt).mousemoved <= magnetThreshold) { return; }
	            }
	            this.dragLinkStart(evt, targetMagnet, x, y);
	        }
	    },

	    dragLinkEnd: function(evt, x, y) {
	        var data = this.eventData(evt);
	        var linkView = data.linkView;
	        if (!linkView) { return; }
	        linkView.pointerup(evt, x, y);
	        this.model.stopBatch('add-link');
	    },

	    getAttributeDefinition: function(attrName) {

	        return this.model.constructor.getAttributeDefinition(attrName);
	    },

	    setNodeAttributes: function(node, attrs) {

	        if (!isEmpty(attrs)) {
	            if (node instanceof SVGElement) {
	                V(node).attr(attrs);
	            } else {
	                $(node).attr(attrs);
	            }
	        }
	    },

	    processNodeAttributes: function(node, attrs) {

	        var attrName, attrVal, def, i, n;
	        var normalAttrs, setAttrs, positionAttrs, offsetAttrs;
	        var relatives = [];
	        // divide the attributes between normal and special
	        for (attrName in attrs) {
	            if (!attrs.hasOwnProperty(attrName)) { continue; }
	            attrVal = attrs[attrName];
	            def = this.getAttributeDefinition(attrName);
	            if (def && (!isFunction(def.qualify) || def.qualify.call(this, attrVal, node, attrs))) {
	                if (isString(def.set)) {
	                    normalAttrs || (normalAttrs = {});
	                    normalAttrs[def.set] = attrVal;
	                }
	                if (attrVal !== null) {
	                    relatives.push(attrName, def);
	                }
	            } else {
	                normalAttrs || (normalAttrs = {});
	                normalAttrs[toKebabCase(attrName)] = attrVal;
	            }
	        }

	        // handle the rest of attributes via related method
	        // from the special attributes namespace.
	        for (i = 0, n = relatives.length; i < n; i+=2) {
	            attrName = relatives[i];
	            def = relatives[i+1];
	            attrVal = attrs[attrName];
	            if (isFunction(def.set)) {
	                setAttrs || (setAttrs = {});
	                setAttrs[attrName] = attrVal;
	            }
	            if (isFunction(def.position)) {
	                positionAttrs || (positionAttrs = {});
	                positionAttrs[attrName] = attrVal;
	            }
	            if (isFunction(def.offset)) {
	                offsetAttrs || (offsetAttrs = {});
	                offsetAttrs[attrName] = attrVal;
	            }
	        }

	        return {
	            raw: attrs,
	            normal: normalAttrs,
	            set: setAttrs,
	            position: positionAttrs,
	            offset: offsetAttrs
	        };
	    },

	    updateRelativeAttributes: function(node, attrs, refBBox, opt) {

	        opt || (opt = {});

	        var attrName, attrVal, def;
	        var rawAttrs = attrs.raw || {};
	        var nodeAttrs = attrs.normal || {};
	        var setAttrs = attrs.set;
	        var positionAttrs = attrs.position;
	        var offsetAttrs = attrs.offset;

	        for (attrName in setAttrs) {
	            attrVal = setAttrs[attrName];
	            def = this.getAttributeDefinition(attrName);
	            // SET - set function should return attributes to be set on the node,
	            // which will affect the node dimensions based on the reference bounding
	            // box. e.g. `width`, `height`, `d`, `rx`, `ry`, `points
	            var setResult = def.set.call(this, attrVal, refBBox.clone(), node, rawAttrs);
	            if (isObject$1(setResult)) {
	                assign(nodeAttrs, setResult);
	            } else if (setResult !== undefined) {
	                nodeAttrs[attrName] = setResult;
	            }
	        }

	        if (node instanceof HTMLElement) {
	            // TODO: setting the `transform` attribute on HTMLElements
	            // via `node.style.transform = 'matrix(...)';` would introduce
	            // a breaking change (e.g. basic.TextBlock).
	            this.setNodeAttributes(node, nodeAttrs);
	            return;
	        }

	        // The final translation of the subelement.
	        var nodeTransform = nodeAttrs.transform;
	        var nodeMatrix = V.transformStringToMatrix(nodeTransform);
	        var nodePosition = Point(nodeMatrix.e, nodeMatrix.f);
	        if (nodeTransform) {
	            nodeAttrs = omit(nodeAttrs, 'transform');
	            nodeMatrix.e = nodeMatrix.f = 0;
	        }

	        // Calculate node scale determined by the scalable group
	        // only if later needed.
	        var sx, sy, translation;
	        if (positionAttrs || offsetAttrs) {
	            var nodeScale = this.getNodeScale(node, opt.scalableNode);
	            sx = nodeScale.sx;
	            sy = nodeScale.sy;
	        }

	        var positioned = false;
	        for (attrName in positionAttrs) {
	            attrVal = positionAttrs[attrName];
	            def = this.getAttributeDefinition(attrName);
	            // POSITION - position function should return a point from the
	            // reference bounding box. The default position of the node is x:0, y:0 of
	            // the reference bounding box or could be further specify by some
	            // SVG attributes e.g. `x`, `y`
	            translation = def.position.call(this, attrVal, refBBox.clone(), node, rawAttrs);
	            if (translation) {
	                nodePosition.offset(Point(translation).scale(sx, sy));
	                positioned || (positioned = true);
	            }
	        }

	        // The node bounding box could depend on the `size` set from the previous loop.
	        // Here we know, that all the size attributes have been already set.
	        this.setNodeAttributes(node, nodeAttrs);

	        var offseted = false;
	        if (offsetAttrs) {
	            // Check if the node is visible
	            var nodeBoundingRect = this.getNodeBoundingRect(node);
	            if (nodeBoundingRect.width > 0 && nodeBoundingRect.height > 0) {
	                var nodeBBox = V.transformRect(nodeBoundingRect, nodeMatrix).scale(1 / sx, 1 / sy);
	                for (attrName in offsetAttrs) {
	                    attrVal = offsetAttrs[attrName];
	                    def = this.getAttributeDefinition(attrName);
	                    // OFFSET - offset function should return a point from the element
	                    // bounding box. The default offset point is x:0, y:0 (origin) or could be further
	                    // specify with some SVG attributes e.g. `text-anchor`, `cx`, `cy`
	                    translation = def.offset.call(this, attrVal, nodeBBox, node, rawAttrs);
	                    if (translation) {
	                        nodePosition.offset(Point(translation).scale(sx, sy));
	                        offseted || (offseted = true);
	                    }
	                }
	            }
	        }

	        // Do not touch node's transform attribute if there is no transformation applied.
	        if (nodeTransform !== undefined || positioned || offseted) {
	            // Round the coordinates to 1 decimal point.
	            nodePosition.round(1);
	            nodeMatrix.e = nodePosition.x;
	            nodeMatrix.f = nodePosition.y;
	            node.setAttribute('transform', V.matrixToTransformString(nodeMatrix));
	            // TODO: store nodeMatrix metrics?
	        }
	    },

	    getNodeScale: function(node, scalableNode) {

	        // Check if the node is a descendant of the scalable group.
	        var sx, sy;
	        if (scalableNode && scalableNode.contains(node)) {
	            var scale = scalableNode.scale();
	            sx = 1 / scale.sx;
	            sy = 1 / scale.sy;
	        } else {
	            sx = 1;
	            sy = 1;
	        }

	        return { sx: sx, sy: sy };
	    },

	    cleanNodesCache: function() {
	        this.metrics = {};
	    },

	    nodeCache: function(magnet) {

	        var metrics = this.metrics;
	        // Don't use cache? It most likely a custom view with overridden update.
	        if (!metrics) { return {}; }
	        var id = V.ensureId(magnet);
	        var value = metrics[id];
	        if (!value) { value = metrics[id] = {}; }
	        return value;
	    },

	    getNodeData: function(magnet) {

	        var metrics = this.nodeCache(magnet);
	        if (!metrics.data) { metrics.data = {}; }
	        return metrics.data;
	    },

	    getNodeBoundingRect: function(magnet) {

	        var metrics = this.nodeCache(magnet);
	        if (metrics.boundingRect === undefined) { metrics.boundingRect = V(magnet).getBBox(); }
	        return new Rect(metrics.boundingRect);
	    },

	    getNodeMatrix: function(magnet) {

	        var metrics = this.nodeCache(magnet);
	        if (metrics.magnetMatrix === undefined) {
	            var target = this.rotatableNode || this.el;
	            metrics.magnetMatrix = V(magnet).getTransformToElement(target);
	        }
	        return V.createSVGMatrix(metrics.magnetMatrix);
	    },

	    getNodeShape: function(magnet) {

	        var metrics = this.nodeCache(magnet);
	        if (metrics.geometryShape === undefined) { metrics.geometryShape = V(magnet).toGeometryShape(); }
	        return metrics.geometryShape.clone();
	    },

	    isNodeConnection: function(node) {
	        return this.model.isLink() && (!node || node === this.el);
	    },

	    findNodesAttributes: function(attrs, root, selectorCache, selectors) {

	        var i, n, nodeAttrs, nodeId;
	        var nodesAttrs = {};
	        var mergeIds = [];
	        for (var selector in attrs) {
	            if (!attrs.hasOwnProperty(selector)) { continue; }
	            nodeAttrs = attrs[selector];
	            if (!isPlainObject(nodeAttrs)) { continue; } // Not a valid selector-attributes pair
	            var selected = selectorCache[selector] = this.findBySelector(selector, root, selectors);
	            for (i = 0, n = selected.length; i < n; i++) {
	                var node = selected[i];
	                nodeId = V.ensureId(node);
	                // "unique" selectors are selectors that referencing a single node (defined by `selector`)
	                // groupSelector referencing a single node is not "unique"
	                var unique = (selectors && selectors[selector] === node);
	                var prevNodeAttrs = nodesAttrs[nodeId];
	                if (prevNodeAttrs) {
	                    // Note, that nodes referenced by deprecated `CSS selectors` are not taken into account.
	                    // e.g. css:`.circle` and selector:`circle` can be applied in a random order
	                    if (!prevNodeAttrs.array) {
	                        mergeIds.push(nodeId);
	                        prevNodeAttrs.array = true;
	                        prevNodeAttrs.attributes = [prevNodeAttrs.attributes];
	                        prevNodeAttrs.selectedLength = [prevNodeAttrs.selectedLength];
	                    }
	                    var attributes = prevNodeAttrs.attributes;
	                    var selectedLength = prevNodeAttrs.selectedLength;
	                    if (unique) {
	                        // node referenced by `selector`
	                        attributes.unshift(nodeAttrs);
	                        selectedLength.unshift(-1);
	                    } else {
	                        // node referenced by `groupSelector`
	                        var sortIndex = sortedIndex(selectedLength, n);
	                        attributes.splice(sortIndex, 0, nodeAttrs);
	                        selectedLength.splice(sortIndex, 0, n);
	                    }
	                } else {
	                    nodesAttrs[nodeId] = {
	                        attributes: nodeAttrs,
	                        selectedLength: unique ? -1 : n,
	                        node: node,
	                        array: false
	                    };
	                }
	            }
	        }

	        for (i = 0, n = mergeIds.length; i < n; i++) {
	            nodeId = mergeIds[i];
	            nodeAttrs = nodesAttrs[nodeId];
	            nodeAttrs.attributes = merge.apply(void 0, [ {} ].concat( nodeAttrs.attributes.reverse() ));
	        }

	        return nodesAttrs;
	    },

	    getEventTarget: function(evt, opt) {
	        if ( opt === void 0 ) opt = {};

	        // Touchmove/Touchend event's target is not reflecting the element under the coordinates as mousemove does.
	        // It holds the element when a touchstart triggered.
	        var target = evt.target;
	        var type = evt.type;
	        var clientX = evt.clientX; if ( clientX === void 0 ) clientX = 0;
	        var clientY = evt.clientY; if ( clientY === void 0 ) clientY = 0;
	        if (opt.fromPoint || type === 'touchmove' || type === 'touchend') {
	            return document.elementFromPoint(clientX, clientY);
	        }

	        return target;
	    },

	    // Default is to process the `model.attributes.attrs` object and set attributes on subelements based on the selectors,
	    // unless `attrs` parameter was passed.
	    updateDOMSubtreeAttributes: function(rootNode, attrs, opt) {

	        opt || (opt = {});
	        opt.rootBBox || (opt.rootBBox = Rect());
	        opt.selectors || (opt.selectors = this.selectors); // selector collection to use

	        // Cache table for query results and bounding box calculation.
	        // Note that `selectorCache` needs to be invalidated for all
	        // `updateAttributes` calls, as the selectors might pointing
	        // to nodes designated by an attribute or elements dynamically
	        // created.
	        var selectorCache = {};
	        var bboxCache = {};
	        var relativeItems = [];
	        var relativeRefItems = [];
	        var item, node, nodeAttrs, nodeData, processedAttrs;

	        var roAttrs = opt.roAttributes;
	        var nodesAttrs = this.findNodesAttributes(roAttrs || attrs, rootNode, selectorCache, opt.selectors);
	        // `nodesAttrs` are different from all attributes, when
	        // rendering only  attributes sent to this method.
	        var nodesAllAttrs = (roAttrs)
	            ? this.findNodesAttributes(attrs, rootNode, selectorCache, opt.selectors)
	            : nodesAttrs;

	        for (var nodeId in nodesAttrs) {
	            nodeData = nodesAttrs[nodeId];
	            nodeAttrs = nodeData.attributes;
	            node = nodeData.node;
	            processedAttrs = this.processNodeAttributes(node, nodeAttrs);

	            if (!processedAttrs.set && !processedAttrs.position && !processedAttrs.offset) {
	                // Set all the normal attributes right on the SVG/HTML element.
	                this.setNodeAttributes(node, processedAttrs.normal);

	            } else {

	                var nodeAllAttrs = nodesAllAttrs[nodeId] && nodesAllAttrs[nodeId].attributes;
	                var refSelector = (nodeAllAttrs && (nodeAttrs.ref === undefined))
	                    ? nodeAllAttrs.ref
	                    : nodeAttrs.ref;

	                var refNode;
	                if (refSelector) {
	                    refNode = (selectorCache[refSelector] || this.findBySelector(refSelector, rootNode, opt.selectors))[0];
	                    if (!refNode) {
	                        throw new Error('dia.CellView: "' + refSelector + '" reference does not exist.');
	                    }
	                } else {
	                    refNode = null;
	                }

	                item = {
	                    node: node,
	                    refNode: refNode,
	                    processedAttributes: processedAttrs,
	                    allAttributes: nodeAllAttrs
	                };

	                if (refNode) {
	                    // If an element in the list is positioned relative to this one, then
	                    // we want to insert this one before it in the list.
	                    var itemIndex = relativeRefItems.findIndex(function(item) {
	                        return item.refNode === node;
	                    });

	                    if (itemIndex > -1) {
	                        relativeRefItems.splice(itemIndex, 0, item);
	                    } else {
	                        relativeRefItems.push(item);
	                    }
	                } else {
	                    // A node with no ref attribute. To be updated before the nodes referencing other nodes.
	                    // The order of no-ref-items is not specified/important.
	                    relativeItems.push(item);
	                }
	            }
	        }

	        relativeItems.push.apply(relativeItems, relativeRefItems);

	        var rotatableMatrix;
	        for (var i = 0, n = relativeItems.length; i < n; i++) {
	            item = relativeItems[i];
	            node = item.node;
	            refNode = item.refNode;

	            // Find the reference element bounding box. If no reference was provided, we
	            // use the optional bounding box.
	            var vRotatable = V(opt.rotatableNode);
	            var refNodeId = refNode ? V.ensureId(refNode) : '';
	            var isRefNodeRotatable = !!vRotatable && !!refNode && vRotatable.contains(refNode);
	            var unrotatedRefBBox = bboxCache[refNodeId];
	            if (!unrotatedRefBBox) {
	                // Get the bounding box of the reference element relative to the `rotatable` `<g>` (without rotation)
	                // or to the root `<g>` element if no rotatable group present if reference node present.
	                // Uses the bounding box provided.
	                var transformationTarget = (isRefNodeRotatable) ? vRotatable : rootNode;
	                unrotatedRefBBox = bboxCache[refNodeId] = (refNode)
	                    ? V(refNode).getBBox({ target: transformationTarget })
	                    : opt.rootBBox;
	            }

	            if (roAttrs) {
	                // if there was a special attribute affecting the position amongst passed-in attributes
	                // we have to merge it with the rest of the element's attributes as they are necessary
	                // to update the position relatively (i.e `ref-x` && 'ref-dx')
	                processedAttrs = this.processNodeAttributes(node, item.allAttributes);
	                this.mergeProcessedAttributes(processedAttrs, item.processedAttributes);

	            } else {
	                processedAttrs = item.processedAttributes;
	            }

	            var refBBox = unrotatedRefBBox;
	            if (isRefNodeRotatable && !vRotatable.contains(node)) {
	                // if the referenced node is inside the rotatable group while the updated node is outside,
	                // we need to take the rotatable node transformation into account
	                if (!rotatableMatrix) { rotatableMatrix = V.transformStringToMatrix(vRotatable.attr('transform')); }
	                refBBox = V.transformRect(unrotatedRefBBox, rotatableMatrix);
	            }

	            this.updateRelativeAttributes(node, processedAttrs, refBBox, opt);
	        }
	    },

	    mergeProcessedAttributes: function(processedAttrs, roProcessedAttrs) {

	        processedAttrs.set || (processedAttrs.set = {});
	        processedAttrs.position || (processedAttrs.position = {});
	        processedAttrs.offset || (processedAttrs.offset = {});

	        assign(processedAttrs.set, roProcessedAttrs.set);
	        assign(processedAttrs.position, roProcessedAttrs.position);
	        assign(processedAttrs.offset, roProcessedAttrs.offset);

	        // Handle also the special transform property.
	        var transform = processedAttrs.normal && processedAttrs.normal.transform;
	        if (transform !== undefined && roProcessedAttrs.normal) {
	            roProcessedAttrs.normal.transform = transform;
	        }
	        processedAttrs.normal = roProcessedAttrs.normal;
	    },

	    onRemove: function() {
	        this.removeTools();
	        this.removeHighlighters();
	    },

	    _toolsView: null,

	    hasTools: function(name) {
	        var toolsView = this._toolsView;
	        if (!toolsView) { return false; }
	        if (!name) { return true; }
	        return (toolsView.getName() === name);
	    },

	    addTools: function(toolsView) {

	        this.removeTools();

	        if (toolsView) {
	            this._toolsView = toolsView;
	            toolsView.configure({ relatedView: this });
	            toolsView.listenTo(this.paper, 'tools:event', this.onToolEvent.bind(this));
	        }
	        return this;
	    },

	    updateTools: function(opt) {

	        var toolsView = this._toolsView;
	        if (toolsView) { toolsView.update(opt); }
	        return this;
	    },

	    removeTools: function() {

	        var toolsView = this._toolsView;
	        if (toolsView) {
	            toolsView.remove();
	            this._toolsView = null;
	        }
	        return this;
	    },

	    hideTools: function() {

	        var toolsView = this._toolsView;
	        if (toolsView) { toolsView.hide(); }
	        return this;
	    },

	    showTools: function() {

	        var toolsView = this._toolsView;
	        if (toolsView) { toolsView.show(); }
	        return this;
	    },

	    onToolEvent: function(event) {
	        switch (event) {
	            case 'remove':
	                this.removeTools();
	                break;
	            case 'hide':
	                this.hideTools();
	                break;
	            case 'show':
	                this.showTools();
	                break;
	        }
	    },

	    removeHighlighters: function() {
	        HighlighterView.remove(this);
	    },

	    updateHighlighters: function(dirty) {
	        if ( dirty === void 0 ) dirty = false;

	        HighlighterView.update(this, null, dirty);
	    },

	    transformHighlighters: function() {
	        HighlighterView.transform(this);
	    },

	    // Interaction. The controller part.
	    // ---------------------------------

	    // Interaction is handled by the paper and delegated to the view in interest.
	    // `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid.
	    // If necessary, real coordinates can be obtained from the `evt` event object.

	    // These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`,
	    // i.e. `joint.dia.Element` and `joint.dia.Link`.

	    pointerdblclick: function(evt, x, y) {

	        this.notify('cell:pointerdblclick', evt, x, y);
	    },

	    pointerclick: function(evt, x, y) {

	        this.notify('cell:pointerclick', evt, x, y);
	    },

	    contextmenu: function(evt, x, y) {

	        this.notify('cell:contextmenu', evt, x, y);
	    },

	    pointerdown: function(evt, x, y) {

	        var ref = this;
	        var model = ref.model;
	        var graph = model.graph;
	        if (graph) {
	            model.startBatch('pointer');
	            this.eventData(evt, { graph: graph });
	        }

	        this.notify('cell:pointerdown', evt, x, y);
	    },

	    pointermove: function(evt, x, y) {

	        this.notify('cell:pointermove', evt, x, y);
	    },

	    pointerup: function(evt, x, y) {

	        var ref = this.eventData(evt);
	        var graph = ref.graph;

	        this.notify('cell:pointerup', evt, x, y);

	        if (graph) {
	            // we don't want to trigger event on model as model doesn't
	            // need to be member of collection anymore (remove)
	            graph.stopBatch('pointer', { cell: this.model });
	        }
	    },

	    mouseover: function(evt) {

	        this.notify('cell:mouseover', evt);
	    },

	    mouseout: function(evt) {

	        this.notify('cell:mouseout', evt);
	    },

	    mouseenter: function(evt) {

	        this.notify('cell:mouseenter', evt);
	    },

	    mouseleave: function(evt) {

	        this.notify('cell:mouseleave', evt);
	    },

	    mousewheel: function(evt, x, y, delta) {

	        this.notify('cell:mousewheel', evt, x, y, delta);
	    },

	    onevent: function(evt, eventName, x, y) {

	        this.notify(eventName, evt, x, y);
	    },

	    onmagnet: function() {

	        // noop
	    },

	    magnetpointerdblclick: function() {

	        // noop
	    },

	    magnetcontextmenu: function() {

	        // noop
	    },

	    checkMouseleave: function checkMouseleave(evt) {
	        var ref = this;
	        var paper = ref.paper;
	        if (paper.isAsync()) {
	            // Do the updates of the current view synchronously now
	            paper.dumpView(this);
	        }
	        var target = this.getEventTarget(evt, { fromPoint: true });
	        var view = paper.findView(target);
	        if (view === this) { return; }
	        // Leaving the current view
	        this.mouseleave(evt);
	        if (!view) { return; }
	        // Entering another view
	        view.mouseenter(evt);
	    },

	    setInteractivity: function(value) {

	        this.options.interactive = value;
	    }
	}, {

	    Highlighting: HighlightingTypes,

	    addPresentationAttributes: function(presentationAttributes) {
	        return merge({}, result(this.prototype, 'presentationAttributes'), presentationAttributes, function(a, b) {
	            if (!a || !b) { return; }
	            if (typeof a === 'string') { a = [a]; }
	            if (typeof b === 'string') { b = [b]; }
	            if (Array.isArray(a) && Array.isArray(b)) { return uniq(a.concat(b)); }
	        });
	    }
	});

	var Flags = {
	    UPDATE: 'UPDATE',
	    TRANSLATE: 'TRANSLATE',
	    TOOLS: 'TOOLS',
	    RESIZE: 'RESIZE',
	    PORTS: 'PORTS',
	    ROTATE: 'ROTATE',
	    RENDER: 'RENDER'
	};

	// Element base view and controller.
	// -------------------------------------------

	var ElementView = CellView.extend({

	    /**
	     * @abstract
	     */
	    _removePorts: function() {
	        // implemented in ports.js
	    },

	    /**
	     *
	     * @abstract
	     */
	    _renderPorts: function() {
	        // implemented in ports.js
	    },

	    className: function() {

	        var classNames = CellView.prototype.className.apply(this).split(' ');

	        classNames.push('element');

	        return classNames.join(' ');
	    },

	    initialize: function() {

	        CellView.prototype.initialize.apply(this, arguments);

	        this._initializePorts();
	    },

	    presentationAttributes: {
	        'attrs': [Flags.UPDATE],
	        'position': [Flags.TRANSLATE, Flags.TOOLS],
	        'size': [Flags.RESIZE, Flags.PORTS, Flags.TOOLS],
	        'angle': [Flags.ROTATE, Flags.TOOLS],
	        'markup': [Flags.RENDER],
	        'ports': [Flags.PORTS],
	    },

	    initFlag: [Flags.RENDER],

	    UPDATE_PRIORITY: 0,

	    confirmUpdate: function(flag, opt) {

	        var useCSSSelectors = config.useCSSSelectors;
	        if (this.hasFlag(flag, Flags.PORTS)) {
	            this._removePorts();
	            this._cleanPortsCache();
	        }
	        var transformHighlighters = false;
	        if (this.hasFlag(flag, Flags.RENDER)) {
	            this.render();
	            this.updateTools(opt);
	            this.updateHighlighters(true);
	            transformHighlighters = true;
	            flag = this.removeFlag(flag, [Flags.RENDER, Flags.UPDATE, Flags.RESIZE, Flags.TRANSLATE, Flags.ROTATE, Flags.PORTS, Flags.TOOLS]);
	        } else {
	            var updateHighlighters = false;

	            // Skip this branch if render is required
	            if (this.hasFlag(flag, Flags.RESIZE)) {
	                this.resize(opt);
	                updateHighlighters = true;
	                // Resize method is calling `update()` internally
	                flag = this.removeFlag(flag, [Flags.RESIZE, Flags.UPDATE]);
	            }
	            if (this.hasFlag(flag, Flags.UPDATE)) {
	                this.update(this.model, null, opt);
	                flag = this.removeFlag(flag, Flags.UPDATE);
	                updateHighlighters = true;
	                if (useCSSSelectors) {
	                    // `update()` will render ports when useCSSSelectors are enabled
	                    flag = this.removeFlag(flag, Flags.PORTS);
	                }
	            }
	            if (this.hasFlag(flag, Flags.TRANSLATE)) {
	                this.translate();
	                flag = this.removeFlag(flag, Flags.TRANSLATE);
	                transformHighlighters = true;
	            }
	            if (this.hasFlag(flag, Flags.ROTATE)) {
	                this.rotate();
	                flag = this.removeFlag(flag, Flags.ROTATE);
	                transformHighlighters = true;
	            }
	            if (this.hasFlag(flag, Flags.PORTS)) {
	                this._renderPorts();
	                updateHighlighters = true;
	                flag = this.removeFlag(flag, Flags.PORTS);
	            }

	            if (updateHighlighters) {
	                this.updateHighlighters(false);
	            }
	        }

	        if (transformHighlighters) {
	            this.transformHighlighters();
	        }

	        if (this.hasFlag(flag, Flags.TOOLS)) {
	            this.updateTools(opt);
	            flag = this.removeFlag(flag, Flags.TOOLS);
	        }

	        return flag;
	    },

	    /**
	     * @abstract
	     */
	    _initializePorts: function() {

	    },

	    update: function(_, renderingOnlyAttrs) {

	        this.cleanNodesCache();

	        // When CSS selector strings are used, make sure no rule matches port nodes.
	        var useCSSSelectors = config.useCSSSelectors;
	        if (useCSSSelectors) { this._removePorts(); }

	        var model = this.model;
	        var modelAttrs = model.attr();
	        this.updateDOMSubtreeAttributes(this.el, modelAttrs, {
	            rootBBox: new Rect(model.size()),
	            selectors: this.selectors,
	            scalableNode: this.scalableNode,
	            rotatableNode: this.rotatableNode,
	            // Use rendering only attributes if they differs from the model attributes
	            roAttributes: (renderingOnlyAttrs === modelAttrs) ? null : renderingOnlyAttrs
	        });

	        if (useCSSSelectors) {
	            this._renderPorts();
	        }
	    },

	    rotatableSelector: 'rotatable',
	    scalableSelector: 'scalable',
	    scalableNode: null,
	    rotatableNode: null,

	    // `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the
	    // default markup is not desirable.
	    renderMarkup: function() {

	        var element = this.model;
	        var markup = element.get('markup') || element.markup;
	        if (!markup) { throw new Error('dia.ElementView: markup required'); }
	        if (Array.isArray(markup)) { return this.renderJSONMarkup(markup); }
	        if (typeof markup === 'string') { return this.renderStringMarkup(markup); }
	        throw new Error('dia.ElementView: invalid markup');
	    },

	    renderJSONMarkup: function(markup) {

	        var doc = this.parseDOMJSON(markup, this.el);
	        var selectors = this.selectors = doc.selectors;
	        this.rotatableNode = V(selectors[this.rotatableSelector]) || null;
	        this.scalableNode = V(selectors[this.scalableSelector]) || null;
	        // Fragment
	        this.vel.append(doc.fragment);
	    },

	    renderStringMarkup: function(markup) {

	        var vel = this.vel;
	        vel.append(V(markup));
	        // Cache transformation groups
	        this.rotatableNode = vel.findOne('.rotatable');
	        this.scalableNode = vel.findOne('.scalable');

	        var selectors = this.selectors = {};
	        selectors[this.selector] = this.el;
	    },

	    render: function() {

	        this.vel.empty();
	        this.renderMarkup();
	        if (this.scalableNode) {
	            // Double update is necessary for elements with the scalable group only
	            // Note the resize() triggers the other `update`.
	            this.update();
	        }
	        this.resize();
	        if (this.rotatableNode) {
	            // Translate transformation is applied on `this.el` while the rotation transformation
	            // on `this.rotatableNode`
	            this.rotate();
	            this.translate();
	        } else {
	            this.updateTransformation();
	        }
	        if (!config.useCSSSelectors) { this._renderPorts(); }
	        return this;
	    },

	    resize: function(opt) {

	        if (this.scalableNode) { return this.sgResize(opt); }
	        if (this.model.attributes.angle) { this.rotate(); }
	        this.update();
	    },

	    translate: function() {

	        if (this.rotatableNode) { return this.rgTranslate(); }
	        this.updateTransformation();
	    },

	    rotate: function() {

	        if (this.rotatableNode) {
	            this.rgRotate();
	            // It's necessary to call the update for the nodes outside
	            // the rotatable group referencing nodes inside the group
	            this.update();
	            return;
	        }
	        this.updateTransformation();
	    },

	    updateTransformation: function() {

	        var transformation = this.getTranslateString();
	        var rotateString = this.getRotateString();
	        if (rotateString) { transformation += ' ' + rotateString; }
	        this.vel.attr('transform', transformation);
	    },

	    getTranslateString: function() {

	        var position = this.model.attributes.position;
	        return 'translate(' + position.x + ',' + position.y + ')';
	    },

	    getRotateString: function() {
	        var attributes = this.model.attributes;
	        var angle = attributes.angle;
	        if (!angle) { return null; }
	        var size = attributes.size;
	        return 'rotate(' + angle + ',' + (size.width / 2) + ',' + (size.height / 2) + ')';
	    },

	    // Rotatable & Scalable Group
	    // always slower, kept mainly for backwards compatibility

	    rgRotate: function() {

	        this.rotatableNode.attr('transform', this.getRotateString());
	    },

	    rgTranslate: function() {

	        this.vel.attr('transform', this.getTranslateString());
	    },

	    sgResize: function(opt) {

	        var model = this.model;
	        var angle = model.angle();
	        var size = model.size();
	        var scalable = this.scalableNode;

	        // Getting scalable group's bbox.
	        // Due to a bug in webkit's native SVG .getBBox implementation, the bbox of groups with path children includes the paths' control points.
	        // To work around the issue, we need to check whether there are any path elements inside the scalable group.
	        var recursive = false;
	        if (scalable.node.getElementsByTagName('path').length > 0) {
	            // If scalable has at least one descendant that is a path, we need to switch to recursive bbox calculation.
	            // If there are no path descendants, group bbox calculation works and so we can use the (faster) native function directly.
	            recursive = true;
	        }
	        var scalableBBox = scalable.getBBox({ recursive: recursive });

	        // Make sure `scalableBbox.width` and `scalableBbox.height` are not zero which can happen if the element does not have any content. By making
	        // the width/height 1, we prevent HTML errors of the type `scale(Infinity, Infinity)`.
	        var sx = (size.width / (scalableBBox.width || 1));
	        var sy = (size.height / (scalableBBox.height || 1));
	        scalable.attr('transform', 'scale(' + sx + ',' + sy + ')');

	        // Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height`
	        // Order of transformations is significant but we want to reconstruct the object always in the order:
	        // resize(), rotate(), translate() no matter of how the object was transformed. For that to work,
	        // we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the
	        // rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation
	        // around the center of the resized object (which is a different origin then the origin of the previous rotation)
	        // and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was.

	        // Cancel the rotation but now around a different origin, which is the center of the scaled object.
	        var rotatable = this.rotatableNode;
	        var rotation = rotatable && rotatable.attr('transform');
	        if (rotation) {

	            rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width / 2) + ',' + (size.height / 2) + ')');
	            var rotatableBBox = scalable.getBBox({ target: this.paper.cells });

	            // Store new x, y and perform rotate() again against the new rotation origin.
	            model.set('position', { x: rotatableBBox.x, y: rotatableBBox.y }, assign({ updateHandled: true }, opt));
	            this.translate();
	            this.rotate();
	        }

	        // Update must always be called on non-rotated element. Otherwise, relative positioning
	        // would work with wrong (rotated) bounding boxes.
	        this.update();
	    },

	    // Embedding mode methods.
	    // -----------------------

	    prepareEmbedding: function(data) {
	        if ( data === void 0 ) data = {};


	        var element = data.model || this.model;
	        var paper = data.paper || this.paper;
	        var graph = paper.model;

	        var initialZIndices = data.initialZIndices = {};
	        var embeddedCells = element.getEmbeddedCells({ deep: true });
	        var connectedLinks = graph.getConnectedLinks(element, { deep: true, includeEnclosed: true });

	        // Note: an embedded cell can be a connect link, but it's fine
	        // to iterate over the cell twice.
	        [
	            element ].concat( embeddedCells,
	            connectedLinks
	        ).forEach(function (cell) { return initialZIndices[cell.id] = cell.attributes.z; });

	        element.startBatch('to-front');

	        // Bring the model to the front with all his embeds.
	        element.toFront({ deep: true, ui: true });

	        // Note that at this point cells in the collection are not sorted by z index (it's running in the batch, see
	        // the dia.Graph._sortOnChangeZ), so we can't assume that the last cell in the collection has the highest z.
	        var maxZ = graph.getElements().reduce(function (max, cell) { return Math.max(max, cell.attributes.z || 0); }, 0);

	        // Move to front also all the inbound and outbound links that are connected
	        // to any of the element descendant. If we bring to front only embedded elements,
	        // links connected to them would stay in the background.
	        connectedLinks.forEach(function (link) {
	            if (link.attributes.z <= maxZ) {
	                link.set('z', maxZ + 1, { ui: true });
	            }
	        });

	        element.stopBatch('to-front');

	        // Before we start looking for suitable parent we remove the current one.
	        var parentId = element.parent();
	        if (parentId) {
	            var parent = graph.getCell(parentId);
	            parent.unembed(element, { ui: true });
	            data.initialParentId = parentId;
	        } else {
	            data.initialParentId = null;
	        }
	    },

	    processEmbedding: function(data) {

	        data || (data = {});

	        var model = data.model || this.model;
	        var paper = data.paper || this.paper;
	        var paperOptions = paper.options;

	        var candidates = [];
	        if (isFunction(paperOptions.findParentBy)) {
	            var parents = toArray(paperOptions.findParentBy.call(paper.model, this));
	            candidates = parents.filter(function(el) {
	                return el instanceof Cell && this.model.id !== el.id && !el.isEmbeddedIn(this.model);
	            }.bind(this));
	        } else {
	            candidates = paper.model.findModelsUnderElement(model, { searchBy: paperOptions.findParentBy });
	        }

	        if (paperOptions.frontParentOnly) {
	            // pick the element with the highest `z` index
	            candidates = candidates.slice(-1);
	        }

	        var newCandidateView = null;
	        var prevCandidateView = data.candidateEmbedView;

	        // iterate over all candidates starting from the last one (has the highest z-index).
	        for (var i = candidates.length - 1; i >= 0; i--) {

	            var candidate = candidates[i];

	            if (prevCandidateView && prevCandidateView.model.id == candidate.id) {

	                // candidate remains the same
	                newCandidateView = prevCandidateView;
	                break;

	            } else {

	                var view = candidate.findView(paper);
	                if (paperOptions.validateEmbedding.call(paper, this, view)) {

	                    // flip to the new candidate
	                    newCandidateView = view;
	                    break;
	                }
	            }
	        }

	        if (newCandidateView && newCandidateView != prevCandidateView) {
	            // A new candidate view found. Highlight the new one.
	            this.clearEmbedding(data);
	            data.candidateEmbedView = newCandidateView.highlight(
	                newCandidateView.findProxyNode(null, 'container'),
	                { embedding: true }
	            );
	        }

	        if (!newCandidateView && prevCandidateView) {
	            // No candidate view found. Unhighlight the previous candidate.
	            this.clearEmbedding(data);
	        }
	    },

	    clearEmbedding: function(data) {

	        data || (data = {});

	        var candidateView = data.candidateEmbedView;
	        if (candidateView) {
	            // No candidate view found. Unhighlight the previous candidate.
	            candidateView.unhighlight(
	                candidateView.findProxyNode(null, 'container'),
	                { embedding: true }
	            );
	            data.candidateEmbedView = null;
	        }
	    },

	    finalizeEmbedding: function(data) {
	        if ( data === void 0 ) data = {};


	        var candidateView = data.candidateEmbedView;
	        var element = data.model || this.model;
	        var paper = data.paper || this.paper;

	        if (candidateView) {

	            // We finished embedding. Candidate view is chosen to become the parent of the model.
	            candidateView.model.embed(element, { ui: true });
	            candidateView.unhighlight(candidateView.findProxyNode(null, 'container'), { embedding: true });

	            data.candidateEmbedView = null;

	        } else {

	            var ref = paper.options;
	            var validateUnembedding = ref.validateUnembedding;
	            var initialParentId = data.initialParentId;
	            // The element was originally embedded into another element.
	            // The interaction would unembed the element. Let's validate
	            // if the element can be unembedded.
	            if (
	                initialParentId &&
	                typeof validateUnembedding === 'function' &&
	                !validateUnembedding.call(paper, this)
	            ) {
	                this._disallowUnembed(data);
	                return;
	            }
	        }

	        paper.model.getConnectedLinks(element, { deep: true }).forEach(function (link) {
	            link.reparent({ ui: true });
	        });
	    },

	    _disallowUnembed: function(data) {
	        var model = data.model;
	        var whenNotAllowed = data.whenNotAllowed; if ( whenNotAllowed === void 0 ) whenNotAllowed = 'revert';
	        var element = model || this.model;
	        var paper = data.paper || this.paper;
	        var graph = paper.model;
	        switch (whenNotAllowed) {
	            case 'remove': {
	                element.remove({ ui: true });
	                break;
	            }
	            case 'revert': {
	                var initialParentId = data.initialParentId;
	                var initialPosition = data.initialPosition;
	                var initialZIndices = data.initialZIndices;
	                // Revert the element's position (and the position of its embedded cells if any)
	                if (initialPosition) {
	                    var x = initialPosition.x;
	                    var y = initialPosition.y;
	                    element.position(x, y, { deep: true, ui: true });
	                }
	                // Revert all the z-indices changed during the embedding
	                if (initialZIndices) {
	                    Object.keys(initialZIndices).forEach(function (id) {
	                        var cell = graph.getCell(id);
	                        if (cell) {
	                            cell.set('z', initialZIndices[id], { ui: true });
	                        }
	                    });
	                }
	                // Revert the original parent
	                var parent = graph.getCell(initialParentId);
	                if (parent) {
	                    parent.embed(element, { ui: true });
	                }
	                break;
	            }
	        }
	    },

	    getDelegatedView: function() {

	        var view = this;
	        var model = view.model;
	        var paper = view.paper;

	        while (view) {
	            if (model.isLink()) { break; }
	            if (!model.isEmbedded() || view.can('stopDelegation')) { return view; }
	            model = model.getParentCell();
	            view = paper.findViewByModel(model);
	        }

	        return null;
	    },

	    findProxyNode: function(el, type) {
	        el || (el = this.el);
	        var nodeSelector = el.getAttribute((type + "-selector"));
	        if (nodeSelector) {
	            var port = this.findAttribute('port', el);
	            if (port) {
	                var proxyPortNode = this.findPortNode(port, nodeSelector);
	                if (proxyPortNode) { return proxyPortNode; }
	            } else {
	                var ref = this.findBySelector(nodeSelector);
	                var proxyNode = ref[0];
	                if (proxyNode) { return proxyNode; }
	            }
	        }
	        return el;
	    },

	    // Interaction. The controller part.
	    // ---------------------------------

	    notifyPointerdown: function notifyPointerdown(evt, x, y) {
	        CellView.prototype.pointerdown.call(this, evt, x, y);
	        this.notify('element:pointerdown', evt, x, y);
	    },

	    notifyPointermove: function notifyPointermove(evt, x, y) {
	        CellView.prototype.pointermove.call(this, evt, x, y);
	        this.notify('element:pointermove', evt, x, y);
	    },

	    notifyPointerup: function notifyPointerup(evt, x, y) {
	        this.notify('element:pointerup', evt, x, y);
	        CellView.prototype.pointerup.call(this, evt, x, y);
	    },

	    pointerdblclick: function(evt, x, y) {

	        CellView.prototype.pointerdblclick.apply(this, arguments);
	        this.notify('element:pointerdblclick', evt, x, y);
	    },

	    pointerclick: function(evt, x, y) {

	        CellView.prototype.pointerclick.apply(this, arguments);
	        this.notify('element:pointerclick', evt, x, y);
	    },

	    contextmenu: function(evt, x, y) {

	        CellView.prototype.contextmenu.apply(this, arguments);
	        this.notify('element:contextmenu', evt, x, y);
	    },

	    pointerdown: function(evt, x, y) {

	        if (this.isPropagationStopped(evt)) { return; }

	        this.notifyPointerdown(evt, x, y);
	        this.dragStart(evt, x, y);
	    },

	    pointermove: function(evt, x, y) {

	        var data = this.eventData(evt);

	        switch (data.action) {
	            case 'magnet':
	                this.dragMagnet(evt, x, y);
	                break;
	            case 'move':
	                (data.delegatedView || this).drag(evt, x, y);
	            // eslint: no-fallthrough=false
	            default:
	                this.notifyPointermove(evt, x, y);
	                break;
	        }

	        // Make sure the element view data is passed along.
	        // It could have been wiped out in the handlers above.
	        this.eventData(evt, data);
	    },

	    pointerup: function(evt, x, y) {

	        var data = this.eventData(evt);
	        switch (data.action) {
	            case 'magnet':
	                this.dragMagnetEnd(evt, x, y);
	                break;
	            case 'move':
	                (data.delegatedView || this).dragEnd(evt, x, y);
	            // eslint: no-fallthrough=false
	            default:
	                this.notifyPointerup(evt, x, y);
	        }

	        var magnet = data.targetMagnet;
	        if (magnet) { this.magnetpointerclick(evt, magnet, x, y); }

	        this.checkMouseleave(evt);
	    },

	    mouseover: function(evt) {

	        CellView.prototype.mouseover.apply(this, arguments);
	        this.notify('element:mouseover', evt);
	    },

	    mouseout: function(evt) {

	        CellView.prototype.mouseout.apply(this, arguments);
	        this.notify('element:mouseout', evt);
	    },

	    mouseenter: function(evt) {

	        CellView.prototype.mouseenter.apply(this, arguments);
	        this.notify('element:mouseenter', evt);
	    },

	    mouseleave: function(evt) {

	        CellView.prototype.mouseleave.apply(this, arguments);
	        this.notify('element:mouseleave', evt);
	    },

	    mousewheel: function(evt, x, y, delta) {

	        CellView.prototype.mousewheel.apply(this, arguments);
	        this.notify('element:mousewheel', evt, x, y, delta);
	    },

	    onmagnet: function(evt, x, y) {

	        this.dragMagnetStart(evt, x, y);
	    },

	    magnetpointerdblclick: function(evt, magnet, x, y) {

	        this.notify('element:magnet:pointerdblclick', evt, magnet, x, y);
	    },

	    magnetcontextmenu: function(evt, magnet, x, y) {

	        this.notify('element:magnet:contextmenu', evt, magnet, x, y);
	    },

	    // Drag Start Handlers

	    dragStart: function(evt, x, y) {

	        var view = this.getDelegatedView();
	        if (!view || !view.can('elementMove')) { return; }

	        this.eventData(evt, {
	            action: 'move',
	            delegatedView: view
	        });

	        var position = view.model.position();
	        view.eventData(evt, {
	            initialPosition: position,
	            pointerOffset: position.difference(x, y),
	            restrictedArea: this.paper.getRestrictedArea(view, x, y)
	        });
	    },

	    dragMagnetStart: function(evt, x, y) {

	        if (!this.can('addLinkFromMagnet')) { return; }

	        var magnet = evt.currentTarget;
	        var paper = this.paper;
	        this.eventData(evt, { targetMagnet: magnet });
	        evt.stopPropagation();

	        if (paper.options.validateMagnet(this, magnet, evt)) {

	            if (paper.options.magnetThreshold <= 0) {
	                this.dragLinkStart(evt, magnet, x, y);
	            }

	            this.eventData(evt, { action: 'magnet' });
	            this.stopPropagation(evt);

	        } else {

	            this.pointerdown(evt, x, y);
	        }

	        paper.delegateDragEvents(this, evt.data);
	    },

	    // Drag Handlers

	    drag: function(evt, x, y) {

	        var paper = this.paper;
	        var grid = paper.options.gridSize;
	        var element = this.model;
	        var data = this.eventData(evt);
	        var pointerOffset = data.pointerOffset;
	        var restrictedArea = data.restrictedArea;
	        var embedding = data.embedding;

	        // Make sure the new element's position always snaps to the current grid
	        var elX = snapToGrid(x + pointerOffset.x, grid);
	        var elY = snapToGrid(y + pointerOffset.y, grid);

	        element.position(elX, elY, { restrictedArea: restrictedArea, deep: true, ui: true });

	        if (paper.options.embeddingMode) {
	            if (!embedding) {
	                // Prepare the element for embedding only if the pointer moves.
	                // We don't want to do unnecessary action with the element
	                // if an user only clicks/dblclicks on it.
	                this.prepareEmbedding(data);
	                embedding = true;
	            }
	            this.processEmbedding(data);
	        }

	        this.eventData(evt, {
	            embedding: embedding
	        });
	    },

	    dragMagnet: function(evt, x, y) {
	        this.dragLink(evt, x, y);
	    },

	    // Drag End Handlers

	    dragEnd: function(evt, x, y) {

	        var data = this.eventData(evt);
	        if (data.embedding) { this.finalizeEmbedding(data); }
	    },

	    dragMagnetEnd: function(evt, x, y) {
	        this.dragLinkEnd(evt, x, y);
	    },

	    magnetpointerclick: function(evt, magnet, x, y) {
	        var paper = this.paper;
	        if (paper.eventData(evt).mousemoved > paper.options.clickThreshold) { return; }
	        this.notify('element:magnet:pointerclick', evt, magnet, x, y);
	    }

	}, {

	    Flags: Flags,
	});

	assign(ElementView.prototype, elementViewPortPrototype);

	// Does not make any changes to vertices.
	// Returns the arguments that are passed to it, unchanged.
	var normal = function(vertices, opt, linkView) {

	    return vertices;
	};

	// Routes the link always to/from a certain side
	//
	// Arguments:
	//   padding ... gap between the element and the first vertex. :: Default 40.
	//   side ... 'left' | 'right' | 'top' | 'bottom' :: Default 'bottom'.
	//
	var oneSide = function(vertices, opt, linkView) {

	    var side = opt.side || 'bottom';
	    var padding = normalizeSides(opt.padding || 40);

	    // LinkView contains cached source an target bboxes.
	    // Note that those are Geometry rectangle objects.
	    var sourceBBox = linkView.sourceBBox;
	    var targetBBox = linkView.targetBBox;
	    var sourcePoint = sourceBBox.center();
	    var targetPoint = targetBBox.center();

	    var coordinate, dimension, direction;

	    switch (side) {
	        case 'bottom':
	            direction = 1;
	            coordinate = 'y';
	            dimension = 'height';
	            break;
	        case 'top':
	            direction = -1;
	            coordinate = 'y';
	            dimension = 'height';
	            break;
	        case 'left':
	            direction = -1;
	            coordinate = 'x';
	            dimension = 'width';
	            break;
	        case 'right':
	            direction = 1;
	            coordinate = 'x';
	            dimension = 'width';
	            break;
	        default:
	            throw new Error('Router: invalid side');
	    }

	    // move the points from the center of the element to outside of it.
	    sourcePoint[coordinate] += direction * (sourceBBox[dimension] / 2 + padding[side]);
	    targetPoint[coordinate] += direction * (targetBBox[dimension] / 2 + padding[side]);

	    // make link orthogonal (at least the first and last vertex).
	    if ((direction * (sourcePoint[coordinate] - targetPoint[coordinate])) > 0) {
	        targetPoint[coordinate] = sourcePoint[coordinate];
	    } else {
	        sourcePoint[coordinate] = targetPoint[coordinate];
	    }

	    return [sourcePoint].concat(vertices, targetPoint);
	};

	// bearing -> opposite bearing
	var opposites = {
	    N: 'S',
	    S: 'N',
	    E: 'W',
	    W: 'E'
	};

	// bearing -> radians
	var radians = {
	    N: -Math.PI / 2 * 3,
	    S: -Math.PI / 2,
	    E: 0,
	    W: Math.PI
	};

	// HELPERS //

	// returns a point `p` where lines p,p1 and p,p2 are perpendicular and p is not contained
	// in the given box
	function freeJoin(p1, p2, bbox) {

	    var p = new Point(p1.x, p2.y);
	    if (bbox.containsPoint(p)) { p = new Point(p2.x, p1.y); }
	    // kept for reference
	    // if (bbox.containsPoint(p)) p = null;

	    return p;
	}

	// returns either width or height of a bbox based on the given bearing
	function getBBoxSize(bbox, bearing) {

	    return bbox[(bearing === 'W' || bearing === 'E') ? 'width' : 'height'];
	}

	// simple bearing method (calculates only orthogonal cardinals)
	function getBearing(from, to) {

	    if (from.x === to.x) { return (from.y > to.y) ? 'N' : 'S'; }
	    if (from.y === to.y) { return (from.x > to.x) ? 'W' : 'E'; }
	    return null;
	}

	// transform point to a rect
	function getPointBox(p) {

	    return new Rect(p.x, p.y, 0, 0);
	}

	function getPaddingBox(opt) {

	    // if both provided, opt.padding wins over opt.elementPadding
	    var sides = normalizeSides(opt.padding || opt.elementPadding || 20);

	    return {
	        x: -sides.left,
	        y: -sides.top,
	        width: sides.left + sides.right,
	        height: sides.top + sides.bottom
	    };
	}

	// return source bbox
	function getSourceBBox(linkView, opt) {

	    return linkView.sourceBBox.clone().moveAndExpand(getPaddingBox(opt));
	}

	// return target bbox
	function getTargetBBox(linkView, opt) {

	    return linkView.targetBBox.clone().moveAndExpand(getPaddingBox(opt));
	}

	// return source anchor
	function getSourceAnchor(linkView, opt) {

	    if (linkView.sourceAnchor) { return linkView.sourceAnchor; }

	    // fallback: center of bbox
	    var sourceBBox = getSourceBBox(linkView, opt);
	    return sourceBBox.center();
	}

	// return target anchor
	function getTargetAnchor(linkView, opt) {

	    if (linkView.targetAnchor) { return linkView.targetAnchor; }

	    // fallback: center of bbox
	    var targetBBox = getTargetBBox(linkView, opt);
	    return targetBBox.center(); // default
	}

	// PARTIAL ROUTERS //

	function vertexVertex(from, to, bearing) {

	    var p1 = new Point(from.x, to.y);
	    var p2 = new Point(to.x, from.y);
	    var d1 = getBearing(from, p1);
	    var d2 = getBearing(from, p2);
	    var opposite = opposites[bearing];

	    var p = (d1 === bearing || (d1 !== opposite && (d2 === opposite || d2 !== bearing))) ? p1 : p2;

	    return { points: [p], direction: getBearing(p, to) };
	}

	function elementVertex(from, to, fromBBox) {

	    var p = freeJoin(from, to, fromBBox);

	    return { points: [p], direction: getBearing(p, to) };
	}

	function vertexElement(from, to, toBBox, bearing) {

	    var route = {};

	    var points = [new Point(from.x, to.y), new Point(to.x, from.y)];
	    var freePoints = points.filter(function(pt) {
	        return !toBBox.containsPoint(pt);
	    });
	    var freeBearingPoints = freePoints.filter(function(pt) {
	        return getBearing(pt, from) !== bearing;
	    });

	    var p;

	    if (freeBearingPoints.length > 0) {
	        // Try to pick a point which bears the same direction as the previous segment.

	        p = freeBearingPoints.filter(function(pt) {
	            return getBearing(from, pt) === bearing;
	        }).pop();
	        p = p || freeBearingPoints[0];

	        route.points = [p];
	        route.direction = getBearing(p, to);

	    } else {
	        // Here we found only points which are either contained in the element or they would create
	        // a link segment going in opposite direction from the previous one.
	        // We take the point inside element and move it outside the element in the direction the
	        // route is going. Now we can join this point with the current end (using freeJoin).

	        p = difference(points, freePoints)[0];

	        var p2 = (new Point(to)).move(p, -getBBoxSize(toBBox, bearing) / 2);
	        var p1 = freeJoin(p2, from, toBBox);

	        route.points = [p1, p2];
	        route.direction = getBearing(p2, to);
	    }

	    return route;
	}

	function elementElement(from, to, fromBBox, toBBox) {

	    var route = elementVertex(to, from, toBBox);
	    var p1 = route.points[0];

	    if (fromBBox.containsPoint(p1)) {

	        route = elementVertex(from, to, fromBBox);
	        var p2 = route.points[0];

	        if (toBBox.containsPoint(p2)) {

	            var fromBorder = (new Point(from)).move(p2, -getBBoxSize(fromBBox, getBearing(from, p2)) / 2);
	            var toBorder = (new Point(to)).move(p1, -getBBoxSize(toBBox, getBearing(to, p1)) / 2);
	            var mid = (new Line(fromBorder, toBorder)).midpoint();

	            var startRoute = elementVertex(from, mid, fromBBox);
	            var endRoute = vertexVertex(mid, to, startRoute.direction);

	            route.points = [startRoute.points[0], endRoute.points[0]];
	            route.direction = endRoute.direction;
	        }
	    }

	    return route;
	}

	// Finds route for situations where one element is inside the other.
	// Typically the route is directed outside the outer element first and
	// then back towards the inner element.
	function insideElement(from, to, fromBBox, toBBox, bearing) {

	    var route = {};
	    var boundary = fromBBox.union(toBBox).inflate(1);

	    // start from the point which is closer to the boundary
	    var reversed = boundary.center().distance(to) > boundary.center().distance(from);
	    var start = reversed ? to : from;
	    var end = reversed ? from : to;

	    var p1, p2, p3;

	    if (bearing) {
	        // Points on circle with radius equals 'W + H` are always outside the rectangle
	        // with width W and height H if the center of that circle is the center of that rectangle.
	        p1 = Point.fromPolar(boundary.width + boundary.height, radians[bearing], start);
	        p1 = boundary.pointNearestToPoint(p1).move(p1, -1);

	    } else {
	        p1 = boundary.pointNearestToPoint(start).move(start, 1);
	    }

	    p2 = freeJoin(p1, end, boundary);

	    if (p1.round().equals(p2.round())) {
	        p2 = Point.fromPolar(boundary.width + boundary.height, toRad(p1.theta(start)) + Math.PI / 2, end);
	        p2 = boundary.pointNearestToPoint(p2).move(end, 1).round();
	        p3 = freeJoin(p1, p2, boundary);
	        route.points = reversed ? [p2, p3, p1] : [p1, p3, p2];

	    } else {
	        route.points = reversed ? [p2, p1] : [p1, p2];
	    }

	    route.direction = reversed ? getBearing(p1, to) : getBearing(p2, to);

	    return route;
	}

	// MAIN ROUTER //

	// Return points through which a connection needs to be drawn in order to obtain an orthogonal link
	// routing from source to target going through `vertices`.
	function orthogonal(vertices, opt, linkView) {

	    var sourceBBox = getSourceBBox(linkView, opt);
	    var targetBBox = getTargetBBox(linkView, opt);

	    var sourceAnchor = getSourceAnchor(linkView, opt);
	    var targetAnchor = getTargetAnchor(linkView, opt);

	    // if anchor lies outside of bbox, the bbox expands to include it
	    sourceBBox = sourceBBox.union(getPointBox(sourceAnchor));
	    targetBBox = targetBBox.union(getPointBox(targetAnchor));

	    vertices = toArray(vertices).map(Point);
	    vertices.unshift(sourceAnchor);
	    vertices.push(targetAnchor);

	    var bearing; // bearing of previous route segment

	    var orthogonalVertices = []; // the array of found orthogonal vertices to be returned
	    for (var i = 0, max = vertices.length - 1; i < max; i++) {

	        var route = null;

	        var from = vertices[i];
	        var to = vertices[i + 1];

	        var isOrthogonal = !!getBearing(from, to);

	        if (i === 0) { // source

	            if (i + 1 === max) { // route source -> target

	                // Expand one of the elements by 1px to detect situations when the two
	                // elements are positioned next to each other with no gap in between.
	                if (sourceBBox.intersect(targetBBox.clone().inflate(1))) {
	                    route = insideElement(from, to, sourceBBox, targetBBox);

	                } else if (!isOrthogonal) {
	                    route = elementElement(from, to, sourceBBox, targetBBox);
	                }

	            } else { // route source -> vertex

	                if (sourceBBox.containsPoint(to)) {
	                    route = insideElement(from, to, sourceBBox, getPointBox(to).moveAndExpand(getPaddingBox(opt)));

	                } else if (!isOrthogonal) {
	                    route = elementVertex(from, to, sourceBBox);
	                }
	            }

	        } else if (i + 1 === max) { // route vertex -> target

	            // prevent overlaps with previous line segment
	            var isOrthogonalLoop = isOrthogonal && getBearing(to, from) === bearing;

	            if (targetBBox.containsPoint(from) || isOrthogonalLoop) {
	                route = insideElement(from, to, getPointBox(from).moveAndExpand(getPaddingBox(opt)), targetBBox, bearing);

	            } else if (!isOrthogonal) {
	                route = vertexElement(from, to, targetBBox, bearing);
	            }

	        } else if (!isOrthogonal) { // route vertex -> vertex
	            route = vertexVertex(from, to, bearing);
	        }

	        // applicable to all routes:

	        // set bearing for next iteration
	        if (route) {
	            Array.prototype.push.apply(orthogonalVertices, route.points);
	            bearing = route.direction;

	        } else {
	            // orthogonal route and not looped
	            bearing = getBearing(from, to);
	        }

	        // push `to` point to identified orthogonal vertices array
	        if (i + 1 < max) {
	            orthogonalVertices.push(to);
	        }
	    }

	    return orthogonalVertices;
	}

	var config$1 = {

	    // size of the step to find a route (the grid of the manhattan pathfinder)
	    step: 10,

	    // the number of route finding loops that cause the router to abort
	    // returns fallback route instead
	    maximumLoops: 2000,

	    // the number of decimal places to round floating point coordinates
	    precision: 1,

	    // maximum change of direction
	    maxAllowedDirectionChange: 90,

	    // should the router use perpendicular linkView option?
	    // does not connect anchor of element but rather a point close-by that is orthogonal
	    // this looks much better
	    perpendicular: true,

	    // should the source and/or target not be considered as obstacles?
	    excludeEnds: [], // 'source', 'target'

	    // should certain types of elements not be considered as obstacles?
	    excludeTypes: ['basic.Text'],

	    // possible starting directions from an element
	    startDirections: ['top', 'right', 'bottom', 'left'],

	    // possible ending directions to an element
	    endDirections: ['top', 'right', 'bottom', 'left'],

	    // specify the directions used above and what they mean
	    directionMap: {
	        top: { x: 0, y: -1 },
	        right: { x: 1, y: 0 },
	        bottom: { x: 0, y: 1 },
	        left: { x: -1, y: 0 }
	    },

	    // cost of an orthogonal step
	    cost: function() {

	        return this.step;
	    },

	    // an array of directions to find next points on the route
	    // different from start/end directions
	    directions: function() {

	        var step = this.step;
	        var cost = this.cost();

	        return [
	            { offsetX: step, offsetY: 0, cost: cost },
	            { offsetX: -step, offsetY: 0, cost: cost },
	            { offsetX: 0, offsetY: step, cost: cost },
	            { offsetX: 0, offsetY: -step, cost: cost }
	        ];
	    },

	    // a penalty received for direction change
	    penalties: function() {

	        return {
	            0: 0,
	            45: this.step / 2,
	            90: this.step / 2
	        };
	    },

	    // padding applied on the element bounding boxes
	    paddingBox: function() {

	        var step = this.step;

	        return {
	            x: -step,
	            y: -step,
	            width: 2 * step,
	            height: 2 * step
	        };
	    },

	    // A function that determines whether a given point is an obstacle or not.
	    // If used, the `padding`, `excludeEnds`and `excludeTypes` options are ignored.
	    // (point: dia.Point) => boolean;
	    isPointObstacle: null,

	    // a router to use when the manhattan router fails
	    // (one of the partial routes returns null)
	    fallbackRouter: function(vertices, opt, linkView) {

	        if (!isFunction(orthogonal)) {
	            throw new Error('Manhattan requires the orthogonal router as default fallback.');
	        }

	        return orthogonal(vertices, assign({}, config$1, opt), linkView);
	    },

	    /* Deprecated */
	    // a simple route used in situations when main routing method fails
	    // (exceed max number of loop iterations, inaccessible)
	    fallbackRoute: function(from, to, opt) {

	        return null; // null result will trigger the fallbackRouter

	        // left for reference:
	        /*// Find an orthogonal route ignoring obstacles.

	        var point = ((opt.previousDirAngle || 0) % 180 === 0)
	                ? new g.Point(from.x, to.y)
	                : new g.Point(to.x, from.y);

	        return [point];*/
	    },

	    // if a function is provided, it's used to route the link while dragging an end
	    // i.e. function(from, to, opt) { return []; }
	    draggingRoute: null
	};

	// HELPER CLASSES //

	// Map of obstacles
	// Helper structure to identify whether a point lies inside an obstacle.
	function ObstacleMap(opt) {

	    this.map = {};
	    this.options = opt;
	    // tells how to divide the paper when creating the elements map
	    this.mapGridSize = 100;
	}

	ObstacleMap.prototype.build = function(graph, link) {

	    var opt = this.options;

	    // source or target element could be excluded from set of obstacles
	    var excludedEnds = toArray(opt.excludeEnds).reduce(function(res, item) {

	        var end = link.get(item);
	        if (end) {
	            var cell = graph.getCell(end.id);
	            if (cell) {
	                res.push(cell);
	            }
	        }

	        return res;
	    }, []);

	    // Exclude any embedded elements from the source and the target element.
	    var excludedAncestors = [];

	    var source = graph.getCell(link.get('source').id);
	    if (source) {
	        excludedAncestors = union(excludedAncestors, source.getAncestors().map(function(cell) {
	            return cell.id;
	        }));
	    }

	    var target = graph.getCell(link.get('target').id);
	    if (target) {
	        excludedAncestors = union(excludedAncestors, target.getAncestors().map(function(cell) {
	            return cell.id;
	        }));
	    }

	    // Builds a map of all elements for quicker obstacle queries (i.e. is a point contained
	    // in any obstacle?) (a simplified grid search).
	    // The paper is divided into smaller cells, where each holds information about which
	    // elements belong to it. When we query whether a point lies inside an obstacle we
	    // don't need to go through all obstacles, we check only those in a particular cell.
	    var mapGridSize = this.mapGridSize;

	    graph.getElements().reduce(function(map, element) {

	        var isExcludedType = toArray(opt.excludeTypes).includes(element.get('type'));
	        var isExcludedEnd = excludedEnds.find(function(excluded) {
	            return excluded.id === element.id;
	        });
	        var isExcludedAncestor = excludedAncestors.includes(element.id);

	        var isExcluded = isExcludedType || isExcludedEnd || isExcludedAncestor;
	        if (!isExcluded) {
	            var bbox = element.getBBox().moveAndExpand(opt.paddingBox);

	            var origin = bbox.origin().snapToGrid(mapGridSize);
	            var corner = bbox.corner().snapToGrid(mapGridSize);

	            for (var x = origin.x; x <= corner.x; x += mapGridSize) {
	                for (var y = origin.y; y <= corner.y; y += mapGridSize) {
	                    var gridKey = x + '@' + y;
	                    map[gridKey] = map[gridKey] || [];
	                    map[gridKey].push(bbox);
	                }
	            }
	        }

	        return map;
	    }, this.map);

	    return this;
	};

	ObstacleMap.prototype.isPointAccessible = function(point) {

	    var mapKey = point.clone().snapToGrid(this.mapGridSize).toString();

	    return toArray(this.map[mapKey]).every(function(obstacle) {
	        return !obstacle.containsPoint(point);
	    });
	};

	// Sorted Set
	// Set of items sorted by given value.
	function SortedSet() {
	    this.items = [];
	    this.hash = {};
	    this.values = {};
	    this.OPEN = 1;
	    this.CLOSE = 2;
	}

	SortedSet.prototype.add = function(item, value) {

	    if (this.hash[item]) {
	        // item removal
	        this.items.splice(this.items.indexOf(item), 1);
	    } else {
	        this.hash[item] = this.OPEN;
	    }

	    this.values[item] = value;

	    var index$1 = sortedIndex(this.items, item, function(i) {
	        return this.values[i];
	    }.bind(this));

	    this.items.splice(index$1, 0, item);
	};

	SortedSet.prototype.remove = function(item) {

	    this.hash[item] = this.CLOSE;
	};

	SortedSet.prototype.isOpen = function(item) {

	    return this.hash[item] === this.OPEN;
	};

	SortedSet.prototype.isClose = function(item) {

	    return this.hash[item] === this.CLOSE;
	};

	SortedSet.prototype.isEmpty = function() {

	    return this.items.length === 0;
	};

	SortedSet.prototype.pop = function() {

	    var item = this.items.shift();
	    this.remove(item);
	    return item;
	};

	// HELPERS //

	// return source bbox
	function getSourceBBox$1(linkView, opt) {

	    // expand by padding box
	    if (opt && opt.paddingBox) { return linkView.sourceBBox.clone().moveAndExpand(opt.paddingBox); }

	    return linkView.sourceBBox.clone();
	}

	// return target bbox
	function getTargetBBox$1(linkView, opt) {

	    // expand by padding box
	    if (opt && opt.paddingBox) { return linkView.targetBBox.clone().moveAndExpand(opt.paddingBox); }

	    return linkView.targetBBox.clone();
	}

	// return source anchor
	function getSourceAnchor$1(linkView, opt) {

	    if (linkView.sourceAnchor) { return linkView.sourceAnchor; }

	    // fallback: center of bbox
	    var sourceBBox = getSourceBBox$1(linkView, opt);
	    return sourceBBox.center();
	}

	// return target anchor
	function getTargetAnchor$1(linkView, opt) {

	    if (linkView.targetAnchor) { return linkView.targetAnchor; }

	    // fallback: center of bbox
	    var targetBBox = getTargetBBox$1(linkView, opt);
	    return targetBBox.center(); // default
	}

	// returns a direction index from start point to end point
	// corrects for grid deformation between start and end
	function getDirectionAngle(start, end, numDirections, grid, opt) {

	    var quadrant = 360 / numDirections;
	    var angleTheta = start.theta(fixAngleEnd(start, end, grid, opt));
	    var normalizedAngle = normalizeAngle(angleTheta + (quadrant / 2));
	    return quadrant * Math.floor(normalizedAngle / quadrant);
	}

	// helper function for getDirectionAngle()
	// corrects for grid deformation
	// (if a point is one grid steps away from another in both dimensions,
	// it is considered to be 45 degrees away, even if the real angle is different)
	// this causes visible angle discrepancies if `opt.step` is much larger than `paper.gridSize`
	function fixAngleEnd(start, end, grid, opt) {

	    var step = opt.step;

	    var diffX = end.x - start.x;
	    var diffY = end.y - start.y;

	    var gridStepsX = diffX / grid.x;
	    var gridStepsY = diffY / grid.y;

	    var distanceX = gridStepsX * step;
	    var distanceY = gridStepsY * step;

	    return new Point(start.x + distanceX, start.y + distanceY);
	}

	// return the change in direction between two direction angles
	function getDirectionChange(angle1, angle2) {

	    var directionChange = Math.abs(angle1 - angle2);
	    return (directionChange > 180) ? (360 - directionChange) : directionChange;
	}

	// fix direction offsets according to current grid
	function getGridOffsets(directions, grid, opt) {

	    var step = opt.step;

	    toArray(opt.directions).forEach(function(direction) {

	        direction.gridOffsetX = (direction.offsetX / step) * grid.x;
	        direction.gridOffsetY = (direction.offsetY / step) * grid.y;
	    });
	}

	// get grid size in x and y dimensions, adapted to source and target positions
	function getGrid(step, source, target) {

	    return {
	        source: source.clone(),
	        x: getGridDimension(target.x - source.x, step),
	        y: getGridDimension(target.y - source.y, step)
	    };
	}

	// helper function for getGrid()
	function getGridDimension(diff, step) {

	    // return step if diff = 0
	    if (!diff) { return step; }

	    var absDiff = Math.abs(diff);
	    var numSteps = Math.round(absDiff / step);

	    // return absDiff if less than one step apart
	    if (!numSteps) { return absDiff; }

	    // otherwise, return corrected step
	    var roundedDiff = numSteps * step;
	    var remainder = absDiff - roundedDiff;
	    var stepCorrection = remainder / numSteps;

	    return step + stepCorrection;
	}

	// return a clone of point snapped to grid
	function snapToGrid$1(point, grid) {

	    var source = grid.source;

	    var snappedX = snapToGrid(point.x - source.x, grid.x) + source.x;
	    var snappedY = snapToGrid(point.y - source.y, grid.y) + source.y;

	    return new Point(snappedX, snappedY);
	}

	// round the point to opt.precision
	function round$4(point, precision) {

	    return point.round(precision);
	}

	// snap to grid and then round the point
	function align(point, grid, precision) {

	    return round$4(snapToGrid$1(point.clone(), grid), precision);
	}

	// return a string representing the point
	// string is rounded in both dimensions
	function getKey(point) {

	    return point.clone().toString();
	}

	// return a normalized vector from given point
	// used to determine the direction of a difference of two points
	function normalizePoint(point) {

	    return new Point(
	        point.x === 0 ? 0 : Math.abs(point.x) / point.x,
	        point.y === 0 ? 0 : Math.abs(point.y) / point.y
	    );
	}

	// PATHFINDING //

	// reconstructs a route by concatenating points with their parents
	function reconstructRoute(parents, points, tailPoint, from, to, grid, opt) {

	    var route = [];

	    var prevDiff = normalizePoint(to.difference(tailPoint));

	    // tailPoint is assumed to be aligned already
	    var currentKey = getKey(tailPoint);
	    var parent = parents[currentKey];

	    var point;
	    while (parent) {

	        // point is assumed to be aligned already
	        point = points[currentKey];

	        var diff = normalizePoint(point.difference(parent));
	        if (!diff.equals(prevDiff)) {
	            route.unshift(point);
	            prevDiff = diff;
	        }

	        // parent is assumed to be aligned already
	        currentKey = getKey(parent);
	        parent = parents[currentKey];
	    }

	    // leadPoint is assumed to be aligned already
	    var leadPoint = points[currentKey];

	    var fromDiff = normalizePoint(leadPoint.difference(from));
	    if (!fromDiff.equals(prevDiff)) {
	        route.unshift(leadPoint);
	    }

	    return route;
	}

	// heuristic method to determine the distance between two points
	function estimateCost(from, endPoints) {

	    var min = Infinity;

	    for (var i = 0, len = endPoints.length; i < len; i++) {
	        var cost = from.manhattanDistance(endPoints[i]);
	        if (cost < min) { min = cost; }
	    }

	    return min;
	}

	// find points around the bbox taking given directions into account
	// lines are drawn from anchor in given directions, intersections recorded
	// if anchor is outside bbox, only those directions that intersect get a rect point
	// the anchor itself is returned as rect point (representing some directions)
	// (since those directions are unobstructed by the bbox)
	function getRectPoints(anchor, bbox, directionList, grid, opt) {

	    var precision = opt.precision;
	    var directionMap = opt.directionMap;

	    var anchorCenterVector = anchor.difference(bbox.center());

	    var keys = isObject$1(directionMap) ? Object.keys(directionMap) : [];
	    var dirList = toArray(directionList);
	    var rectPoints = keys.reduce(function(res, key) {

	        if (dirList.includes(key)) {
	            var direction = directionMap[key];

	            // create a line that is guaranteed to intersect the bbox if bbox is in the direction
	            // even if anchor lies outside of bbox
	            var endpoint = new Point(
	                anchor.x + direction.x * (Math.abs(anchorCenterVector.x) + bbox.width),
	                anchor.y + direction.y * (Math.abs(anchorCenterVector.y) + bbox.height)
	            );
	            var intersectionLine = new Line(anchor, endpoint);

	            // get the farther intersection, in case there are two
	            // (that happens if anchor lies next to bbox)
	            var intersections = intersectionLine.intersect(bbox) || [];
	            var numIntersections = intersections.length;
	            var farthestIntersectionDistance;
	            var farthestIntersection = null;
	            for (var i = 0; i < numIntersections; i++) {
	                var currentIntersection = intersections[i];
	                var distance = anchor.squaredDistance(currentIntersection);
	                if ((farthestIntersectionDistance === undefined) || (distance > farthestIntersectionDistance)) {
	                    farthestIntersectionDistance = distance;
	                    farthestIntersection = currentIntersection;
	                }
	            }

	            // if an intersection was found in this direction, it is our rectPoint
	            if (farthestIntersection) {
	                var point = align(farthestIntersection, grid, precision);

	                // if the rectPoint lies inside the bbox, offset it by one more step
	                if (bbox.containsPoint(point)) {
	                    point = align(point.offset(direction.x * grid.x, direction.y * grid.y), grid, precision);
	                }

	                // then add the point to the result array
	                // aligned
	                res.push(point);
	            }
	        }

	        return res;
	    }, []);

	    // if anchor lies outside of bbox, add it to the array of points
	    if (!bbox.containsPoint(anchor)) {
	        // aligned
	        rectPoints.push(align(anchor, grid, precision));
	    }

	    return rectPoints;
	}

	// finds the route between two points/rectangles (`from`, `to`) implementing A* algorithm
	// rectangles get rect points assigned by getRectPoints()
	function findRoute(from, to, isPointObstacle, opt) {

	    var precision = opt.precision;

	    // Get grid for this route.

	    var sourceAnchor, targetAnchor;

	    if (from instanceof Rect) { // `from` is sourceBBox
	        sourceAnchor = round$4(getSourceAnchor$1(this, opt).clone(), precision);
	    } else {
	        sourceAnchor = round$4(from.clone(), precision);
	    }

	    if (to instanceof Rect) { // `to` is targetBBox
	        targetAnchor = round$4(getTargetAnchor$1(this, opt).clone(), precision);
	    } else {
	        targetAnchor = round$4(to.clone(), precision);
	    }

	    var grid = getGrid(opt.step, sourceAnchor, targetAnchor);

	    // Get pathfinding points.

	    var start, end; // aligned with grid by definition
	    var startPoints, endPoints; // assumed to be aligned with grid already

	    // set of points we start pathfinding from
	    if (from instanceof Rect) { // `from` is sourceBBox
	        start = sourceAnchor;
	        startPoints = getRectPoints(start, from, opt.startDirections, grid, opt);

	    } else {
	        start = sourceAnchor;
	        startPoints = [start];
	    }

	    // set of points we want the pathfinding to finish at
	    if (to instanceof Rect) { // `to` is targetBBox
	        end = targetAnchor;
	        endPoints = getRectPoints(targetAnchor, to, opt.endDirections, grid, opt);

	    } else {
	        end = targetAnchor;
	        endPoints = [end];
	    }

	    // take into account only accessible rect points (those not under obstacles)
	    startPoints = startPoints.filter(function (p) { return !isPointObstacle(p); });
	    endPoints = endPoints.filter(function (p) { return !isPointObstacle(p); });

	    // Check that there is an accessible route point on both sides.
	    // Otherwise, use fallbackRoute().
	    if (startPoints.length > 0 && endPoints.length > 0) {

	        // The set of tentative points to be evaluated, initially containing the start points.
	        // Rounded to nearest integer for simplicity.
	        var openSet = new SortedSet();
	        // Keeps reference to actual points for given elements of the open set.
	        var points = {};
	        // Keeps reference to a point that is immediate predecessor of given element.
	        var parents = {};
	        // Cost from start to a point along best known path.
	        var costs = {};

	        for (var i = 0, n = startPoints.length; i < n; i++) {
	            // startPoint is assumed to be aligned already
	            var startPoint = startPoints[i];

	            var key = getKey(startPoint);

	            openSet.add(key, estimateCost(startPoint, endPoints));
	            points[key] = startPoint;
	            costs[key] = 0;
	        }

	        var previousRouteDirectionAngle = opt.previousDirectionAngle; // undefined for first route
	        var isPathBeginning = (previousRouteDirectionAngle === undefined);

	        // directions
	        var direction, directionChange;
	        var directions = opt.directions;
	        getGridOffsets(directions, grid, opt);

	        var numDirections = directions.length;

	        var endPointsKeys = toArray(endPoints).reduce(function(res, endPoint) {
	            // endPoint is assumed to be aligned already

	            var key = getKey(endPoint);
	            res.push(key);
	            return res;
	        }, []);

	        // main route finding loop
	        var loopsRemaining = opt.maximumLoops;
	        while (!openSet.isEmpty() && loopsRemaining > 0) {

	            // remove current from the open list
	            var currentKey = openSet.pop();
	            var currentPoint = points[currentKey];
	            var currentParent = parents[currentKey];
	            var currentCost = costs[currentKey];

	            var isRouteBeginning = (currentParent === undefined); // undefined for route starts
	            var isStart = currentPoint.equals(start); // (is source anchor or `from` point) = can leave in any direction

	            var previousDirectionAngle;
	            if (!isRouteBeginning) { previousDirectionAngle = getDirectionAngle(currentParent, currentPoint, numDirections, grid, opt); } // a vertex on the route
	            else if (!isPathBeginning) { previousDirectionAngle = previousRouteDirectionAngle; } // beginning of route on the path
	            else if (!isStart) { previousDirectionAngle = getDirectionAngle(start, currentPoint, numDirections, grid, opt); } // beginning of path, start rect point
	            else { previousDirectionAngle = null; } // beginning of path, source anchor or `from` point

	            // check if we reached any endpoint
	            var samePoints = startPoints.length === endPoints.length;
	            if (samePoints) {
	                for (var j = 0; j < startPoints.length; j++) {
	                    if (!startPoints[j].equals(endPoints[j])) {
	                        samePoints = false;
	                        break;
	                    }
	                }
	            }
	            var skipEndCheck = (isRouteBeginning && samePoints);
	            if (!skipEndCheck && (endPointsKeys.indexOf(currentKey) >= 0)) {
	                opt.previousDirectionAngle = previousDirectionAngle;
	                return reconstructRoute(parents, points, currentPoint, start, end, grid, opt);
	            }

	            // go over all possible directions and find neighbors
	            for (i = 0; i < numDirections; i++) {
	                direction = directions[i];

	                var directionAngle = direction.angle;
	                directionChange = getDirectionChange(previousDirectionAngle, directionAngle);

	                // if the direction changed rapidly, don't use this point
	                // any direction is allowed for starting points
	                if (!(isPathBeginning && isStart) && directionChange > opt.maxAllowedDirectionChange) { continue; }

	                var neighborPoint = align(currentPoint.clone().offset(direction.gridOffsetX, direction.gridOffsetY), grid, precision);
	                var neighborKey = getKey(neighborPoint);

	                // Closed points from the openSet were already evaluated.
	                if (openSet.isClose(neighborKey) || isPointObstacle(neighborPoint)) { continue; }

	                // We can only enter end points at an acceptable angle.
	                if (endPointsKeys.indexOf(neighborKey) >= 0) { // neighbor is an end point

	                    var isNeighborEnd = neighborPoint.equals(end); // (is target anchor or `to` point) = can be entered in any direction

	                    if (!isNeighborEnd) {
	                        var endDirectionAngle = getDirectionAngle(neighborPoint, end, numDirections, grid, opt);
	                        var endDirectionChange = getDirectionChange(directionAngle, endDirectionAngle);

	                        if (endDirectionChange > opt.maxAllowedDirectionChange) { continue; }
	                    }
	                }

	                // The current direction is ok.

	                var neighborCost = direction.cost;
	                var neighborPenalty = isStart ? 0 : opt.penalties[directionChange]; // no penalties for start point
	                var costFromStart = currentCost + neighborCost + neighborPenalty;

	                if (!openSet.isOpen(neighborKey) || (costFromStart < costs[neighborKey])) {
	                    // neighbor point has not been processed yet
	                    // or the cost of the path from start is lower than previously calculated

	                    points[neighborKey] = neighborPoint;
	                    parents[neighborKey] = currentPoint;
	                    costs[neighborKey] = costFromStart;
	                    openSet.add(neighborKey, costFromStart + estimateCost(neighborPoint, endPoints));
	                }
	            }

	            loopsRemaining--;
	        }
	    }

	    // no route found (`to` point either wasn't accessible or finding route took
	    // way too much calculation)
	    return opt.fallbackRoute.call(this, start, end, opt);
	}

	// resolve some of the options
	function resolveOptions(opt) {

	    opt.directions = result(opt, 'directions');
	    opt.penalties = result(opt, 'penalties');
	    opt.paddingBox = result(opt, 'paddingBox');
	    opt.padding = result(opt, 'padding');

	    if (opt.padding) {
	        // if both provided, opt.padding wins over opt.paddingBox
	        var sides = normalizeSides(opt.padding);
	        opt.paddingBox = {
	            x: -sides.left,
	            y: -sides.top,
	            width: sides.left + sides.right,
	            height: sides.top + sides.bottom
	        };
	    }

	    toArray(opt.directions).forEach(function(direction) {

	        var point1 = new Point(0, 0);
	        var point2 = new Point(direction.offsetX, direction.offsetY);

	        direction.angle = normalizeAngle(point1.theta(point2));
	    });
	}

	// initialization of the route finding
	function router(vertices, opt, linkView) {

	    resolveOptions(opt);

	    // enable/disable linkView perpendicular option
	    linkView.options.perpendicular = !!opt.perpendicular;

	    var sourceBBox = getSourceBBox$1(linkView, opt);
	    var targetBBox = getTargetBBox$1(linkView, opt);

	    var sourceAnchor = getSourceAnchor$1(linkView, opt);
	    //var targetAnchor = getTargetAnchor(linkView, opt);

	    // pathfinding
	    var isPointObstacle;
	    if (typeof opt.isPointObstacle === 'function') {
	        isPointObstacle = opt.isPointObstacle;
	    } else {
	        var map = new ObstacleMap(opt);
	        map.build(linkView.paper.model, linkView.model);
	        isPointObstacle = function (point) { return !map.isPointAccessible(point); };
	    }

	    var oldVertices = toArray(vertices).map(Point);
	    var newVertices = [];
	    var tailPoint = sourceAnchor; // the origin of first route's grid, does not need snapping

	    // find a route by concatenating all partial routes (routes need to pass through vertices)
	    // source -> vertex[1] -> ... -> vertex[n] -> target
	    var to, from;

	    for (var i = 0, len = oldVertices.length; i <= len; i++) {

	        var partialRoute = null;

	        from = to || sourceBBox;
	        to = oldVertices[i];

	        if (!to) {
	            // this is the last iteration
	            // we ran through all vertices in oldVertices
	            // 'to' is not a vertex.

	            to = targetBBox;

	            // If the target is a point (i.e. it's not an element), we
	            // should use dragging route instead of main routing method if it has been provided.
	            var isEndingAtPoint = !linkView.model.get('source').id || !linkView.model.get('target').id;

	            if (isEndingAtPoint && isFunction(opt.draggingRoute)) {
	                // Make sure we are passing points only (not rects).
	                var dragFrom = (from === sourceBBox) ? sourceAnchor : from;
	                var dragTo = to.origin();

	                partialRoute = opt.draggingRoute.call(linkView, dragFrom, dragTo, opt);
	            }
	        }

	        // if partial route has not been calculated yet use the main routing method to find one
	        partialRoute = partialRoute || findRoute.call(linkView, from, to, isPointObstacle, opt);

	        if (partialRoute === null) { // the partial route cannot be found
	            return opt.fallbackRouter(vertices, opt, linkView);
	        }

	        var leadPoint = partialRoute[0];

	        // remove the first point if the previous partial route had the same point as last
	        if (leadPoint && leadPoint.equals(tailPoint)) { partialRoute.shift(); }

	        // save tailPoint for next iteration
	        tailPoint = partialRoute[partialRoute.length - 1] || tailPoint;

	        Array.prototype.push.apply(newVertices, partialRoute);
	    }

	    return newVertices;
	}

	// public function
	var manhattan = function(vertices, opt, linkView) {
	    return router(vertices, assign({}, config$1, opt), linkView);
	};

	var config$2 = {

	    maxAllowedDirectionChange: 45,

	    // cost of a diagonal step
	    diagonalCost: function() {

	        var step = this.step;
	        return Math.ceil(Math.sqrt(step * step << 1));
	    },

	    // an array of directions to find next points on the route
	    // different from start/end directions
	    directions: function() {

	        var step = this.step;
	        var cost = this.cost();
	        var diagonalCost = this.diagonalCost();

	        return [
	            { offsetX: step, offsetY: 0, cost: cost },
	            { offsetX: step, offsetY: step, cost: diagonalCost },
	            { offsetX: 0, offsetY: step, cost: cost },
	            { offsetX: -step, offsetY: step, cost: diagonalCost },
	            { offsetX: -step, offsetY: 0, cost: cost },
	            { offsetX: -step, offsetY: -step, cost: diagonalCost },
	            { offsetX: 0, offsetY: -step, cost: cost },
	            { offsetX: step, offsetY: -step, cost: diagonalCost }
	        ];
	    },

	    // a simple route used in situations when main routing method fails
	    // (exceed max number of loop iterations, inaccessible)
	    fallbackRoute: function(from, to, opt) {

	        // Find a route which breaks by 45 degrees ignoring all obstacles.

	        var theta = from.theta(to);

	        var route = [];

	        var a = { x: to.x, y: from.y };
	        var b = { x: from.x, y: to.y };

	        if (theta % 180 > 90) {
	            var t = a;
	            a = b;
	            b = t;
	        }

	        var p1 = (theta % 90) < 45 ? a : b;
	        var l1 = new Line(from, p1);

	        var alpha = 90 * Math.ceil(theta / 90);

	        var p2 = Point.fromPolar(l1.squaredLength(), toRad(alpha + 135), p1);
	        var l2 = new Line(to, p2);

	        var intersectionPoint = l1.intersection(l2);
	        var point = intersectionPoint ? intersectionPoint : to;

	        var directionFrom = intersectionPoint ? point : from;

	        var quadrant = 360 / opt.directions.length;
	        var angleTheta = directionFrom.theta(to);
	        var normalizedAngle = normalizeAngle(angleTheta + (quadrant / 2));
	        var directionAngle = quadrant * Math.floor(normalizedAngle / quadrant);

	        opt.previousDirectionAngle = directionAngle;

	        if (point) { route.push(point.round()); }
	        route.push(to);

	        return route;
	    }
	};

	// public function
	var metro = function(vertices, opt, linkView) {

	    if (!isFunction(manhattan)) {
	        throw new Error('Metro requires the manhattan router.');
	    }

	    return manhattan(vertices, assign({}, config$2, opt), linkView);
	};



	var routers = ({
		normal: normal,
		oneSide: oneSide,
		orthogonal: orthogonal,
		manhattan: manhattan,
		metro: metro
	});

	// default size of jump if not specified in options
	var JUMP_SIZE = 5;

	// available jump types
	// first one taken as default
	var JUMP_TYPES = ['arc', 'gap', 'cubic'];

	// default radius
	var RADIUS = 0;

	// takes care of math. error for case when jump is too close to end of line
	var CLOSE_PROXIMITY_PADDING = 1;

	// list of connector types not to jump over.
	var IGNORED_CONNECTORS = ['smooth'];

	// internal constants for round segment
	var _13 = 1 / 3;
	var _23 = 2 / 3;

	/**
	 * Transform start/end and route into series of lines
	 * @param {g.point} sourcePoint start point
	 * @param {g.point} targetPoint end point
	 * @param {g.point[]} route optional list of route
	 * @return {g.line[]} [description]
	 */
	function createLines(sourcePoint, targetPoint, route) {
	    // make a flattened array of all points
	    var points = [].concat(sourcePoint, route, targetPoint);
	    return points.reduce(function(resultLines, point, idx) {
	        // if there is a next point, make a line with it
	        var nextPoint = points[idx + 1];
	        if (nextPoint != null) {
	            resultLines[idx] = line(point, nextPoint);
	        }
	        return resultLines;
	    }, []);
	}

	function setupUpdating(jumpOverLinkView) {
	    var paper = jumpOverLinkView.paper;
	    var updateList = paper._jumpOverUpdateList;

	    // first time setup for this paper
	    if (updateList == null) {
	        updateList = paper._jumpOverUpdateList = [];
	        var graph = paper.model;
	        graph.on('batch:stop', function() {
	            if (this.hasActiveBatch()) { return; }
	            updateJumpOver(paper);
	        });
	        graph.on('reset', function() {
	            updateList = paper._jumpOverUpdateList = [];
	        });
	    }

	    // add this link to a list so it can be updated when some other link is updated
	    if (updateList.indexOf(jumpOverLinkView) < 0) {
	        updateList.push(jumpOverLinkView);

	        // watch for change of connector type or removal of link itself
	        // to remove the link from a list of jump over connectors
	        jumpOverLinkView.listenToOnce(jumpOverLinkView.model, 'change:connector remove', function() {
	            updateList.splice(updateList.indexOf(jumpOverLinkView), 1);
	        });
	    }
	}

	/**
	 * Handler for a batch:stop event to force
	 * update of all registered links with jump over connector
	 * @param {object} batchEvent optional object with info about batch
	 */
	function updateJumpOver(paper) {
	    var updateList = paper._jumpOverUpdateList;
	    for (var i = 0; i < updateList.length; i++) {
	        var linkView = updateList[i];
	        var updateFlag = linkView.getFlag(linkView.constructor.Flags.CONNECTOR);
	        linkView.requestUpdate(updateFlag);
	    }
	}

	/**
	 * Utility function to collect all intersection points of a single
	 * line against group of other lines.
	 * @param {g.line} line where to find points
	 * @param {g.line[]} crossCheckLines lines to cross
	 * @return {g.point[]} list of intersection points
	 */
	function findLineIntersections(line, crossCheckLines) {
	    return toArray(crossCheckLines).reduce(function(res, crossCheckLine) {
	        var intersection = line.intersection(crossCheckLine);
	        if (intersection) {
	            res.push(intersection);
	        }
	        return res;
	    }, []);
	}

	/**
	 * Sorting function for list of points by their distance.
	 * @param {g.point} p1 first point
	 * @param {g.point} p2 second point
	 * @return {number} squared distance between points
	 */
	function sortPoints(p1, p2) {
	    return line(p1, p2).squaredLength();
	}

	/**
	 * Split input line into multiple based on intersection points.
	 * @param {g.line} line input line to split
	 * @param {g.point[]} intersections points where to split the line
	 * @param {number} jumpSize the size of jump arc (length empty spot on a line)
	 * @return {g.line[]} list of lines being split
	 */
	function createJumps(line$1, intersections, jumpSize) {
	    return intersections.reduce(function(resultLines, point$1, idx) {
	        // skipping points that were merged with the previous line
	        // to make bigger arc over multiple lines that are close to each other
	        if (point$1.skip === true) {
	            return resultLines;
	        }

	        // always grab the last line from buffer and modify it
	        var lastLine = resultLines.pop() || line$1;

	        // calculate start and end of jump by moving by a given size of jump
	        var jumpStart = point(point$1).move(lastLine.start, -(jumpSize));
	        var jumpEnd = point(point$1).move(lastLine.start, +(jumpSize));

	        // now try to look at the next intersection point
	        var nextPoint = intersections[idx + 1];
	        if (nextPoint != null) {
	            var distance = jumpEnd.distance(nextPoint);
	            if (distance <= jumpSize) {
	                // next point is close enough, move the jump end by this
	                // difference and mark the next point to be skipped
	                jumpEnd = nextPoint.move(lastLine.start, distance);
	                nextPoint.skip = true;
	            }
	        } else {
	            // this block is inside of `else` as an optimization so the distance is
	            // not calculated when we know there are no other intersection points
	            var endDistance = jumpStart.distance(lastLine.end);
	            // if the end is too close to possible jump, draw remaining line instead of a jump
	            if (endDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) {
	                resultLines.push(lastLine);
	                return resultLines;
	            }
	        }

	        var startDistance = jumpEnd.distance(lastLine.start);
	        if (startDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) {
	            // if the start of line is too close to jump, draw that line instead of a jump
	            resultLines.push(lastLine);
	            return resultLines;
	        }

	        // finally create a jump line
	        var jumpLine = line(jumpStart, jumpEnd);
	        // it's just simple line but with a `isJump` property
	        jumpLine.isJump = true;

	        resultLines.push(
	            line(lastLine.start, jumpStart),
	            jumpLine,
	            line(jumpEnd, lastLine.end)
	        );
	        return resultLines;
	    }, []);
	}

	/**
	 * Assemble `D` attribute of a SVG path by iterating given lines.
	 * @param {g.line[]} lines source lines to use
	 * @param {number} jumpSize the size of jump arc (length empty spot on a line)
	 * @param {number} radius the radius
	 * @return {string}
	 */
	function buildPath(lines, jumpSize, jumpType, radius) {

	    var path = new Path();
	    var segment;

	    // first move to the start of a first line
	    segment = Path.createSegment('M', lines[0].start);
	    path.appendSegment(segment);

	    // make a paths from lines
	    toArray(lines).forEach(function(line, index) {

	        if (line.isJump) {
	            var angle, diff;

	            var control1, control2;

	            if (jumpType === 'arc') { // approximates semicircle with 2 curves
	                angle = -90;
	                // determine rotation of arc based on difference between points
	                diff = line.start.difference(line.end);
	                // make sure the arc always points up (or right)
	                var xAxisRotate = Number((diff.x < 0) || (diff.x === 0 && diff.y < 0));
	                if (xAxisRotate) { angle += 180; }

	                var midpoint = line.midpoint();
	                var centerLine = new Line(midpoint, line.end).rotate(midpoint, angle);

	                var halfLine;

	                // first half
	                halfLine = new Line(line.start, midpoint);

	                control1 = halfLine.pointAt(2 / 3).rotate(line.start, angle);
	                control2 = centerLine.pointAt(1 / 3).rotate(centerLine.end, -angle);

	                segment = Path.createSegment('C', control1, control2, centerLine.end);
	                path.appendSegment(segment);

	                // second half
	                halfLine = new Line(midpoint, line.end);

	                control1 = centerLine.pointAt(1 / 3).rotate(centerLine.end, angle);
	                control2 = halfLine.pointAt(1 / 3).rotate(line.end, -angle);

	                segment = Path.createSegment('C', control1, control2, line.end);
	                path.appendSegment(segment);

	            } else if (jumpType === 'gap') {
	                segment = Path.createSegment('M', line.end);
	                path.appendSegment(segment);

	            } else if (jumpType === 'cubic') { // approximates semicircle with 1 curve
	                angle = line.start.theta(line.end);

	                var xOffset = jumpSize * 0.6;
	                var yOffset = jumpSize * 1.35;

	                // determine rotation of arc based on difference between points
	                diff = line.start.difference(line.end);
	                // make sure the arc always points up (or right)
	                xAxisRotate = Number((diff.x < 0) || (diff.x === 0 && diff.y < 0));
	                if (xAxisRotate) { yOffset *= -1; }

	                control1 = Point(line.start.x + xOffset, line.start.y + yOffset).rotate(line.start, angle);
	                control2 = Point(line.end.x - xOffset, line.end.y + yOffset).rotate(line.end, angle);

	                segment = Path.createSegment('C', control1, control2, line.end);
	                path.appendSegment(segment);
	            }

	        } else {
	            var nextLine = lines[index + 1];
	            if (radius == 0 || !nextLine || nextLine.isJump) {
	                segment = Path.createSegment('L', line.end);
	                path.appendSegment(segment);
	            } else {
	                buildRoundedSegment(radius, path, line.end, line.start, nextLine.end);
	            }
	        }
	    });

	    return path;
	}

	function buildRoundedSegment(offset, path, curr, prev, next) {
	    var prevDistance = curr.distance(prev) / 2;
	    var nextDistance = curr.distance(next) / 2;

	    var startMove = -Math.min(offset, prevDistance);
	    var endMove = -Math.min(offset, nextDistance);

	    var roundedStart = curr.clone().move(prev, startMove).round();
	    var roundedEnd = curr.clone().move(next, endMove).round();

	    var control1 = new Point((_13 * roundedStart.x) + (_23 * curr.x), (_23 * curr.y) + (_13 * roundedStart.y));
	    var control2 = new Point((_13 * roundedEnd.x) + (_23 * curr.x), (_23 * curr.y) + (_13 * roundedEnd.y));

	    var segment;
	    segment = Path.createSegment('L', roundedStart);
	    path.appendSegment(segment);

	    segment = Path.createSegment('C', control1, control2, roundedEnd);
	    path.appendSegment(segment);
	}

	/**
	 * Actual connector function that will be run on every update.
	 * @param {g.point} sourcePoint start point of this link
	 * @param {g.point} targetPoint end point of this link
	 * @param {g.point[]} route of this link
	 * @param {object} opt options
	 * @property {number} size optional size of a jump arc
	 * @return {string} created `D` attribute of SVG path
	 */
	var jumpover = function(sourcePoint, targetPoint, route, opt) { // eslint-disable-line max-params

	    setupUpdating(this);

	    var raw = opt.raw;
	    var jumpSize = opt.size || JUMP_SIZE;
	    var jumpType = opt.jump && ('' + opt.jump).toLowerCase();
	    var radius = opt.radius || RADIUS;
	    var ignoreConnectors = opt.ignoreConnectors || IGNORED_CONNECTORS;

	    // grab the first jump type as a default if specified one is invalid
	    if (JUMP_TYPES.indexOf(jumpType) === -1) {
	        jumpType = JUMP_TYPES[0];
	    }

	    var paper = this.paper;
	    var graph = paper.model;
	    var allLinks = graph.getLinks();

	    // there is just one link, draw it directly
	    if (allLinks.length === 1) {
	        return buildPath(
	            createLines(sourcePoint, targetPoint, route),
	            jumpSize, jumpType, radius
	        );
	    }

	    var thisModel = this.model;
	    var thisIndex = allLinks.indexOf(thisModel);
	    var defaultConnector = paper.options.defaultConnector || {};

	    // not all links are meant to be jumped over.
	    var links = allLinks.filter(function(link, idx) {

	        var connector = link.get('connector') || defaultConnector;

	        // avoid jumping over links with connector type listed in `ignored connectors`.
	        if (toArray(ignoreConnectors).includes(connector.name)) {
	            return false;
	        }
	        // filter out links that are above this one and  have the same connector type
	        // otherwise there would double hoops for each intersection
	        if (idx > thisIndex) {
	            return connector.name !== 'jumpover';
	        }
	        return true;
	    });

	    // find views for all links
	    var linkViews = links.map(function(link) {
	        return paper.findViewByModel(link);
	    });

	    // create lines for this link
	    var thisLines = createLines(
	        sourcePoint,
	        targetPoint,
	        route
	    );

	    // create lines for all other links
	    var linkLines = linkViews.map(function(linkView) {
	        if (linkView == null) {
	            return [];
	        }
	        if (linkView === this) {
	            return thisLines;
	        }
	        return createLines(
	            linkView.sourcePoint,
	            linkView.targetPoint,
	            linkView.route
	        );
	    }, this);

	    // transform lines for this link by splitting with jump lines at
	    // points of intersection with other links
	    var jumpingLines = thisLines.reduce(function(resultLines, thisLine) {
	        // iterate all links and grab the intersections with this line
	        // these are then sorted by distance so the line can be split more easily

	        var intersections = links.reduce(function(res, link, i) {
	            // don't intersection with itself
	            if (link !== thisModel) {

	                var lineIntersections = findLineIntersections(thisLine, linkLines[i]);
	                res.push.apply(res, lineIntersections);
	            }
	            return res;
	        }, []).sort(function(a, b) {
	            return sortPoints(thisLine.start, a) - sortPoints(thisLine.start, b);
	        });

	        if (intersections.length > 0) {
	            // split the line based on found intersection points
	            resultLines.push.apply(resultLines, createJumps(thisLine, intersections, jumpSize));
	        } else {
	            // without any intersection the line goes uninterrupted
	            resultLines.push(thisLine);
	        }
	        return resultLines;
	    }, []);

	    var path = buildPath(jumpingLines, jumpSize, jumpType, radius);
	    return (raw) ? path : path.serialize();
	};

	var normal$1 = function(sourcePoint, targetPoint, route, opt) {

	    var raw = opt && opt.raw;
	    var points = [sourcePoint].concat(route).concat([targetPoint]);

	    var polyline = new Polyline(points);
	    var path = new Path(polyline);

	    return (raw) ? path : path.serialize();
	};

	var rounded = function(sourcePoint, targetPoint, route, opt) {

	    opt || (opt = {});

	    var offset = opt.radius || 10;
	    var raw = opt.raw;
	    var path = new Path();
	    var segment;

	    segment = Path.createSegment('M', sourcePoint);
	    path.appendSegment(segment);

	    var _13 = 1 / 3;
	    var _23 = 2 / 3;

	    var curr;
	    var prev, next;
	    var prevDistance, nextDistance;
	    var startMove, endMove;
	    var roundedStart, roundedEnd;
	    var control1, control2;

	    for (var index = 0, n = route.length; index < n; index++) {

	        curr = new Point(route[index]);

	        prev = route[index - 1] || sourcePoint;
	        next = route[index + 1] || targetPoint;

	        prevDistance = nextDistance || (curr.distance(prev) / 2);
	        nextDistance = curr.distance(next) / 2;

	        startMove = -Math.min(offset, prevDistance);
	        endMove = -Math.min(offset, nextDistance);

	        roundedStart = curr.clone().move(prev, startMove).round();
	        roundedEnd = curr.clone().move(next, endMove).round();

	        control1 = new Point((_13 * roundedStart.x) + (_23 * curr.x), (_23 * curr.y) + (_13 * roundedStart.y));
	        control2 = new Point((_13 * roundedEnd.x) + (_23 * curr.x), (_23 * curr.y) + (_13 * roundedEnd.y));

	        segment = Path.createSegment('L', roundedStart);
	        path.appendSegment(segment);

	        segment = Path.createSegment('C', control1, control2, roundedEnd);
	        path.appendSegment(segment);
	    }

	    segment = Path.createSegment('L', targetPoint);
	    path.appendSegment(segment);

	    return (raw) ? path : path.serialize();
	};

	var smooth = function(sourcePoint, targetPoint, route, opt) {

	    var raw = opt && opt.raw;
	    var path;

	    if (route && route.length !== 0) {

	        var points = [sourcePoint].concat(route).concat([targetPoint]);
	        var curves = Curve.throughPoints(points);

	        path = new Path(curves);

	    } else {
	        // if we have no route, use a default cubic bezier curve
	        // cubic bezier requires two control points
	        // the control points have `x` midway between source and target
	        // this produces an S-like curve

	        path = new Path();

	        var segment;

	        segment = Path.createSegment('M', sourcePoint);
	        path.appendSegment(segment);

	        if ((Math.abs(sourcePoint.x - targetPoint.x)) >= (Math.abs(sourcePoint.y - targetPoint.y))) {
	            var controlPointX = (sourcePoint.x + targetPoint.x) / 2;

	            segment = Path.createSegment('C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y, targetPoint.x, targetPoint.y);
	            path.appendSegment(segment);

	        } else {
	            var controlPointY = (sourcePoint.y + targetPoint.y) / 2;

	            segment = Path.createSegment('C', sourcePoint.x, controlPointY, targetPoint.x, controlPointY, targetPoint.x, targetPoint.y);
	            path.appendSegment(segment);

	        }
	    }

	    return (raw) ? path : path.serialize();
	};



	var connectors = ({
		jumpover: jumpover,
		normal: normal$1,
		rounded: rounded,
		smooth: smooth
	});

	var Flags$1 = {
	    RENDER: 'RENDER',
	    UPDATE: 'UPDATE',
	    TOOLS: 'TOOLS',
	    LEGACY_TOOLS: 'LEGACY_TOOLS',
	    LABELS: 'LABELS',
	    VERTICES: 'VERTICES',
	    SOURCE: 'SOURCE',
	    TARGET: 'TARGET',
	    CONNECTOR: 'CONNECTOR'
	};

	// Link base view and controller.
	// ----------------------------------------

	var LinkView = CellView.extend({

	    className: function() {

	        var classNames = CellView.prototype.className.apply(this).split(' ');

	        classNames.push('link');

	        return classNames.join(' ');
	    },

	    options: {

	        shortLinkLength: 105,
	        doubleLinkTools: false,
	        longLinkLength: 155,
	        linkToolsOffset: 40,
	        doubleLinkToolsOffset: 65,
	        sampleInterval: 50,
	    },

	    _labelCache: null,
	    _labelSelectors: null,
	    _markerCache: null,
	    _V: null,
	    _dragData: null, // deprecated

	    metrics: null,
	    decimalsRounding: 2,

	    initialize: function() {

	        CellView.prototype.initialize.apply(this, arguments);

	        // `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to
	        // `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the
	        // nodes in `updateLabelPosition()` in order to update the label positions.
	        this._labelCache = {};

	        // a cache of label selectors
	        this._labelSelectors = {};

	        // keeps markers bboxes and positions again for quicker access
	        this._markerCache = {};

	        // cache of default markup nodes
	        this._V = {};

	        // connection path metrics
	        this.cleanNodesCache();
	    },

	    presentationAttributes: {
	        markup: [Flags$1.RENDER],
	        attrs: [Flags$1.UPDATE],
	        router: [Flags$1.UPDATE],
	        connector: [Flags$1.CONNECTOR],
	        smooth: [Flags$1.UPDATE],
	        manhattan: [Flags$1.UPDATE],
	        toolMarkup: [Flags$1.LEGACY_TOOLS],
	        labels: [Flags$1.LABELS],
	        labelMarkup: [Flags$1.LABELS],
	        vertices: [Flags$1.VERTICES, Flags$1.UPDATE],
	        vertexMarkup: [Flags$1.VERTICES],
	        source: [Flags$1.SOURCE, Flags$1.UPDATE],
	        target: [Flags$1.TARGET, Flags$1.UPDATE]
	    },

	    initFlag: [Flags$1.RENDER, Flags$1.SOURCE, Flags$1.TARGET, Flags$1.TOOLS],

	    UPDATE_PRIORITY: 1,

	    confirmUpdate: function(flags, opt) {

	        opt || (opt = {});

	        if (this.hasFlag(flags, Flags$1.SOURCE)) {
	            if (!this.updateEndProperties('source')) { return flags; }
	            flags = this.removeFlag(flags, Flags$1.SOURCE);
	        }

	        if (this.hasFlag(flags, Flags$1.TARGET)) {
	            if (!this.updateEndProperties('target')) { return flags; }
	            flags = this.removeFlag(flags, Flags$1.TARGET);
	        }

	        var ref = this;
	        var paper = ref.paper;
	        var sourceView = ref.sourceView;
	        var targetView = ref.targetView;
	        if (paper && ((sourceView && !paper.isViewMounted(sourceView)) || (targetView && !paper.isViewMounted(targetView)))) {
	            // Wait for the sourceView and targetView to be rendered
	            return flags;
	        }

	        if (this.hasFlag(flags, Flags$1.RENDER)) {
	            this.render();
	            this.updateHighlighters(true);
	            this.updateTools(opt);
	            flags = this.removeFlag(flags, [Flags$1.RENDER, Flags$1.UPDATE, Flags$1.VERTICES, Flags$1.LABELS, Flags$1.TOOLS, Flags$1.LEGACY_TOOLS, Flags$1.CONNECTOR]);
	            return flags;
	        }

	        var updateHighlighters = false;

	        if (this.hasFlag(flags, Flags$1.VERTICES)) {
	            this.renderVertexMarkers();
	            flags = this.removeFlag(flags, Flags$1.VERTICES);
	        }

	        var ref$1 = this;
	        var model = ref$1.model;
	        var attributes = model.attributes;
	        var updateLabels = this.hasFlag(flags, Flags$1.LABELS);
	        var updateLegacyTools = this.hasFlag(flags, Flags$1.LEGACY_TOOLS);

	        if (updateLabels) {
	            this.onLabelsChange(model, attributes.labels, opt);
	            flags = this.removeFlag(flags, Flags$1.LABELS);
	            updateHighlighters = true;
	        }

	        if (updateLegacyTools) {
	            this.renderTools();
	            flags = this.removeFlag(flags, Flags$1.LEGACY_TOOLS);
	        }

	        var updateAll = this.hasFlag(flags, Flags$1.UPDATE);
	        var updateConnector = this.hasFlag(flags, Flags$1.CONNECTOR);
	        if (updateAll || updateConnector) {
	            if (!updateAll) {
	                // Keep the current route and update the geometry
	                this.updatePath();
	                this.updateDOM();
	            } else if (opt.translateBy && model.isRelationshipEmbeddedIn(opt.translateBy)) {
	                // The link is being translated by an ancestor that will
	                // shift source point, target point and all vertices
	                // by an equal distance.
	                this.translate(opt.tx, opt.ty);
	            } else {
	                this.update();
	            }
	            this.updateTools(opt);
	            flags = this.removeFlag(flags, [Flags$1.UPDATE, Flags$1.TOOLS, Flags$1.CONNECTOR]);
	            updateLabels = false;
	            updateLegacyTools = false;
	            updateHighlighters = true;
	        }

	        if (updateLabels) {
	            this.updateLabelPositions();
	        }

	        if (updateLegacyTools) {
	            this.updateToolsPosition();
	        }

	        if (updateHighlighters) {
	            this.updateHighlighters();
	        }

	        if (this.hasFlag(flags, Flags$1.TOOLS)) {
	            this.updateTools(opt);
	            flags = this.removeFlag(flags, Flags$1.TOOLS);
	        }

	        return flags;
	    },

	    requestConnectionUpdate: function(opt) {
	        this.requestUpdate(this.getFlag(Flags$1.UPDATE), opt);
	    },

	    isLabelsRenderRequired: function(opt) {
	        if ( opt === void 0 ) opt = {};


	        var previousLabels = this.model.previous('labels');
	        if (!previousLabels) { return true; }

	        // Here is an optimization for cases when we know, that change does
	        // not require re-rendering of all labels.
	        if (('propertyPathArray' in opt) && ('propertyValue' in opt)) {
	            // The label is setting by `prop()` method
	            var pathArray = opt.propertyPathArray || [];
	            var pathLength = pathArray.length;
	            if (pathLength > 1) {
	                // We are changing a single label here e.g. 'labels/0/position'
	                var labelExists = !!previousLabels[pathArray[1]];
	                if (labelExists) {
	                    if (pathLength === 2) {
	                        // We are changing the entire label. Need to check if the
	                        // markup is also being changed.
	                        return ('markup' in Object(opt.propertyValue));
	                    } else if (pathArray[2] !== 'markup') {
	                        // We are changing a label property but not the markup
	                        return false;
	                    }
	                }
	            }
	        }

	        return true;
	    },

	    onLabelsChange: function(_link, _labels, opt) {

	        // Note: this optimization works in async=false mode only
	        if (this.isLabelsRenderRequired(opt)) {
	            this.renderLabels();
	        } else {
	            this.updateLabels();
	        }
	    },

	    // Rendering.
	    // ----------

	    render: function() {

	        this.vel.empty();
	        this._V = {};
	        this.renderMarkup();
	        // rendering labels has to be run after the link is appended to DOM tree. (otherwise <Text> bbox
	        // returns zero values)
	        this.renderLabels();
	        this.update();

	        return this;
	    },

	    renderMarkup: function() {

	        var link = this.model;
	        var markup = link.get('markup') || link.markup;
	        if (!markup) { throw new Error('dia.LinkView: markup required'); }
	        if (Array.isArray(markup)) { return this.renderJSONMarkup(markup); }
	        if (typeof markup === 'string') { return this.renderStringMarkup(markup); }
	        throw new Error('dia.LinkView: invalid markup');
	    },

	    renderJSONMarkup: function(markup) {

	        var doc = this.parseDOMJSON(markup, this.el);
	        // Selectors
	        this.selectors = doc.selectors;
	        // Fragment
	        this.vel.append(doc.fragment);
	    },

	    renderStringMarkup: function(markup) {

	        // A special markup can be given in the `properties.markup` property. This might be handy
	        // if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s.
	        // `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors
	        // of elements with special meaning though. Therefore, those classes should be preserved in any
	        // special markup passed in `properties.markup`.
	        var children = V(markup);
	        // custom markup may contain only one children
	        if (!Array.isArray(children)) { children = [children]; }
	        // Cache all children elements for quicker access.
	        var cache = this._V; // vectorized markup;
	        for (var i = 0, n = children.length; i < n; i++) {
	            var child = children[i];
	            var className = child.attr('class');
	            if (className) {
	                // Strip the joint class name prefix, if there is one.
	                className = removeClassNamePrefix(className);
	                cache[$.camelCase(className)] = child;
	            }
	        }
	        // partial rendering
	        this.renderTools();
	        this.renderVertexMarkers();
	        this.renderArrowheadMarkers();
	        this.vel.append(children);
	    },

	    _getLabelMarkup: function(labelMarkup) {

	        if (!labelMarkup) { return undefined; }

	        if (Array.isArray(labelMarkup)) { return this.parseDOMJSON(labelMarkup, null); }
	        if (typeof labelMarkup === 'string') { return this._getLabelStringMarkup(labelMarkup); }
	        throw new Error('dia.linkView: invalid label markup');
	    },

	    _getLabelStringMarkup: function(labelMarkup) {

	        var children = V(labelMarkup);
	        var fragment = document.createDocumentFragment();

	        if (!Array.isArray(children)) {
	            fragment.appendChild(children.node);

	        } else {
	            for (var i = 0, n = children.length; i < n; i++) {
	                var currentChild = children[i].node;
	                fragment.appendChild(currentChild);
	            }
	        }

	        return { fragment: fragment, selectors: {}}; // no selectors
	    },

	    // Label markup fragment may come wrapped in <g class="label" />, or not.
	    // If it doesn't, add the <g /> container here.
	    _normalizeLabelMarkup: function(markup) {

	        if (!markup) { return undefined; }

	        var fragment = markup.fragment;
	        if (!(markup.fragment instanceof DocumentFragment) || !markup.fragment.hasChildNodes()) { throw new Error('dia.LinkView: invalid label markup.'); }

	        var vNode;
	        var childNodes = fragment.childNodes;

	        if ((childNodes.length > 1) || childNodes[0].nodeName.toUpperCase() !== 'G') {
	            // default markup fragment is not wrapped in <g />
	            // add a <g /> container
	            vNode = V('g').append(fragment);
	        } else {
	            vNode = V(childNodes[0]);
	        }

	        vNode.addClass('label');

	        return { node: vNode.node, selectors: markup.selectors };
	    },

	    renderLabels: function() {

	        var cache = this._V;
	        var vLabels = cache.labels;
	        var labelCache = this._labelCache = {};
	        var labelSelectors = this._labelSelectors = {};
	        var model = this.model;
	        var labels = model.attributes.labels || [];
	        var labelsCount = labels.length;

	        if (labelsCount === 0) {
	            if (vLabels) { vLabels.remove(); }
	            return this;
	        }

	        if (vLabels) {
	            vLabels.empty();
	        }  else {
	            // there is no label container in the markup but some labels are defined
	            // add a <g class="labels" /> container
	            vLabels = cache.labels = V('g').addClass('labels');
	        }

	        var container = vLabels.node;

	        for (var i = 0; i < labelsCount; i++) {

	            var label = labels[i];
	            var labelMarkup = this._normalizeLabelMarkup(this._getLabelMarkup(label.markup));
	            var labelNode;
	            var selectors;
	            if (labelMarkup) {

	                labelNode = labelMarkup.node;
	                selectors = labelMarkup.selectors;

	            } else {

	                var builtinDefaultLabel =  model._builtins.defaultLabel;
	                var builtinDefaultLabelMarkup = this._normalizeLabelMarkup(this._getLabelMarkup(builtinDefaultLabel.markup));
	                var defaultLabel = model._getDefaultLabel();
	                var defaultLabelMarkup = this._normalizeLabelMarkup(this._getLabelMarkup(defaultLabel.markup));
	                var defaultMarkup = defaultLabelMarkup || builtinDefaultLabelMarkup;

	                labelNode = defaultMarkup.node;
	                selectors = defaultMarkup.selectors;
	            }

	            labelNode.setAttribute('label-idx', i); // assign label-idx
	            container.appendChild(labelNode);
	            labelCache[i] = labelNode; // cache node for `updateLabels()` so it can just update label node positions

	            var rootSelector = this.selector;
	            if (selectors[rootSelector]) { throw new Error('dia.LinkView: ambiguous label root selector.'); }
	            selectors[rootSelector] = labelNode;

	            labelSelectors[i] = selectors; // cache label selectors for `updateLabels()`
	        }

	        if (!container.parentNode) {
	            this.el.appendChild(container);
	        }

	        this.updateLabels();

	        return this;
	    },

	    findLabelNode: function(labelIndex, selector) {
	        var labelRoot = this._labelCache[labelIndex];
	        if (!labelRoot) { return null; }
	        var labelSelectors = this._labelSelectors[labelIndex];
	        var ref = this.findBySelector(selector, labelRoot, labelSelectors);
	        var node = ref[0]; if ( node === void 0 ) node = null;
	        return node;
	    },


	    // merge default label attrs into label attrs
	    // keep `undefined` or `null` because `{}` means something else
	    _mergeLabelAttrs: function(hasCustomMarkup, labelAttrs, defaultLabelAttrs, builtinDefaultLabelAttrs) {

	        if (labelAttrs === null) { return null; }
	        if (labelAttrs === undefined) {

	            if (defaultLabelAttrs === null) { return null; }
	            if (defaultLabelAttrs === undefined) {

	                if (hasCustomMarkup) { return undefined; }
	                return builtinDefaultLabelAttrs;
	            }

	            if (hasCustomMarkup) { return defaultLabelAttrs; }
	            return merge({}, builtinDefaultLabelAttrs, defaultLabelAttrs);
	        }

	        if (hasCustomMarkup) { return merge({}, defaultLabelAttrs, labelAttrs); }
	        return merge({}, builtinDefaultLabelAttrs, defaultLabelAttrs, labelAttrs);
	    },

	    updateLabels: function() {

	        if (!this._V.labels) { return this; }

	        var model = this.model;
	        var labels = model.get('labels') || [];
	        var canLabelMove = this.can('labelMove');

	        var builtinDefaultLabel = model._builtins.defaultLabel;
	        var builtinDefaultLabelAttrs = builtinDefaultLabel.attrs;

	        var defaultLabel = model._getDefaultLabel();
	        var defaultLabelMarkup = defaultLabel.markup;
	        var defaultLabelAttrs = defaultLabel.attrs;

	        for (var i = 0, n = labels.length; i < n; i++) {

	            var labelNode = this._labelCache[i];
	            labelNode.setAttribute('cursor', (canLabelMove ? 'move' : 'default'));

	            var selectors = this._labelSelectors[i];

	            var label = labels[i];
	            var labelMarkup = label.markup;
	            var labelAttrs = label.attrs;

	            var attrs = this._mergeLabelAttrs(
	                (labelMarkup || defaultLabelMarkup),
	                labelAttrs,
	                defaultLabelAttrs,
	                builtinDefaultLabelAttrs
	            );

	            this.updateDOMSubtreeAttributes(labelNode, attrs, {
	                rootBBox: new Rect(label.size),
	                selectors: selectors
	            });
	        }

	        return this;
	    },

	    renderTools: function() {

	        if (!this._V.linkTools) { return this; }

	        // Tools are a group of clickable elements that manipulate the whole link.
	        // A good example of this is the remove tool that removes the whole link.
	        // Tools appear after hovering the link close to the `source` element/point of the link
	        // but are offset a bit so that they don't cover the `marker-arrowhead`.

	        var $tools = $(this._V.linkTools.node).empty();
	        var toolTemplate = template(this.model.get('toolMarkup') || this.model.toolMarkup);
	        var tool = V(toolTemplate());

	        $tools.append(tool.node);

	        // Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly.
	        this._toolCache = tool;

	        // If `doubleLinkTools` is enabled, we render copy of the tools on the other side of the
	        // link as well but only if the link is longer than `longLinkLength`.
	        if (this.options.doubleLinkTools) {

	            var tool2;
	            if (this.model.get('doubleToolMarkup') || this.model.doubleToolMarkup) {
	                toolTemplate = template(this.model.get('doubleToolMarkup') || this.model.doubleToolMarkup);
	                tool2 = V(toolTemplate());
	            } else {
	                tool2 = tool.clone();
	            }

	            $tools.append(tool2.node);
	            this._tool2Cache = tool2;
	        }

	        return this;
	    },

	    renderVertexMarkers: function() {

	        if (!this._V.markerVertices) { return this; }

	        var $markerVertices = $(this._V.markerVertices.node).empty();

	        // A special markup can be given in the `properties.vertexMarkup` property. This might be handy
	        // if default styling (elements) are not desired. This makes it possible to use any
	        // SVG elements for .marker-vertex and .marker-vertex-remove tools.
	        var markupTemplate = template(this.model.get('vertexMarkup') || this.model.vertexMarkup);

	        this.model.vertices().forEach(function(vertex, idx) {
	            $markerVertices.append(V(markupTemplate(assign({ idx: idx }, vertex))).node);
	        });

	        return this;
	    },

	    renderArrowheadMarkers: function() {

	        // Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case.
	        if (!this._V.markerArrowheads) { return this; }

	        var $markerArrowheads = $(this._V.markerArrowheads.node);

	        $markerArrowheads.empty();

	        // A special markup can be given in the `properties.vertexMarkup` property. This might be handy
	        // if default styling (elements) are not desired. This makes it possible to use any
	        // SVG elements for .marker-vertex and .marker-vertex-remove tools.
	        var markupTemplate = template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup);

	        this._V.sourceArrowhead = V(markupTemplate({ end: 'source' }));
	        this._V.targetArrowhead = V(markupTemplate({ end: 'target' }));

	        $markerArrowheads.append(this._V.sourceArrowhead.node, this._V.targetArrowhead.node);

	        return this;
	    },

	    // remove vertices that lie on (or nearly on) straight lines within the link
	    // return the number of removed points
	    removeRedundantLinearVertices: function(opt) {

	        var SIMPLIFY_THRESHOLD = 0.001;

	        var link = this.model;
	        var vertices = link.vertices();
	        var routePoints = [this.sourceAnchor ].concat( vertices, [this.targetAnchor]);
	        var numRoutePoints = routePoints.length;

	        // put routePoints into a polyline and try to simplify
	        var polyline = new Polyline(routePoints);
	        polyline.simplify({ threshold: SIMPLIFY_THRESHOLD });
	        var polylinePoints = polyline.points.map(function (point) { return (point.toJSON()); }); // JSON of points after simplification
	        var numPolylinePoints = polylinePoints.length; // number of points after simplification

	        // shortcut if simplification did not remove any redundant vertices:
	        if (numRoutePoints === numPolylinePoints) { return 0; }

	        // else: set simplified polyline points as link vertices
	        // remove first and last polyline points again (= source/target anchors)
	        link.vertices(polylinePoints.slice(1, numPolylinePoints - 1), opt);
	        return (numRoutePoints - numPolylinePoints);
	    },

	    updateDefaultConnectionPath: function() {

	        var cache = this._V;

	        if (cache.connection) {
	            cache.connection.attr('d', this.getSerializedConnection());
	        }

	        if (cache.connectionWrap) {
	            cache.connectionWrap.attr('d', this.getSerializedConnection());
	        }

	        if (cache.markerSource && cache.markerTarget) {
	            this._translateAndAutoOrientArrows(cache.markerSource, cache.markerTarget);
	        }
	    },

	    getEndView: function(type) {
	        switch (type) {
	            case 'source':
	                return this.sourceView || null;
	            case 'target':
	                return this.targetView || null;
	            default:
	                throw new Error('dia.LinkView: type parameter required.');
	        }
	    },

	    getEndAnchor: function(type) {
	        switch (type) {
	            case 'source':
	                return new Point(this.sourceAnchor);
	            case 'target':
	                return new Point(this.targetAnchor);
	            default:
	                throw new Error('dia.LinkView: type parameter required.');
	        }
	    },

	    getEndConnectionPoint: function(type) {
	        switch (type) {
	            case 'source':
	                return new Point(this.sourcePoint);
	            case 'target':
	                return new Point(this.targetPoint);
	            default:
	                throw new Error('dia.LinkView: type parameter required.');
	        }
	    },

	    getEndMagnet: function(type) {
	        switch (type) {
	            case 'source':
	                var sourceView = this.sourceView;
	                if (!sourceView) { break; }
	                return this.sourceMagnet || sourceView.el;
	            case 'target':
	                var targetView = this.targetView;
	                if (!targetView) { break; }
	                return this.targetMagnet || targetView.el;
	            default:
	                throw new Error('dia.LinkView: type parameter required.');
	        }
	        return null;
	    },


	    // Updating.
	    // ---------

	    update: function() {
	        this.updateRoute();
	        this.updatePath();
	        this.updateDOM();
	        return this;
	    },

	    translate: function(tx, ty) {
	        if ( tx === void 0 ) tx = 0;
	        if ( ty === void 0 ) ty = 0;

	        var ref = this;
	        var route = ref.route;
	        var path = ref.path;
	        if (!route || !path) { return; }
	        // translate the route
	        var polyline = new Polyline(route);
	        polyline.translate(tx, ty);
	        this.route = polyline.points;
	        // translate source and target connection and marker points.
	        this._translateConnectionPoints(tx, ty);
	        // translate the geometry path
	        path.translate(tx, ty);
	        this.updateDOM();
	    },

	    updateDOM: function updateDOM() {
	        var ref = this;
	        var el = ref.el;
	        var model = ref.model;
	        var selectors = ref.selectors;
	        this.cleanNodesCache();
	        // update SVG attributes defined by 'attrs/'.
	        this.updateDOMSubtreeAttributes(el, model.attr(), { selectors: selectors });
	        // legacy link path update
	        this.updateDefaultConnectionPath();
	        // update the label position etc.
	        this.updateLabelPositions();
	        this.updateToolsPosition();
	        this.updateArrowheadMarkers();
	        // *Deprecated*
	        // Local perpendicular flag (as opposed to one defined on paper).
	        // Could be enabled inside a connector/router. It's valid only
	        // during the update execution.
	        this.options.perpendicular = null;
	    },

	    updateRoute: function() {
	        var ref = this;
	        var model = ref.model;
	        var vertices = model.vertices();
	        // 1. Find Anchors
	        var anchors = this.findAnchors(vertices);
	        var sourceAnchor = this.sourceAnchor = anchors.source;
	        var targetAnchor = this.targetAnchor = anchors.target;
	        // 2. Find Route
	        var route = this.findRoute(vertices);
	        this.route = route;
	        // 3. Find Connection Points
	        var connectionPoints = this.findConnectionPoints(route, sourceAnchor, targetAnchor);
	        this.sourcePoint = connectionPoints.source;
	        this.targetPoint = connectionPoints.target;
	    },

	    updatePath: function() {
	        var ref = this;
	        var route = ref.route;
	        var sourcePoint = ref.sourcePoint;
	        var targetPoint = ref.targetPoint;
	        // 3b. Find Marker Connection Point - Backwards Compatibility
	        var markerPoints = this.findMarkerPoints(route, sourcePoint, targetPoint);
	        // 4. Find Connection
	        var path = this.findPath(route, markerPoints.source || sourcePoint, markerPoints.target || targetPoint);
	        this.path = path;
	    },

	    findMarkerPoints: function(route, sourcePoint, targetPoint) {

	        var firstWaypoint = route[0];
	        var lastWaypoint = route[route.length - 1];

	        // Move the source point by the width of the marker taking into account
	        // its scale around x-axis. Note that scale is the only transform that
	        // makes sense to be set in `.marker-source` attributes object
	        // as all other transforms (translate/rotate) will be replaced
	        // by the `translateAndAutoOrient()` function.
	        var cache = this._markerCache;
	        // cache source and target points
	        var sourceMarkerPoint, targetMarkerPoint;

	        if (this._V.markerSource) {

	            cache.sourceBBox = cache.sourceBBox || this._V.markerSource.getBBox();
	            sourceMarkerPoint = Point(sourcePoint).move(
	                firstWaypoint || targetPoint,
	                cache.sourceBBox.width * this._V.markerSource.scale().sx * -1
	            ).round();
	        }

	        if (this._V.markerTarget) {

	            cache.targetBBox = cache.targetBBox || this._V.markerTarget.getBBox();
	            targetMarkerPoint = Point(targetPoint).move(
	                lastWaypoint || sourcePoint,
	                cache.targetBBox.width * this._V.markerTarget.scale().sx * -1
	            ).round();
	        }

	        // if there was no markup for the marker, use the connection point.
	        cache.sourcePoint = sourceMarkerPoint || sourcePoint.clone();
	        cache.targetPoint = targetMarkerPoint || targetPoint.clone();

	        return {
	            source: sourceMarkerPoint,
	            target: targetMarkerPoint
	        };
	    },

	    findAnchorsOrdered: function(firstEndType, firstRef, secondEndType, secondRef) {

	        var firstAnchor, secondAnchor;
	        var firstAnchorRef, secondAnchorRef;
	        var model = this.model;
	        var firstDef = model.get(firstEndType);
	        var secondDef = model.get(secondEndType);
	        var firstView = this.getEndView(firstEndType);
	        var secondView = this.getEndView(secondEndType);
	        var firstMagnet = this.getEndMagnet(firstEndType);
	        var secondMagnet = this.getEndMagnet(secondEndType);

	        // Anchor first
	        if (firstView) {
	            if (firstRef) {
	                firstAnchorRef = new Point(firstRef);
	            } else if (secondView) {
	                firstAnchorRef = secondMagnet;
	            } else {
	                firstAnchorRef = new Point(secondDef);
	            }
	            firstAnchor = this.getAnchor(firstDef.anchor, firstView, firstMagnet, firstAnchorRef, firstEndType);
	        } else {
	            firstAnchor = new Point(firstDef);
	        }

	        // Anchor second
	        if (secondView) {
	            secondAnchorRef = new Point(secondRef || firstAnchor);
	            secondAnchor = this.getAnchor(secondDef.anchor, secondView, secondMagnet, secondAnchorRef, secondEndType);
	        } else {
	            secondAnchor = new Point(secondDef);
	        }

	        var res = {};
	        res[firstEndType] = firstAnchor;
	        res[secondEndType] = secondAnchor;
	        return res;
	    },

	    findAnchors: function(vertices) {

	        var model = this.model;
	        var firstVertex = vertices[0];
	        var lastVertex = vertices[vertices.length - 1];

	        if (model.target().priority && !model.source().priority) {
	            // Reversed order
	            return this.findAnchorsOrdered('target', lastVertex, 'source', firstVertex);
	        }

	        // Usual order
	        return this.findAnchorsOrdered('source', firstVertex, 'target', lastVertex);
	    },

	    findConnectionPoints: function(route, sourceAnchor, targetAnchor) {

	        var firstWaypoint = route[0];
	        var lastWaypoint = route[route.length - 1];
	        var model = this.model;
	        var sourceDef = model.get('source');
	        var targetDef = model.get('target');
	        var sourceView = this.sourceView;
	        var targetView = this.targetView;
	        var paperOptions = this.paper.options;
	        var sourceMagnet, targetMagnet;

	        // Connection Point Source
	        var sourcePoint;
	        if (sourceView && !sourceView.isNodeConnection(this.sourceMagnet)) {
	            sourceMagnet = (this.sourceMagnet || sourceView.el);
	            var sourceConnectionPointDef = sourceDef.connectionPoint || paperOptions.defaultConnectionPoint;
	            var sourcePointRef = firstWaypoint || targetAnchor;
	            var sourceLine = new Line(sourcePointRef, sourceAnchor);
	            sourcePoint = this.getConnectionPoint(
	                sourceConnectionPointDef,
	                sourceView,
	                sourceMagnet,
	                sourceLine,
	                'source'
	            );
	        } else {
	            sourcePoint = sourceAnchor;
	        }
	        // Connection Point Target
	        var targetPoint;
	        if (targetView && !targetView.isNodeConnection(this.targetMagnet)) {
	            targetMagnet = (this.targetMagnet || targetView.el);
	            var targetConnectionPointDef = targetDef.connectionPoint || paperOptions.defaultConnectionPoint;
	            var targetPointRef = lastWaypoint || sourceAnchor;
	            var targetLine = new Line(targetPointRef, targetAnchor);
	            targetPoint = this.getConnectionPoint(
	                targetConnectionPointDef,
	                targetView,
	                targetMagnet,
	                targetLine,
	                'target'
	            );
	        } else {
	            targetPoint = targetAnchor;
	        }

	        return {
	            source: sourcePoint,
	            target: targetPoint
	        };
	    },

	    getAnchor: function(anchorDef, cellView, magnet, ref, endType) {

	        var isConnection = cellView.isNodeConnection(magnet);
	        var paperOptions = this.paper.options;
	        if (!anchorDef) {
	            if (isConnection) {
	                anchorDef = paperOptions.defaultLinkAnchor;
	            } else {
	                if (paperOptions.perpendicularLinks || this.options.perpendicular) {
	                    // Backwards compatibility
	                    // If `perpendicularLinks` flag is set on the paper and there are vertices
	                    // on the link, then try to find a connection point that makes the link perpendicular
	                    // even though the link won't point to the center of the targeted object.
	                    anchorDef = { name: 'perpendicular' };
	                } else {
	                    anchorDef = paperOptions.defaultAnchor;
	                }
	            }
	        }

	        if (!anchorDef) { throw new Error('Anchor required.'); }
	        var anchorFn;
	        if (typeof anchorDef === 'function') {
	            anchorFn = anchorDef;
	        } else {
	            var anchorName = anchorDef.name;
	            var anchorNamespace = isConnection ? 'linkAnchorNamespace' : 'anchorNamespace';
	            anchorFn = paperOptions[anchorNamespace][anchorName];
	            if (typeof anchorFn !== 'function') { throw new Error('Unknown anchor: ' + anchorName); }
	        }
	        var anchor = anchorFn.call(
	            this,
	            cellView,
	            magnet,
	            ref,
	            anchorDef.args || {},
	            endType,
	            this
	        );
	        if (!anchor) { return new Point(); }
	        return anchor.round(this.decimalsRounding);
	    },


	    getConnectionPoint: function(connectionPointDef, view, magnet, line, endType) {

	        var connectionPoint;
	        var anchor = line.end;
	        var paperOptions = this.paper.options;

	        // Backwards compatibility
	        if (typeof paperOptions.linkConnectionPoint === 'function') {
	            var linkConnectionMagnet = (magnet === view.el) ? undefined : magnet;
	            connectionPoint = paperOptions.linkConnectionPoint(this, view, linkConnectionMagnet, line.start, endType);
	            if (connectionPoint) { return connectionPoint; }
	        }

	        if (!connectionPointDef) { return anchor; }
	        var connectionPointFn;
	        if (typeof connectionPointDef === 'function') {
	            connectionPointFn = connectionPointDef;
	        } else {
	            var connectionPointName = connectionPointDef.name;
	            connectionPointFn = paperOptions.connectionPointNamespace[connectionPointName];
	            if (typeof connectionPointFn !== 'function') { throw new Error('Unknown connection point: ' + connectionPointName); }
	        }
	        connectionPoint = connectionPointFn.call(this, line, view, magnet, connectionPointDef.args || {}, endType, this);
	        if (!connectionPoint) { return anchor; }
	        return connectionPoint.round(this.decimalsRounding);
	    },

	    _translateConnectionPoints: function(tx, ty) {

	        var cache = this._markerCache;

	        cache.sourcePoint.offset(tx, ty);
	        cache.targetPoint.offset(tx, ty);
	        this.sourcePoint.offset(tx, ty);
	        this.targetPoint.offset(tx, ty);
	        this.sourceAnchor.offset(tx, ty);
	        this.targetAnchor.offset(tx, ty);
	    },

	    // if label position is a number, normalize it to a position object
	    // this makes sure that label positions can be merged properly
	    _normalizeLabelPosition: function(labelPosition) {

	        if (typeof labelPosition === 'number') { return { distance: labelPosition, offset: null, angle: 0, args: null }; }
	        return labelPosition;
	    },

	    updateLabelPositions: function() {

	        if (!this._V.labels) { return this; }

	        var path = this.path;
	        if (!path) { return this; }

	        // This method assumes all the label nodes are stored in the `this._labelCache` hash table
	        // by their indices in the `this.get('labels')` array. This is done in the `renderLabels()` method.

	        var model = this.model;
	        var labels = model.get('labels') || [];
	        if (!labels.length) { return this; }

	        var builtinDefaultLabel = model._builtins.defaultLabel;
	        var builtinDefaultLabelPosition = builtinDefaultLabel.position;

	        var defaultLabel = model._getDefaultLabel();
	        var defaultLabelPosition = this._normalizeLabelPosition(defaultLabel.position);

	        var defaultPosition = merge({}, builtinDefaultLabelPosition, defaultLabelPosition);

	        for (var idx = 0, n = labels.length; idx < n; idx++) {
	            var labelNode = this._labelCache[idx];
	            if (!labelNode) { continue; }
	            var label = labels[idx];
	            var labelPosition = this._normalizeLabelPosition(label.position);
	            var position = merge({}, defaultPosition, labelPosition);
	            var transformationMatrix = this._getLabelTransformationMatrix(position);
	            labelNode.setAttribute('transform', V.matrixToTransformString(transformationMatrix));
	            this._cleanLabelMatrices(idx);
	        }

	        return this;
	    },

	    _cleanLabelMatrices: function(index) {
	        // Clean magnetMatrix for all nodes of the label.
	        // Cached BoundingRect does not need to updated when the position changes
	        // TODO: this doesn't work for labels with XML String markups.
	        var ref = this;
	        var metrics = ref.metrics;
	        var _labelSelectors = ref._labelSelectors;
	        var selectors = _labelSelectors[index];
	        if (!selectors) { return; }
	        for (var selector in selectors) {
	            var ref$1 = selectors[selector];
	            var id = ref$1.id;
	            if (id && (id in metrics)) { delete metrics[id].magnetMatrix; }
	        }
	    },

	    updateToolsPosition: function() {

	        if (!this._V.linkTools) { return this; }

	        // Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker.
	        // Note that the offset is hardcoded here. The offset should be always
	        // more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking
	        // this up all the time would be slow.

	        var scale = '';
	        var offset = this.options.linkToolsOffset;
	        var connectionLength = this.getConnectionLength();

	        // Firefox returns connectionLength=NaN in odd cases (for bezier curves).
	        // In that case we won't update tools position at all.
	        if (!Number.isNaN(connectionLength)) {

	            // If the link is too short, make the tools half the size and the offset twice as low.
	            if (connectionLength < this.options.shortLinkLength) {
	                scale = 'scale(.5)';
	                offset /= 2;
	            }

	            var toolPosition = this.getPointAtLength(offset);

	            this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale);

	            if (this.options.doubleLinkTools && connectionLength >= this.options.longLinkLength) {

	                var doubleLinkToolsOffset = this.options.doubleLinkToolsOffset || offset;

	                toolPosition = this.getPointAtLength(connectionLength - doubleLinkToolsOffset);
	                this._tool2Cache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale);
	                this._tool2Cache.attr('visibility', 'visible');

	            } else if (this.options.doubleLinkTools) {

	                this._tool2Cache.attr('visibility', 'hidden');
	            }
	        }

	        return this;
	    },

	    updateArrowheadMarkers: function() {

	        if (!this._V.markerArrowheads) { return this; }

	        // getting bbox of an element with `display="none"` in IE9 ends up with access violation
	        if ($.css(this._V.markerArrowheads.node, 'display') === 'none') { return this; }

	        var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1;
	        this._V.sourceArrowhead.scale(sx);
	        this._V.targetArrowhead.scale(sx);

	        this._translateAndAutoOrientArrows(this._V.sourceArrowhead, this._V.targetArrowhead);

	        return this;
	    },

	    updateEndProperties: function(endType) {

	        var ref = this;
	        var model = ref.model;
	        var paper = ref.paper;
	        var endViewProperty = endType + "View";
	        var endDef = model.get(endType);
	        var endId = endDef && endDef.id;

	        if (!endId) {
	            // the link end is a point ~ rect 0x0
	            this[endViewProperty] = null;
	            this.updateEndMagnet(endType);
	            return true;
	        }

	        var endModel = paper.getModelById(endId);
	        if (!endModel) { throw new Error('LinkView: invalid ' + endType + ' cell.'); }

	        var endView = endModel.findView(paper);
	        if (!endView) {
	            // A view for a model should always exist
	            return false;
	        }

	        this[endViewProperty] = endView;
	        this.updateEndMagnet(endType);
	        return true;
	    },

	    updateEndMagnet: function(endType) {

	        var endMagnetProperty = endType + "Magnet";
	        var endView = this.getEndView(endType);
	        if (endView) {
	            var connectedMagnet = endView.getMagnetFromLinkEnd(this.model.get(endType));
	            if (connectedMagnet === endView.el) { connectedMagnet = null; }
	            this[endMagnetProperty] = connectedMagnet;
	        } else {
	            this[endMagnetProperty] = null;
	        }
	    },

	    _translateAndAutoOrientArrows: function(sourceArrow, targetArrow) {

	        // Make the markers "point" to their sticky points being auto-oriented towards
	        // `targetPosition`/`sourcePosition`. And do so only if there is a markup for them.
	        var route = toArray(this.route);
	        if (sourceArrow) {
	            sourceArrow.translateAndAutoOrient(
	                this.sourcePoint,
	                route[0] || this.targetPoint,
	                this.paper.cells
	            );
	        }

	        if (targetArrow) {
	            targetArrow.translateAndAutoOrient(
	                this.targetPoint,
	                route[route.length - 1] || this.sourcePoint,
	                this.paper.cells
	            );
	        }
	    },

	    _getLabelPositionAngle: function(idx) {

	        var labelPosition = this.model.label(idx).position || {};
	        return (labelPosition.angle || 0);
	    },

	    _getLabelPositionArgs: function(idx) {

	        var labelPosition = this.model.label(idx).position || {};
	        return labelPosition.args;
	    },

	    _getDefaultLabelPositionArgs: function() {

	        var defaultLabel = this.model._getDefaultLabel();
	        var defaultLabelPosition = defaultLabel.position || {};
	        return defaultLabelPosition.args;
	    },

	    // merge default label position args into label position args
	    // keep `undefined` or `null` because `{}` means something else
	    _mergeLabelPositionArgs: function(labelPositionArgs, defaultLabelPositionArgs) {

	        if (labelPositionArgs === null) { return null; }
	        if (labelPositionArgs === undefined) {

	            if (defaultLabelPositionArgs === null) { return null; }
	            return defaultLabelPositionArgs;
	        }

	        return merge({}, defaultLabelPositionArgs, labelPositionArgs);
	    },

	    // Add default label at given position at end of `labels` array.
	    // Four signatures:
	    // - obj, obj = point, opt
	    // - obj, num, obj = point, angle, opt
	    // - num, num, obj = x, y, opt
	    // - num, num, num, obj = x, y, angle, opt
	    // Assigns relative coordinates by default:
	    // `opt.absoluteDistance` forces absolute coordinates.
	    // `opt.reverseDistance` forces reverse absolute coordinates (if absoluteDistance = true).
	    // `opt.absoluteOffset` forces absolute coordinates for offset.
	    // Additional args:
	    // `opt.keepGradient` auto-adjusts the angle of the label to match path gradient at position.
	    // `opt.ensureLegibility` rotates labels so they are never upside-down.
	    addLabel: function(p1, p2, p3, p4) {

	        // normalize data from the four possible signatures
	        var localX;
	        var localY;
	        var localAngle = 0;
	        var localOpt;
	        if (typeof p1 !== 'number') {
	            // {x, y} object provided as first parameter
	            localX = p1.x;
	            localY = p1.y;
	            if (typeof p2 === 'number') {
	                // angle and opt provided as second and third parameters
	                localAngle = p2;
	                localOpt = p3;
	            } else {
	                // opt provided as second parameter
	                localOpt = p2;
	            }
	        } else {
	            // x and y provided as first and second parameters
	            localX = p1;
	            localY = p2;
	            if (typeof p3 === 'number') {
	                // angle and opt provided as third and fourth parameters
	                localAngle = p3;
	                localOpt = p4;
	            } else {
	                // opt provided as third parameter
	                localOpt = p3;
	            }
	        }

	        // merge label position arguments
	        var defaultLabelPositionArgs = this._getDefaultLabelPositionArgs();
	        var labelPositionArgs = localOpt;
	        var positionArgs = this._mergeLabelPositionArgs(labelPositionArgs, defaultLabelPositionArgs);

	        // append label to labels array
	        var label = { position: this.getLabelPosition(localX, localY, localAngle, positionArgs) };
	        var idx = -1;
	        this.model.insertLabel(idx, label, localOpt);
	        return idx;
	    },

	    // Add a new vertex at calculated index to the `vertices` array.
	    addVertex: function(x, y, opt) {

	        // accept input in form `{ x, y }, opt` or `x, y, opt`
	        var isPointProvided = (typeof x !== 'number');
	        var localX = isPointProvided ? x.x : x;
	        var localY = isPointProvided ? x.y : y;
	        var localOpt = isPointProvided ? y : opt;

	        var vertex = { x: localX, y: localY };
	        var idx = this.getVertexIndex(localX, localY);
	        this.model.insertVertex(idx, vertex, localOpt);
	        return idx;
	    },

	    // Send a token (an SVG element, usually a circle) along the connection path.
	    // Example: `link.findView(paper).sendToken(V('circle', { r: 7, fill: 'green' }).node)`
	    // `opt.duration` is optional and is a time in milliseconds that the token travels from the source to the target of the link. Default is `1000`.
	    // `opt.directon` is optional and it determines whether the token goes from source to target or other way round (`reverse`)
	    // `opt.connection` is an optional selector to the connection path.
	    // `callback` is optional and is a function to be called once the token reaches the target.
	    sendToken: function(token, opt, callback) {

	        function onAnimationEnd(vToken, callback) {
	            return function() {
	                vToken.remove();
	                if (typeof callback === 'function') {
	                    callback();
	                }
	            };
	        }

	        var duration, isReversed, selector;
	        if (isObject$1(opt)) {
	            duration = opt.duration;
	            isReversed = (opt.direction === 'reverse');
	            selector = opt.connection;
	        } else {
	            // Backwards compatibility
	            duration = opt;
	            isReversed = false;
	            selector = null;
	        }

	        duration = duration || 1000;

	        var animationAttributes = {
	            dur: duration + 'ms',
	            repeatCount: 1,
	            calcMode: 'linear',
	            fill: 'freeze'
	        };

	        if (isReversed) {
	            animationAttributes.keyPoints = '1;0';
	            animationAttributes.keyTimes = '0;1';
	        }

	        var vToken = V(token);
	        var connection;
	        if (typeof selector === 'string') {
	            // Use custom connection path.
	            connection = this.findBySelector(selector, this.el, this.selectors)[0];
	        } else {
	            // Select connection path automatically.
	            var cache = this._V;
	            connection = (cache.connection) ? cache.connection.node : this.el.querySelector('path');
	        }

	        if (!(connection instanceof SVGPathElement)) {
	            throw new Error('dia.LinkView: token animation requires a valid connection path.');
	        }

	        vToken
	            .appendTo(this.paper.cells)
	            .animateAlongPath(animationAttributes, connection);

	        setTimeout(onAnimationEnd(vToken, callback), duration);
	    },

	    findRoute: function(vertices) {

	        vertices || (vertices = []);

	        var namespace = this.paper.options.routerNamespace || routers;
	        var router = this.model.router();
	        var defaultRouter = this.paper.options.defaultRouter;

	        if (!router) {
	            if (defaultRouter) { router = defaultRouter; }
	            else { return vertices.map(Point); } // no router specified
	        }

	        var routerFn = isFunction(router) ? router : namespace[router.name];
	        if (!isFunction(routerFn)) {
	            throw new Error('dia.LinkView: unknown router: "' + router.name + '".');
	        }

	        var args = router.args || {};

	        var route = routerFn.call(
	            this, // context
	            vertices, // vertices
	            args, // options
	            this // linkView
	        );

	        if (!route) { return vertices.map(Point); }
	        return route;
	    },

	    // Return the `d` attribute value of the `<path>` element representing the link
	    // between `source` and `target`.
	    findPath: function(route, sourcePoint, targetPoint) {

	        var namespace = this.paper.options.connectorNamespace || connectors;
	        var connector = this.model.connector();
	        var defaultConnector = this.paper.options.defaultConnector;

	        if (!connector) {
	            connector = defaultConnector || {};
	        }

	        var connectorFn = isFunction(connector) ? connector : namespace[connector.name];
	        if (!isFunction(connectorFn)) {
	            throw new Error('dia.LinkView: unknown connector: "' + connector.name + '".');
	        }

	        var args = clone(connector.args || {});
	        args.raw = true; // Request raw g.Path as the result.

	        var path = connectorFn.call(
	            this, // context
	            sourcePoint, // start point
	            targetPoint, // end point
	            route, // vertices
	            args, // options
	            this // linkView
	        );

	        if (typeof path === 'string') {
	            // Backwards compatibility for connectors not supporting `raw` option.
	            path = new Path(V.normalizePathData(path));
	        }

	        return path;
	    },

	    // Public API.
	    // -----------

	    getConnection: function() {

	        var path = this.path;
	        if (!path) { return null; }

	        return path.clone();
	    },

	    getSerializedConnection: function() {

	        var path = this.path;
	        if (!path) { return null; }

	        var metrics = this.metrics;
	        if (metrics.hasOwnProperty('data')) { return metrics.data; }
	        var data = path.serialize();
	        metrics.data = data;
	        return data;
	    },

	    getConnectionSubdivisions: function() {

	        var path = this.path;
	        if (!path) { return null; }

	        var metrics = this.metrics;
	        if (metrics.hasOwnProperty('segmentSubdivisions')) { return metrics.segmentSubdivisions; }
	        var subdivisions = path.getSegmentSubdivisions();
	        metrics.segmentSubdivisions = subdivisions;
	        return subdivisions;
	    },

	    getConnectionLength: function() {

	        var path = this.path;
	        if (!path) { return 0; }

	        var metrics = this.metrics;
	        if (metrics.hasOwnProperty('length')) { return metrics.length; }
	        var length = path.length({ segmentSubdivisions: this.getConnectionSubdivisions() });
	        metrics.length = length;
	        return length;
	    },

	    getPointAtLength: function(length) {

	        var path = this.path;
	        if (!path) { return null; }

	        return path.pointAtLength(length, { segmentSubdivisions: this.getConnectionSubdivisions() });
	    },

	    getPointAtRatio: function(ratio) {

	        var path = this.path;
	        if (!path) { return null; }
	        if (isPercentage(ratio)) { ratio = parseFloat(ratio) / 100; }
	        return path.pointAt(ratio, { segmentSubdivisions: this.getConnectionSubdivisions() });
	    },

	    getTangentAtLength: function(length) {

	        var path = this.path;
	        if (!path) { return null; }

	        return path.tangentAtLength(length, { segmentSubdivisions: this.getConnectionSubdivisions() });
	    },

	    getTangentAtRatio: function(ratio) {

	        var path = this.path;
	        if (!path) { return null; }

	        return path.tangentAt(ratio, { segmentSubdivisions: this.getConnectionSubdivisions() });
	    },

	    getClosestPoint: function(point) {

	        var path = this.path;
	        if (!path) { return null; }

	        return path.closestPoint(point, { segmentSubdivisions: this.getConnectionSubdivisions() });
	    },

	    getClosestPointLength: function(point) {

	        var path = this.path;
	        if (!path) { return null; }

	        return path.closestPointLength(point, { segmentSubdivisions: this.getConnectionSubdivisions() });
	    },

	    getClosestPointRatio: function(point) {

	        var path = this.path;
	        if (!path) { return null; }

	        return path.closestPointNormalizedLength(point, { segmentSubdivisions: this.getConnectionSubdivisions() });
	    },

	    // Get label position object based on two provided coordinates, x and y.
	    // (Used behind the scenes when user moves labels around.)
	    // Two signatures:
	    // - num, num, obj = x, y, options
	    // - num, num, num, obj = x, y, angle, options
	    // Accepts distance/offset options = `absoluteDistance: boolean`, `reverseDistance: boolean`, `absoluteOffset: boolean`
	    // - `absoluteOffset` is necessary in order to move beyond connection endpoints
	    // Additional options = `keepGradient: boolean`, `ensureLegibility: boolean`
	    getLabelPosition: function(x, y, p3, p4) {

	        var position = {};

	        // normalize data from the two possible signatures
	        var localAngle = 0;
	        var localOpt;
	        if (typeof p3 === 'number') {
	            // angle and opt provided as third and fourth argument
	            localAngle = p3;
	            localOpt = p4;
	        } else {
	            // opt provided as third argument
	            localOpt = p3;
	        }

	        // save localOpt as `args` of the position object that is passed along
	        if (localOpt) { position.args = localOpt; }

	        // identify distance/offset settings
	        var isDistanceRelative = !(localOpt && localOpt.absoluteDistance); // relative by default
	        var isDistanceAbsoluteReverse = (localOpt && localOpt.absoluteDistance && localOpt.reverseDistance); // non-reverse by default
	        var isOffsetAbsolute = localOpt && localOpt.absoluteOffset; // offset is non-absolute by default

	        // find closest point t
	        var path = this.path;
	        var pathOpt = { segmentSubdivisions: this.getConnectionSubdivisions() };
	        var labelPoint = new Point(x, y);
	        var t = path.closestPointT(labelPoint, pathOpt);

	        // DISTANCE:
	        var labelDistance = path.lengthAtT(t, pathOpt);
	        if (isDistanceRelative) { labelDistance = (labelDistance / this.getConnectionLength()) || 0; } // fix to prevent NaN for 0 length
	        if (isDistanceAbsoluteReverse) { labelDistance = (-1 * (this.getConnectionLength() - labelDistance)) || 1; } // fix for end point (-0 => 1)
	        position.distance = labelDistance;

	        // OFFSET:
	        // use absolute offset if:
	        // - opt.absoluteOffset is true,
	        // - opt.absoluteOffset is not true but there is no tangent
	        var tangent;
	        if (!isOffsetAbsolute) { tangent = path.tangentAtT(t); }
	        var labelOffset;
	        if (tangent) {
	            labelOffset = tangent.pointOffset(labelPoint);
	        } else {
	            var closestPoint = path.pointAtT(t);
	            var labelOffsetDiff = labelPoint.difference(closestPoint);
	            labelOffset = { x: labelOffsetDiff.x, y: labelOffsetDiff.y };
	        }
	        position.offset = labelOffset;

	        // ANGLE:
	        position.angle = localAngle;

	        return position;
	    },

	    _getLabelTransformationMatrix: function(labelPosition) {

	        var labelDistance;
	        var labelAngle = 0;
	        var args = {};
	        if (typeof labelPosition === 'number') {
	            labelDistance = labelPosition;
	        } else if (typeof labelPosition.distance === 'number') {
	            args = labelPosition.args || {};
	            labelDistance = labelPosition.distance;
	            labelAngle = labelPosition.angle || 0;
	        } else {
	            throw new Error('dia.LinkView: invalid label position distance.');
	        }

	        var isDistanceRelative = ((labelDistance > 0) && (labelDistance <= 1));

	        var labelOffset = 0;
	        var labelOffsetCoordinates = { x: 0, y: 0 };
	        if (labelPosition.offset) {
	            var positionOffset = labelPosition.offset;
	            if (typeof positionOffset === 'number') { labelOffset = positionOffset; }
	            if (positionOffset.x) { labelOffsetCoordinates.x = positionOffset.x; }
	            if (positionOffset.y) { labelOffsetCoordinates.y = positionOffset.y; }
	        }

	        var isOffsetAbsolute = ((labelOffsetCoordinates.x !== 0) || (labelOffsetCoordinates.y !== 0) || labelOffset === 0);

	        var isKeepGradient = args.keepGradient;
	        var isEnsureLegibility = args.ensureLegibility;

	        var path = this.path;
	        var pathOpt = { segmentSubdivisions: this.getConnectionSubdivisions() };

	        var distance = isDistanceRelative ? (labelDistance * this.getConnectionLength()) : labelDistance;
	        var tangent = path.tangentAtLength(distance, pathOpt);

	        var translation;
	        var angle = labelAngle;
	        if (tangent) {
	            if (isOffsetAbsolute) {
	                translation = tangent.start;
	                translation.offset(labelOffsetCoordinates);
	            } else {
	                var normal = tangent.clone();
	                normal.rotate(tangent.start, -90);
	                normal.setLength(labelOffset);
	                translation = normal.end;
	            }
	            if (isKeepGradient) {
	                angle = (tangent.angle() + labelAngle);
	                if (isEnsureLegibility) {
	                    angle = normalizeAngle(((angle + 90) % 180) - 90);
	                }
	            }
	        } else {
	            // fallback - the connection has zero length
	            translation = path.start;
	            if (isOffsetAbsolute) { translation.offset(labelOffsetCoordinates); }
	        }

	        return V.createSVGMatrix()
	            .translate(translation.x, translation.y)
	            .rotate(angle);
	    },

	    getLabelCoordinates: function(labelPosition) {

	        var transformationMatrix = this._getLabelTransformationMatrix(labelPosition);
	        return new Point(transformationMatrix.e, transformationMatrix.f);
	    },

	    getVertexIndex: function(x, y) {

	        var model = this.model;
	        var vertices = model.vertices();

	        var vertexLength = this.getClosestPointLength(new Point(x, y));

	        var idx = 0;
	        for (var n = vertices.length; idx < n; idx++) {
	            var currentVertex = vertices[idx];
	            var currentVertexLength = this.getClosestPointLength(currentVertex);
	            if (vertexLength < currentVertexLength) { break; }
	        }

	        return idx;
	    },

	    // Interaction. The controller part.
	    // ---------------------------------

	    notifyPointerdown: function notifyPointerdown(evt, x, y) {
	        CellView.prototype.pointerdown.call(this, evt, x, y);
	        this.notify('link:pointerdown', evt, x, y);
	    },

	    notifyPointermove: function notifyPointermove(evt, x, y) {
	        CellView.prototype.pointermove.call(this, evt, x, y);
	        this.notify('link:pointermove', evt, x, y);
	    },

	    notifyPointerup: function notifyPointerup(evt, x, y) {
	        this.notify('link:pointerup', evt, x, y);
	        CellView.prototype.pointerup.call(this, evt, x, y);
	    },

	    pointerdblclick: function(evt, x, y) {

	        CellView.prototype.pointerdblclick.apply(this, arguments);
	        this.notify('link:pointerdblclick', evt, x, y);
	    },

	    pointerclick: function(evt, x, y) {

	        CellView.prototype.pointerclick.apply(this, arguments);
	        this.notify('link:pointerclick', evt, x, y);
	    },

	    contextmenu: function(evt, x, y) {

	        CellView.prototype.contextmenu.apply(this, arguments);
	        this.notify('link:contextmenu', evt, x, y);
	    },

	    pointerdown: function(evt, x, y) {

	        this.notifyPointerdown(evt, x, y);

	        // Backwards compatibility for the default markup
	        var className = evt.target.getAttribute('class');
	        switch (className) {

	            case 'marker-vertex':
	                this.dragVertexStart(evt, x, y);
	                return;

	            case 'marker-vertex-remove':
	            case 'marker-vertex-remove-area':
	                this.dragVertexRemoveStart(evt, x, y);
	                return;

	            case 'marker-arrowhead':
	                this.dragArrowheadStart(evt, x, y);
	                return;

	            case 'connection':
	            case 'connection-wrap':
	                this.dragConnectionStart(evt, x, y);
	                return;

	            case 'marker-source':
	            case 'marker-target':
	                return;
	        }

	        this.dragStart(evt, x, y);
	    },

	    pointermove: function(evt, x, y) {

	        // Backwards compatibility
	        var dragData = this._dragData;
	        if (dragData) { this.eventData(evt, dragData); }

	        var data = this.eventData(evt);
	        switch (data.action) {

	            case 'vertex-move':
	                this.dragVertex(evt, x, y);
	                break;

	            case 'label-move':
	                this.dragLabel(evt, x, y);
	                break;

	            case 'arrowhead-move':
	                this.dragArrowhead(evt, x, y);
	                break;

	            case 'move':
	                this.drag(evt, x, y);
	                break;
	        }

	        // Backwards compatibility
	        if (dragData) { assign(dragData, this.eventData(evt)); }

	        this.notifyPointermove(evt, x, y);
	    },

	    pointerup: function(evt, x, y) {

	        // Backwards compatibility
	        var dragData = this._dragData;
	        if (dragData) {
	            this.eventData(evt, dragData);
	            this._dragData = null;
	        }

	        var data = this.eventData(evt);
	        switch (data.action) {

	            case 'vertex-move':
	                this.dragVertexEnd(evt, x, y);
	                break;

	            case 'label-move':
	                this.dragLabelEnd(evt, x, y);
	                break;

	            case 'arrowhead-move':
	                this.dragArrowheadEnd(evt, x, y);
	                break;

	            case 'move':
	                this.dragEnd(evt, x, y);
	        }

	        this.notifyPointerup(evt, x, y);
	        this.checkMouseleave(evt);
	    },

	    mouseover: function(evt) {

	        CellView.prototype.mouseover.apply(this, arguments);
	        this.notify('link:mouseover', evt);
	    },

	    mouseout: function(evt) {

	        CellView.prototype.mouseout.apply(this, arguments);
	        this.notify('link:mouseout', evt);
	    },

	    mouseenter: function(evt) {

	        CellView.prototype.mouseenter.apply(this, arguments);
	        this.notify('link:mouseenter', evt);
	    },

	    mouseleave: function(evt) {

	        CellView.prototype.mouseleave.apply(this, arguments);
	        this.notify('link:mouseleave', evt);
	    },

	    mousewheel: function(evt, x, y, delta) {

	        CellView.prototype.mousewheel.apply(this, arguments);
	        this.notify('link:mousewheel', evt, x, y, delta);
	    },

	    onevent: function(evt, eventName, x, y) {

	        // Backwards compatibility
	        var linkTool = V(evt.target).findParentByClass('link-tool', this.el);
	        if (linkTool) {
	            // No further action to be executed
	            evt.stopPropagation();

	            // Allow `interactive.useLinkTools=false`
	            if (this.can('useLinkTools')) {
	                if (eventName === 'remove') {
	                    // Built-in remove event
	                    this.model.remove({ ui: true });
	                    // Do not trigger link pointerdown
	                    return;

	                } else {
	                    // link:options and other custom events inside the link tools
	                    this.notify(eventName, evt, x, y);
	                }
	            }

	            this.notifyPointerdown(evt, x, y);
	            this.paper.delegateDragEvents(this, evt.data);

	        } else {
	            CellView.prototype.onevent.apply(this, arguments);
	        }
	    },

	    onlabel: function(evt, x, y) {

	        this.notifyPointerdown(evt, x, y);

	        this.dragLabelStart(evt, x, y);

	        var stopPropagation = this.eventData(evt).stopPropagation;
	        if (stopPropagation) { evt.stopPropagation(); }
	    },

	    // Drag Start Handlers

	    dragConnectionStart: function(evt, x, y) {

	        if (!this.can('vertexAdd')) { return; }

	        // Store the index at which the new vertex has just been placed.
	        // We'll be update the very same vertex position in `pointermove()`.
	        var vertexIdx = this.addVertex({ x: x, y: y }, { ui: true });
	        this.eventData(evt, {
	            action: 'vertex-move',
	            vertexIdx: vertexIdx
	        });
	    },

	    dragLabelStart: function(evt, _x, _y) {

	        if (this.can('labelMove')) {

	            var labelNode = evt.currentTarget;
	            var labelIdx = parseInt(labelNode.getAttribute('label-idx'), 10);

	            var positionAngle = this._getLabelPositionAngle(labelIdx);
	            var labelPositionArgs = this._getLabelPositionArgs(labelIdx);
	            var defaultLabelPositionArgs = this._getDefaultLabelPositionArgs();
	            var positionArgs = this._mergeLabelPositionArgs(labelPositionArgs, defaultLabelPositionArgs);

	            this.eventData(evt, {
	                action: 'label-move',
	                labelIdx: labelIdx,
	                positionAngle: positionAngle,
	                positionArgs: positionArgs,
	                stopPropagation: true
	            });

	        } else {

	            // Backwards compatibility:
	            // If labels can't be dragged no default action is triggered.
	            this.eventData(evt, { stopPropagation: true });
	        }

	        this.paper.delegateDragEvents(this, evt.data);
	    },

	    dragVertexStart: function(evt, x, y) {

	        if (!this.can('vertexMove')) { return; }

	        var vertexNode = evt.target;
	        var vertexIdx = parseInt(vertexNode.getAttribute('idx'), 10);
	        this.eventData(evt, {
	            action: 'vertex-move',
	            vertexIdx: vertexIdx
	        });
	    },

	    dragVertexRemoveStart: function(evt, x, y) {

	        if (!this.can('vertexRemove')) { return; }

	        var removeNode = evt.target;
	        var vertexIdx = parseInt(removeNode.getAttribute('idx'), 10);
	        this.model.removeVertex(vertexIdx);
	    },

	    dragArrowheadStart: function(evt, x, y) {

	        if (!this.can('arrowheadMove')) { return; }

	        var arrowheadNode = evt.target;
	        var arrowheadType = arrowheadNode.getAttribute('end');
	        var data = this.startArrowheadMove(arrowheadType, { ignoreBackwardsCompatibility: true });

	        this.eventData(evt, data);
	    },

	    dragStart: function(evt, x, y) {

	        if (!this.can('linkMove')) { return; }

	        this.eventData(evt, {
	            action: 'move',
	            dx: x,
	            dy: y
	        });
	    },

	    // Drag Handlers
	    dragLabel: function(evt, x, y) {

	        var data = this.eventData(evt);
	        var label = { position: this.getLabelPosition(x, y, data.positionAngle, data.positionArgs) };
	        if (this.paper.options.snapLabels) { delete label.position.offset; }
	        this.model.label(data.labelIdx, label);
	    },

	    dragVertex: function(evt, x, y) {

	        var data = this.eventData(evt);
	        this.model.vertex(data.vertexIdx, { x: x, y: y }, { ui: true });
	    },

	    dragArrowhead: function(evt, x, y) {

	        if (this.paper.options.snapLinks) {

	            this._snapArrowhead(evt, x, y);

	        } else {

	            this._connectArrowhead(this.getEventTarget(evt), x, y, this.eventData(evt));
	        }
	    },

	    drag: function(evt, x, y) {

	        var data = this.eventData(evt);
	        this.model.translate(x - data.dx, y - data.dy, { ui: true });
	        this.eventData(evt, {
	            dx: x,
	            dy: y
	        });
	    },

	    // Drag End Handlers

	    dragLabelEnd: function() {
	        // noop
	    },

	    dragVertexEnd: function() {
	        // noop
	    },

	    dragArrowheadEnd: function(evt, x, y) {

	        var data = this.eventData(evt);
	        var paper = this.paper;

	        if (paper.options.snapLinks) {
	            this._snapArrowheadEnd(data);
	        } else {
	            this._connectArrowheadEnd(data, x, y);
	        }

	        if (!paper.linkAllowed(this)) {
	            // If the changed link is not allowed, revert to its previous state.
	            this._disallow(data);
	        } else {
	            this._finishEmbedding(data);
	            this._notifyConnectEvent(data, evt);
	        }

	        this._afterArrowheadMove(data);
	    },

	    dragEnd: function() {
	        // noop
	    },

	    _disallow: function(data) {

	        switch (data.whenNotAllowed) {

	            case 'remove':
	                this.model.remove({ ui: true });
	                break;

	            case 'revert':
	            default:
	                this.model.set(data.arrowhead, data.initialEnd, { ui: true });
	                break;
	        }
	    },

	    _finishEmbedding: function(data) {

	        // Reparent the link if embedding is enabled
	        if (this.paper.options.embeddingMode && this.model.reparent()) {
	            // Make sure we don't reverse to the original 'z' index (see afterArrowheadMove()).
	            data.z = null;
	        }
	    },

	    _notifyConnectEvent: function(data, evt) {

	        var arrowhead = data.arrowhead;
	        var initialEnd = data.initialEnd;
	        var currentEnd = this.model.prop(arrowhead);
	        var endChanged = currentEnd && !Link.endsEqual(initialEnd, currentEnd);
	        if (endChanged) {
	            var paper = this.paper;
	            if (initialEnd.id) {
	                this.notify('link:disconnect', evt, paper.findViewByModel(initialEnd.id), data.initialMagnet, arrowhead);
	            }
	            if (currentEnd.id) {
	                this.notify('link:connect', evt, paper.findViewByModel(currentEnd.id), data.magnetUnderPointer, arrowhead);
	            }
	        }
	    },

	    _snapArrowhead: function(evt, x, y) {

	        var data = this.eventData(evt);
	        // checking view in close area of the pointer

	        var r = this.paper.options.snapLinks.radius || 50;
	        var viewsInArea = this.paper.findViewsInArea({ x: x - r, y: y - r, width: 2 * r, height: 2 * r });

	        var prevClosestView = data.closestView || null;
	        var prevClosestMagnet = data.closestMagnet || null;
	        var prevMagnetProxy = data.magnetProxy || null;

	        data.closestView = data.closestMagnet = data.magnetProxy = null;

	        var minDistance = Number.MAX_VALUE;
	        var pointer = new Point(x, y);
	        var paper = this.paper;

	        viewsInArea.forEach(function(view) {
	            var candidates = [];
	            // skip connecting to the element in case '.': { magnet: false } attribute present
	            if (view.el.getAttribute('magnet') !== 'false') {
	                candidates.push({
	                    bbox: view.model.getBBox(),
	                    magnet: view.el
	                });
	            }

	            view.$('[magnet]').toArray().forEach(function (magnet) {
	                candidates.push({
	                    bbox: view.getNodeBBox(magnet),
	                    magnet: magnet
	                });
	            });

	            candidates.forEach(function (candidate) {
	                var magnet = candidate.magnet;
	                var bbox = candidate.bbox;
	                // find distance from the center of the model to pointer coordinates
	                var distance = bbox.center().squaredDistance(pointer);
	                // the connection is looked up in a circle area by `distance < r`
	                if (distance < minDistance) {
	                    var isAlreadyValidated = prevClosestMagnet === magnet;
	                    if (isAlreadyValidated || paper.options.validateConnection.apply(
	                        paper, data.validateConnectionArgs(view, (view.el === magnet) ? null : magnet)
	                    )) {
	                        minDistance = distance;
	                        data.closestView = view;
	                        data.closestMagnet = magnet;
	                    }
	                }
	            });

	        }, this);

	        var end;
	        var magnetProxy = null;
	        var closestView = data.closestView;
	        var closestMagnet = data.closestMagnet;
	        if (closestMagnet) {
	            magnetProxy = data.magnetProxy = closestView.findProxyNode(closestMagnet, 'highlighter');
	        }
	        var endType = data.arrowhead;
	        var newClosestMagnet = (prevClosestMagnet !== closestMagnet);
	        if (prevClosestView && newClosestMagnet) {
	            prevClosestView.unhighlight(prevMagnetProxy, {
	                connecting: true,
	                snapping: true
	            });
	        }

	        if (closestView) {

	            if (!newClosestMagnet) { return; }

	            closestView.highlight(magnetProxy, {
	                connecting: true,
	                snapping: true
	            });
	            end = closestView.getLinkEnd(closestMagnet, x, y, this.model, endType);

	        } else {

	            end = { x: x, y: y };
	        }

	        this.model.set(endType, end || { x: x, y: y }, { ui: true });

	        if (prevClosestView) {
	            this.notify('link:snap:disconnect', evt, prevClosestView, prevClosestMagnet, endType);
	        }
	        if (closestView) {
	            this.notify('link:snap:connect', evt, closestView, closestMagnet, endType);
	        }
	    },

	    _snapArrowheadEnd: function(data) {

	        // Finish off link snapping.
	        // Everything except view unhighlighting was already done on pointermove.
	        var closestView = data.closestView;
	        var closestMagnet = data.closestMagnet;
	        if (closestView && closestMagnet) {

	            closestView.unhighlight(data.magnetProxy, { connecting: true, snapping: true });
	            data.magnetUnderPointer = closestView.findMagnet(closestMagnet);
	        }

	        data.closestView = data.closestMagnet = null;
	    },

	    _connectArrowhead: function(target, x, y, data) {

	        // checking views right under the pointer
	        var ref = this;
	        var paper = ref.paper;
	        var model = ref.model;

	        if (data.eventTarget !== target) {
	            // Unhighlight the previous view under pointer if there was one.
	            if (data.magnetProxy) {
	                data.viewUnderPointer.unhighlight(data.magnetProxy, {
	                    connecting: true
	                });
	            }

	            var viewUnderPointer = data.viewUnderPointer = paper.findView(target);
	            if (viewUnderPointer) {
	                // If we found a view that is under the pointer, we need to find the closest
	                // magnet based on the real target element of the event.
	                var magnetUnderPointer = data.magnetUnderPointer = viewUnderPointer.findMagnet(target);
	                var magnetProxy = data.magnetProxy = viewUnderPointer.findProxyNode(magnetUnderPointer, 'highlighter');

	                if (magnetUnderPointer && this.paper.options.validateConnection.apply(
	                    paper,
	                    data.validateConnectionArgs(viewUnderPointer, magnetUnderPointer)
	                )) {
	                    // If there was no magnet found, do not highlight anything and assume there
	                    // is no view under pointer we're interested in reconnecting to.
	                    // This can only happen if the overall element has the attribute `'.': { magnet: false }`.
	                    if (magnetProxy) {
	                        viewUnderPointer.highlight(magnetProxy, {
	                            connecting: true
	                        });
	                    }
	                } else {
	                    // This type of connection is not valid. Disregard this magnet.
	                    data.magnetUnderPointer = null;
	                    data.magnetProxy = null;
	                }
	            } else {
	                // Make sure we'll unset previous magnet.
	                data.magnetUnderPointer = null;
	                data.magnetProxy = null;
	            }
	        }

	        data.eventTarget = target;

	        model.set(data.arrowhead, { x: x, y: y }, { ui: true });
	    },

	    _connectArrowheadEnd: function(data, x, y) {
	        if ( data === void 0 ) data = {};


	        var ref = this;
	        var model = ref.model;
	        var viewUnderPointer = data.viewUnderPointer;
	        var magnetUnderPointer = data.magnetUnderPointer;
	        var magnetProxy = data.magnetProxy;
	        var arrowhead = data.arrowhead;

	        if (!magnetUnderPointer || !magnetProxy || !viewUnderPointer) { return; }

	        viewUnderPointer.unhighlight(magnetProxy, { connecting: true });

	        // The link end is taken from the magnet under the pointer, not the proxy.
	        var end = viewUnderPointer.getLinkEnd(magnetUnderPointer, x, y, model, arrowhead);
	        model.set(arrowhead, end, { ui: true });
	    },

	    _beforeArrowheadMove: function(data) {

	        data.z = this.model.get('z');
	        this.model.toFront();

	        // Let the pointer propagate through the link view elements so that
	        // the `evt.target` is another element under the pointer, not the link itself.
	        var style = this.el.style;
	        data.pointerEvents = style.pointerEvents;
	        style.pointerEvents = 'none';

	        if (this.paper.options.markAvailable) {
	            this._markAvailableMagnets(data);
	        }
	    },

	    _afterArrowheadMove: function(data) {

	        if (data.z !== null) {
	            this.model.set('z', data.z, { ui: true });
	            data.z = null;
	        }

	        // Put `pointer-events` back to its original value. See `_beforeArrowheadMove()` for explanation.
	        this.el.style.pointerEvents = data.pointerEvents;

	        if (this.paper.options.markAvailable) {
	            this._unmarkAvailableMagnets(data);
	        }
	    },

	    _createValidateConnectionArgs: function(arrowhead) {
	        // It makes sure the arguments for validateConnection have the following form:
	        // (source view, source magnet, target view, target magnet and link view)
	        var args = [];

	        args[4] = arrowhead;
	        args[5] = this;

	        var oppositeArrowhead;
	        var i = 0;
	        var j = 0;

	        if (arrowhead === 'source') {
	            i = 2;
	            oppositeArrowhead = 'target';
	        } else {
	            j = 2;
	            oppositeArrowhead = 'source';
	        }

	        var end = this.model.get(oppositeArrowhead);

	        if (end.id) {
	            var view = args[i] = this.paper.findViewByModel(end.id);
	            var magnet = view.getMagnetFromLinkEnd(end);
	            if (magnet === view.el) { magnet = undefined; }
	            args[i + 1] = magnet;
	        }

	        function validateConnectionArgs(cellView, magnet) {
	            args[j] = cellView;
	            args[j + 1] = cellView.el === magnet ? undefined : magnet;
	            return args;
	        }

	        return validateConnectionArgs;
	    },

	    _markAvailableMagnets: function(data) {

	        function isMagnetAvailable(view, magnet) {
	            var paper = view.paper;
	            var validate = paper.options.validateConnection;
	            return validate.apply(paper, this.validateConnectionArgs(view, magnet));
	        }

	        var paper = this.paper;
	        var elements = paper.model.getCells();
	        data.marked = {};

	        for (var i = 0, n = elements.length; i < n; i++) {
	            var view = elements[i].findView(paper);

	            if (!view) {
	                continue;
	            }

	            var magnets = Array.prototype.slice.call(view.el.querySelectorAll('[magnet]'));
	            if (view.el.getAttribute('magnet') !== 'false') {
	                // Element wrapping group is also a magnet
	                magnets.push(view.el);
	            }

	            var availableMagnets = magnets.filter(isMagnetAvailable.bind(data, view));

	            if (availableMagnets.length > 0) {
	                // highlight all available magnets
	                for (var j = 0, m = availableMagnets.length; j < m; j++) {
	                    view.highlight(availableMagnets[j], { magnetAvailability: true });
	                }
	                // highlight the entire view
	                view.highlight(null, { elementAvailability: true });

	                data.marked[view.model.id] = availableMagnets;
	            }
	        }
	    },

	    _unmarkAvailableMagnets: function(data) {

	        var markedKeys = Object.keys(data.marked);
	        var id;
	        var markedMagnets;

	        for (var i = 0, n = markedKeys.length; i < n; i++) {
	            id = markedKeys[i];
	            markedMagnets = data.marked[id];

	            var view = this.paper.findViewByModel(id);
	            if (view) {
	                for (var j = 0, m = markedMagnets.length; j < m; j++) {
	                    view.unhighlight(markedMagnets[j], { magnetAvailability: true });
	                }
	                view.unhighlight(null, { elementAvailability: true });
	            }
	        }

	        data.marked = null;
	    },

	    startArrowheadMove: function(end, opt) {

	        opt || (opt = {});

	        // Allow to delegate events from an another view to this linkView in order to trigger arrowhead
	        // move without need to click on the actual arrowhead dom element.
	        var data = {
	            action: 'arrowhead-move',
	            arrowhead: end,
	            whenNotAllowed: opt.whenNotAllowed || 'revert',
	            initialMagnet: this[end + 'Magnet'] || (this[end + 'View'] ? this[end + 'View'].el : null),
	            initialEnd: clone(this.model.get(end)),
	            validateConnectionArgs: this._createValidateConnectionArgs(end)
	        };

	        this._beforeArrowheadMove(data);

	        if (opt.ignoreBackwardsCompatibility !== true) {
	            this._dragData = data;
	        }

	        return data;
	    }
	}, {

	    Flags: Flags$1,
	});

	Object.defineProperty(LinkView.prototype, 'sourceBBox', {

	    enumerable: true,

	    get: function() {
	        var sourceView = this.sourceView;
	        if (!sourceView) {
	            var sourceDef = this.model.source();
	            return new Rect(sourceDef.x, sourceDef.y);
	        }
	        var sourceMagnet = this.sourceMagnet;
	        if (sourceView.isNodeConnection(sourceMagnet)) {
	            return new Rect(this.sourceAnchor);
	        }
	        return sourceView.getNodeBBox(sourceMagnet || sourceView.el);
	    }

	});

	Object.defineProperty(LinkView.prototype, 'targetBBox', {

	    enumerable: true,

	    get: function() {
	        var targetView = this.targetView;
	        if (!targetView) {
	            var targetDef = this.model.target();
	            return new Rect(targetDef.x, targetDef.y);
	        }
	        var targetMagnet = this.targetMagnet;
	        if (targetView.isNodeConnection(targetMagnet)) {
	            return new Rect(this.targetAnchor);
	        }
	        return targetView.getNodeBBox(targetMagnet || targetView.el);
	    }
	});

	var stroke = HighlighterView.extend({

	    tagName: 'path',
	    className: 'highlight-stroke',
	    attributes: {
	        'pointer-events': 'none',
	        'vector-effect': 'non-scaling-stroke',
	        'fill': 'none'
	    },

	    options: {
	        padding: 3,
	        rx: 0,
	        ry: 0,
	        useFirstSubpath: false,
	        attrs: {
	            'stroke-width': 3,
	            'stroke': '#FEB663'
	        }
	    },

	    getPathData: function getPathData(cellView, node) {
	        var ref = this;
	        var options = ref.options;
	        var useFirstSubpath = options.useFirstSubpath;
	        var d;
	        try {
	            var vNode = V(node);
	            d = vNode.convertToPathData().trim();
	            if (vNode.tagName() === 'PATH' && useFirstSubpath) {
	                var secondSubpathIndex = d.search(/.M/i) + 1;
	                if (secondSubpathIndex > 0) {
	                    d = d.substr(0, secondSubpathIndex);
	                }
	            }
	        } catch (error) {
	            // Failed to get path data from magnet element.
	            // Draw a rectangle around the node instead.
	            var nodeBBox = cellView.getNodeBoundingRect(node);
	            d = V.rectToPath(assign({}, options, nodeBBox.toJSON()));
	        }
	        return d;
	    },

	    highlightConnection: function highlightConnection(cellView) {
	        this.vel.attr('d', cellView.getSerializedConnection());
	    },

	    highlightNode: function highlightNode(cellView, node) {
	        var ref = this;
	        var vel = ref.vel;
	        var options = ref.options;
	        var padding = options.padding;
	        var layer = options.layer;
	        var highlightMatrix = cellView.getNodeMatrix(node);
	        // Add padding to the highlight element.
	        if (padding) {
	            if (!layer && node === cellView.el) {
	                // If the highlighter is appended to the cellView
	                // and we measure the size of the cellView wrapping group
	                // it's necessary to remove the highlighter first
	                vel.remove();
	            }
	            var nodeBBox = cellView.getNodeBoundingRect(node);
	            var cx = nodeBBox.x + (nodeBBox.width / 2);
	            var cy = nodeBBox.y + (nodeBBox.height / 2);
	            nodeBBox = V.transformRect(nodeBBox, highlightMatrix);
	            var width = Math.max(nodeBBox.width, 1);
	            var height = Math.max(nodeBBox.height, 1);
	            var sx = (width + padding) / width;
	            var sy = (height + padding) / height;
	            var paddingMatrix = V.createSVGMatrix({
	                a: sx,
	                b: 0,
	                c: 0,
	                d: sy,
	                e: cx - sx * cx,
	                f: cy - sy * cy
	            });
	            highlightMatrix = highlightMatrix.multiply(paddingMatrix);
	        }
	        vel.attr({
	            'd': this.getPathData(cellView, node),
	            'transform': V.matrixToTransformString(highlightMatrix)
	        });
	    },

	    highlight: function highlight(cellView, node) {
	        var ref = this;
	        var vel = ref.vel;
	        var options = ref.options;
	        vel.attr(options.attrs);
	        if (cellView.isNodeConnection(node)) {
	            this.highlightConnection(cellView);
	        } else {
	            this.highlightNode(cellView, node);
	        }
	    }

	});

	var MASK_CLIP = 20;

	function forEachDescendant(vel, fn) {
	    var descendants = vel.children();
	    while (descendants.length > 0) {
	        var descendant = descendants.shift();
	        if (fn(descendant)) {
	            descendants.push.apply(descendants, descendant.children());
	        }
	    }
	}

	var mask = HighlighterView.extend({

	    tagName: 'rect',
	    className: 'highlight-mask',
	    attributes: {
	        'pointer-events': 'none'
	    },

	    options: {
	        padding: 3,
	        maskClip: MASK_CLIP,
	        deep: false,
	        attrs: {
	            'stroke': '#FEB663',
	            'stroke-width': 3,
	            'stroke-linecap': 'butt',
	            'stroke-linejoin': 'miter',
	        }
	    },

	    VISIBLE: 'white',
	    INVISIBLE: 'black',

	    MASK_ROOT_ATTRIBUTE_BLACKLIST: [
	        'marker-start',
	        'marker-end',
	        'marker-mid',
	        'transform',
	        'stroke-dasharray'
	    ],

	    MASK_CHILD_ATTRIBUTE_BLACKLIST: [
	        'stroke',
	        'fill',
	        'stroke-width',
	        'stroke-opacity',
	        'stroke-dasharray',
	        'fill-opacity',
	        'marker-start',
	        'marker-end',
	        'marker-mid'
	    ],

	    // TODO: change the list to a function callback
	    MASK_REPLACE_TAGS: [
	        'FOREIGNOBJECT',
	        'IMAGE',
	        'USE',
	        'TEXT',
	        'TSPAN',
	        'TEXTPATH'
	    ],

	    // TODO: change the list to a function callback
	    MASK_REMOVE_TAGS: [
	        'TEXT',
	        'TSPAN',
	        'TEXTPATH'
	    ],

	    transformMaskChild: function transformMaskChild(cellView, childEl) {
	        var ref = this;
	        var MASK_CHILD_ATTRIBUTE_BLACKLIST = ref.MASK_CHILD_ATTRIBUTE_BLACKLIST;
	        var MASK_REPLACE_TAGS = ref.MASK_REPLACE_TAGS;
	        var MASK_REMOVE_TAGS = ref.MASK_REMOVE_TAGS;
	        var childTagName = childEl.tagName();
	        // Do not include the element in the mask's image
	        if (!V.isSVGGraphicsElement(childEl) || MASK_REMOVE_TAGS.includes(childTagName)) {
	            childEl.remove();
	            return false;
	        }
	        // Replace the element with a rectangle
	        if (MASK_REPLACE_TAGS.includes(childTagName)) {
	            // Note: clone() method does not change the children ids
	            var originalChild = cellView.vel.findOne(("#" + (childEl.id)));
	            if (originalChild) {
	                var originalNode = originalChild.node;
	                var childBBox = cellView.getNodeBoundingRect(originalNode);
	                if (cellView.model.isElement()) {
	                    childBBox = V.transformRect(childBBox, cellView.getNodeMatrix(originalNode));
	                }
	                var replacement = V('rect', childBBox.toJSON());
	                var ref$1 = childBBox.center();
	                var ox = ref$1.x;
	                var oy = ref$1.y;
	                var ref$2 = originalChild.rotate();
	                var angle = ref$2.angle;
	                var cx = ref$2.cx; if ( cx === void 0 ) cx = ox;
	                var cy = ref$2.cy; if ( cy === void 0 ) cy = oy;
	                if (angle) { replacement.rotate(angle, cx, cy); }
	                // Note: it's not important to keep the same sibling index since all subnodes are filled
	                childEl.parent().append(replacement);
	            }
	            childEl.remove();
	            return false;
	        }
	        // Keep the element, but clean it from certain attributes
	        MASK_CHILD_ATTRIBUTE_BLACKLIST.forEach(function (attrName) {
	            if (attrName === 'fill' && childEl.attr('fill') === 'none') { return; }
	            childEl.removeAttr(attrName);
	        });
	        return true;
	    },

	    transformMaskRoot: function transformMaskRoot(_cellView, rootEl) {
	        var ref = this;
	        var MASK_ROOT_ATTRIBUTE_BLACKLIST = ref.MASK_ROOT_ATTRIBUTE_BLACKLIST;
	        MASK_ROOT_ATTRIBUTE_BLACKLIST.forEach(function (attrName) {
	            rootEl.removeAttr(attrName);
	        });
	    },

	    getMaskShape: function getMaskShape(cellView, vel) {
	        var this$1 = this;

	        var ref = this;
	        var options = ref.options;
	        var MASK_REPLACE_TAGS = ref.MASK_REPLACE_TAGS;
	        var deep = options.deep;
	        var tagName = vel.tagName();
	        var maskRoot;
	        if (tagName === 'G') {
	            if (!deep) { return null; }
	            maskRoot = vel.clone();
	            forEachDescendant(maskRoot, function (maskChild) { return this$1.transformMaskChild(cellView, maskChild); });
	        } else {
	            if (MASK_REPLACE_TAGS.includes(tagName)) { return null; }
	            maskRoot = vel.clone();
	        }
	        this.transformMaskRoot(cellView, maskRoot);
	        return maskRoot;
	    },

	    getMaskId: function getMaskId() {
	        return ("highlight-mask-" + (this.cid));
	    },

	    getMask: function getMask(cellView, vNode) {

	        var ref = this;
	        var VISIBLE = ref.VISIBLE;
	        var INVISIBLE = ref.INVISIBLE;
	        var options = ref.options;
	        var padding = options.padding;
	        var attrs = options.attrs;

	        var strokeWidth = ('stroke-width' in attrs) ? attrs['stroke-width'] : 1;
	        var hasNodeFill = vNode.attr('fill') !== 'none';
	        var magnetStrokeWidth = parseFloat(vNode.attr('stroke-width'));
	        if (isNaN(magnetStrokeWidth)) { magnetStrokeWidth = 1; }
	        // stroke of the invisible shape
	        var minStrokeWidth = magnetStrokeWidth + padding * 2;
	        // stroke of the visible shape
	        var maxStrokeWidth = minStrokeWidth + strokeWidth * 2;
	        var maskEl = this.getMaskShape(cellView, vNode);
	        if (!maskEl) {
	            var nodeBBox = cellView.getNodeBoundingRect(vNode.node);
	            // Make sure the rect is visible
	            nodeBBox.inflate(nodeBBox.width ? 0 : 0.5, nodeBBox.height ? 0 : 0.5);
	            maskEl =  V('rect', nodeBBox.toJSON());
	        }
	        maskEl.attr(attrs);
	        return V('mask', {
	            'id': this.getMaskId()
	        }).append([
	            maskEl.clone().attr({
	                'fill': hasNodeFill ? VISIBLE : 'none',
	                'stroke': VISIBLE,
	                'stroke-width': maxStrokeWidth
	            }),
	            maskEl.clone().attr({
	                'fill': hasNodeFill ? INVISIBLE : 'none',
	                'stroke': INVISIBLE,
	                'stroke-width': minStrokeWidth
	            })
	        ]);
	    },

	    removeMask: function removeMask(paper) {
	        var maskNode = paper.svg.getElementById(this.getMaskId());
	        if (maskNode) {
	            paper.defs.removeChild(maskNode);
	        }
	    },

	    addMask: function addMask(paper, maskEl) {
	        paper.defs.appendChild(maskEl.node);
	    },

	    highlight: function highlight(cellView, node) {
	        var ref = this;
	        var options = ref.options;
	        var vel = ref.vel;
	        var padding = options.padding;
	        var attrs = options.attrs;
	        var maskClip = options.maskClip; if ( maskClip === void 0 ) maskClip = MASK_CLIP;
	        var layer = options.layer;
	        var color = ('stroke' in attrs) ? attrs['stroke'] : '#000000';
	        if (!layer && node === cellView.el) {
	            // If the highlighter is appended to the cellView
	            // and we measure the size of the cellView wrapping group
	            // it's necessary to remove the highlighter first
	            vel.remove();
	        }
	        var highlighterBBox = cellView.getNodeBoundingRect(node).inflate(padding + maskClip);
	        var maskEl = this.getMask(cellView, V(node));
	        this.addMask(cellView.paper, maskEl);
	        vel.attr(highlighterBBox.toJSON());
	        vel.attr({
	            'transform': V.matrixToTransformString(cellView.getNodeMatrix(node)),
	            'mask': ("url(#" + (maskEl.id) + ")"),
	            'fill': color
	        });
	    },

	    unhighlight: function unhighlight(cellView) {
	        this.removeMask(cellView.paper);
	    }

	});

	var opacity = HighlighterView.extend({

	    UPDATABLE: false,
	    MOUNTABLE: false,

	    opacityClassName: addClassNamePrefix('highlight-opacity'),

	    highlight: function(_cellView, node) {
	        V(node).addClass(this.opacityClassName);
	    },

	    unhighlight: function(_cellView, node) {
	        V(node).removeClass(this.opacityClassName);
	    }

	});

	var className = addClassNamePrefix('highlighted');

	var addClass = HighlighterView.extend({

	    UPDATABLE: false,
	    MOUNTABLE: false,

	    options: {
	        className: className
	    },

	    highlight: function(_cellView, node) {
	        V(node).addClass(this.options.className);
	    },

	    unhighlight: function(_cellView, node) {
	        V(node).removeClass(this.options.className);
	    }

	}, {
	    // Backwards Compatibility
	    className: className
	});



	var highlighters = ({
		stroke: stroke,
		mask: mask,
		opacity: opacity,
		addClass: addClass
	});

	function connectionRatio(view, _magnet, _refPoint, opt) {

	    var ratio = ('ratio' in opt) ? opt.ratio : 0.5;
	    return view.getPointAtRatio(ratio);
	}

	function connectionLength(view, _magnet, _refPoint, opt) {

	    var length = ('length' in opt) ? opt.length : 20;
	    return view.getPointAtLength(length);
	}

	function _connectionPerpendicular(view, _magnet, refPoint, opt) {

	    var OFFSET = 1e6;
	    var path = view.getConnection();
	    var segmentSubdivisions = view.getConnectionSubdivisions();
	    var verticalLine = new Line(refPoint.clone().offset(0, OFFSET), refPoint.clone().offset(0, -OFFSET));
	    var horizontalLine = new Line(refPoint.clone().offset(OFFSET, 0), refPoint.clone().offset(-OFFSET, 0));
	    var verticalIntersections = verticalLine.intersect(path, { segmentSubdivisions: segmentSubdivisions });
	    var horizontalIntersections = horizontalLine.intersect(path, { segmentSubdivisions: segmentSubdivisions });
	    var intersections = [];
	    if (verticalIntersections) { Array.prototype.push.apply(intersections, verticalIntersections); }
	    if (horizontalIntersections) { Array.prototype.push.apply(intersections, horizontalIntersections); }
	    if (intersections.length > 0) { return refPoint.chooseClosest(intersections); }
	    if ('fallbackAt' in opt) {
	        return getPointAtLink(view, opt.fallbackAt);
	    }
	    return connectionClosest(view, _magnet, refPoint, opt);
	}

	function _connectionClosest(view, _magnet, refPoint, _opt) {

	    var closestPoint = view.getClosestPoint(refPoint);
	    if (!closestPoint) { return new Point(); }
	    return closestPoint;
	}

	function resolveRef(fn) {
	    return function(view, magnet, ref, opt) {
	        if (ref instanceof Element) {
	            var refView = this.paper.findView(ref);
	            var refPoint;
	            if (refView) {
	                if (refView.isNodeConnection(ref)) {
	                    var distance = ('fixedAt' in opt) ? opt.fixedAt : '50%';
	                    refPoint = getPointAtLink(refView, distance);
	                } else {
	                    refPoint = refView.getNodeBBox(ref).center();
	                }
	            } else {
	                // Something went wrong
	                refPoint = new Point();
	            }
	            return fn.call(this, view, magnet, refPoint, opt);
	        }
	        return fn.apply(this, arguments);
	    };
	}

	function getPointAtLink(view, value) {
	    var parsedValue = parseFloat(value);
	    if (isPercentage(value)) {
	        return view.getPointAtRatio(parsedValue / 100);
	    } else {
	        return view.getPointAtLength(parsedValue);
	    }
	}
	var connectionPerpendicular = resolveRef(_connectionPerpendicular);
	var connectionClosest = resolveRef(_connectionClosest);

	var linkAnchors = ({
		resolveRef: resolveRef,
		connectionRatio: connectionRatio,
		connectionLength: connectionLength,
		connectionPerpendicular: connectionPerpendicular,
		connectionClosest: connectionClosest
	});

	function offsetPoint(p1, p2, offset) {
	    if (isPlainObject(offset)) {
	        var x = offset.x;
	        var y = offset.y;
	        if (isFinite(y)) {
	            var line =  new Line(p2, p1);
	            var ref = line.parallel(y);
	            var start = ref.start;
	            var end = ref.end;
	            p2 = start;
	            p1 = end;
	        }
	        offset = x;
	    }
	    if (!isFinite(offset)) { return p1; }
	    var length = p1.distance(p2);
	    if (offset === 0 && length > 0) { return p1; }
	    return p1.move(p2, -Math.min(offset, length - 1));
	}

	function stroke$1(magnet) {

	    var stroke = magnet.getAttribute('stroke-width');
	    if (stroke === null) { return 0; }
	    return parseFloat(stroke) || 0;
	}

	function alignLine(line, type, offset) {
	    if ( offset === void 0 ) offset = 0;

	    var coordinate, a, b, direction;
	    var start = line.start;
	    var end = line.end;
	    switch (type) {
	        case 'left':
	            coordinate = 'x';
	            a = end;
	            b = start;
	            direction = -1;
	            break;
	        case 'right':
	            coordinate = 'x';
	            a = start;
	            b = end;
	            direction = 1;
	            break;
	        case 'top':
	            coordinate = 'y';
	            a = end;
	            b = start;
	            direction = -1;
	            break;
	        case 'bottom':
	            coordinate = 'y';
	            a = start;
	            b = end;
	            direction = 1;
	            break;
	        default:
	            return;
	    }
	    if (start[coordinate] < end[coordinate]) {
	        a[coordinate] = b[coordinate];
	    } else {
	        b[coordinate] = a[coordinate];
	    }
	    if (isFinite(offset)) {
	        a[coordinate] += direction * offset;
	        b[coordinate] += direction * offset;
	    }
	}

	// Connection Points

	function anchorConnectionPoint(line, _view, _magnet, opt) {
	    var offset = opt.offset;
	    var alignOffset = opt.alignOffset;
	    var align = opt.align;
	    if (align) { alignLine(line, align, alignOffset); }
	    return offsetPoint(line.end, line.start, offset);
	}

	function bboxIntersection(line, view, magnet, opt) {

	    var bbox = view.getNodeBBox(magnet);
	    if (opt.stroke) { bbox.inflate(stroke$1(magnet) / 2); }
	    var intersections = line.intersect(bbox);
	    var cp = (intersections)
	        ? line.start.chooseClosest(intersections)
	        : line.end;
	    return offsetPoint(cp, line.start, opt.offset);
	}

	function rectangleIntersection(line, view, magnet, opt) {

	    var angle = view.model.angle();
	    if (angle === 0) {
	        return bboxIntersection(line, view, magnet, opt);
	    }

	    var bboxWORotation = view.getNodeUnrotatedBBox(magnet);
	    if (opt.stroke) { bboxWORotation.inflate(stroke$1(magnet) / 2); }
	    var center = bboxWORotation.center();
	    var lineWORotation = line.clone().rotate(center, angle);
	    var intersections = lineWORotation.setLength(1e6).intersect(bboxWORotation);
	    var cp = (intersections)
	        ? lineWORotation.start.chooseClosest(intersections).rotate(center, -angle)
	        : line.end;
	    return offsetPoint(cp, line.start, opt.offset);
	}

	function findShapeNode(magnet) {
	    if (!magnet) { return null; }
	    var node = magnet;
	    do {
	        var tagName = node.tagName;
	        if (typeof tagName !== 'string') { return null; }
	        tagName = tagName.toUpperCase();
	        if (tagName === 'G') {
	            node = node.firstElementChild;
	        } else if (tagName === 'TITLE') {
	            node = node.nextElementSibling;
	        } else { break; }
	    } while (node);
	    return node;
	}

	var BNDR_SUBDIVISIONS = 'segmentSubdivisons';
	var BNDR_SHAPE_BBOX = 'shapeBBox';

	function boundaryIntersection(line, view, magnet, opt) {

	    var node, intersection;
	    var selector = opt.selector;
	    var anchor = line.end;

	    if (typeof selector === 'string') {
	        node = view.findBySelector(selector)[0];
	    } else if (Array.isArray(selector)) {
	        node = getByPath(magnet, selector);
	    } else {
	        node = findShapeNode(magnet);
	    }

	    if (!V.isSVGGraphicsElement(node)) {
	        if (node === magnet || !V.isSVGGraphicsElement(magnet)) { return anchor; }
	        node = magnet;
	    }

	    var localShape = view.getNodeShape(node);
	    var magnetMatrix = view.getNodeMatrix(node);
	    var translateMatrix = view.getRootTranslateMatrix();
	    var rotateMatrix = view.getRootRotateMatrix();
	    var targetMatrix = translateMatrix.multiply(rotateMatrix).multiply(magnetMatrix);
	    var localMatrix = targetMatrix.inverse();
	    var localLine = V.transformLine(line, localMatrix);
	    var localRef = localLine.start.clone();
	    var data = view.getNodeData(node);

	    if (opt.insideout === false) {
	        if (!data[BNDR_SHAPE_BBOX]) { data[BNDR_SHAPE_BBOX] = localShape.bbox(); }
	        var localBBox = data[BNDR_SHAPE_BBOX];
	        if (localBBox.containsPoint(localRef)) { return anchor; }
	    }

	    // Caching segment subdivisions for paths
	    var pathOpt;
	    if (localShape instanceof Path) {
	        var precision = opt.precision || 2;
	        if (!data[BNDR_SUBDIVISIONS]) { data[BNDR_SUBDIVISIONS] = localShape.getSegmentSubdivisions({ precision: precision }); }
	        pathOpt = {
	            precision: precision,
	            segmentSubdivisions: data[BNDR_SUBDIVISIONS]
	        };
	    }

	    if (opt.extrapolate === true) { localLine.setLength(1e6); }

	    intersection = localLine.intersect(localShape, pathOpt);
	    if (intersection) {
	        // More than one intersection
	        if (V.isArray(intersection)) { intersection = localRef.chooseClosest(intersection); }
	    } else if (opt.sticky === true) {
	        // No intersection, find the closest point instead
	        if (localShape instanceof Rect) {
	            intersection = localShape.pointNearestToPoint(localRef);
	        } else if (localShape instanceof Ellipse) {
	            intersection = localShape.intersectionWithLineFromCenterToPoint(localRef);
	        } else {
	            intersection = localShape.closestPoint(localRef, pathOpt);
	        }
	    }

	    var cp = (intersection) ? V.transformPoint(intersection, targetMatrix) : anchor;
	    var cpOffset = opt.offset || 0;
	    if (opt.stroke) { cpOffset += stroke$1(node) / 2; }

	    return offsetPoint(cp, line.start, cpOffset);
	}

	var anchor = anchorConnectionPoint;
	var bbox = bboxIntersection;
	var rectangle = rectangleIntersection;
	var boundary = boundaryIntersection;

	var connectionPoints = ({
		anchor: anchor,
		bbox: bbox,
		rectangle: rectangle,
		boundary: boundary
	});

	function bboxWrapper(method) {

	    return function(view, magnet, ref, opt) {

	        var rotate = !!opt.rotate;
	        var bbox = (rotate) ? view.getNodeUnrotatedBBox(magnet) : view.getNodeBBox(magnet);
	        var anchor = bbox[method]();

	        var dx = opt.dx;
	        if (dx) {
	            var dxPercentage = isPercentage(dx);
	            dx = parseFloat(dx);
	            if (isFinite(dx)) {
	                if (dxPercentage) {
	                    dx /= 100;
	                    dx *= bbox.width;
	                }
	                anchor.x += dx;
	            }
	        }

	        var dy = opt.dy;
	        if (dy) {
	            var dyPercentage = isPercentage(dy);
	            dy = parseFloat(dy);
	            if (isFinite(dy)) {
	                if (dyPercentage) {
	                    dy /= 100;
	                    dy *= bbox.height;
	                }
	                anchor.y += dy;
	            }
	        }

	        return (rotate) ? anchor.rotate(view.model.getBBox().center(), -view.model.angle()) : anchor;
	    };
	}

	function _perpendicular(view, magnet, refPoint, opt) {

	    var angle = view.model.angle();
	    var bbox = view.getNodeBBox(magnet);
	    var anchor = bbox.center();
	    var topLeft = bbox.origin();
	    var bottomRight = bbox.corner();

	    var padding = opt.padding;
	    if (!isFinite(padding)) { padding = 0; }

	    if ((topLeft.y + padding) <= refPoint.y && refPoint.y <= (bottomRight.y - padding)) {
	        var dy = (refPoint.y - anchor.y);
	        anchor.x += (angle === 0 || angle === 180) ? 0 : dy * 1 / Math.tan(toRad(angle));
	        anchor.y += dy;
	    } else if ((topLeft.x + padding) <= refPoint.x && refPoint.x <= (bottomRight.x - padding)) {
	        var dx = (refPoint.x - anchor.x);
	        anchor.y += (angle === 90 || angle === 270) ? 0 : dx * Math.tan(toRad(angle));
	        anchor.x += dx;
	    }

	    return anchor;
	}

	function _midSide(view, magnet, refPoint, opt) {

	    var rotate = !!opt.rotate;
	    var bbox, angle, center;
	    if (rotate) {
	        bbox = view.getNodeUnrotatedBBox(magnet);
	        center = view.model.getBBox().center();
	        angle = view.model.angle();
	    } else {
	        bbox = view.getNodeBBox(magnet);
	    }

	    var padding = opt.padding;
	    if (isFinite(padding)) { bbox.inflate(padding); }

	    if (rotate) { refPoint.rotate(center, angle); }

	    var side = bbox.sideNearestToPoint(refPoint);
	    var anchor;
	    switch (side) {
	        case 'left':
	            anchor = bbox.leftMiddle();
	            break;
	        case 'right':
	            anchor = bbox.rightMiddle();
	            break;
	        case 'top':
	            anchor = bbox.topMiddle();
	            break;
	        case 'bottom':
	            anchor = bbox.bottomMiddle();
	            break;
	    }

	    return (rotate) ? anchor.rotate(center, -angle) : anchor;
	}

	// Can find anchor from model, when there is no selector or the link end
	// is connected to a port
	function _modelCenter(view, _magnet, _refPoint, opt, endType) {
	    return view.model.getPointFromConnectedLink(this.model, endType).offset(opt.dx, opt.dy);
	}

	//joint.anchors
	var center = bboxWrapper('center');
	var top$2 = bboxWrapper('topMiddle');
	var bottom$2 = bboxWrapper('bottomMiddle');
	var left$2 = bboxWrapper('leftMiddle');
	var right$2 = bboxWrapper('rightMiddle');
	var topLeft = bboxWrapper('origin');
	var topRight = bboxWrapper('topRight');
	var bottomLeft = bboxWrapper('bottomLeft');
	var bottomRight = bboxWrapper('corner');
	var perpendicular = resolveRef(_perpendicular);
	var midSide = resolveRef(_midSide);
	var modelCenter = _modelCenter;

	var anchors = ({
		center: center,
		top: top$2,
		bottom: bottom$2,
		left: left$2,
		right: right$2,
		topLeft: topLeft,
		topRight: topRight,
		bottomLeft: bottomLeft,
		bottomRight: bottomRight,
		perpendicular: perpendicular,
		midSide: midSide,
		modelCenter: modelCenter
	});

	var sortingTypes = {
	    NONE: 'sorting-none',
	    APPROX: 'sorting-approximate',
	    EXACT: 'sorting-exact'
	};

	var LayersNames = {
	    CELLS: 'cells',
	    BACK: 'back',
	    FRONT: 'front',
	    TOOLS: 'tools'
	};

	var MOUNT_BATCH_SIZE = 1000;
	var UPDATE_BATCH_SIZE = Infinity;
	var MIN_PRIORITY = 9007199254740991; // Number.MAX_SAFE_INTEGER

	var HighlightingTypes$1 = CellView.Highlighting;

	var defaultHighlighting = {};
	defaultHighlighting[HighlightingTypes$1.DEFAULT] = {
	        name: 'stroke',
	        options: {
	            padding: 3
	        }
	    };
	defaultHighlighting[HighlightingTypes$1.MAGNET_AVAILABILITY] = {
	        name: 'addClass',
	        options: {
	            className: 'available-magnet'
	        }
	    };
	defaultHighlighting[HighlightingTypes$1.ELEMENT_AVAILABILITY] = {
	        name: 'addClass',
	        options: {
	            className: 'available-cell'
	        }
	    };

	var Paper = View.extend({

	    className: 'paper',

	    options: {

	        width: 800,
	        height: 600,
	        origin: { x: 0, y: 0 }, // x,y coordinates in top-left corner
	        gridSize: 1,

	        // Whether or not to draw the grid lines on the paper's DOM element.
	        // e.g drawGrid: true, drawGrid: { color: 'red', thickness: 2 }
	        drawGrid: false,

	        // Whether or not to draw the background on the paper's DOM element.
	        // e.g. background: { color: 'lightblue', image: '/paper-background.png', repeat: 'flip-xy' }
	        background: false,

	        perpendicularLinks: false,
	        elementView: ElementView,
	        linkView: LinkView,
	        snapLabels: false, // false, true
	        snapLinks: false, // false, true, { radius: value }

	        // When set to FALSE, an element may not have more than 1 link with the same source and target element.
	        multiLinks: true,

	        // For adding custom guard logic.
	        guard: function(evt, view) {

	            // FALSE means the event isn't guarded.
	            return false;
	        },

	        highlighting: defaultHighlighting,

	        // Prevent the default context menu from being displayed.
	        preventContextMenu: true,

	        // Prevent the default action for blank:pointer<action>.
	        preventDefaultBlankAction: true,

	        // Restrict the translation of elements by given bounding box.
	        // Option accepts a boolean:
	        //  true - the translation is restricted to the paper area
	        //  false - no restrictions
	        // A method:
	        // restrictTranslate: function(elementView) {
	        //     var parentId = elementView.model.get('parent');
	        //     return parentId && this.model.getCell(parentId).getBBox();
	        // },
	        // Or a bounding box:
	        // restrictTranslate: { x: 10, y: 10, width: 790, height: 590 }
	        restrictTranslate: false,

	        // Marks all available magnets with 'available-magnet' class name and all available cells with
	        // 'available-cell' class name. Marks them when dragging a link is started and unmark
	        // when the dragging is stopped.
	        markAvailable: false,

	        // Defines what link model is added to the graph after an user clicks on an active magnet.
	        // Value could be the Backbone.model or a function returning the Backbone.model
	        // defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() }
	        defaultLink: new Link,

	        // A connector that is used by links with no connector defined on the model.
	        // e.g. { name: 'rounded', args: { radius: 5 }} or a function
	        defaultConnector: { name: 'normal' },

	        // A router that is used by links with no router defined on the model.
	        // e.g. { name: 'oneSide', args: { padding: 10 }} or a function
	        defaultRouter: { name: 'normal' },

	        defaultAnchor: { name: 'center' },

	        defaultLinkAnchor: { name: 'connectionRatio' },

	        defaultConnectionPoint: { name: 'bbox' },

	        /* CONNECTING */

	        connectionStrategy: null,

	        // Check whether to add a new link to the graph when user clicks on an a magnet.
	        validateMagnet: function(_cellView, magnet, _evt) {
	            return magnet.getAttribute('magnet') !== 'passive';
	        },

	        // Check whether to allow or disallow the link connection while an arrowhead end (source/target)
	        // being changed.
	        validateConnection: function(cellViewS, _magnetS, cellViewT, _magnetT, end, _linkView) {
	            return (end === 'target' ? cellViewT : cellViewS) instanceof ElementView;
	        },

	        /* EMBEDDING */

	        // Enables embedding. Re-parent the dragged element with elements under it and makes sure that
	        // all links and elements are visible taken the level of embedding into account.
	        embeddingMode: false,

	        // Check whether to allow or disallow the element embedding while an element being translated.
	        validateEmbedding: function(childView, parentView) {
	            // by default all elements can be in relation child-parent
	            return true;
	        },

	        // Check whether to allow or disallow an embedded element to be unembedded / to become a root.
	        validateUnembedding: function(childView) {
	            // by default all elements can become roots
	            return true;
	        },

	        // Determines the way how a cell finds a suitable parent when it's dragged over the paper.
	        // The cell with the highest z-index (visually on the top) will be chosen.
	        findParentBy: 'bbox', // 'bbox'|'center'|'origin'|'corner'|'topRight'|'bottomLeft'

	        // If enabled only the element on the very front is taken into account for the embedding.
	        // If disabled the elements under the dragged view are tested one by one
	        // (from front to back) until a valid parent found.
	        frontParentOnly: true,

	        // Interactive flags. See online docs for the complete list of interactive flags.
	        interactive: {
	            labelMove: false
	        },

	        // When set to true the links can be pinned to the paper.
	        // i.e. link source/target can be a point e.g. link.get('source') ==> { x: 100, y: 100 };
	        linkPinning: true,

	        // Custom validation after an interaction with a link ends.
	        // Recognizes a function. If `false` is returned, the link is disallowed (removed or reverted)
	        // (linkView, paper) => boolean
	        allowLink: null,

	        // Allowed number of mousemove events after which the pointerclick event will be still triggered.
	        clickThreshold: 0,

	        // Number of required mousemove events before the first pointermove event will be triggered.
	        moveThreshold: 0,

	        // Number of required mousemove events before the a link is created out of the magnet.
	        // Or string `onleave` so the link is created when the pointer leaves the magnet
	        magnetThreshold: 0,

	        // Rendering Options

	        sorting: sortingTypes.EXACT,

	        frozen: false,

	        // no docs yet
	        onViewUpdate: function(view, flag, priority, opt, paper) {
	            // Do not update connected links when:
	            // 1. the view was just inserted (added to the graph and rendered)
	            // 2. the view was just mounted (added back to the paper by viewport function)
	            // 3. the change was marked as `isolate`.
	            if ((flag & view.FLAG_INSERT) || opt.mounting || opt.isolate) { return; }
	            paper.requestConnectedLinksUpdate(view, priority, opt);
	        },

	        // no docs yet
	        onViewPostponed: function(view, flag, paper) {
	            return paper.forcePostponedViewUpdate(view, flag);
	        },

	        beforeRender: null, // function(opt, paper) { },

	        afterRender: null, // function(stats, opt, paper) {

	        viewport: null,

	        // Default namespaces

	        cellViewNamespace: null,

	        routerNamespace: null,

	        connectorNamespace: null,

	        highlighterNamespace: highlighters,

	        anchorNamespace: anchors,

	        linkAnchorNamespace: linkAnchors,

	        connectionPointNamespace: connectionPoints
	    },

	    events: {
	        'dblclick': 'pointerdblclick',
	        'contextmenu': 'contextmenu',
	        'mousedown': 'pointerdown',
	        'touchstart': 'pointerdown',
	        'mouseover': 'mouseover',
	        'mouseout': 'mouseout',
	        'mouseenter': 'mouseenter',
	        'mouseleave': 'mouseleave',
	        'mousewheel': 'mousewheel',
	        'DOMMouseScroll': 'mousewheel',
	        'mouseenter .joint-cell': 'mouseenter',
	        'mouseleave .joint-cell': 'mouseleave',
	        'mouseenter .joint-tools': 'mouseenter',
	        'mouseleave .joint-tools': 'mouseleave',
	        'mousedown .joint-cell [event]': 'onevent', // interaction with cell with `event` attribute set
	        'touchstart .joint-cell [event]': 'onevent',
	        'mousedown .joint-cell [magnet]': 'onmagnet', // interaction with cell with `magnet` attribute set
	        'touchstart .joint-cell [magnet]': 'onmagnet',
	        'dblclick .joint-cell [magnet]': 'magnetpointerdblclick',
	        'contextmenu .joint-cell [magnet]': 'magnetcontextmenu',
	        'mousedown .joint-link .label': 'onlabel', // interaction with link label
	        'touchstart .joint-link .label': 'onlabel',
	        'dragstart .joint-cell image': 'onImageDragStart' // firefox fix
	    },

	    documentEvents: {
	        'mousemove': 'pointermove',
	        'touchmove': 'pointermove',
	        'mouseup': 'pointerup',
	        'touchend': 'pointerup',
	        'touchcancel': 'pointerup'
	    },

	    svg: null,
	    viewport: null,
	    defs: null,
	    tools: null,
	    $background: null,
	    layers: null,
	    $grid: null,
	    $document: null,

	    _zPivots: null,
	    // For storing the current transformation matrix (CTM) of the paper's viewport.
	    _viewportMatrix: null,
	    // For verifying whether the CTM is up-to-date. The viewport transform attribute
	    // could have been manipulated directly.
	    _viewportTransformString: null,
	    // Updates data (priorities, unmounted views etc.)
	    _updates: null,
	    // Paper Layers
	    _layers: null,

	    SORT_DELAYING_BATCHES: ['add', 'to-front', 'to-back'],
	    UPDATE_DELAYING_BATCHES: ['translate'],
	    MIN_SCALE: 1e-6,

	    init: function() {

	        var ref = this;
	        var options = ref.options;
	        var el = ref.el;
	        if (!options.cellViewNamespace) {
	            /* global joint: true */
	            options.cellViewNamespace = typeof joint !== 'undefined' && has$2(joint, 'shapes') ? joint.shapes : null;
	            /* global joint: false */
	        }

	        var model = this.model = options.model || new Graph;

	        // Layers (SVGGroups)
	        // TODO: layer classes
	        this._layers = {};

	        this.setGrid(options.drawGrid);
	        this.cloneOptions();
	        this.render();
	        this.setDimensions();
	        this.startListening();

	        // Hash of all cell views.
	        this._views = {};
	        // z-index pivots
	        this._zPivots = {};
	        // Reference to the paper owner document
	        this.$document = $(el.ownerDocument);
	        // Render existing cells in the graph
	        this.resetViews(model.attributes.cells.models);
	        // Start the Rendering Loop
	        if (!this.isFrozen() && this.isAsync()) { this.updateViewsAsync(); }
	    },

	    _resetUpdates: function() {
	        return this._updates = {
	            id: null,
	            priorities: [{}, {}, {}],
	            unmountedCids: [],
	            mountedCids: [],
	            unmounted: {},
	            mounted: {},
	            count: 0,
	            keyFrozen: false,
	            freezeKey: null,
	            sort: false
	        };
	    },

	    startListening: function() {
	        var model = this.model;
	        this.listenTo(model, 'add', this.onCellAdded)
	            .listenTo(model, 'remove', this.onCellRemoved)
	            .listenTo(model, 'change', this.onCellChange)
	            .listenTo(model, 'reset', this.onGraphReset)
	            .listenTo(model, 'sort', this.onGraphSort)
	            .listenTo(model, 'batch:stop', this.onGraphBatchStop);
	        this.on('cell:highlight', this.onCellHighlight)
	            .on('cell:unhighlight', this.onCellUnhighlight)
	            .on('scale translate', this.update);
	    },

	    onCellAdded: function(cell, _, opt) {
	        var position = opt.position;
	        if (this.isAsync() || !isNumber(position)) {
	            this.renderView(cell, opt);
	        } else {
	            if (opt.maxPosition === position) { this.freeze({ key: 'addCells' }); }
	            this.renderView(cell, opt);
	            if (position === 0) { this.unfreeze({ key: 'addCells' }); }
	        }
	    },

	    onCellRemoved: function(cell, _, opt) {
	        var view = this.findViewByModel(cell);
	        if (view) { this.requestViewUpdate(view, view.FLAG_REMOVE, view.UPDATE_PRIORITY, opt); }
	    },

	    onCellChange: function(cell, opt) {
	        if (cell === this.model.attributes.cells) { return; }
	        if (cell.hasChanged('z') && this.options.sorting === sortingTypes.APPROX) {
	            var view = this.findViewByModel(cell);
	            if (view) { this.requestViewUpdate(view, view.FLAG_INSERT, view.UPDATE_PRIORITY, opt); }
	        }
	    },

	    onGraphReset: function(collection, opt) {
	        this.removeZPivots();
	        this.resetViews(collection.models, opt);
	    },

	    onGraphSort: function() {
	        if (this.model.hasActiveBatch(this.SORT_DELAYING_BATCHES)) { return; }
	        this.sortViews();
	    },

	    onGraphBatchStop: function(data) {
	        if (this.isFrozen()) { return; }
	        var name = data && data.batchName;
	        var graph = this.model;
	        if (!this.isAsync()) {
	            var updateDelayingBatches = this.UPDATE_DELAYING_BATCHES;
	            if (updateDelayingBatches.includes(name) && !graph.hasActiveBatch(updateDelayingBatches)) {
	                this.updateViews(data);
	            }
	        }
	        var sortDelayingBatches = this.SORT_DELAYING_BATCHES;
	        if (sortDelayingBatches.includes(name) && !graph.hasActiveBatch(sortDelayingBatches)) {
	            this.sortViews();
	        }
	    },

	    cloneOptions: function() {

	        var ref = this;
	        var options = ref.options;
	        var defaultConnector = options.defaultConnector;
	        var defaultRouter = options.defaultRouter;
	        var defaultConnectionPoint = options.defaultConnectionPoint;
	        var defaultAnchor = options.defaultAnchor;
	        var defaultLinkAnchor = options.defaultLinkAnchor;
	        var origin = options.origin;
	        var highlighting = options.highlighting;
	        var cellViewNamespace = options.cellViewNamespace;
	        var interactive = options.interactive;

	        // Default cellView namespace for ES5
	        /* global joint: true */
	        if (!cellViewNamespace && typeof joint !== 'undefined' && has$2(joint, 'shapes')) {
	            options.cellViewNamespace = joint.shapes;
	        }
	        /* global joint: false */

	        // Here if a function was provided, we can not clone it, as this would result in loosing the function.
	        // If the default is used, the cloning is necessary in order to prevent modifying the options on prototype.
	        if (!isFunction(defaultConnector)) {
	            options.defaultConnector = cloneDeep(defaultConnector);
	        }
	        if (!isFunction(defaultRouter)) {
	            options.defaultRouter = cloneDeep(defaultRouter);
	        }
	        if (!isFunction(defaultConnectionPoint)) {
	            options.defaultConnectionPoint = cloneDeep(defaultConnectionPoint);
	        }
	        if (!isFunction(defaultAnchor)) {
	            options.defaultAnchor = cloneDeep(defaultAnchor);
	        }
	        if (!isFunction(defaultLinkAnchor)) {
	            options.defaultLinkAnchor = cloneDeep(defaultLinkAnchor);
	        }
	        if (isPlainObject(interactive)) {
	            options.interactive = assign({}, interactive);
	        }
	        if (isPlainObject(highlighting)) {
	            // Return the default highlighting options into the user specified options.
	            options.highlighting = defaultsDeep({}, highlighting, defaultHighlighting);
	        }
	        options.origin = assign({}, origin);
	    },

	    children: function() {
	        var ns = V.namespace;
	        return [{
	            namespaceURI: ns.xhtml,
	            tagName: 'div',
	            className: addClassNamePrefix('paper-background'),
	            selector: 'background'
	        }, {
	            namespaceURI: ns.xhtml,
	            tagName: 'div',
	            className: addClassNamePrefix('paper-grid'),
	            selector: 'grid'
	        }, {
	            namespaceURI: ns.svg,
	            tagName: 'svg',
	            attributes: {
	                'width': '100%',
	                'height': '100%',
	                'xmlns:xlink': ns.xlink
	            },
	            selector: 'svg',
	            children: [{
	                // Append `<defs>` element to the SVG document. This is useful for filters and gradients.
	                // It's desired to have the defs defined before the viewport (e.g. to make a PDF document pick up defs properly).
	                tagName: 'defs',
	                selector: 'defs'
	            }, {
	                tagName: 'g',
	                className: addClassNamePrefix('layers'),
	                selector: 'layers',
	                children: [{
	                    tagName: 'g',
	                    className: addClassNamePrefix('back-layer'),
	                    selector: 'back',
	                }, {
	                    tagName: 'g',
	                    className: addClassNamePrefix('cells-layer viewport'),
	                    selector: 'cells',
	                }, {
	                    tagName: 'g',
	                    className: addClassNamePrefix('front-layer'),
	                    selector: 'front',
	                }, {
	                    tagName: 'g',
	                    className: addClassNamePrefix('tools-layer'),
	                    selector: 'tools'
	                }]
	            }]
	        }];
	    },

	    getLayerNode: function getLayerNode(layerName) {
	        var ref = this;
	        var _layers = ref._layers;
	        if (layerName in _layers) { return _layers[layerName]; }
	        throw new Error(("dia.Paper: Unknown layer \"" + layerName + "\""));
	    },

	    render: function() {
	        var obj;


	        this.renderChildren();
	        var ref = this;
	        var childNodes = ref.childNodes;
	        var options = ref.options;
	        var svg = childNodes.svg;
	        var cells = childNodes.cells;
	        var defs = childNodes.defs;
	        var tools = childNodes.tools;
	        var layers = childNodes.layers;
	        var back = childNodes.back;
	        var front = childNodes.front;
	        var background = childNodes.background;
	        var grid = childNodes.grid;

	        this.svg = svg;
	        this.defs = defs;
	        this.tools = tools;
	        this.cells = cells;
	        this.layers = layers;
	        this.$background = $(background);
	        this.$grid = $(grid);

	        assign(this._layers, ( obj = {}, obj[LayersNames.BACK] = back, obj[LayersNames.CELLS] = cells, obj[LayersNames.FRONT] = front, obj[LayersNames.TOOLS] = tools, obj ));

	        V.ensureId(svg);

	        // backwards compatibility
	        this.viewport = cells;

	        if (options.background) {
	            this.drawBackground(options.background);
	        }

	        if (options.drawGrid) {
	            this.drawGrid();
	        }

	        return this;
	    },

	    update: function() {

	        if (this.options.drawGrid) {
	            this.drawGrid();
	        }

	        if (this._background) {
	            this.updateBackgroundImage(this._background);
	        }

	        return this;
	    },

	    matrix: function(ctm) {

	        var viewport = this.layers;

	        // Getter:
	        if (ctm === undefined) {

	            var transformString = viewport.getAttribute('transform');

	            if ((this._viewportTransformString || null) === transformString) {
	                // It's ok to return the cached matrix. The transform attribute has not changed since
	                // the matrix was stored.
	                ctm = this._viewportMatrix;
	            } else {
	                // The viewport transform attribute has changed. Measure the matrix and cache again.
	                ctm = viewport.getCTM();
	                this._viewportMatrix = ctm;
	                this._viewportTransformString = transformString;
	            }

	            // Clone the cached current transformation matrix.
	            // If no matrix previously stored the identity matrix is returned.
	            return V.createSVGMatrix(ctm);
	        }

	        // Setter:
	        ctm = V.createSVGMatrix(ctm);
	        var ctmString = V.matrixToTransformString(ctm);
	        viewport.setAttribute('transform', ctmString);

	        this._viewportMatrix = ctm;
	        this._viewportTransformString = viewport.getAttribute('transform');

	        return this;
	    },

	    clientMatrix: function() {

	        return V.createSVGMatrix(this.cells.getScreenCTM());
	    },

	    requestConnectedLinksUpdate: function(view, priority, opt) {
	        if (view instanceof CellView) {
	            var model = view.model;
	            var links = this.model.getConnectedLinks(model);
	            for (var j = 0, n = links.length; j < n; j++) {
	                var link = links[j];
	                var linkView = this.findViewByModel(link);
	                if (!linkView) { continue; }
	                var flagLabels = ['UPDATE'];
	                if (link.getTargetCell() === model) { flagLabels.push('TARGET'); }
	                if (link.getSourceCell() === model) { flagLabels.push('SOURCE'); }
	                var nextPriority = Math.max(priority + 1, linkView.UPDATE_PRIORITY);
	                this.scheduleViewUpdate(linkView, linkView.getFlag(flagLabels), nextPriority, opt);
	            }
	        }
	    },

	    forcePostponedViewUpdate: function(view, flag) {
	        if (!view || !(view instanceof CellView)) { return false; }
	        var model = view.model;
	        if (model.isElement()) { return false; }
	        if ((flag & view.getFlag(['SOURCE', 'TARGET'])) === 0) {
	            // LinkView is waiting for the target or the source cellView to be rendered
	            // This can happen when the cells are not in the viewport.
	            var sourceFlag = 0;
	            var sourceView = this.findViewByModel(model.getSourceCell());
	            if (sourceView && !this.isViewMounted(sourceView)) {
	                sourceFlag = this.dumpView(sourceView);
	                view.updateEndMagnet('source');
	            }
	            var targetFlag = 0;
	            var targetView = this.findViewByModel(model.getTargetCell());
	            if (targetView && !this.isViewMounted(targetView)) {
	                targetFlag = this.dumpView(targetView);
	                view.updateEndMagnet('target');
	            }
	            if (sourceFlag === 0 && targetFlag === 0) {
	                // If leftover flag is 0, all view updates were done.
	                return !this.dumpView(view);
	            }
	        }
	        return false;
	    },

	    requestViewUpdate: function(view, flag, priority, opt) {
	        opt || (opt = {});
	        this.scheduleViewUpdate(view, flag, priority, opt);
	        var isAsync = this.isAsync();
	        if (this.isFrozen() || (isAsync && opt.async !== false)) { return; }
	        if (this.model.hasActiveBatch(this.UPDATE_DELAYING_BATCHES)) { return; }
	        var stats = this.updateViews(opt);
	        if (isAsync) { this.notifyAfterRender(stats, opt); }
	    },

	    scheduleViewUpdate: function(view, type, priority, opt) {
	        var ref = this;
	        var updates = ref._updates;
	        var options = ref.options;
	        var FLAG_REMOVE = view.FLAG_REMOVE;
	        var FLAG_INSERT = view.FLAG_INSERT;
	        var UPDATE_PRIORITY = view.UPDATE_PRIORITY;
	        var cid = view.cid;
	        var priorityUpdates = updates.priorities[priority];
	        if (!priorityUpdates) { priorityUpdates = updates.priorities[priority] = {}; }
	        // Move higher priority updates to this priority
	        if (priority > UPDATE_PRIORITY) {
	            // Not the default priority for this view. It's most likely a link view
	            // connected to another link view, which triggered the update.
	            // TODO: If there is an update scheduled with a lower priority already, we should
	            // change the requested priority to the lowest one. Does not seem to be critical
	            // right now, as it "only" results in multiple updates on the same view.
	            for (var i = priority - 1; i >= UPDATE_PRIORITY; i--) {
	                var prevPriorityUpdates = updates.priorities[i];
	                if (!prevPriorityUpdates || !(cid in prevPriorityUpdates)) { continue; }
	                priorityUpdates[cid] |= prevPriorityUpdates[cid];
	                delete prevPriorityUpdates[cid];
	            }
	        }
	        var currentType = priorityUpdates[cid] || 0;
	        // Prevent cycling
	        if ((currentType & type) === type) { return; }
	        if (!currentType) { updates.count++; }
	        if (type & FLAG_REMOVE && currentType & FLAG_INSERT) {
	            // When a view is removed we need to remove the insert flag as this is a reinsert
	            priorityUpdates[cid] ^= FLAG_INSERT;
	        } else if (type & FLAG_INSERT && currentType & FLAG_REMOVE) {
	            // When a view is added we need to remove the remove flag as this is view was previously removed
	            priorityUpdates[cid] ^= FLAG_REMOVE;
	        }
	        priorityUpdates[cid] |= type;
	        var viewUpdateFn = options.onViewUpdate;
	        if (typeof viewUpdateFn === 'function') { viewUpdateFn.call(this, view, type, priority, opt || {}, this); }
	    },

	    dumpViewUpdate: function(view) {
	        if (!view) { return 0; }
	        var updates = this._updates;
	        var cid = view.cid;
	        var priorityUpdates = updates.priorities[view.UPDATE_PRIORITY];
	        var flag = this.registerMountedView(view) | priorityUpdates[cid];
	        delete priorityUpdates[cid];
	        return flag;
	    },

	    dumpView: function(view, opt) {
	        var flag = this.dumpViewUpdate(view);
	        if (!flag) { return 0; }
	        return this.updateView(view, flag, opt);
	    },

	    updateView: function(view, flag, opt) {
	        if (!view) { return 0; }
	        var FLAG_REMOVE = view.FLAG_REMOVE;
	        var FLAG_INSERT = view.FLAG_INSERT;
	        var model = view.model;
	        if (view instanceof CellView) {
	            if (flag & FLAG_REMOVE) {
	                this.removeView(model);
	                return 0;
	            }
	            if (flag & FLAG_INSERT) {
	                this.insertView(view);
	                flag ^= FLAG_INSERT;
	            }
	        }
	        if (!flag) { return 0; }
	        return view.confirmUpdate(flag, opt || {});
	    },

	    requireView: function(model, opt) {
	        var view = this.findViewByModel(model);
	        if (!view) { return null; }
	        this.dumpView(view, opt);
	        return view;
	    },

	    registerUnmountedView: function(view) {
	        var cid = view.cid;
	        var updates = this._updates;
	        if (cid in updates.unmounted) { return 0; }
	        var flag = updates.unmounted[cid] |= view.FLAG_INSERT;
	        updates.unmountedCids.push(cid);
	        delete updates.mounted[cid];
	        return flag;
	    },

	    registerMountedView: function(view) {
	        var cid = view.cid;
	        var updates = this._updates;
	        if (cid in updates.mounted) { return 0; }
	        updates.mounted[cid] = true;
	        updates.mountedCids.push(cid);
	        var flag = updates.unmounted[cid] || 0;
	        delete updates.unmounted[cid];
	        return flag;
	    },

	    isViewMounted: function(view) {
	        if (!view) { return false; }
	        var cid = view.cid;
	        var updates = this._updates;
	        return (cid in updates.mounted);
	    },

	    dumpViews: function(opt) {
	        var passingOpt = defaults({}, opt, { viewport: null });
	        this.checkViewport(passingOpt);
	        this.updateViews(passingOpt);
	    },

	    // Synchronous views update
	    updateViews: function(opt) {
	        this.notifyBeforeRender(opt);
	        var batchStats;
	        var updateCount = 0;
	        var batchCount = 0;
	        var priority = MIN_PRIORITY;
	        do {
	            batchCount++;
	            batchStats = this.updateViewsBatch(opt);
	            updateCount += batchStats.updated;
	            priority = Math.min(batchStats.priority, priority);
	        } while (!batchStats.empty);
	        var stats = { updated: updateCount, batches: batchCount, priority: priority };
	        this.notifyAfterRender(stats, opt);
	        return stats;
	    },

	    hasScheduledUpdates: function() {
	        var priorities = this._updates.priorities;
	        var priorityIndexes = Object.keys(priorities); // convert priorities to a dense array
	        var i = priorityIndexes.length;
	        while (i > 0 && i--) {
	            // a faster way how to check if an object is empty
	            for (var _key in priorities[priorityIndexes[i]]) { return true; }
	        }
	        return false;
	    },

	    updateViewsAsync: function(opt, data) {
	        opt || (opt = {});
	        data || (data = { processed: 0, priority: MIN_PRIORITY });
	        var updates = this._updates;
	        var id = updates.id;
	        if (id) {
	            cancelFrame(id);
	            if (data.processed === 0 && this.hasScheduledUpdates()) {
	                this.notifyBeforeRender(opt);
	            }
	            var stats = this.updateViewsBatch(opt);
	            var passingOpt = defaults({}, opt, {
	                mountBatchSize: MOUNT_BATCH_SIZE - stats.mounted,
	                unmountBatchSize: MOUNT_BATCH_SIZE - stats.unmounted
	            });
	            var checkStats = this.checkViewport(passingOpt);
	            var unmountCount = checkStats.unmounted;
	            var mountCount = checkStats.mounted;
	            var processed = data.processed;
	            var total = updates.count;
	            if (stats.updated > 0) {
	                // Some updates have been just processed
	                processed += stats.updated + stats.unmounted;
	                stats.processed = processed;
	                data.priority = Math.min(stats.priority, data.priority);
	                if (stats.empty && mountCount === 0) {
	                    stats.unmounted += unmountCount;
	                    stats.mounted += mountCount;
	                    stats.priority = data.priority;
	                    this.notifyAfterRender(stats, opt);
	                    data.processed = 0;
	                    updates.count = 0;
	                } else {
	                    data.processed = processed;
	                }
	            }
	            // Progress callback
	            var progressFn = opt.progress;
	            if (total && typeof progressFn === 'function') {
	                progressFn.call(this, stats.empty, processed, total, stats, this);
	            }
	            // The current frame could have been canceled in a callback
	            if (updates.id !== id) { return; }
	        }
	        updates.id = nextFrame(this.updateViewsAsync, this, opt, data);
	    },

	    notifyBeforeRender: function(opt) {
	        if ( opt === void 0 ) opt = {};

	        var beforeFn = opt.beforeRender;
	        if (typeof beforeFn !== 'function') {
	            beforeFn = this.options.beforeRender;
	            if (typeof beforeFn !== 'function') { return; }
	        }
	        beforeFn.call(this, opt, this);
	    },

	    notifyAfterRender: function(stats, opt) {
	        if ( opt === void 0 ) opt = {};

	        var afterFn = opt.afterRender;
	        if (typeof afterFn !== 'function') {
	            afterFn = this.options.afterRender;
	        }
	        if (typeof afterFn === 'function') {
	            afterFn.call(this, stats, opt, this);
	        }
	        this.trigger('render:done', stats, opt);
	    },

	    updateViewsBatch: function(opt) {
	        opt || (opt = {});
	        var batchSize = opt.batchSize || UPDATE_BATCH_SIZE;
	        var updates = this._updates;
	        var updateCount = 0;
	        var postponeCount = 0;
	        var unmountCount = 0;
	        var mountCount = 0;
	        var maxPriority = MIN_PRIORITY;
	        var empty = true;
	        var options = this.options;
	        var priorities = updates.priorities;
	        var viewportFn = 'viewport' in opt ? opt.viewport : options.viewport;
	        if (typeof viewportFn !== 'function') { viewportFn = null; }
	        var postponeViewFn = options.onViewPostponed;
	        if (typeof postponeViewFn !== 'function') { postponeViewFn = null; }
	        var priorityIndexes = Object.keys(priorities); // convert priorities to a dense array
	        main: for (var i = 0, n = priorityIndexes.length; i < n; i++) {
	            var priority = priorityIndexes[i];
	            var priorityUpdates = priorities[priority];
	            for (var cid in priorityUpdates) {
	                if (updateCount >= batchSize) {
	                    empty = false;
	                    break main;
	                }
	                var view = views[cid];
	                if (!view) {
	                    // This should not occur
	                    delete priorityUpdates[cid];
	                    continue;
	                }
	                var currentFlag = priorityUpdates[cid];
	                if ((currentFlag & view.FLAG_REMOVE) === 0) {
	                    // We should never check a view for viewport if we are about to remove the view
	                    var isDetached = cid in updates.unmounted;
	                    if (view.DETACHABLE && viewportFn && !viewportFn.call(this, view, !isDetached, this)) {
	                        // Unmount View
	                        if (!isDetached) {
	                            this.registerUnmountedView(view);
	                            view.unmount();
	                        }
	                        updates.unmounted[cid] |= currentFlag;
	                        delete priorityUpdates[cid];
	                        unmountCount++;
	                        continue;
	                    }
	                    // Mount View
	                    if (isDetached) {
	                        currentFlag |= view.FLAG_INSERT;
	                        mountCount++;
	                    }
	                    currentFlag |= this.registerMountedView(view);
	                }
	                var leftoverFlag = this.updateView(view, currentFlag, opt);
	                if (leftoverFlag > 0) {
	                    // View update has not finished completely
	                    priorityUpdates[cid] = leftoverFlag;
	                    if (!postponeViewFn || !postponeViewFn.call(this, view, leftoverFlag, this) || priorityUpdates[cid]) {
	                        postponeCount++;
	                        empty = false;
	                        continue;
	                    }
	                }
	                if (maxPriority > priority) { maxPriority = priority; }
	                updateCount++;
	                delete priorityUpdates[cid];
	            }
	        }
	        return {
	            priority: maxPriority,
	            updated: updateCount,
	            postponed: postponeCount,
	            unmounted: unmountCount,
	            mounted: mountCount,
	            empty: empty
	        };
	    },

	    getUnmountedViews: function() {
	        var updates = this._updates;
	        var unmountedCids = Object.keys(updates.unmounted);
	        var n = unmountedCids.length;
	        var unmountedViews = new Array(n);
	        for (var i = 0; i < n; i++) {
	            unmountedViews[i] = views[unmountedCids[i]];
	        }
	        return unmountedViews;
	    },

	    getMountedViews: function() {
	        var updates = this._updates;
	        var mountedCids = Object.keys(updates.mounted);
	        var n = mountedCids.length;
	        var mountedViews = new Array(n);
	        for (var i = 0; i < n; i++) {
	            mountedViews[i] = views[mountedCids[i]];
	        }
	        return mountedViews;
	    },

	    checkUnmountedViews: function(viewportFn, opt) {
	        opt || (opt  = {});
	        var mountCount = 0;
	        if (typeof viewportFn !== 'function') { viewportFn = null; }
	        var batchSize = 'mountBatchSize' in opt ? opt.mountBatchSize : Infinity;
	        var updates = this._updates;
	        var unmountedCids = updates.unmountedCids;
	        var unmounted = updates.unmounted;
	        for (var i = 0, n = Math.min(unmountedCids.length, batchSize); i < n; i++) {
	            var cid = unmountedCids[i];
	            if (!(cid in unmounted)) { continue; }
	            var view = views[cid];
	            if (!view) { continue; }
	            if (view.DETACHABLE && viewportFn && !viewportFn.call(this, view, false, this)) {
	                // Push at the end of all unmounted ids, so this can be check later again
	                unmountedCids.push(cid);
	                continue;
	            }
	            mountCount++;
	            var flag = this.registerMountedView(view);
	            if (flag) { this.scheduleViewUpdate(view, flag, view.UPDATE_PRIORITY, { mounting: true }); }
	        }
	        // Get rid of views, that have been mounted
	        unmountedCids.splice(0, i);
	        return mountCount;
	    },

	    checkMountedViews: function(viewportFn, opt) {
	        opt || (opt = {});
	        var unmountCount = 0;
	        if (typeof viewportFn !== 'function') { return unmountCount; }
	        var batchSize = 'unmountBatchSize' in opt ? opt.unmountBatchSize : Infinity;
	        var updates = this._updates;
	        var mountedCids = updates.mountedCids;
	        var mounted = updates.mounted;
	        for (var i = 0, n = Math.min(mountedCids.length, batchSize); i < n; i++) {
	            var cid = mountedCids[i];
	            if (!(cid in mounted)) { continue; }
	            var view = views[cid];
	            if (!view) { continue; }
	            if (!view.DETACHABLE || viewportFn.call(this, view, true, this)) {
	                // Push at the end of all mounted ids, so this can be check later again
	                mountedCids.push(cid);
	                continue;
	            }
	            unmountCount++;
	            var flag = this.registerUnmountedView(view);
	            if (flag) { view.unmount(); }
	        }
	        // Get rid of views, that have been unmounted
	        mountedCids.splice(0, i);
	        return unmountCount;
	    },

	    checkViewport: function(opt) {
	        var passingOpt = defaults({}, opt, {
	            mountBatchSize: Infinity,
	            unmountBatchSize: Infinity
	        });
	        var viewportFn = 'viewport' in passingOpt ? passingOpt.viewport : this.options.viewport;
	        var unmountedCount = this.checkMountedViews(viewportFn, passingOpt);
	        if (unmountedCount > 0) {
	            // Do not check views, that have been just unmounted and pushed at the end of the cids array
	            var unmountedCids = this._updates.unmountedCids;
	            passingOpt.mountBatchSize = Math.min(unmountedCids.length - unmountedCount, passingOpt.mountBatchSize);
	        }
	        var mountedCount = this.checkUnmountedViews(viewportFn, passingOpt);
	        return {
	            mounted: mountedCount,
	            unmounted: unmountedCount
	        };
	    },

	    freeze: function(opt) {
	        opt || (opt = {});
	        var updates = this._updates;
	        var key = opt.key;
	        var isFrozen = this.options.frozen;
	        var freezeKey = updates.freezeKey;
	        if (key && key !== freezeKey)  {
	            // key passed, but the paper is already freezed with another key
	            if (isFrozen && freezeKey) { return; }
	            updates.freezeKey = key;
	            updates.keyFrozen = isFrozen;
	        }
	        this.options.frozen = true;
	        var id = updates.id;
	        updates.id = null;
	        if (this.isAsync() && id) { cancelFrame(id); }
	    },

	    unfreeze: function(opt) {
	        opt || (opt = {});
	        var updates = this._updates;
	        var key = opt.key;
	        var freezeKey = updates.freezeKey;
	        // key passed, but the paper is already freezed with another key
	        if (key && freezeKey && key !== freezeKey) { return; }
	        updates.freezeKey = null;
	        // key passed, but the paper is already freezed
	        if (key && key === freezeKey && updates.keyFrozen) { return; }
	        if (this.isAsync()) {
	            this.freeze();
	            this.updateViewsAsync(opt);
	        } else {
	            this.updateViews(opt);
	        }
	        this.options.frozen = updates.keyFrozen = false;
	        if (updates.sort) {
	            this.sortViews();
	            updates.sort = false;
	        }
	    },

	    isAsync: function() {
	        return !!this.options.async;
	    },

	    isFrozen: function() {
	        return !!this.options.frozen;
	    },

	    isExactSorting: function() {
	        return this.options.sorting === sortingTypes.EXACT;
	    },

	    onRemove: function() {

	        this.freeze();
	        //clean up all DOM elements/views to prevent memory leaks
	        this.removeViews();
	    },

	    getComputedSize: function() {

	        var options = this.options;
	        var w = options.width;
	        var h = options.height;
	        if (!isNumber(w)) { w = this.el.clientWidth; }
	        if (!isNumber(h)) { h = this.el.clientHeight; }
	        return { width: w, height: h };
	    },

	    setDimensions: function(width, height) {

	        var options = this.options;
	        var w = (width === undefined) ? options.width : width;
	        var h = (height === undefined) ? options.height : height;
	        this.options.width = w;
	        this.options.height = h;
	        if (isNumber(w)) { w = Math.round(w); }
	        if (isNumber(h)) { h = Math.round(h); }
	        this.$el.css({
	            width: (w === null) ? '' : w,
	            height: (h === null) ? '' : h
	        });
	        var computedSize = this.getComputedSize();
	        this.trigger('resize', computedSize.width, computedSize.height);
	    },

	    setOrigin: function(ox, oy) {

	        return this.translate(ox || 0, oy || 0, { absolute: true });
	    },

	    // Expand/shrink the paper to fit the content. Snap the width/height to the grid
	    // defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper.
	    // When options { fitNegative: true } it also translates the viewport in order to make all
	    // the content visible.
	    fitToContent: function(gridWidth, gridHeight, padding, opt) { // alternatively function(opt)

	        if (isObject$1(gridWidth)) {
	            // first parameter is an option object
	            opt = gridWidth;
	            gridWidth = opt.gridWidth || 1;
	            gridHeight = opt.gridHeight || 1;
	            padding = opt.padding || 0;

	        } else {

	            opt || (opt = {});
	            gridWidth = gridWidth || 1;
	            gridHeight = gridHeight || 1;
	            padding = padding || 0;
	        }

	        // Calculate the paper size to accommodate all the graph's elements.

	        var minWidth = Math.max(opt.minWidth || 0, gridWidth);
	        var minHeight = Math.max(opt.minHeight || 0, gridHeight);
	        var maxWidth = opt.maxWidth || Number.MAX_VALUE;
	        var maxHeight = opt.maxHeight || Number.MAX_VALUE;
	        var newOrigin = opt.allowNewOrigin;

	        padding = normalizeSides(padding);

	        var area = ('contentArea' in opt) ? new Rect(opt.contentArea) : this.getContentArea(opt);

	        var currentScale = this.scale();
	        var currentTranslate = this.translate();
	        var sx = currentScale.sx;
	        var sy = currentScale.sy;

	        area.x *= sx;
	        area.y *= sy;
	        area.width *= sx;
	        area.height *= sy;

	        var calcWidth = Math.ceil((area.width + area.x) / gridWidth);
	        var calcHeight = Math.ceil((area.height + area.y) / gridHeight);
	        if (!opt.allowNegativeBottomRight) {
	            calcWidth = Math.max(calcWidth, 1);
	            calcHeight = Math.max(calcHeight, 1);
	        }
	        calcWidth *= gridWidth;
	        calcHeight *= gridHeight;

	        var tx = 0;
	        var ty = 0;

	        if ((newOrigin === 'negative' && area.x < 0) || (newOrigin === 'positive' && area.x >= 0) || newOrigin === 'any') {
	            tx = Math.ceil(-area.x / gridWidth) * gridWidth;
	            tx += padding.left;
	            calcWidth += tx;
	        }

	        if ((newOrigin === 'negative' && area.y < 0) || (newOrigin === 'positive' && area.y >= 0) || newOrigin === 'any') {
	            ty = Math.ceil(-area.y / gridHeight) * gridHeight;
	            ty += padding.top;
	            calcHeight += ty;
	        }

	        calcWidth += padding.right;
	        calcHeight += padding.bottom;

	        // Make sure the resulting width and height are greater than minimum.
	        calcWidth = Math.max(calcWidth, minWidth);
	        calcHeight = Math.max(calcHeight, minHeight);

	        // Make sure the resulting width and height are lesser than maximum.
	        calcWidth = Math.min(calcWidth, maxWidth);
	        calcHeight = Math.min(calcHeight, maxHeight);

	        var computedSize = this.getComputedSize();
	        var dimensionChange = calcWidth != computedSize.width || calcHeight != computedSize.height;
	        var originChange = tx != currentTranslate.tx || ty != currentTranslate.ty;

	        // Change the dimensions only if there is a size discrepancy or an origin change
	        if (originChange) {
	            this.translate(tx, ty);
	        }
	        if (dimensionChange) {
	            this.setDimensions(calcWidth, calcHeight);
	        }

	        return new Rect(-tx / sx, -ty / sy, calcWidth / sx, calcHeight / sy);
	    },

	    scaleContentToFit: function(opt) {

	        opt || (opt = {});

	        var contentBBox, contentLocalOrigin;
	        if ('contentArea' in opt) {
	            var contentArea = opt.contentArea;
	            contentBBox = this.localToPaperRect(contentArea);
	            contentLocalOrigin = new Point(contentArea);
	        } else {
	            contentBBox = this.getContentBBox(opt);
	            contentLocalOrigin = this.paperToLocalPoint(contentBBox);
	        }

	        if (!contentBBox.width || !contentBBox.height) { return; }

	        defaults(opt, {
	            padding: 0,
	            preserveAspectRatio: true,
	            scaleGrid: null,
	            minScale: 0,
	            maxScale: Number.MAX_VALUE
	            //minScaleX
	            //minScaleY
	            //maxScaleX
	            //maxScaleY
	            //fittingBBox
	        });

	        var padding = normalizeSides(opt.padding);

	        var minScaleX = opt.minScaleX || opt.minScale;
	        var maxScaleX = opt.maxScaleX || opt.maxScale;
	        var minScaleY = opt.minScaleY || opt.minScale;
	        var maxScaleY = opt.maxScaleY || opt.maxScale;

	        var fittingBBox;
	        if (opt.fittingBBox) {
	            fittingBBox = opt.fittingBBox;
	        } else {
	            var currentTranslate = this.translate();
	            var computedSize = this.getComputedSize();
	            fittingBBox = {
	                x: currentTranslate.tx,
	                y: currentTranslate.ty,
	                width: computedSize.width,
	                height: computedSize.height
	            };
	        }

	        fittingBBox = new Rect(fittingBBox).moveAndExpand({
	            x: padding.left,
	            y: padding.top,
	            width: -padding.left - padding.right,
	            height: -padding.top - padding.bottom
	        });

	        var currentScale = this.scale();

	        var newSx = fittingBBox.width / contentBBox.width * currentScale.sx;
	        var newSy = fittingBBox.height / contentBBox.height * currentScale.sy;

	        if (opt.preserveAspectRatio) {
	            newSx = newSy = Math.min(newSx, newSy);
	        }

	        // snap scale to a grid
	        if (opt.scaleGrid) {

	            var gridSize = opt.scaleGrid;

	            newSx = gridSize * Math.floor(newSx / gridSize);
	            newSy = gridSize * Math.floor(newSy / gridSize);
	        }

	        // scale min/max boundaries
	        newSx = Math.min(maxScaleX, Math.max(minScaleX, newSx));
	        newSy = Math.min(maxScaleY, Math.max(minScaleY, newSy));

	        var origin = this.options.origin;
	        var newOx = fittingBBox.x - contentLocalOrigin.x * newSx - origin.x;
	        var newOy = fittingBBox.y - contentLocalOrigin.y * newSy - origin.y;

	        this.scale(newSx, newSy);
	        this.translate(newOx, newOy);
	    },

	    // Return the dimensions of the content area in local units (without transformations).
	    getContentArea: function(opt) {

	        if (opt && opt.useModelGeometry) {
	            return this.model.getBBox() || new Rect();
	        }

	        return V(this.cells).getBBox();
	    },

	    // Return the dimensions of the content bbox in the paper units (as it appears on screen).
	    getContentBBox: function(opt) {

	        return this.localToPaperRect(this.getContentArea(opt));
	    },

	    // Returns a geometry rectangle representing the entire
	    // paper area (coordinates from the left paper border to the right one
	    // and the top border to the bottom one).
	    getArea: function() {

	        return this.paperToLocalRect(this.getComputedSize());
	    },

	    getRestrictedArea: function() {
	        var args = [], len = arguments.length;
	        while ( len-- ) args[ len ] = arguments[ len ];


	        var ref = this.options;
	        var restrictTranslate = ref.restrictTranslate;

	        var restrictedArea;
	        if (isFunction(restrictTranslate)) {
	            // A method returning a bounding box
	            restrictedArea = restrictTranslate.apply(this, args);
	        } else if (restrictTranslate === true) {
	            // The paper area
	            restrictedArea = this.getArea();
	        } else if (!restrictTranslate) {
	            // falsy value
	            restrictedArea = null;
	        } else {
	            // any other value
	            restrictedArea = new Rect(restrictTranslate);
	        }

	        return restrictedArea;
	    },

	    createViewForModel: function(cell) {

	        // A class taken from the paper options.
	        var optionalViewClass;

	        // A default basic class (either dia.ElementView or dia.LinkView)
	        var defaultViewClass;

	        // A special class defined for this model in the corresponding namespace.
	        // e.g. joint.shapes.basic.Rect searches for joint.shapes.basic.RectView
	        var namespace = this.options.cellViewNamespace;
	        var type = cell.get('type') + 'View';
	        var namespaceViewClass = getByPath(namespace, type, '.');

	        if (cell.isLink()) {
	            optionalViewClass = this.options.linkView;
	            defaultViewClass = LinkView;
	        } else {
	            optionalViewClass = this.options.elementView;
	            defaultViewClass = ElementView;
	        }

	        // a) the paper options view is a class (deprecated)
	        //  1. search the namespace for a view
	        //  2. if no view was found, use view from the paper options
	        // b) the paper options view is a function
	        //  1. call the function from the paper options
	        //  2. if no view was return, search the namespace for a view
	        //  3. if no view was found, use the default
	        var ViewClass = (optionalViewClass.prototype instanceof Backbone.View)
	            ? namespaceViewClass || optionalViewClass
	            : optionalViewClass.call(this, cell) || namespaceViewClass || defaultViewClass;

	        return new ViewClass({
	            model: cell,
	            interactive: this.options.interactive
	        });
	    },

	    removeView: function(cell) {

	        var id = cell.id;
	        var ref = this;
	        var _views = ref._views;
	        var _updates = ref._updates;
	        var view = _views[id];
	        if (view) {
	            var cid = view.cid;
	            var mounted = _updates.mounted;
	            var unmounted = _updates.unmounted;
	            view.remove();
	            delete _views[id];
	            delete mounted[cid];
	            delete unmounted[cid];
	        }
	        return view;
	    },

	    renderView: function(cell, opt) {

	        var id = cell.id;
	        var views = this._views;
	        var view, flag;
	        if (id in views) {
	            view = views[id];
	            flag = view.FLAG_INSERT;
	        } else {
	            view = views[cell.id] = this.createViewForModel(cell);
	            view.paper = this;
	            flag = this.registerUnmountedView(view) | view.getFlag(result(view, 'initFlag'));
	        }
	        this.requestViewUpdate(view, flag, view.UPDATE_PRIORITY, opt);
	        return view;
	    },

	    onImageDragStart: function() {
	        // This is the only way to prevent image dragging in Firefox that works.
	        // Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help.

	        return false;
	    },

	    resetViews: function(cells, opt) {
	        opt || (opt = {});
	        cells || (cells = []);
	        this._resetUpdates();
	        // clearing views removes any event listeners
	        this.removeViews();
	        this.freeze({ key: 'reset' });
	        for (var i = 0, n = cells.length; i < n; i++) {
	            this.renderView(cells[i], opt);
	        }
	        this.unfreeze({ key: 'reset' });
	        this.sortViews();
	    },

	    removeViews: function() {

	        invoke(this._views, 'remove');

	        this._views = {};
	    },

	    sortViews: function() {

	        if (!this.isExactSorting()) {
	            // noop
	            return;
	        }
	        if (this.isFrozen()) {
	            // sort views once unfrozen
	            this._updates.sort = true;
	            return;
	        }
	        this.sortViewsExact();
	    },

	    sortViewsExact: function() {

	        // Run insertion sort algorithm in order to efficiently sort DOM elements according to their
	        // associated model `z` attribute.

	        var $cells = $(this.cells).children('[model-id]');
	        var cells = this.model.get('cells');

	        sortElements($cells, function(a, b) {
	            var cellA = cells.get(a.getAttribute('model-id'));
	            var cellB = cells.get(b.getAttribute('model-id'));
	            var zA = cellA.attributes.z || 0;
	            var zB = cellB.attributes.z || 0;
	            return (zA === zB) ? 0 : (zA < zB) ? -1 : 1;
	        });
	    },


	    insertView: function(view) {
	        var layer = this.cells;
	        switch (this.options.sorting) {
	            case sortingTypes.APPROX:
	                var z = view.model.get('z');
	                var pivot = this.addZPivot(z);
	                layer.insertBefore(view.el, pivot);
	                break;
	            case sortingTypes.EXACT:
	            default:
	                layer.appendChild(view.el);
	                break;
	        }
	    },

	    addZPivot: function(z) {
	        z = +z;
	        z || (z = 0);
	        var pivots = this._zPivots;
	        var pivot = pivots[z];
	        if (pivot) { return pivot; }
	        pivot = pivots[z] = document.createComment('z-index:' + (z + 1));
	        var neighborZ = -Infinity;
	        for (var currentZ in pivots) {
	            currentZ = +currentZ;
	            if (currentZ < z && currentZ > neighborZ) {
	                neighborZ = currentZ;
	                if (neighborZ === z - 1) { continue; }
	            }
	        }
	        var layer = this.cells;
	        if (neighborZ !== -Infinity) {
	            var neighborPivot = pivots[neighborZ];
	            // Insert After
	            layer.insertBefore(pivot, neighborPivot.nextSibling);
	        } else {
	            // First Child
	            layer.insertBefore(pivot, layer.firstChild);
	        }
	        return pivot;
	    },

	    removeZPivots: function() {
	        var ref = this;
	        var pivots = ref._zPivots;
	        var viewport = ref.viewport;
	        for (var z in pivots) { viewport.removeChild(pivots[z]); }
	        this._zPivots = {};
	    },

	    scale: function(sx, sy, ox, oy) {

	        // getter
	        if (sx === undefined) {
	            return V.matrixToScale(this.matrix());
	        }

	        // setter
	        if (sy === undefined) {
	            sy = sx;
	        }
	        if (ox === undefined) {
	            ox = 0;
	            oy = 0;
	        }

	        var translate = this.translate();

	        if (ox || oy || translate.tx || translate.ty) {
	            var newTx = translate.tx - ox * (sx - 1);
	            var newTy = translate.ty - oy * (sy - 1);
	            this.translate(newTx, newTy);
	        }

	        sx = Math.max(sx || 0, this.MIN_SCALE);
	        sy = Math.max(sy || 0, this.MIN_SCALE);

	        var ctm = this.matrix();
	        ctm.a = sx;
	        ctm.d = sy;

	        this.matrix(ctm);

	        this.trigger('scale', sx, sy, ox, oy);

	        return this;
	    },

	    // Experimental - do not use in production.
	    rotate: function(angle, cx, cy) {

	        // getter
	        if (angle === undefined) {
	            return V.matrixToRotate(this.matrix());
	        }

	        // setter

	        // If the origin is not set explicitely, rotate around the center. Note that
	        // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us
	        // the real bounding box (`bbox()`) including transformations).
	        if (cx === undefined) {
	            var bbox = this.cells.getBBox();
	            cx = bbox.width / 2;
	            cy = bbox.height / 2;
	        }

	        var ctm = this.matrix().translate(cx, cy).rotate(angle).translate(-cx, -cy);
	        this.matrix(ctm);

	        return this;
	    },

	    translate: function(tx, ty) {

	        // getter
	        if (tx === undefined) {
	            return V.matrixToTranslate(this.matrix());
	        }

	        // setter

	        var ctm = this.matrix();
	        ctm.e = tx || 0;
	        ctm.f = ty || 0;

	        this.matrix(ctm);

	        var newTranslate = this.translate();
	        var origin = this.options.origin;
	        origin.x = newTranslate.tx;
	        origin.y = newTranslate.ty;

	        this.trigger('translate', newTranslate.tx, newTranslate.ty);

	        if (this.options.drawGrid) {
	            this.drawGrid();
	        }

	        return this;
	    },

	    // Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also
	    // be a selector or a jQuery object.
	    findView: function($el) {

	        var el = isString($el)
	            ? this.cells.querySelector($el)
	            : $el instanceof $ ? $el[0] : $el;

	        var id = this.findAttribute('model-id', el);
	        if (id) { return this._views[id]; }

	        return undefined;
	    },

	    // Find a view for a model `cell`. `cell` can also be a string or number representing a model `id`.
	    findViewByModel: function(cell) {

	        var id = (isString(cell) || isNumber(cell)) ? cell : (cell && cell.id);

	        return this._views[id];
	    },

	    // Find all views at given point
	    findViewsFromPoint: function(p) {

	        p = new Point(p);

	        var views = this.model.getElements().map(this.findViewByModel, this);

	        return views.filter(function(view) {
	            return view && view.vel.getBBox({ target: this.cells }).containsPoint(p);
	        }, this);
	    },

	    // Find all views in given area
	    findViewsInArea: function(rect, opt) {

	        opt = defaults(opt || {}, { strict: false });
	        rect = new Rect(rect);

	        var views = this.model.getElements().map(this.findViewByModel, this);
	        var method = opt.strict ? 'containsRect' : 'intersect';

	        return views.filter(function(view) {
	            return view && rect[method](view.vel.getBBox({ target: this.cells }));
	        }, this);
	    },

	    removeTools: function() {
	        this.dispatchToolsEvent('remove');
	        return this;
	    },

	    hideTools: function() {
	        this.dispatchToolsEvent('hide');
	        return this;
	    },

	    showTools: function() {
	        this.dispatchToolsEvent('show');
	        return this;
	    },

	    dispatchToolsEvent: function(event) {
	        var ref;

	        var args = [], len = arguments.length - 1;
	        while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];
	        if (typeof event !== 'string') { return; }
	        (ref = this).trigger.apply(ref, [ 'tools:event', event ].concat( args ));
	    },


	    getModelById: function(id) {

	        return this.model.getCell(id);
	    },

	    snapToGrid: function(x, y) {

	        // Convert global coordinates to the local ones of the `viewport`. Otherwise,
	        // improper transformation would be applied when the viewport gets transformed (scaled/rotated).
	        return this.clientToLocalPoint(x, y).snapToGrid(this.options.gridSize);
	    },

	    localToPaperPoint: function(x, y) {
	        // allow `x` to be a point and `y` undefined
	        var localPoint = new Point(x, y);
	        var paperPoint = V.transformPoint(localPoint, this.matrix());
	        return paperPoint;
	    },

	    localToPaperRect: function(x, y, width, height) {
	        // allow `x` to be a rectangle and rest arguments undefined
	        var localRect = new Rect(x, y, width, height);
	        var paperRect = V.transformRect(localRect, this.matrix());
	        return paperRect;
	    },

	    paperToLocalPoint: function(x, y) {
	        // allow `x` to be a point and `y` undefined
	        var paperPoint = new Point(x, y);
	        var localPoint = V.transformPoint(paperPoint, this.matrix().inverse());
	        return localPoint;
	    },

	    paperToLocalRect: function(x, y, width, height) {
	        // allow `x` to be a rectangle and rest arguments undefined
	        var paperRect = new Rect(x, y, width, height);
	        var localRect = V.transformRect(paperRect, this.matrix().inverse());
	        return localRect;
	    },

	    localToClientPoint: function(x, y) {
	        // allow `x` to be a point and `y` undefined
	        var localPoint = new Point(x, y);
	        var clientPoint = V.transformPoint(localPoint, this.clientMatrix());
	        return clientPoint;
	    },

	    localToClientRect: function(x, y, width, height) {
	        // allow `x` to be a point and `y` undefined
	        var localRect = new Rect(x, y, width, height);
	        var clientRect = V.transformRect(localRect, this.clientMatrix());
	        return clientRect;
	    },

	    // Transform client coordinates to the paper local coordinates.
	    // Useful when you have a mouse event object and you'd like to get coordinates
	    // inside the paper that correspond to `evt.clientX` and `evt.clientY` point.
	    // Example: var localPoint = paper.clientToLocalPoint({ x: evt.clientX, y: evt.clientY });
	    clientToLocalPoint: function(x, y) {
	        // allow `x` to be a point and `y` undefined
	        var clientPoint = new Point(x, y);
	        var localPoint = V.transformPoint(clientPoint, this.clientMatrix().inverse());
	        return localPoint;
	    },

	    clientToLocalRect: function(x, y, width, height) {
	        // allow `x` to be a point and `y` undefined
	        var clientRect = new Rect(x, y, width, height);
	        var localRect = V.transformRect(clientRect, this.clientMatrix().inverse());
	        return localRect;
	    },

	    localToPagePoint: function(x, y) {

	        return this.localToPaperPoint(x, y).offset(this.pageOffset());
	    },

	    localToPageRect: function(x, y, width, height) {

	        return this.localToPaperRect(x, y, width, height).offset(this.pageOffset());
	    },

	    pageToLocalPoint: function(x, y) {

	        var pagePoint = new Point(x, y);
	        var paperPoint = pagePoint.difference(this.pageOffset());
	        return this.paperToLocalPoint(paperPoint);
	    },

	    pageToLocalRect: function(x, y, width, height) {

	        var pageOffset = this.pageOffset();
	        var paperRect = new Rect(x, y, width, height);
	        paperRect.x -= pageOffset.x;
	        paperRect.y -= pageOffset.y;
	        return this.paperToLocalRect(paperRect);
	    },

	    clientOffset: function() {

	        var clientRect = this.svg.getBoundingClientRect();
	        return new Point(clientRect.left, clientRect.top);
	    },

	    pageOffset: function() {

	        return this.clientOffset().offset(window.scrollX, window.scrollY);
	    },

	    linkAllowed: function(linkView) {

	        if (!(linkView instanceof LinkView)) {
	            throw new Error('Must provide a linkView.');
	        }

	        var link = linkView.model;
	        var paperOptions = this.options;
	        var graph = this.model;
	        var ns = graph.constructor.validations;

	        if (!paperOptions.multiLinks) {
	            if (!ns.multiLinks.call(this, graph, link)) { return false; }
	        }

	        if (!paperOptions.linkPinning) {
	            // Link pinning is not allowed and the link is not connected to the target.
	            if (!ns.linkPinning.call(this, graph, link)) { return false; }
	        }

	        if (typeof paperOptions.allowLink === 'function') {
	            if (!paperOptions.allowLink.call(this, linkView, this)) { return false; }
	        }

	        return true;
	    },

	    getDefaultLink: function(cellView, magnet) {

	        return isFunction(this.options.defaultLink)
	        // default link is a function producing link model
	            ? this.options.defaultLink.call(this, cellView, magnet)
	        // default link is the Backbone model
	            : this.options.defaultLink.clone();
	    },

	    // Cell highlighting.
	    // ------------------

	    resolveHighlighter: function(opt) {
	        if ( opt === void 0 ) opt = {};


	        var highlighterDef = opt.highlighter;
	        var type = opt.type;
	        var ref = this.options;
	        var highlighting = ref.highlighting;
	        var highlighterNamespace = ref.highlighterNamespace;

	        /*
	            Expecting opt.highlighter to have the following structure:
	            {
	                name: 'highlighter-name',
	                options: {
	                    some: 'value'
	                }
	            }
	        */
	        if (highlighterDef === undefined) {

	            // Is highlighting disabled?
	            if (!highlighting) { return false; }
	            // check for built-in types
	            if (type) {
	                highlighterDef = highlighting[type];
	                // Is a specific type highlight disabled?
	                if (highlighterDef === false) { return false; }
	            }
	            if (!highlighterDef) {
	                // Type not defined use default highlight
	                highlighterDef = highlighting['default'];
	            }
	        }

	        // Do nothing if opt.highlighter is falsy.
	        // This allows the case to not highlight cell(s) in certain cases.
	        // For example, if you want to NOT highlight when embedding elements
	        // or use a custom highlighter.
	        if (!highlighterDef) { return false; }

	        // Allow specifying a highlighter by name.
	        if (isString(highlighterDef)) {
	            highlighterDef = {
	                name: highlighterDef
	            };
	        }

	        var name = highlighterDef.name;
	        var highlighter = highlighterNamespace[name];

	        // Highlighter validation
	        if (!highlighter) {
	            throw new Error('Unknown highlighter ("' + name + '")');
	        }
	        if (typeof highlighter.highlight !== 'function') {
	            throw new Error('Highlighter ("' + name + '") is missing required highlight() method');
	        }
	        if (typeof highlighter.unhighlight !== 'function') {
	            throw new Error('Highlighter ("' + name + '") is missing required unhighlight() method');
	        }

	        return {
	            highlighter: highlighter,
	            options: highlighterDef.options || {},
	            name: name
	        };
	    },

	    onCellHighlight: function(cellView, magnetEl, opt) {
	        var highlighterDescriptor = this.resolveHighlighter(opt);
	        if (!highlighterDescriptor) { return; }
	        var highlighter = highlighterDescriptor.highlighter;
	        var options = highlighterDescriptor.options;
	        highlighter.highlight(cellView, magnetEl, options);
	    },

	    onCellUnhighlight: function(cellView, magnetEl, opt) {
	        var highlighterDescriptor = this.resolveHighlighter(opt);
	        if (!highlighterDescriptor) { return; }
	        var highlighter = highlighterDescriptor.highlighter;
	        var options = highlighterDescriptor.options;
	        highlighter.unhighlight(cellView, magnetEl, options);
	    },

	    // Interaction.
	    // ------------

	    pointerdblclick: function(evt) {

	        evt.preventDefault();

	        // magnetpointerdblclick can stop propagation

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }

	        var localPoint = this.snapToGrid(evt.clientX, evt.clientY);

	        if (view) {
	            view.pointerdblclick(evt, localPoint.x, localPoint.y);

	        } else {
	            this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y);
	        }
	    },

	    pointerclick: function(evt) {

	        // magnetpointerclick can stop propagation

	        var data = this.eventData(evt);
	        // Trigger event only if mouse has not moved.
	        if (data.mousemoved <= this.options.clickThreshold) {

	            evt = normalizeEvent(evt);

	            var view = this.findView(evt.target);
	            if (this.guard(evt, view)) { return; }

	            var localPoint = this.snapToGrid(evt.clientX, evt.clientY);

	            if (view) {
	                view.pointerclick(evt, localPoint.x, localPoint.y);

	            } else {
	                this.trigger('blank:pointerclick', evt, localPoint.x, localPoint.y);
	            }
	        }
	    },

	    contextmenu: function(evt) {

	        if (this.options.preventContextMenu) { evt.preventDefault(); }

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }

	        var localPoint = this.snapToGrid(evt.clientX, evt.clientY);

	        if (view) {
	            view.contextmenu(evt, localPoint.x, localPoint.y);

	        } else {
	            this.trigger('blank:contextmenu', evt, localPoint.x, localPoint.y);
	        }
	    },

	    pointerdown: function(evt) {

	        // onmagnet stops propagation when `addLinkFromMagnet` is allowed
	        // onevent can stop propagation

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }

	        var localPoint = this.snapToGrid(evt.clientX, evt.clientY);

	        if (view) {

	            evt.preventDefault();
	            view.pointerdown(evt, localPoint.x, localPoint.y);

	        } else {

	            if (this.options.preventDefaultBlankAction) { evt.preventDefault(); }

	            this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y);
	        }

	        this.delegateDragEvents(view, evt.data);
	    },

	    pointermove: function(evt) {

	        // mouse moved counter
	        var data = this.eventData(evt);
	        data.mousemoved || (data.mousemoved = 0);
	        var mousemoved = ++data.mousemoved;

	        if (mousemoved <= this.options.moveThreshold) { return; }

	        evt = normalizeEvent(evt);

	        var localPoint = this.snapToGrid(evt.clientX, evt.clientY);

	        var view = data.sourceView;
	        if (view) {
	            view.pointermove(evt, localPoint.x, localPoint.y);
	        } else {
	            this.trigger('blank:pointermove', evt, localPoint.x, localPoint.y);
	        }

	        this.eventData(evt, data);
	    },

	    pointerup: function(evt) {

	        this.undelegateDocumentEvents();

	        var normalizedEvt = normalizeEvent(evt);

	        var localPoint = this.snapToGrid(normalizedEvt.clientX, normalizedEvt.clientY);

	        var view = this.eventData(evt).sourceView;
	        if (view) {
	            view.pointerup(normalizedEvt, localPoint.x, localPoint.y);
	        } else {
	            this.trigger('blank:pointerup', normalizedEvt, localPoint.x, localPoint.y);
	        }

	        if (!normalizedEvt.isPropagationStopped()) {
	            this.pointerclick($.Event(evt, { type: 'click', data: evt.data }));
	        }

	        evt.stopImmediatePropagation();
	        this.delegateEvents();
	    },

	    mouseover: function(evt) {

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }

	        if (view) {
	            view.mouseover(evt);

	        } else {
	            if (this.el === evt.target) { return; } // prevent border of paper from triggering this
	            this.trigger('blank:mouseover', evt);
	        }
	    },

	    mouseout: function(evt) {

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }

	        if (view) {
	            view.mouseout(evt);

	        } else {
	            if (this.el === evt.target) { return; } // prevent border of paper from triggering this
	            this.trigger('blank:mouseout', evt);
	        }
	    },

	    mouseenter: function(evt) {

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }
	        var relatedView = this.findView(evt.relatedTarget);
	        if (view) {
	            // mouse moved from tool over view?
	            if (relatedView === view) { return; }
	            view.mouseenter(evt);
	        } else {
	            if (relatedView) { return; }
	            // `paper` (more descriptive), not `blank`
	            this.trigger('paper:mouseenter', evt);
	        }
	    },

	    mouseleave: function(evt) {

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }
	        var relatedView = this.findView(evt.relatedTarget);
	        if (view) {
	            // mouse moved from view over tool?
	            if (relatedView === view) { return; }
	            view.mouseleave(evt);
	        } else {
	            if (relatedView) { return; }
	            // `paper` (more descriptive), not `blank`
	            this.trigger('paper:mouseleave', evt);
	        }
	    },

	    mousewheel: function(evt) {

	        evt = normalizeEvent(evt);

	        var view = this.findView(evt.target);
	        if (this.guard(evt, view)) { return; }

	        var originalEvent = evt.originalEvent;
	        var localPoint = this.snapToGrid(originalEvent.clientX, originalEvent.clientY);
	        var delta = Math.max(-1, Math.min(1, (originalEvent.wheelDelta || -originalEvent.detail)));

	        if (view) {
	            view.mousewheel(evt, localPoint.x, localPoint.y, delta);

	        } else {
	            this.trigger('blank:mousewheel', evt, localPoint.x, localPoint.y, delta);
	        }
	    },

	    onevent: function(evt) {

	        var eventNode = evt.currentTarget;
	        var eventName = eventNode.getAttribute('event');
	        if (eventName) {
	            var view = this.findView(eventNode);
	            if (view) {

	                evt = normalizeEvent(evt);
	                if (this.guard(evt, view)) { return; }

	                var localPoint = this.snapToGrid(evt.clientX, evt.clientY);
	                view.onevent(evt, eventName, localPoint.x, localPoint.y);
	            }
	        }
	    },

	    magnetEvent: function(evt, handler) {

	        var magnetNode = evt.currentTarget;
	        var magnetValue = magnetNode.getAttribute('magnet');
	        if (magnetValue) {
	            var view = this.findView(magnetNode);
	            if (view) {
	                evt = normalizeEvent(evt);
	                if (this.guard(evt, view)) { return; }
	                var localPoint = this.snapToGrid(evt.clientX, evt.clientY);
	                handler.call(this, view, evt, magnetNode, localPoint.x, localPoint.y);
	            }
	        }
	    },

	    onmagnet: function(evt) {

	        this.magnetEvent(evt, function(view, evt, _, x, y) {
	            view.onmagnet(evt, x, y);
	        });
	    },


	    magnetpointerdblclick: function(evt) {

	        this.magnetEvent(evt, function(view, evt, magnet, x, y) {
	            view.magnetpointerdblclick(evt, magnet, x, y);
	        });
	    },

	    magnetcontextmenu: function(evt) {

	        if (this.options.preventContextMenu) { evt.preventDefault(); }
	        this.magnetEvent(evt, function(view, evt, magnet, x, y) {
	            view.magnetcontextmenu(evt, magnet, x, y);
	        });
	    },

	    onlabel: function(evt) {

	        var labelNode = evt.currentTarget;
	        var view = this.findView(labelNode);
	        if (view) {

	            evt = normalizeEvent(evt);
	            if (this.guard(evt, view)) { return; }

	            var localPoint = this.snapToGrid(evt.clientX, evt.clientY);
	            view.onlabel(evt, localPoint.x, localPoint.y);
	        }
	    },

	    getPointerArgs: function getPointerArgs(evt) {
	        var normalizedEvt = normalizeEvent(evt);
	        var ref = this.snapToGrid(normalizedEvt.clientX, normalizedEvt.clientY);
	        var x = ref.x;
	        var y = ref.y;
	        return [normalizedEvt, x, y];
	    },

	    delegateDragEvents: function(view, data) {

	        data || (data = {});
	        this.eventData({ data: data }, { sourceView: view || null, mousemoved: 0 });
	        this.delegateDocumentEvents(null, data);
	        this.undelegateEvents();
	    },

	    // Guard the specified event. If the event is not interesting, guard returns `true`.
	    // Otherwise, it returns `false`.
	    guard: function(evt, view) {

	        if (evt.type === 'mousedown' && evt.button === 2) {
	            // handled as `contextmenu` type
	            return true;
	        }

	        if (this.options.guard && this.options.guard(evt, view)) {
	            return true;
	        }

	        if (evt.data && evt.data.guarded !== undefined) {
	            return evt.data.guarded;
	        }

	        if (view && view.model && (view.model instanceof Cell)) {
	            return false;
	        }

	        if (this.svg === evt.target || this.el === evt.target || $.contains(this.svg, evt.target)) {
	            return false;
	        }

	        return true;    // Event guarded. Paper should not react on it in any way.
	    },

	    setGridSize: function(gridSize) {

	        this.options.gridSize = gridSize;

	        if (this.options.drawGrid) {
	            this.drawGrid();
	        }

	        return this;
	    },

	    clearGrid: function() {

	        if (this.$grid) {
	            this.$grid.css('backgroundImage', 'none');
	        }
	        return this;
	    },

	    _getGridRefs: function() {

	        if (!this._gridCache) {

	            this._gridCache = {
	                root: V('svg', { width: '100%', height: '100%' }, V('defs')),
	                patterns: {},
	                add: function(id, vel) {
	                    V(this.root.node.childNodes[0]).append(vel);
	                    this.patterns[id] = vel;
	                    this.root.append(V('rect', { width: '100%', height: '100%', fill: 'url(#' + id + ')' }));
	                },
	                get: function(id) {
	                    return this.patterns[id];
	                },
	                exist: function(id) {
	                    return this.patterns[id] !== undefined;
	                }
	            };
	        }

	        return this._gridCache;
	    },

	    setGrid: function(drawGrid) {

	        this.clearGrid();

	        this._gridCache = null;
	        this._gridSettings = [];

	        var optionsList = Array.isArray(drawGrid) ? drawGrid : [drawGrid || {}];
	        optionsList.forEach(function(item) {
	            this._gridSettings.push.apply(this._gridSettings, this._resolveDrawGridOption(item));
	        }, this);
	        return this;
	    },

	    _resolveDrawGridOption: function(opt) {

	        var namespace = this.constructor.gridPatterns;
	        if (isString(opt) && Array.isArray(namespace[opt])) {
	            return namespace[opt].map(function(item) {
	                return assign({}, item);
	            });
	        }

	        var options = opt || { args: [{}] };
	        var isArray = Array.isArray(options);
	        var name = options.name;

	        if (!isArray && !name && !options.markup) {
	            name = 'dot';
	        }

	        if (name && Array.isArray(namespace[name])) {
	            var pattern = namespace[name].map(function(item) {
	                return assign({}, item);
	            });

	            var args = Array.isArray(options.args) ? options.args : [options.args || {}];

	            defaults(args[0], omit(opt, 'args'));
	            for (var i = 0; i < args.length; i++) {
	                if (pattern[i]) {
	                    assign(pattern[i], args[i]);
	                }
	            }
	            return pattern;
	        }

	        return isArray ? options : [options];
	    },

	    drawGrid: function(opt) {

	        var gridSize = this.options.gridSize;
	        if (gridSize <= 1) {
	            return this.clearGrid();
	        }

	        var localOptions = Array.isArray(opt) ? opt : [opt];

	        var ctm = this.matrix();
	        var refs = this._getGridRefs();

	        this._gridSettings.forEach(function(gridLayerSetting, index) {

	            var id = 'pattern_' + index;
	            var options = merge(gridLayerSetting, localOptions[index], {
	                sx: ctm.a || 1,
	                sy: ctm.d || 1,
	                ox: ctm.e || 0,
	                oy: ctm.f || 0
	            });

	            options.width = gridSize * (ctm.a || 1) * (options.scaleFactor || 1);
	            options.height = gridSize * (ctm.d || 1) * (options.scaleFactor || 1);

	            if (!refs.exist(id)) {
	                refs.add(id, V('pattern', { id: id, patternUnits: 'userSpaceOnUse' }, V(options.markup)));
	            }

	            var patternDefVel = refs.get(id);

	            if (isFunction(options.update)) {
	                options.update(patternDefVel.node.childNodes[0], options);
	            }

	            var x = options.ox % options.width;
	            if (x < 0) { x += options.width; }

	            var y = options.oy % options.height;
	            if (y < 0) { y += options.height; }

	            patternDefVel.attr({
	                x: x,
	                y: y,
	                width: options.width,
	                height: options.height
	            });
	        });

	        var patternUri = new XMLSerializer().serializeToString(refs.root.node);
	        patternUri = 'url(data:image/svg+xml;base64,' + btoa(patternUri) + ')';

	        this.$grid.css('backgroundImage', patternUri);

	        return this;
	    },

	    updateBackgroundImage: function(opt) {

	        opt = opt || {};

	        var backgroundPosition = opt.position || 'center';
	        var backgroundSize = opt.size || 'auto auto';

	        var currentScale = this.scale();
	        var currentTranslate = this.translate();

	        // backgroundPosition
	        if (isObject$1(backgroundPosition)) {
	            var x = currentTranslate.tx + (currentScale.sx * (backgroundPosition.x || 0));
	            var y = currentTranslate.ty + (currentScale.sy * (backgroundPosition.y || 0));
	            backgroundPosition = x + 'px ' + y + 'px';
	        }

	        // backgroundSize
	        if (isObject$1(backgroundSize)) {
	            backgroundSize = new Rect(backgroundSize).scale(currentScale.sx, currentScale.sy);
	            backgroundSize = backgroundSize.width + 'px ' + backgroundSize.height + 'px';
	        }

	        this.$background.css({
	            backgroundSize: backgroundSize,
	            backgroundPosition: backgroundPosition
	        });
	    },

	    drawBackgroundImage: function(img, opt) {

	        // Clear the background image if no image provided
	        if (!(img instanceof HTMLImageElement)) {
	            this.$background.css('backgroundImage', '');
	            return;
	        }

	        opt = opt || {};

	        var backgroundImage;
	        var backgroundSize = opt.size;
	        var backgroundRepeat = opt.repeat || 'no-repeat';
	        var backgroundOpacity = opt.opacity || 1;
	        var backgroundQuality = Math.abs(opt.quality) || 1;
	        var backgroundPattern = this.constructor.backgroundPatterns[camelCase(backgroundRepeat)];

	        if (isFunction(backgroundPattern)) {
	            // 'flip-x', 'flip-y', 'flip-xy', 'watermark' and custom
	            img.width *= backgroundQuality;
	            img.height *= backgroundQuality;
	            var canvas = backgroundPattern(img, opt);
	            if (!(canvas instanceof HTMLCanvasElement)) {
	                throw new Error('dia.Paper: background pattern must return an HTML Canvas instance');
	            }

	            backgroundImage = canvas.toDataURL('image/png');
	            backgroundRepeat = 'repeat';
	            if (isObject$1(backgroundSize)) {
	                // recalculate the tile size if an object passed in
	                backgroundSize.width *= canvas.width / img.width;
	                backgroundSize.height *= canvas.height / img.height;
	            } else if (backgroundSize === undefined) {
	                // calculate the tile size if no provided
	                opt.size = {
	                    width: canvas.width / backgroundQuality,
	                    height: canvas.height / backgroundQuality
	                };
	            }
	        } else {
	            // backgroundRepeat:
	            // no-repeat', 'round', 'space', 'repeat', 'repeat-x', 'repeat-y'
	            backgroundImage = img.src;
	            if (backgroundSize === undefined) {
	                // pass the image size for  the backgroundSize if no size provided
	                opt.size = {
	                    width: img.width,
	                    height: img.height
	                };
	            }
	        }

	        this.$background.css({
	            opacity: backgroundOpacity,
	            backgroundRepeat: backgroundRepeat,
	            backgroundImage: 'url(' + backgroundImage + ')'
	        });

	        this.updateBackgroundImage(opt);
	    },

	    updateBackgroundColor: function(color) {

	        this.$el.css('backgroundColor', color || '');
	    },

	    drawBackground: function(opt) {

	        opt = opt || {};

	        this.updateBackgroundColor(opt.color);

	        if (opt.image) {
	            opt = this._background = cloneDeep(opt);
	            var img = document.createElement('img');
	            img.onload = this.drawBackgroundImage.bind(this, img, opt);
	            img.src = opt.image;
	        } else {
	            this.drawBackgroundImage(null);
	            this._background = null;
	        }

	        return this;
	    },

	    setInteractivity: function(value) {

	        this.options.interactive = value;

	        invoke(this._views, 'setInteractivity', value);
	    },

	    // Paper definitions.
	    // ------------------

	    isDefined: function(defId) {

	        return !!this.svg.getElementById(defId);
	    },

	    defineFilter: function(filter$1) {

	        if (!isObject$1(filter$1)) {
	            throw new TypeError('dia.Paper: defineFilter() requires 1. argument to be an object.');
	        }

	        var filterId = filter$1.id;
	        var name = filter$1.name;
	        // Generate a hash code from the stringified filter definition. This gives us
	        // a unique filter ID for different definitions.
	        if (!filterId) {
	            filterId = name + this.svg.id + hashCode(JSON.stringify(filter$1));
	        }
	        // If the filter already exists in the document,
	        // we're done and we can just use it (reference it using `url()`).
	        // If not, create one.
	        if (!this.isDefined(filterId)) {

	            var namespace = filter;
	            var filterSVGString = namespace[name] && namespace[name](filter$1.args || {});
	            if (!filterSVGString) {
	                throw new Error('Non-existing filter ' + name);
	            }

	            // Set the filter area to be 3x the bounding box of the cell
	            // and center the filter around the cell.
	            var filterAttrs = assign({
	                filterUnits: 'objectBoundingBox',
	                x: -1,
	                y: -1,
	                width: 3,
	                height: 3
	            }, filter$1.attrs, {
	                id: filterId
	            });

	            V(filterSVGString, filterAttrs).appendTo(this.defs);
	        }

	        return filterId;
	    },

	    defineGradient: function(gradient) {

	        if (!isObject$1(gradient)) {
	            throw new TypeError('dia.Paper: defineGradient() requires 1. argument to be an object.');
	        }

	        var gradientId = gradient.id;
	        var type = gradient.type;
	        var stops = gradient.stops;
	        // Generate a hash code from the stringified filter definition. This gives us
	        // a unique filter ID for different definitions.
	        if (!gradientId) {
	            gradientId = type + this.svg.id + hashCode(JSON.stringify(gradient));
	        }
	        // If the gradient already exists in the document,
	        // we're done and we can just use it (reference it using `url()`).
	        // If not, create one.
	        if (!this.isDefined(gradientId)) {

	            var stopTemplate = template('<stop offset="${offset}" stop-color="${color}" stop-opacity="${opacity}"/>');
	            var gradientStopsStrings = toArray(stops).map(function(stop) {
	                return stopTemplate({
	                    offset: stop.offset,
	                    color: stop.color,
	                    opacity: Number.isFinite(stop.opacity) ? stop.opacity : 1
	                });
	            });

	            var gradientSVGString = [
	                '<' + type + '>',
	                gradientStopsStrings.join(''),
	                '</' + type + '>'
	            ].join('');

	            var gradientAttrs = assign({ id: gradientId }, gradient.attrs);

	            V(gradientSVGString, gradientAttrs).appendTo(this.defs);
	        }

	        return gradientId;
	    },

	    defineMarker: function(marker) {

	        if (!isObject$1(marker)) {
	            throw new TypeError('dia.Paper: defineMarker() requires 1. argument to be an object.');
	        }

	        var markerId = marker.id;

	        // Generate a hash code from the stringified filter definition. This gives us
	        // a unique filter ID for different definitions.
	        if (!markerId) {
	            markerId = this.svg.id + hashCode(JSON.stringify(marker));
	        }

	        if (!this.isDefined(markerId)) {

	            var attrs = omit(marker, 'type', 'userSpaceOnUse');
	            var pathMarker = V('marker', {
	                id: markerId,
	                orient: 'auto',
	                overflow: 'visible',
	                markerUnits: marker.markerUnits || 'userSpaceOnUse'
	            }, [
	                V(marker.type || 'path', attrs)
	            ]);

	            pathMarker.appendTo(this.defs);
	        }

	        return markerId;
	    }

	}, {

	    sorting: sortingTypes,

	    Layers: LayersNames,

	    backgroundPatterns: {

	        flipXy: function(img) {
	            // d b
	            // q p

	            var canvas = document.createElement('canvas');
	            var imgWidth = img.width;
	            var imgHeight = img.height;

	            canvas.width = 2 * imgWidth;
	            canvas.height = 2 * imgHeight;

	            var ctx = canvas.getContext('2d');
	            // top-left image
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
	            // xy-flipped bottom-right image
	            ctx.setTransform(-1, 0, 0, -1, canvas.width, canvas.height);
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
	            // x-flipped top-right image
	            ctx.setTransform(-1, 0, 0, 1, canvas.width, 0);
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
	            // y-flipped bottom-left image
	            ctx.setTransform(1, 0, 0, -1, 0, canvas.height);
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);

	            return canvas;
	        },

	        flipX: function(img) {
	            // d b
	            // d b

	            var canvas = document.createElement('canvas');
	            var imgWidth = img.width;
	            var imgHeight = img.height;

	            canvas.width = imgWidth * 2;
	            canvas.height = imgHeight;

	            var ctx = canvas.getContext('2d');
	            // left image
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
	            // flipped right image
	            ctx.translate(2 * imgWidth, 0);
	            ctx.scale(-1, 1);
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);

	            return canvas;
	        },

	        flipY: function(img) {
	            // d d
	            // q q

	            var canvas = document.createElement('canvas');
	            var imgWidth = img.width;
	            var imgHeight = img.height;

	            canvas.width = imgWidth;
	            canvas.height = imgHeight * 2;

	            var ctx = canvas.getContext('2d');
	            // top image
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
	            // flipped bottom image
	            ctx.translate(0, 2 * imgHeight);
	            ctx.scale(1, -1);
	            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);

	            return canvas;
	        },

	        watermark: function(img, opt) {
	            //   d
	            // d

	            opt = opt || {};

	            var imgWidth = img.width;
	            var imgHeight = img.height;

	            var canvas = document.createElement('canvas');
	            canvas.width = imgWidth * 3;
	            canvas.height = imgHeight * 3;

	            var ctx = canvas.getContext('2d');
	            var angle = isNumber(opt.watermarkAngle) ? -opt.watermarkAngle : -20;
	            var radians = toRad(angle);
	            var stepX = canvas.width / 4;
	            var stepY = canvas.height / 4;

	            for (var i = 0; i < 4; i++) {
	                for (var j = 0; j < 4; j++) {
	                    if ((i + j) % 2 > 0) {
	                        // reset the current transformations
	                        ctx.setTransform(1, 0, 0, 1, (2 * i - 1) * stepX, (2 * j - 1) * stepY);
	                        ctx.rotate(radians);
	                        ctx.drawImage(img, -imgWidth / 2, -imgHeight / 2, imgWidth, imgHeight);
	                    }
	                }
	            }

	            return canvas;
	        }
	    },

	    gridPatterns: {
	        dot: [{
	            color: '#AAAAAA',
	            thickness: 1,
	            markup: 'rect',
	            update: function(el, opt) {
	                V(el).attr({
	                    width: opt.thickness * opt.sx,
	                    height: opt.thickness * opt.sy,
	                    fill: opt.color
	                });
	            }
	        }],
	        fixedDot: [{
	            color: '#AAAAAA',
	            thickness: 1,
	            markup: 'rect',
	            update: function(el, opt) {
	                var size = opt.sx <= 1 ? opt.thickness * opt.sx : opt.thickness;
	                V(el).attr({ width: size, height: size, fill: opt.color });
	            }
	        }],
	        mesh: [{
	            color: '#AAAAAA',
	            thickness: 1,
	            markup: 'path',
	            update: function(el, opt) {

	                var d;
	                var width = opt.width;
	                var height = opt.height;
	                var thickness = opt.thickness;

	                if (width - thickness >= 0 && height - thickness >= 0) {
	                    d = ['M', width, 0, 'H0 M0 0 V0', height].join(' ');
	                } else {
	                    d = 'M 0 0 0 0';
	                }

	                V(el).attr({ 'd': d, stroke: opt.color, 'stroke-width': opt.thickness });
	            }
	        }],
	        doubleMesh: [{
	            color: '#AAAAAA',
	            thickness: 1,
	            markup: 'path',
	            update: function(el, opt) {

	                var d;
	                var width = opt.width;
	                var height = opt.height;
	                var thickness = opt.thickness;

	                if (width - thickness >= 0 && height - thickness >= 0) {
	                    d = ['M', width, 0, 'H0 M0 0 V0', height].join(' ');
	                } else {
	                    d = 'M 0 0 0 0';
	                }

	                V(el).attr({ 'd': d, stroke: opt.color, 'stroke-width': opt.thickness });
	            }
	        }, {
	            color: '#000000',
	            thickness: 3,
	            scaleFactor: 4,
	            markup: 'path',
	            update: function(el, opt) {

	                var d;
	                var width = opt.width;
	                var height = opt.height;
	                var thickness = opt.thickness;

	                if (width - thickness >= 0 && height - thickness >= 0) {
	                    d = ['M', width, 0, 'H0 M0 0 V0', height].join(' ');
	                } else {
	                    d = 'M 0 0 0 0';
	                }

	                V(el).attr({ 'd': d, stroke: opt.color, 'stroke-width': opt.thickness });
	            }
	        }]
	    }
	});

	var ToolView = View.extend({
	    name: null,
	    tagName: 'g',
	    className: 'tool',
	    svgElement: true,
	    _visible: true,

	    init: function() {
	        var name = this.name;
	        if (name) { this.vel.attr('data-tool-name', name); }
	    },

	    configure: function(view, toolsView) {
	        this.relatedView = view;
	        this.paper = view.paper;
	        this.parentView = toolsView;
	        this.simulateRelatedView(this.el);
	        // Delegate events in case the ToolView was removed from the DOM and reused.
	        this.delegateEvents();
	        return this;
	    },

	    simulateRelatedView: function(el) {
	        if (el) { el.setAttribute('model-id', this.relatedView.model.id); }
	    },

	    getName: function() {
	        return this.name;
	    },

	    show: function() {
	        this.el.style.display = '';
	        this._visible = true;
	    },

	    hide: function() {
	        this.el.style.display = 'none';
	        this._visible = false;
	    },

	    isVisible: function() {
	        return !!this._visible;
	    },

	    focus: function() {
	        var opacity = this.options.focusOpacity;
	        if (isFinite(opacity)) { this.el.style.opacity = opacity; }
	        this.parentView.focusTool(this);
	    },

	    blur: function() {
	        this.el.style.opacity = '';
	        this.parentView.blurTool(this);
	    },

	    update: function() {
	        // to be overridden
	    },

	    guard: function(evt) {
	        // Let the context-menu event bubble up to the relatedView
	        var ref = this;
	        var paper = ref.paper;
	        var relatedView = ref.relatedView;
	        if (!paper || !relatedView) { return true; }
	        return paper.guard(evt, relatedView);
	    }
	});

	var ToolsView = View.extend({
	    tagName: 'g',
	    className: 'tools',
	    svgElement: true,
	    tools: null,
	    isRendered: false,
	    options: {
	        tools: null,
	        relatedView: null,
	        name: null,
	        component: false
	    },

	    configure: function(options) {
	        options = assign(this.options, options);
	        var tools = options.tools;
	        if (!Array.isArray(tools)) { return this; }
	        var relatedView = options.relatedView;
	        if (!(relatedView instanceof CellView)) { return this; }
	        var views = this.tools = [];
	        for (var i = 0, n = tools.length; i < n; i++) {
	            var tool = tools[i];
	            if (!(tool instanceof ToolView)) { continue; }
	            tool.configure(relatedView, this);
	            this.vel.append(tool.el);
	            views.push(tool);
	        }
	        this.isRendered = false;
	        relatedView.requestUpdate(relatedView.getFlag('TOOLS'));
	        return this;
	    },

	    getName: function() {
	        return this.options.name;
	    },

	    update: function(opt) {

	        opt || (opt = {});
	        var tools = this.tools;
	        if (!tools) { return this; }
	        var isRendered = this.isRendered;
	        for (var i = 0, n = tools.length; i < n; i++) {
	            var tool = tools[i];
	            if (!isRendered) {
	                // First update executes render()
	                tool.render();
	            } else if (opt.tool !== tool.cid && tool.isVisible()) {
	                tool.update();
	            }
	        }
	        if (!isRendered) {
	            this.mount();
	            // Make sure tools are visible (if they were hidden and the tool removed)
	            this.blurTool();
	            this.isRendered = true;
	        }
	        return this;
	    },

	    focusTool: function(focusedTool) {

	        var tools = this.tools;
	        if (!tools) { return this; }
	        for (var i = 0, n = tools.length; i < n; i++) {
	            var tool = tools[i];
	            if (focusedTool === tool) {
	                tool.show();
	            } else {
	                tool.hide();
	            }
	        }
	        return this;
	    },

	    blurTool: function(blurredTool) {
	        var tools = this.tools;
	        if (!tools) { return this; }
	        for (var i = 0, n = tools.length; i < n; i++) {
	            var tool = tools[i];
	            if (tool !== blurredTool && !tool.isVisible()) {
	                tool.show();
	                tool.update();
	            }
	        }
	        return this;
	    },

	    hide: function() {
	        return this.focusTool(null);
	    },

	    show: function() {
	        return this.blurTool(null);
	    },

	    onRemove: function() {
	        var tools = this.tools;
	        if (!tools) { return this; }
	        for (var i = 0, n = tools.length; i < n; i++) {
	            tools[i].remove();
	        }
	        this.tools = null;
	    },

	    mount: function() {
	        var options = this.options;
	        var relatedView = options.relatedView;
	        if (relatedView) {
	            var container = (options.component) ? relatedView.el : relatedView.paper.tools;
	            container.appendChild(this.el);
	        }
	        return this;
	    }

	});



	var index$2 = ({
		Graph: Graph,
		attributes: attributes,
		Cell: Cell,
		CellView: CellView,
		Element: Element$1,
		ElementView: ElementView,
		Link: Link,
		LinkView: LinkView,
		Paper: Paper,
		ToolView: ToolView,
		ToolsView: ToolsView,
		HighlighterView: HighlighterView
	});

	var DirectedGraph = {

	    exportElement: function(element) {

	        // The width and height of the element.
	        return element.size();
	    },

	    exportLink: function(link) {

	        var labelSize = link.get('labelSize') || {};
	        var edge = {
	            // The number of ranks to keep between the source and target of the edge.
	            minLen: link.get('minLen') || 1,
	            // The weight to assign edges. Higher weight edges are generally
	            // made shorter and straighter than lower weight edges.
	            weight: link.get('weight') || 1,
	            // Where to place the label relative to the edge.
	            // l = left, c = center r = right.
	            labelpos: link.get('labelPosition') || 'c',
	            // How many pixels to move the label away from the edge.
	            // Applies only when labelpos is l or r.
	            labeloffset: link.get('labelOffset') || 0,
	            // The width of the edge label in pixels.
	            width: labelSize.width || 0,
	            // The height of the edge label in pixels.
	            height: labelSize.height || 0
	        };

	        return edge;
	    },

	    importElement: function(opt, v, gl) {

	        var element = this.getCell(v);
	        var glNode = gl.node(v);

	        if (opt.setPosition) {
	            opt.setPosition(element, glNode);
	        } else {
	            element.set('position', {
	                x: glNode.x - glNode.width / 2,
	                y: glNode.y - glNode.height / 2
	            });
	        }
	    },

	    importLink: function(opt, edgeObj, gl) {

	        var SIMPLIFY_THRESHOLD = 0.001;

	        var link = this.getCell(edgeObj.name);
	        var glEdge = gl.edge(edgeObj);
	        var points = glEdge.points || [];
	        var polyline = new Polyline(points);

	        // check the `setLinkVertices` here for backwards compatibility
	        if (opt.setVertices || opt.setLinkVertices) {
	            if (isFunction(opt.setVertices)) {
	                opt.setVertices(link, points);
	            } else {
	                // simplify the `points` polyline
	                polyline.simplify({ threshold: SIMPLIFY_THRESHOLD });
	                var polylinePoints = polyline.points.map(function (point) { return (point.toJSON()); }); // JSON of points after simplification
	                var numPolylinePoints = polylinePoints.length; // number of points after simplification
	                // set simplified polyline points as link vertices
	                // remove first and last polyline points (= source/target sonnectionPoints)
	                link.set('vertices', polylinePoints.slice(1, numPolylinePoints - 1));
	            }
	        }

	        if (opt.setLabels && ('x' in glEdge) && ('y' in glEdge)) {
	            var labelPosition = { x: glEdge.x, y: glEdge.y };
	            if (isFunction(opt.setLabels)) {
	                opt.setLabels(link, labelPosition, points);
	            } else {
	                // convert the absolute label position to a relative position
	                // towards the closest point on the edge
	                var length = polyline.closestPointLength(labelPosition);
	                var closestPoint = polyline.pointAtLength(length);
	                var distance = (length / polyline.length());
	                var offset = new Point(labelPosition).difference(closestPoint).toJSON();
	                link.label(0, {
	                    position: {
	                        distance: distance,
	                        offset: offset
	                    }
	                });
	            }
	        }
	    },

	    layout: function(graphOrCells, opt) {

	        var graph;

	        if (graphOrCells instanceof Graph) {
	            graph = graphOrCells;
	        } else {
	            // Reset cells in dry mode so the graph reference is not stored on the cells.
	            // `sort: false` to prevent elements to change their order based on the z-index
	            graph = (new Graph()).resetCells(graphOrCells, { dry: true, sort: false });
	        }

	        // This is not needed anymore.
	        graphOrCells = null;

	        opt = defaults(opt || {}, {
	            resizeClusters: true,
	            clusterPadding: 10,
	            exportElement: this.exportElement,
	            exportLink: this.exportLink
	        });

	        /* global dagre: true */
	        var dagreUtil = opt.dagre || (typeof dagre !== 'undefined' ? dagre : undefined);
	        /* global dagre: false */

	        if (dagreUtil === undefined) { throw new Error('The the "dagre" utility is a mandatory dependency.'); }

	        // create a graphlib.Graph that represents the joint.dia.Graph
	        // var glGraph = graph.toGraphLib({
	        var glGraph = DirectedGraph.toGraphLib(graph, {
	            graphlib: opt.graphlib,
	            directed: true,
	            // We are about to use edge naming feature.
	            multigraph: true,
	            // We are able to layout graphs with embeds.
	            compound: true,
	            setNodeLabel: opt.exportElement,
	            setEdgeLabel: opt.exportLink,
	            setEdgeName: function(link) {
	                // Graphlib edges have no ids. We use edge name property
	                // to store and retrieve ids instead.
	                return link.id;
	            }
	        });

	        var glLabel = {};
	        var marginX = opt.marginX || 0;
	        var marginY = opt.marginY || 0;

	        // Dagre layout accepts options as lower case.
	        // Direction for rank nodes. Can be TB, BT, LR, or RL
	        if (opt.rankDir) { glLabel.rankdir = opt.rankDir; }
	        // Alignment for rank nodes. Can be UL, UR, DL, or DR
	        if (opt.align) { glLabel.align = opt.align; }
	        // Number of pixels that separate nodes horizontally in the layout.
	        if (opt.nodeSep) { glLabel.nodesep = opt.nodeSep; }
	        // Number of pixels that separate edges horizontally in the layout.
	        if (opt.edgeSep) { glLabel.edgesep = opt.edgeSep; }
	        // Number of pixels between each rank in the layout.
	        if (opt.rankSep) { glLabel.ranksep = opt.rankSep; }
	        // Type of algorithm to assign a rank to each node in the input graph.
	        // Possible values: network-simplex, tight-tree or longest-path
	        if (opt.ranker) { glLabel.ranker = opt.ranker; }
	        // Number of pixels to use as a margin around the left and right of the graph.
	        if (marginX) { glLabel.marginx = marginX; }
	        // Number of pixels to use as a margin around the top and bottom of the graph.
	        if (marginY) { glLabel.marginy = marginY; }

	        // Set the option object for the graph label.
	        glGraph.setGraph(glLabel);

	        // Executes the layout.
	        dagreUtil.layout(glGraph, { debugTiming: !!opt.debugTiming });

	        // Wrap all graph changes into a batch.
	        graph.startBatch('layout');

	        DirectedGraph.fromGraphLib(glGraph, {
	            importNode: this.importElement.bind(graph, opt),
	            importEdge: this.importLink.bind(graph, opt)
	        });

	        // // Update the graph.
	        // graph.fromGraphLib(glGraph, {
	        //     importNode: this.importElement.bind(graph, opt),
	        //     importEdge: this.importLink.bind(graph, opt)
	        // });

	        if (opt.resizeClusters) {
	            // Resize and reposition cluster elements (parents of other elements)
	            // to fit their children.
	            // 1. filter clusters only
	            // 2. map id on cells
	            // 3. sort cells by their depth (the deepest first)
	            // 4. resize cell to fit their direct children only.
	            var clusters = glGraph.nodes()
	                .filter(function(v) { return glGraph.children(v).length > 0; })
	                .map(graph.getCell.bind(graph))
	                .sort(function(aCluster, bCluster) {
	                    return bCluster.getAncestors().length - aCluster.getAncestors().length;
	                });

	            invoke(clusters, 'fitEmbeds', { padding: opt.clusterPadding });
	        }

	        graph.stopBatch('layout');

	        // Width and height of the graph extended by margins.
	        var glSize = glGraph.graph();
	        // Return the bounding box of the graph after the layout.
	        return new Rect(
	            marginX,
	            marginY,
	            Math.abs(glSize.width - 2 * marginX),
	            Math.abs(glSize.height - 2 * marginY)
	        );
	    },

	    fromGraphLib: function(glGraph, opt) {

	        opt = opt || {};

	        var importNode = opt.importNode || noop;
	        var importEdge = opt.importEdge || noop;
	        var graph = (this instanceof Graph) ? this : new Graph;

	        // Import all nodes.
	        glGraph.nodes().forEach(function(node) {
	            importNode.call(graph, node, glGraph, graph, opt);
	        });

	        // Import all edges.
	        glGraph.edges().forEach(function(edge) {
	            importEdge.call(graph, edge, glGraph, graph, opt);
	        });

	        return graph;
	    },

	    // Create new graphlib graph from existing JointJS graph.
	    toGraphLib: function(graph, opt) {

	        opt = opt || {};

	        /* global graphlib: true */
	        var graphlibUtil = opt.graphlib || (typeof graphlib !== 'undefined' ? graphlib : undefined);
	        /* global graphlib: false */

	        if (graphlibUtil === undefined) { throw new Error('The the "graphlib" utility is a mandatory dependency.'); }

	        var glGraphType = pick(opt, 'directed', 'compound', 'multigraph');
	        var glGraph = new graphlibUtil.Graph(glGraphType);
	        var setNodeLabel = opt.setNodeLabel || noop;
	        var setEdgeLabel = opt.setEdgeLabel || noop;
	        var setEdgeName = opt.setEdgeName || noop;
	        var collection = graph.get('cells');

	        for (var i = 0, n = collection.length; i < n; i++) {

	            var cell = collection.at(i);
	            if (cell.isLink()) {

	                var source = cell.get('source');
	                var target = cell.get('target');

	                // Links that end at a point are ignored.
	                if (!source.id || !target.id) { break; }

	                // Note that if we are creating a multigraph we can name the edges. If
	                // we try to name edges on a non-multigraph an exception is thrown.
	                glGraph.setEdge(source.id, target.id, setEdgeLabel(cell), setEdgeName(cell));

	            } else {

	                glGraph.setNode(cell.id, setNodeLabel(cell));

	                // For the compound graphs we have to take embeds into account.
	                if (glGraph.isCompound() && cell.has('parent')) {
	                    var parentId = cell.get('parent');
	                    if (collection.has(parentId)) {
	                        // Make sure the parent cell is included in the graph (this can
	                        // happen when the layout is run on part of the graph only).
	                        glGraph.setParent(cell.id, parentId);
	                    }
	                }
	            }
	        }

	        return glGraph;
	    }
	};

	Graph.prototype.toGraphLib = function(opt) {

	    return DirectedGraph.toGraphLib(this, opt);
	};

	Graph.prototype.fromGraphLib = function(glGraph, opt) {

	    return DirectedGraph.fromGraphLib.call(this, glGraph, opt);
	};

	var env = {

	    _results: {},

	    _tests: {

	        svgforeignobject: function() {
	            return !!document.createElementNS &&
	                /SVGForeignObject/.test(({}).toString.call(document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')));
	        }
	    },

	    addTest: function(name, fn) {

	        return this._tests[name] = fn;
	    },

	    test: function(name) {

	        var fn = this._tests[name];

	        if (!fn) {
	            throw new Error('Test not defined ("' + name + '"). Use `joint.env.addTest(name, fn) to add a new test.`');
	        }

	        var result = this._results[name];

	        if (typeof result !== 'undefined') {
	            return result;
	        }

	        try {
	            result = fn();
	        } catch (error) {
	            result = false;
	        }

	        // Cache the test result.
	        this._results[name] = result;

	        return result;
	    }
	};

	var Generic = Element$1.define('basic.Generic', {
	    attrs: {
	        '.': { fill: '#ffffff', stroke: 'none' }
	    }
	});

	var Rect$1 = Generic.define('basic.Rect', {
	    attrs: {
	        'rect': {
	            fill: '#ffffff',
	            stroke: '#000000',
	            width: 100,
	            height: 60
	        },
	        'text': {
	            fill: '#000000',
	            text: '',
	            'font-size': 14,
	            'ref-x': .5,
	            'ref-y': .5,
	            'text-anchor': 'middle',
	            'y-alignment': 'middle',
	            'font-family': 'Arial, helvetica, sans-serif'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>'
	});

	var TextView = ElementView.extend({

	    presentationAttributes: ElementView.addPresentationAttributes({
	        // The element view is not automatically re-scaled to fit the model size
	        // when the attribute 'attrs' is changed.
	        attrs: ['SCALE']
	    }),

	    confirmUpdate: function() {
	        var flags = ElementView.prototype.confirmUpdate.apply(this, arguments);
	        if (this.hasFlag(flags, 'SCALE')) {
	            this.resize();
	            flags = this.removeFlag(flags, 'SCALE');
	        }
	        return flags;
	    }
	});

	var Text = Generic.define('basic.Text', {
	    attrs: {
	        'text': {
	            'font-size': 18,
	            fill: '#000000'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><text/></g></g>',
	});

	var Circle = Generic.define('basic.Circle', {
	    size: { width: 60, height: 60 },
	    attrs: {
	        'circle': {
	            fill: '#ffffff',
	            stroke: '#000000',
	            r: 30,
	            cx: 30,
	            cy: 30
	        },
	        'text': {
	            'font-size': 14,
	            text: '',
	            'text-anchor': 'middle',
	            'ref-x': .5,
	            'ref-y': .5,
	            'y-alignment': 'middle',
	            fill: '#000000',
	            'font-family': 'Arial, helvetica, sans-serif'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>',
	});

	var Ellipse$1 = Generic.define('basic.Ellipse', {
	    size: { width: 60, height: 40 },
	    attrs: {
	        'ellipse': {
	            fill: '#ffffff',
	            stroke: '#000000',
	            rx: 30,
	            ry: 20,
	            cx: 30,
	            cy: 20
	        },
	        'text': {
	            'font-size': 14,
	            text: '',
	            'text-anchor': 'middle',
	            'ref-x': .5,
	            'ref-y': .5,
	            'y-alignment': 'middle',
	            fill: '#000000',
	            'font-family': 'Arial, helvetica, sans-serif'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><ellipse/></g><text/></g>',
	});

	var Polygon = Generic.define('basic.Polygon', {
	    size: { width: 60, height: 40 },
	    attrs: {
	        'polygon': {
	            fill: '#ffffff',
	            stroke: '#000000'
	        },
	        'text': {
	            'font-size': 14,
	            text: '',
	            'text-anchor': 'middle',
	            'ref-x': .5,
	            'ref-dy': 20,
	            'y-alignment': 'middle',
	            fill: '#000000',
	            'font-family': 'Arial, helvetica, sans-serif'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>',
	});

	var Polyline$1 = Generic.define('basic.Polyline', {
	    size: { width: 60, height: 40 },
	    attrs: {
	        'polyline': {
	            fill: '#ffffff',
	            stroke: '#000000'
	        },
	        'text': {
	            'font-size': 14,
	            text: '',
	            'text-anchor': 'middle',
	            'ref-x': .5,
	            'ref-dy': 20,
	            'y-alignment': 'middle',
	            fill: '#000000',
	            'font-family': 'Arial, helvetica, sans-serif'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><polyline/></g><text/></g>',
	});

	var Image = Generic.define('basic.Image', {
	    attrs: {
	        'text': {
	            'font-size': 14,
	            text: '',
	            'text-anchor': 'middle',
	            'ref-x': .5,
	            'ref-dy': 20,
	            'y-alignment': 'middle',
	            fill: '#000000',
	            'font-family': 'Arial, helvetica, sans-serif'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>',
	});

	var Path$1 = Generic.define('basic.Path', {
	    size: { width: 60, height: 60 },
	    attrs: {
	        'path': {
	            fill: '#ffffff',
	            stroke: '#000000'
	        },
	        'text': {
	            'font-size': 14,
	            text: '',
	            'text-anchor': 'middle',
	            'ref': 'path',
	            'ref-x': .5,
	            'ref-dy': 10,
	            fill: '#000000',
	            'font-family': 'Arial, helvetica, sans-serif'
	        }
	    }

	}, {
	    markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>',
	});

	var Rhombus = Path$1.define('basic.Rhombus', {
	    attrs: {
	        'path': {
	            d: 'M 30 0 L 60 30 30 60 0 30 z'
	        },
	        'text': {
	            'ref-y': .5,
	            'ref-dy': null,
	            'y-alignment': 'middle'
	        }
	    }
	});

	var svgForeignObjectSupported = env.test('svgforeignobject');

	var TextBlock = Generic.define('basic.TextBlock', {
	    // see joint.css for more element styles
	    attrs: {
	        rect: {
	            fill: '#ffffff',
	            stroke: '#000000',
	            width: 80,
	            height: 100
	        },
	        text: {
	            fill: '#000000',
	            'font-size': 14,
	            'font-family': 'Arial, helvetica, sans-serif'
	        },
	        '.content': {
	            text: '',
	            'ref-x': .5,
	            'ref-y': .5,
	            'y-alignment': 'middle',
	            'x-alignment': 'middle'
	        }
	    },

	    content: ''
	}, {
	    markup: [
	        '<g class="rotatable">',
	        '<g class="scalable"><rect/></g>',
	        svgForeignObjectSupported
	            ? '<foreignObject class="fobj"><body xmlns="http://www.w3.org/1999/xhtml"><div class="content"/></body></foreignObject>'
	            : '<text class="content"/>',
	        '</g>'
	    ].join(''),

	    initialize: function() {

	        this.listenTo(this, 'change:size', this.updateSize);
	        this.listenTo(this, 'change:content', this.updateContent);
	        this.updateSize(this, this.get('size'));
	        this.updateContent(this, this.get('content'));
	        Generic.prototype.initialize.apply(this, arguments);
	    },

	    updateSize: function(cell, size) {

	        // Selector `foreignObject' doesn't work across all browsers, we're using class selector instead.
	        // We have to clone size as we don't want attributes.div.style to be same object as attributes.size.
	        this.attr({
	            '.fobj': assign({}, size),
	            div: {
	                style: assign({}, size)
	            }
	        });
	    },

	    updateContent: function(cell, content) {

	        if (svgForeignObjectSupported) {

	            // Content element is a <div> element.
	            this.attr({
	                '.content': {
	                    html: sanitizeHTML(content)
	                }
	            });

	        } else {

	            // Content element is a <text> element.
	            // SVG elements don't have innerHTML attribute.
	            this.attr({
	                '.content': {
	                    text: content
	                }
	            });
	        }
	    },

	    // Here for backwards compatibility:
	    setForeignObjectSize: function() {

	        this.updateSize.apply(this, arguments);
	    },

	    // Here for backwards compatibility:
	    setDivContent: function() {

	        this.updateContent.apply(this, arguments);
	    }
	});

	// TextBlockView implements the fallback for IE when no foreignObject exists and
	// the text needs to be manually broken.
	var TextBlockView = ElementView.extend({

	    presentationAttributes: svgForeignObjectSupported
	        ? ElementView.prototype.presentationAttributes
	        : ElementView.addPresentationAttributes({
	            content: ['CONTENT'],
	            size: ['CONTENT']
	        }),

	    initFlag: ['RENDER', 'CONTENT'],

	    confirmUpdate: function() {
	        var flags = ElementView.prototype.confirmUpdate.apply(this, arguments);
	        if (this.hasFlag(flags, 'CONTENT')) {
	            this.updateContent(this.model);
	            flags = this.removeFlag(flags, 'CONTENT');
	        }
	        return flags;
	    },

	    update: function(_, renderingOnlyAttrs) {

	        var model = this.model;

	        if (!svgForeignObjectSupported) {

	            // Update everything but the content first.
	            var noTextAttrs = omit(renderingOnlyAttrs || model.get('attrs'), '.content');
	            ElementView.prototype.update.call(this, model, noTextAttrs);

	            if (!renderingOnlyAttrs || has$2(renderingOnlyAttrs, '.content')) {
	                // Update the content itself.
	                this.updateContent(model, renderingOnlyAttrs);
	            }

	        } else {

	            ElementView.prototype.update.call(this, model, renderingOnlyAttrs);
	        }
	    },

	    updateContent: function(cell, renderingOnlyAttrs) {

	        // Create copy of the text attributes
	        var textAttrs = merge({}, (renderingOnlyAttrs || cell.get('attrs'))['.content']);

	        textAttrs = omit(textAttrs, 'text');

	        // Break the content to fit the element size taking into account the attributes
	        // set on the model.
	        var text = breakText(cell.get('content'), cell.get('size'), textAttrs, {
	            // measuring sandbox svg document
	            svgDocument: this.paper.svg
	        });

	        // Create a new attrs with same structure as the model attrs { text: { *textAttributes* }}
	        var attrs = setByPath({}, '.content', textAttrs, '/');

	        // Replace text attribute with the one we just processed.
	        attrs['.content'].text = text;

	        // Update the view using renderingOnlyAttributes parameter.
	        ElementView.prototype.update.call(this, cell, attrs);
	    }
	});

	var basic = ({
		Generic: Generic,
		Rect: Rect$1,
		TextView: TextView,
		Text: Text,
		Circle: Circle,
		Ellipse: Ellipse$1,
		Polygon: Polygon,
		Polyline: Polyline$1,
		Image: Image,
		Path: Path$1,
		Rhombus: Rhombus,
		TextBlock: TextBlock,
		TextBlockView: TextBlockView
	});

	// ELEMENTS

	var Rectangle = Element$1.define('standard.Rectangle', {
	    attrs: {
	        body: {
	            refWidth: '100%',
	            refHeight: '100%',
	            strokeWidth: 2,
	            stroke: '#000000',
	            fill: '#FFFFFF'
	        },
	        label: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '50%',
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'rect',
	        selector: 'body',
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var Circle$1 = Element$1.define('standard.Circle', {
	    attrs: {
	        body: {
	            refCx: '50%',
	            refCy: '50%',
	            refR: '50%',
	            strokeWidth: 2,
	            stroke: '#333333',
	            fill: '#FFFFFF'
	        },
	        label: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '50%',
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'circle',
	        selector: 'body'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var Ellipse$2 = Element$1.define('standard.Ellipse', {
	    attrs: {
	        body: {
	            refCx: '50%',
	            refCy: '50%',
	            refRx: '50%',
	            refRy: '50%',
	            strokeWidth: 2,
	            stroke: '#333333',
	            fill: '#FFFFFF'
	        },
	        label: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '50%',
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'ellipse',
	        selector: 'body'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var Path$2 = Element$1.define('standard.Path', {
	    attrs: {
	        body: {
	            refD: 'M 0 0 L 10 0 10 10 0 10 Z',
	            strokeWidth: 2,
	            stroke: '#333333',
	            fill: '#FFFFFF'
	        },
	        label: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '50%',
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'path',
	        selector: 'body'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var Polygon$1 = Element$1.define('standard.Polygon', {
	    attrs: {
	        body: {
	            refPoints: '0 0 10 0 10 10 0 10',
	            strokeWidth: 2,
	            stroke: '#333333',
	            fill: '#FFFFFF'
	        },
	        label: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '50%',
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'polygon',
	        selector: 'body'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var Polyline$2 = Element$1.define('standard.Polyline', {
	    attrs: {
	        body: {
	            refPoints: '0 0 10 0 10 10 0 10 0 0',
	            strokeWidth: 2,
	            stroke: '#333333',
	            fill: '#FFFFFF'
	        },
	        label: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '50%',
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'polyline',
	        selector: 'body'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var Image$1 = Element$1.define('standard.Image', {
	    attrs: {
	        image: {
	            refWidth: '100%',
	            refHeight: '100%',
	            // xlinkHref: '[URL]'
	        },
	        label: {
	            textVerticalAnchor: 'top',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '100%',
	            refY2: 10,
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'image',
	        selector: 'image'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var BorderedImage = Element$1.define('standard.BorderedImage', {
	    attrs: {
	        border: {
	            refWidth: '100%',
	            refHeight: '100%',
	            stroke: '#333333',
	            strokeWidth: 2
	        },
	        background: {
	            refWidth: -1,
	            refHeight: -1,
	            x: 0.5,
	            y: 0.5,
	            fill: '#FFFFFF'
	        },
	        image: {
	            // xlinkHref: '[URL]'
	            refWidth: -1,
	            refHeight: -1,
	            x: 0.5,
	            y: 0.5
	        },
	        label: {
	            textVerticalAnchor: 'top',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '100%',
	            refY2: 10,
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'rect',
	        selector: 'background',
	        attributes: {
	            'stroke': 'none'
	        }
	    }, {
	        tagName: 'image',
	        selector: 'image'
	    }, {
	        tagName: 'rect',
	        selector: 'border',
	        attributes: {
	            'fill': 'none'
	        }
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var EmbeddedImage = Element$1.define('standard.EmbeddedImage', {
	    attrs: {
	        body: {
	            refWidth: '100%',
	            refHeight: '100%',
	            stroke: '#333333',
	            fill: '#FFFFFF',
	            strokeWidth: 2
	        },
	        image: {
	            // xlinkHref: '[URL]'
	            refWidth: '30%',
	            refHeight: -20,
	            x: 10,
	            y: 10,
	            preserveAspectRatio: 'xMidYMin'
	        },
	        label: {
	            textVerticalAnchor: 'top',
	            textAnchor: 'left',
	            refX: '30%',
	            refX2: 20, // 10 + 10
	            refY: 10,
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'rect',
	        selector: 'body'
	    }, {
	        tagName: 'image',
	        selector: 'image'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var InscribedImage = Element$1.define('standard.InscribedImage', {
	    attrs: {
	        border: {
	            refRx: '50%',
	            refRy: '50%',
	            refCx: '50%',
	            refCy: '50%',
	            stroke: '#333333',
	            strokeWidth: 2
	        },
	        background: {
	            refRx: '50%',
	            refRy: '50%',
	            refCx: '50%',
	            refCy: '50%',
	            fill: '#FFFFFF'
	        },
	        image: {
	            // The image corners touch the border when its size is Math.sqrt(2) / 2 = 0.707.. ~= 70%
	            refWidth: '68%',
	            refHeight: '68%',
	            // The image offset is calculated as (100% - 68%) / 2
	            refX: '16%',
	            refY: '16%',
	            preserveAspectRatio: 'xMidYMid'
	            // xlinkHref: '[URL]'
	        },
	        label: {
	            textVerticalAnchor: 'top',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '100%',
	            refY2: 10,
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'ellipse',
	        selector: 'background'
	    }, {
	        tagName: 'image',
	        selector: 'image'
	    }, {
	        tagName: 'ellipse',
	        selector: 'border',
	        attributes: {
	            'fill': 'none'
	        }
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }]
	});

	var HeaderedRectangle = Element$1.define('standard.HeaderedRectangle', {
	    attrs: {
	        body: {
	            refWidth: '100%',
	            refHeight: '100%',
	            strokeWidth: 2,
	            stroke: '#000000',
	            fill: '#FFFFFF'
	        },
	        header: {
	            refWidth: '100%',
	            height: 30,
	            strokeWidth: 2,
	            stroke: '#000000',
	            fill: '#FFFFFF'
	        },
	        headerText: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: 15,
	            fontSize: 16,
	            fill: '#333333'
	        },
	        bodyText: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '50%',
	            refY2: 15,
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'rect',
	        selector: 'body'
	    }, {
	        tagName: 'rect',
	        selector: 'header'
	    }, {
	        tagName: 'text',
	        selector: 'headerText'
	    }, {
	        tagName: 'text',
	        selector: 'bodyText'
	    }]
	});

	var CYLINDER_TILT = 10;

	var Cylinder = Element$1.define('standard.Cylinder', {
	    attrs: {
	        body: {
	            lateralArea: CYLINDER_TILT,
	            fill: '#FFFFFF',
	            stroke: '#333333',
	            strokeWidth: 2
	        },
	        top: {
	            refCx: '50%',
	            cy: CYLINDER_TILT,
	            refRx: '50%',
	            ry: CYLINDER_TILT,
	            fill: '#FFFFFF',
	            stroke: '#333333',
	            strokeWidth: 2
	        },
	        label: {
	            textVerticalAnchor: 'middle',
	            textAnchor: 'middle',
	            refX: '50%',
	            refY: '100%',
	            refY2: 15,
	            fontSize: 14,
	            fill: '#333333'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'path',
	        selector: 'body'
	    }, {
	        tagName: 'ellipse',
	        selector: 'top'
	    }, {
	        tagName: 'text',
	        selector: 'label'
	    }],

	    topRy: function(t, opt) {
	        // getter
	        if (t === undefined) { return this.attr('body/lateralArea'); }

	        // setter
	        var isPercentageSetter = isPercentage(t);

	        var bodyAttrs = { lateralArea: t };
	        var topAttrs = isPercentageSetter
	            ? { refCy: t, refRy: t, cy: null, ry: null }
	            : { refCy: null, refRy: null, cy: t, ry: t };

	        return this.attr({ body: bodyAttrs, top: topAttrs }, opt);
	    }

	}, {
	    attributes: {
	        lateralArea: {
	            set: function(t, refBBox) {
	                var isPercentageSetter = isPercentage(t);
	                if (isPercentageSetter) { t = parseFloat(t) / 100; }

	                var x = refBBox.x;
	                var y = refBBox.y;
	                var w = refBBox.width;
	                var h = refBBox.height;

	                // curve control point variables
	                var rx = w / 2;
	                var ry = isPercentageSetter ? (h * t) : t;

	                var kappa = V.KAPPA;
	                var cx = kappa * rx;
	                var cy = kappa * (isPercentageSetter ? (h * t) : t);

	                // shape variables
	                var xLeft = x;
	                var xCenter = x + (w / 2);
	                var xRight = x + w;

	                var ySideTop = y + ry;
	                var yCurveTop = ySideTop - ry;
	                var ySideBottom = y + h - ry;
	                var yCurveBottom = y + h;

	                // return calculated shape
	                var data = [
	                    'M', xLeft, ySideTop,
	                    'L', xLeft, ySideBottom,
	                    'C', x, (ySideBottom + cy), (xCenter - cx), yCurveBottom, xCenter, yCurveBottom,
	                    'C', (xCenter + cx), yCurveBottom, xRight, (ySideBottom + cy), xRight, ySideBottom,
	                    'L', xRight, ySideTop,
	                    'C', xRight, (ySideTop - cy), (xCenter + cx), yCurveTop, xCenter, yCurveTop,
	                    'C', (xCenter - cx), yCurveTop, xLeft, (ySideTop - cy), xLeft, ySideTop,
	                    'Z'
	                ];
	                return { d: data.join(' ') };
	            }
	        }
	    }
	});

	var foLabelMarkup = {
	    tagName: 'foreignObject',
	    selector: 'foreignObject',
	    attributes: {
	        'overflow': 'hidden'
	    },
	    children: [{
	        tagName: 'div',
	        namespaceURI: 'http://www.w3.org/1999/xhtml',
	        selector: 'label',
	        style: {
	            width: '100%',
	            height: '100%',
	            position: 'static',
	            backgroundColor: 'transparent',
	            textAlign: 'center',
	            margin: 0,
	            padding: '0px 5px',
	            boxSizing: 'border-box',
	            display: 'flex',
	            alignItems: 'center',
	            justifyContent: 'center'
	        }
	    }]
	};

	var svgLabelMarkup = {
	    tagName: 'text',
	    selector: 'label',
	    attributes: {
	        'text-anchor': 'middle'
	    }
	};

	var labelMarkup = (env.test('svgforeignobject')) ? foLabelMarkup : svgLabelMarkup;

	var TextBlock$1 = Element$1.define('standard.TextBlock', {
	    attrs: {
	        body: {
	            refWidth: '100%',
	            refHeight: '100%',
	            stroke: '#333333',
	            fill: '#ffffff',
	            strokeWidth: 2
	        },
	        foreignObject: {
	            refWidth: '100%',
	            refHeight: '100%'
	        },
	        label: {
	            style: {
	                fontSize: 14
	            }
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'rect',
	        selector: 'body'
	    }, labelMarkup]
	}, {
	    attributes: {
	        text: {
	            set: function(text, refBBox, node, attrs) {
	                if (node instanceof HTMLElement) {
	                    node.textContent = text;
	                } else {
	                    // No foreign object
	                    var style = attrs.style || {};
	                    var wrapValue = { text: text, width: -5, height: '100%' };
	                    var wrapAttrs = assign({ textVerticalAnchor: 'middle' }, style);
	                    attributes.textWrap.set.call(this, wrapValue, refBBox, node, wrapAttrs);
	                    return { fill: style.color || null };
	                }
	            },
	            position: function(text, refBBox, node) {
	                // No foreign object
	                if (node instanceof SVGElement) { return refBBox.center(); }
	            }
	        }
	    }
	});

	// LINKS

	var Link$1 = Link.define('standard.Link', {
	    attrs: {
	        line: {
	            connection: true,
	            stroke: '#333333',
	            strokeWidth: 2,
	            strokeLinejoin: 'round',
	            targetMarker: {
	                'type': 'path',
	                'd': 'M 10 -5 0 0 10 5 z'
	            }
	        },
	        wrapper: {
	            connection: true,
	            strokeWidth: 10,
	            strokeLinejoin: 'round'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'path',
	        selector: 'wrapper',
	        attributes: {
	            'fill': 'none',
	            'cursor': 'pointer',
	            'stroke': 'transparent',
	            'stroke-linecap': 'round'
	        }
	    }, {
	        tagName: 'path',
	        selector: 'line',
	        attributes: {
	            'fill': 'none',
	            'pointer-events': 'none'
	        }
	    }]
	});

	var DoubleLink = Link.define('standard.DoubleLink', {
	    attrs: {
	        line: {
	            connection: true,
	            stroke: '#DDDDDD',
	            strokeWidth: 4,
	            strokeLinejoin: 'round',
	            targetMarker: {
	                type: 'path',
	                stroke: '#000000',
	                d: 'M 10 -3 10 -10 -2 0 10 10 10 3'
	            }
	        },
	        outline: {
	            connection: true,
	            stroke: '#000000',
	            strokeWidth: 6,
	            strokeLinejoin: 'round'
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'path',
	        selector: 'outline',
	        attributes: {
	            'fill': 'none'
	        }
	    }, {
	        tagName: 'path',
	        selector: 'line',
	        attributes: {
	            'fill': 'none'
	        }
	    }]
	});

	var ShadowLink = Link.define('standard.ShadowLink', {
	    attrs: {
	        line: {
	            connection: true,
	            stroke: '#FF0000',
	            strokeWidth: 20,
	            strokeLinejoin: 'round',
	            targetMarker: {
	                'type': 'path',
	                'stroke': 'none',
	                'd': 'M 0 -10 -10 0 0 10 z'
	            },
	            sourceMarker: {
	                'type': 'path',
	                'stroke': 'none',
	                'd': 'M -10 -10 0 0 -10 10 0 10 0 -10 z'
	            }
	        },
	        shadow: {
	            connection: true,
	            refX: 3,
	            refY: 6,
	            stroke: '#000000',
	            strokeOpacity: 0.2,
	            strokeWidth: 20,
	            strokeLinejoin: 'round',
	            targetMarker: {
	                'type': 'path',
	                'd': 'M 0 -10 -10 0 0 10 z',
	                'stroke': 'none'
	            },
	            sourceMarker: {
	                'type': 'path',
	                'stroke': 'none',
	                'd': 'M -10 -10 0 0 -10 10 0 10 0 -10 z'
	            }
	        }
	    }
	}, {
	    markup: [{
	        tagName: 'path',
	        selector: 'shadow',
	        attributes: {
	            'fill': 'none'
	        }
	    }, {
	        tagName: 'path',
	        selector: 'line',
	        attributes: {
	            'fill': 'none'
	        }
	    }]
	});

	var standard = ({
		Rectangle: Rectangle,
		Circle: Circle$1,
		Ellipse: Ellipse$2,
		Path: Path$2,
		Polygon: Polygon$1,
		Polyline: Polyline$2,
		Image: Image$1,
		BorderedImage: BorderedImage,
		EmbeddedImage: EmbeddedImage,
		InscribedImage: InscribedImage,
		HeaderedRectangle: HeaderedRectangle,
		Cylinder: Cylinder,
		TextBlock: TextBlock$1,
		Link: Link$1,
		DoubleLink: DoubleLink,
		ShadowLink: ShadowLink
	});

	/**
	 * @deprecated use the port api instead
	 */
	var Model = Generic.define('devs.Model', {
	    inPorts: [],
	    outPorts: [],
	    size: {
	        width: 80,
	        height: 80
	    },
	    attrs: {
	        '.': {
	            magnet: false
	        },
	        '.label': {
	            text: 'Model',
	            'ref-x': .5,
	            'ref-y': 10,
	            'font-size': 18,
	            'text-anchor': 'middle',
	            fill: '#000'
	        },
	        '.body': {
	            'ref-width': '100%',
	            'ref-height': '100%',
	            stroke: '#000'
	        }
	    },
	    ports: {
	        groups: {
	            'in': {
	                position: {
	                    name: 'left'
	                },
	                attrs: {
	                    '.port-label': {
	                        fill: '#000'
	                    },
	                    '.port-body': {
	                        fill: '#fff',
	                        stroke: '#000',
	                        r: 10,
	                        magnet: true
	                    }
	                },
	                label: {
	                    position: {
	                        name: 'left',
	                        args: {
	                            y: 10
	                        }
	                    }
	                }
	            },
	            'out': {
	                position: {
	                    name: 'right'
	                },
	                attrs: {
	                    '.port-label': {
	                        fill: '#000'
	                    },
	                    '.port-body': {
	                        fill: '#fff',
	                        stroke: '#000',
	                        r: 10,
	                        magnet: true
	                    }
	                },
	                label: {
	                    position: {
	                        name: 'right',
	                        args: {
	                            y: 10
	                        }
	                    }
	                }
	            }
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><rect class="body"/><text class="label"/></g>',
	    portMarkup: '<circle class="port-body"/>',
	    portLabelMarkup: '<text class="port-label"/>',

	    initialize: function() {

	        Generic.prototype.initialize.apply(this, arguments);

	        this.on('change:inPorts change:outPorts', this.updatePortItems, this);
	        this.updatePortItems();
	    },

	    updatePortItems: function(model, changed, opt) {

	        // Make sure all ports are unique.
	        var inPorts = uniq(this.get('inPorts'));
	        var outPorts = difference(uniq(this.get('outPorts')), inPorts);

	        var inPortItems = this.createPortItems('in', inPorts);
	        var outPortItems = this.createPortItems('out', outPorts);

	        this.prop('ports/items', inPortItems.concat(outPortItems), assign({ rewrite: true }, opt));
	    },

	    createPortItem: function(group, port) {

	        return {
	            id: port,
	            group: group,
	            attrs: {
	                '.port-label': {
	                    text: port
	                }
	            }
	        };
	    },

	    createPortItems: function(group, ports) {

	        return toArray(ports).map(this.createPortItem.bind(this, group));
	    },

	    _addGroupPort: function(port, group, opt) {

	        var ports = this.get(group);
	        return this.set(group, Array.isArray(ports) ? ports.concat(port) : [port], opt);
	    },

	    addOutPort: function(port, opt) {

	        return this._addGroupPort(port, 'outPorts', opt);
	    },

	    addInPort: function(port, opt) {

	        return this._addGroupPort(port, 'inPorts', opt);
	    },

	    _removeGroupPort: function(port, group, opt) {

	        return this.set(group, without(this.get(group), port), opt);
	    },

	    removeOutPort: function(port, opt) {

	        return this._removeGroupPort(port, 'outPorts', opt);
	    },

	    removeInPort: function(port, opt) {

	        return this._removeGroupPort(port, 'inPorts', opt);
	    },

	    _changeGroup: function(group, properties, opt) {

	        return this.prop('ports/groups/' + group, isObject$1(properties) ? properties : {}, opt);
	    },

	    changeInGroup: function(properties, opt) {

	        return this._changeGroup('in', properties, opt);
	    },

	    changeOutGroup: function(properties, opt) {

	        return this._changeGroup('out', properties, opt);
	    }
	});

	var Atomic = Model.define('devs.Atomic', {
	    size: {
	        width: 80,
	        height: 80
	    },
	    attrs: {
	        '.label': {
	            text: 'Atomic'
	        }
	    }
	});

	var Coupled = Model.define('devs.Coupled', {
	    size: {
	        width: 200,
	        height: 300
	    },
	    attrs: {
	        '.label': {
	            text: 'Coupled'
	        }
	    }
	});

	var Link$2 = Link.define('devs.Link', {
	    attrs: {
	        '.connection': {
	            'stroke-width': 2
	        }
	    }
	});

	var devs = ({
		Model: Model,
		Atomic: Atomic,
		Coupled: Coupled,
		Link: Link$2
	});

	var Gate = Generic.define('logic.Gate', {
	    size: { width: 80, height: 40 },
	    attrs: {
	        '.': { magnet: false },
	        '.body': { width: 100, height: 50 },
	        circle: { r: 7, stroke: 'black', fill: 'transparent', 'stroke-width': 2 }
	    }
	}, {
	    operation: function() {
	        return true;
	    }
	});

	var IO = Gate.define('logic.IO', {
	    size: { width: 60, height: 30 },
	    attrs: {
	        '.body': { fill: 'white', stroke: 'black', 'stroke-width': 2 },
	        '.wire': { ref: '.body', 'ref-y': .5, stroke: 'black' },
	        text: {
	            fill: 'black',
	            ref: '.body', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle',
	            'text-anchor': 'middle',
	            'font-weight': 'bold',
	            'font-variant': 'small-caps',
	            'text-transform': 'capitalize',
	            'font-size': '14px'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><rect class="body"/></g><path class="wire"/><circle/><text/></g>',
	});

	var Input = IO.define('logic.Input', {
	    attrs: {
	        '.wire': { 'ref-dx': 0, d: 'M 0 0 L 23 0' },
	        circle: { ref: '.body', 'ref-dx': 30, 'ref-y': 0.5, magnet: true, 'class': 'output', port: 'out' },
	        text: { text: 'input' }
	    }
	});

	var Output = IO.define('logic.Output', {
	    attrs: {
	        '.wire': { 'ref-x': 0, d: 'M 0 0 L -23 0' },
	        circle: { ref: '.body', 'ref-x': -30, 'ref-y': 0.5, magnet: 'passive', 'class': 'input', port: 'in' },
	        text: { text: 'output' }
	    }
	});

	var Gate11 = Gate.define('logic.Gate11', {
	    attrs: {
	        '.input': { ref: '.body', 'ref-x': -2, 'ref-y': 0.5, magnet: 'passive', port: 'in' },
	        '.output': { ref: '.body', 'ref-dx': 2, 'ref-y': 0.5, magnet: true, port: 'out' }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><image class="body"/></g><circle class="input"/><circle class="output"/></g>',
	});

	var Gate21 = Gate.define('logic.Gate21', {
	    attrs: {
	        '.input1': { ref: '.body', 'ref-x': -2, 'ref-y': 0.3, magnet: 'passive', port: 'in1' },
	        '.input2': { ref: '.body', 'ref-x': -2, 'ref-y': 0.7, magnet: 'passive', port: 'in2' },
	        '.output': { ref: '.body', 'ref-dx': 2, 'ref-y': 0.5, magnet: true, port: 'out' }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><image class="body"/></g><circle class="input input1"/><circle  class="input input2"/><circle class="output"/></g>',
	});

	var Repeater = Gate11.define('logic.Repeater', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}
	}, {
	    operation: function(input) {
	        return input;
	    }
	});

	var Not = Gate11.define('logic.Not', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}
	}, {
	    operation: function(input) {
	        return !input;
	    }
	});

	var Or = Gate21.define('logic.Or', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}
	}, {
	    operation: function(input1, input2) {
	        return input1 || input2;
	    }
	});

	var And = Gate21.define('logic.And', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}

	}, {
	    operation: function(input1, input2) {
	        return input1 && input2;
	    }
	});

	var Nor = Gate21.define('logic.Nor', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}
	}, {
	    operation: function(input1, input2) {
	        return !(input1 || input2);
	    }
	});

	var Nand = Gate21.define('logic.Nand', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}
	}, {
	    operation: function(input1, input2) {
	        return !(input1 && input2);
	    }
	});

	var Xor = Gate21.define('logic.Xor', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}
	}, {
	    operation: function(input1, input2) {
	        return (!input1 || input2) && (input1 || !input2);
	    }
	});

	var Xnor = Gate21.define('logic.Xnor', {
	    attrs: { image: { 'xlink:href': 'data:image/svg+xml;base64, ' }}
	}, {
	    operation: function(input1, input2) {
	        return (!input1 || !input2) && (input1 || input2);
	    }
	});

	var Wire = Link.define('logic.Wire', {
	    attrs: {
	        '.connection': { 'stroke-width': 2 },
	        '.marker-vertex': { r: 7 }
	    },

	    router: { name: 'orthogonal' },
	    connector: { name: 'rounded', args: { radius: 10 }}
	}, {
	    arrowheadMarkup: [
	        '<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">',
	        '<circle class="marker-arrowhead" end="<%= end %>" r="7"/>',
	        '</g>'
	    ].join(''),

	    vertexMarkup: [
	        '<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">',
	        '<circle class="marker-vertex" idx="<%= idx %>" r="10" />',
	        '<g class="marker-vertex-remove-group">',
	        '<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>',
	        '<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',
	        '<title>Remove vertex.</title>',
	        '</path>',
	        '</g>',
	        '</g>'
	    ].join('')
	});

	var logic = ({
		Gate: Gate,
		IO: IO,
		Input: Input,
		Output: Output,
		Gate11: Gate11,
		Gate21: Gate21,
		Repeater: Repeater,
		Not: Not,
		Or: Or,
		And: And,
		Nor: Nor,
		Nand: Nand,
		Xor: Xor,
		Xnor: Xnor,
		Wire: Wire
	});

	var KingWhite = Generic.define('chess.KingWhite', {
	    size: { width: 42, height: 38 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;"><path      d="M 22.5,11.63 L 22.5,6"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path      d="M 20,8 L 25,8"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path      d="M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25"      style="fill:#ffffff; stroke:#000000; stroke-linecap:butt; stroke-linejoin:miter;" />    <path      d="M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z "      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 11.5,30 C 17,27 27,27 32.5,30"      style="fill:none; stroke:#000000;" />    <path      d="M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5"      style="fill:none; stroke:#000000;" />    <path      d="M 11.5,37 C 17,34 27,34 32.5,37"      style="fill:none; stroke:#000000;" />  </g></g></g>'
	});

	var KingBlack = Generic.define('chess.KingBlack', {
	    size: { width: 42, height: 38 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path       d="M 22.5,11.63 L 22.5,6"       style="fill:none; stroke:#000000; stroke-linejoin:miter;"       id="path6570" />    <path       d="M 22.5,25 C 22.5,25 27,17.5 25.5,14.5 C 25.5,14.5 24.5,12 22.5,12 C 20.5,12 19.5,14.5 19.5,14.5 C 18,17.5 22.5,25 22.5,25"       style="fill:#000000;fill-opacity:1; stroke-linecap:butt; stroke-linejoin:miter;" />    <path       d="M 11.5,37 C 17,40.5 27,40.5 32.5,37 L 32.5,30 C 32.5,30 41.5,25.5 38.5,19.5 C 34.5,13 25,16 22.5,23.5 L 22.5,27 L 22.5,23.5 C 19,16 9.5,13 6.5,19.5 C 3.5,25.5 11.5,29.5 11.5,29.5 L 11.5,37 z "       style="fill:#000000; stroke:#000000;" />    <path       d="M 20,8 L 25,8"       style="fill:none; stroke:#000000; stroke-linejoin:miter;" />    <path       d="M 32,29.5 C 32,29.5 40.5,25.5 38.03,19.85 C 34.15,14 25,18 22.5,24.5 L 22.51,26.6 L 22.5,24.5 C 20,18 9.906,14 6.997,19.85 C 4.5,25.5 11.85,28.85 11.85,28.85"       style="fill:none; stroke:#ffffff;" />    <path       d="M 11.5,30 C 17,27 27,27 32.5,30 M 11.5,33.5 C 17,30.5 27,30.5 32.5,33.5 M 11.5,37 C 17,34 27,34 32.5,37"       style="fill:none; stroke:#ffffff;" />  </g></g></g>'
	});

	var QueenWhite = Generic.define('chess.QueenWhite', {
	    size: { width: 42, height: 38 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(-1,-1)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(15.5,-5.5)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(32,-1)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(7,-4.5)" />    <path      d="M 9 13 A 2 2 0 1 1  5,13 A 2 2 0 1 1  9 13 z"      transform="translate(24,-4)" />    <path      d="M 9,26 C 17.5,24.5 30,24.5 36,26 L 38,14 L 31,25 L 31,11 L 25.5,24.5 L 22.5,9.5 L 19.5,24.5 L 14,10.5 L 14,25 L 7,14 L 9,26 z "      style="stroke-linecap:butt;" />    <path      d="M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z "      style="stroke-linecap:butt;" />    <path      d="M 11.5,30 C 15,29 30,29 33.5,30"      style="fill:none;" />    <path      d="M 12,33.5 C 18,32.5 27,32.5 33,33.5"      style="fill:none;" />  </g></g></g>'
	});

	var QueenBlack = Generic.define('chess.QueenBlack', {
	    size: { width: 42, height: 38 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#000000; stroke:none;">      <circle cx="6"    cy="12" r="2.75" />      <circle cx="14"   cy="9"  r="2.75" />      <circle cx="22.5" cy="8"  r="2.75" />      <circle cx="31"   cy="9"  r="2.75" />      <circle cx="39"   cy="12" r="2.75" />    </g>    <path       d="M 9,26 C 17.5,24.5 30,24.5 36,26 L 38.5,13.5 L 31,25 L 30.7,10.9 L 25.5,24.5 L 22.5,10 L 19.5,24.5 L 14.3,10.9 L 14,25 L 6.5,13.5 L 9,26 z"       style="stroke-linecap:butt; stroke:#000000;" />    <path       d="M 9,26 C 9,28 10.5,28 11.5,30 C 12.5,31.5 12.5,31 12,33.5 C 10.5,34.5 10.5,36 10.5,36 C 9,37.5 11,38.5 11,38.5 C 17.5,39.5 27.5,39.5 34,38.5 C 34,38.5 35.5,37.5 34,36 C 34,36 34.5,34.5 33,33.5 C 32.5,31 32.5,31.5 33.5,30 C 34.5,28 36,28 36,26 C 27.5,24.5 17.5,24.5 9,26 z"       style="stroke-linecap:butt;" />    <path       d="M 11,38.5 A 35,35 1 0 0 34,38.5"       style="fill:none; stroke:#000000; stroke-linecap:butt;" />    <path       d="M 11,29 A 35,35 1 0 1 34,29"       style="fill:none; stroke:#ffffff;" />    <path       d="M 12.5,31.5 L 32.5,31.5"       style="fill:none; stroke:#ffffff;" />    <path       d="M 11.5,34.5 A 35,35 1 0 0 33.5,34.5"       style="fill:none; stroke:#ffffff;" />    <path       d="M 10.5,37.5 A 35,35 1 0 0 34.5,37.5"       style="fill:none; stroke:#ffffff;" />  </g></g></g>'
	});

	var RookWhite = Generic.define('chess.RookWhite', {
	    size: { width: 32, height: 34 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z "      style="stroke-linecap:butt;" />    <path      d="M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z "      style="stroke-linecap:butt;" />    <path      d="M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14"      style="stroke-linecap:butt;" />    <path      d="M 34,14 L 31,17 L 14,17 L 11,14" />    <path      d="M 31,17 L 31,29.5 L 14,29.5 L 14,17"      style="stroke-linecap:butt; stroke-linejoin:miter;" />    <path      d="M 31,29.5 L 32.5,32 L 12.5,32 L 14,29.5" />    <path      d="M 11,14 L 34,14"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />  </g></g></g>'
	});

	var RookBlack = Generic.define('chess.RookBlack', {
	    size: { width: 32, height: 34 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 9,39 L 36,39 L 36,36 L 9,36 L 9,39 z "      style="stroke-linecap:butt;" />    <path      d="M 12.5,32 L 14,29.5 L 31,29.5 L 32.5,32 L 12.5,32 z "      style="stroke-linecap:butt;" />    <path      d="M 12,36 L 12,32 L 33,32 L 33,36 L 12,36 z "      style="stroke-linecap:butt;" />    <path      d="M 14,29.5 L 14,16.5 L 31,16.5 L 31,29.5 L 14,29.5 z "      style="stroke-linecap:butt;stroke-linejoin:miter;" />    <path      d="M 14,16.5 L 11,14 L 34,14 L 31,16.5 L 14,16.5 z "      style="stroke-linecap:butt;" />    <path      d="M 11,14 L 11,9 L 15,9 L 15,11 L 20,11 L 20,9 L 25,9 L 25,11 L 30,11 L 30,9 L 34,9 L 34,14 L 11,14 z "      style="stroke-linecap:butt;" />    <path      d="M 12,35.5 L 33,35.5 L 33,35.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 13,31.5 L 32,31.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 14,29.5 L 31,29.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 14,16.5 L 31,16.5"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />    <path      d="M 11,14 L 34,14"      style="fill:none; stroke:#ffffff; stroke-width:1; stroke-linejoin:miter;" />  </g></g></g>'
	});

	var BishopWhite = Generic.define('chess.BishopWhite', {
	    size: { width: 38, height: 38 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-rule:evenodd; fill-opacity:1; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:round; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#ffffff; stroke:#000000; stroke-linecap:butt;">       <path        d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />      <path        d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />      <path        d="M 25 8 A 2.5 2.5 0 1 1  20,8 A 2.5 2.5 0 1 1  25 8 z" />    </g>    <path      d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"      style="fill:none; stroke:#000000; stroke-linejoin:miter;" />  </g></g></g>'
	});

	var BishopBlack = Generic.define('chess.BishopBlack', {
	    size: { width: 38, height: 38 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-rule:evenodd; fill-opacity:1; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:round; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <g style="fill:#000000; stroke:#000000; stroke-linecap:butt;">       <path        d="M 9,36 C 12.39,35.03 19.11,36.43 22.5,34 C 25.89,36.43 32.61,35.03 36,36 C 36,36 37.65,36.54 39,38 C 38.32,38.97 37.35,38.99 36,38.5 C 32.61,37.53 25.89,38.96 22.5,37.5 C 19.11,38.96 12.39,37.53 9,38.5 C 7.646,38.99 6.677,38.97 6,38 C 7.354,36.06 9,36 9,36 z" />      <path        d="M 15,32 C 17.5,34.5 27.5,34.5 30,32 C 30.5,30.5 30,30 30,30 C 30,27.5 27.5,26 27.5,26 C 33,24.5 33.5,14.5 22.5,10.5 C 11.5,14.5 12,24.5 17.5,26 C 17.5,26 15,27.5 15,30 C 15,30 14.5,30.5 15,32 z" />      <path        d="M 25 8 A 2.5 2.5 0 1 1  20,8 A 2.5 2.5 0 1 1  25 8 z" />    </g>    <path       d="M 17.5,26 L 27.5,26 M 15,30 L 30,30 M 22.5,15.5 L 22.5,20.5 M 20,18 L 25,18"       style="fill:none; stroke:#ffffff; stroke-linejoin:miter;" />  </g></g></g>'
	});

	var KnightWhite = Generic.define('chess.KnightWhite', {
	    size: { width: 38, height: 37 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18"      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10"      style="fill:#ffffff; stroke:#000000;" />    <path      d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z"      style="fill:#000000; stroke:#000000;" />    <path      d="M 15 15.5 A 0.5 1.5 0 1 1  14,15.5 A 0.5 1.5 0 1 1  15 15.5 z"      transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)"      style="fill:#000000; stroke:#000000;" />  </g></g></g>'
	});

	var KnightBlack = Generic.define('chess.KnightBlack', {
	    size: { width: 38, height: 37 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><g style="opacity:1; fill:none; fill-opacity:1; fill-rule:evenodd; stroke:#000000; stroke-width:1.5; stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;">    <path      d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18"      style="fill:#000000; stroke:#000000;" />    <path      d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,9.506 13.5,8.5 13.5,7.5 C 14.5,6.5 16.5,10 16.5,10 L 18.5,10 C 18.5,10 19.28,8.008 21,7 C 22,7 22,10 22,10"      style="fill:#000000; stroke:#000000;" />    <path      d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z"      style="fill:#ffffff; stroke:#ffffff;" />    <path      d="M 15 15.5 A 0.5 1.5 0 1 1  14,15.5 A 0.5 1.5 0 1 1  15 15.5 z"      transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)"      style="fill:#ffffff; stroke:#ffffff;" />    <path      d="M 24.55,10.4 L 24.1,11.85 L 24.6,12 C 27.75,13 30.25,14.49 32.5,18.75 C 34.75,23.01 35.75,29.06 35.25,39 L 35.2,39.5 L 37.45,39.5 L 37.5,39 C 38,28.94 36.62,22.15 34.25,17.66 C 31.88,13.17 28.46,11.02 25.06,10.5 L 24.55,10.4 z "      style="fill:#ffffff; stroke:none;" />  </g></g></g>'
	});

	var PawnWhite = Generic.define('chess.PawnWhite', {
	    size: { width: 28, height: 33 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><path d="M 22,9 C 19.79,9 18,10.79 18,13 C 18,13.89 18.29,14.71 18.78,15.38 C 16.83,16.5 15.5,18.59 15.5,21 C 15.5,23.03 16.44,24.84 17.91,26.03 C 14.91,27.09 10.5,31.58 10.5,39.5 L 33.5,39.5 C 33.5,31.58 29.09,27.09 26.09,26.03 C 27.56,24.84 28.5,23.03 28.5,21 C 28.5,18.59 27.17,16.5 25.22,15.38 C 25.71,14.71 26,13.89 26,13 C 26,10.79 24.21,9 22,9 z "  style="opacity:1; fill:#ffffff; fill-opacity:1; fill-rule:nonzero; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:miter; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;" /></g></g>'
	});

	var PawnBlack = Generic.define('chess.PawnBlack', {
	    size: { width: 28, height: 33 }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><path d="M 22,9 C 19.79,9 18,10.79 18,13 C 18,13.89 18.29,14.71 18.78,15.38 C 16.83,16.5 15.5,18.59 15.5,21 C 15.5,23.03 16.44,24.84 17.91,26.03 C 14.91,27.09 10.5,31.58 10.5,39.5 L 33.5,39.5 C 33.5,31.58 29.09,27.09 26.09,26.03 C 27.56,24.84 28.5,23.03 28.5,21 C 28.5,18.59 27.17,16.5 25.22,15.38 C 25.71,14.71 26,13.89 26,13 C 26,10.79 24.21,9 22,9 z "  style="opacity:1; fill:#000000; fill-opacity:1; fill-rule:nonzero; stroke:#000000; stroke-width:1.5; stroke-linecap:round; stroke-linejoin:miter; stroke-miterlimit:4; stroke-dasharray:none; stroke-opacity:1;" /></g></g>'
	});

	var chess = ({
		KingWhite: KingWhite,
		KingBlack: KingBlack,
		QueenWhite: QueenWhite,
		QueenBlack: QueenBlack,
		RookWhite: RookWhite,
		RookBlack: RookBlack,
		BishopWhite: BishopWhite,
		BishopBlack: BishopBlack,
		KnightWhite: KnightWhite,
		KnightBlack: KnightBlack,
		PawnWhite: PawnWhite,
		PawnBlack: PawnBlack
	});

	var Entity = Element$1.define('erd.Entity', {
	    size: { width: 150, height: 60 },
	    attrs: {
	        '.outer': {
	            fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2,
	            points: '100,0 100,60 0,60 0,0'
	        },
	        '.inner': {
	            fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2,
	            points: '95,5 95,55 5,55 5,5',
	            display: 'none'
	        },
	        text: {
	            text: 'Entity',
	            'font-family': 'Arial', 'font-size': 14,
	            'ref-x': .5, 'ref-y': .5,
	            'y-alignment': 'middle', 'text-anchor': 'middle'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',
	});

	var WeakEntity = Entity.define('erd.WeakEntity', {
	    attrs: {
	        '.inner': { display: 'auto' },
	        text: { text: 'Weak Entity' }
	    }
	});

	var Relationship = Element$1.define('erd.Relationship', {
	    size: { width: 80, height: 80 },
	    attrs: {
	        '.outer': {
	            fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2,
	            points: '40,0 80,40 40,80 0,40'
	        },
	        '.inner': {
	            fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2,
	            points: '40,5 75,40 40,75 5,40',
	            display: 'none'
	        },
	        text: {
	            text: 'Relationship',
	            'font-family': 'Arial', 'font-size': 12,
	            'ref-x': .5, 'ref-y': .5,
	            'y-alignment': 'middle', 'text-anchor': 'middle'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>',
	});

	var IdentifyingRelationship = Relationship.define('erd.IdentifyingRelationship', {
	    attrs: {
	        '.inner': { display: 'auto' },
	        text: { text: 'Identifying' }
	    }
	});

	var Attribute = Element$1.define('erd.Attribute', {
	    size: { width: 100, height: 50 },
	    attrs: {
	        'ellipse': {
	            transform: 'translate(50, 25)'
	        },
	        '.outer': {
	            stroke: '#D35400', 'stroke-width': 2,
	            cx: 0, cy: 0, rx: 50, ry: 25,
	            fill: '#E67E22'
	        },
	        '.inner': {
	            stroke: '#D35400', 'stroke-width': 2,
	            cx: 0, cy: 0, rx: 45, ry: 20,
	            fill: '#E67E22', display: 'none'
	        },
	        text: {
	            'font-family': 'Arial', 'font-size': 14,
	            'ref-x': .5, 'ref-y': .5,
	            'y-alignment': 'middle', 'text-anchor': 'middle'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><ellipse class="outer"/><ellipse class="inner"/></g><text/></g>',
	});

	var Multivalued = Attribute.define('erd.Multivalued', {
	    attrs: {
	        '.inner': { display: 'block' },
	        text: { text: 'multivalued' }
	    }
	});

	var Derived = Attribute.define('erd.Derived', {
	    attrs: {
	        '.outer': { 'stroke-dasharray': '3,5' },
	        text: { text: 'derived' }
	    }
	});

	var Key = Attribute.define('erd.Key', {
	    attrs: {
	        ellipse: { 'stroke-width': 4 },
	        text: { text: 'key', 'font-weight': '800', 'text-decoration': 'underline' }
	    }
	});

	var Normal = Attribute.define('erd.Normal', {
	    attrs: { text: { text: 'Normal' }}
	});

	var ISA = Element$1.define('erd.ISA', {
	    type: 'erd.ISA',
	    size: { width: 100, height: 50 },
	    attrs: {
	        polygon: {
	            points: '0,0 50,50 100,0',
	            fill: '#F1C40F', stroke: '#F39C12', 'stroke-width': 2
	        },
	        text: {
	            text: 'ISA', 'font-size': 18,
	            'ref-x': .5, 'ref-y': .3,
	            'y-alignment': 'middle', 'text-anchor': 'middle'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>',
	});

	var Line$1 = Link.define('erd.Line', {}, {
	    cardinality: function(value) {
	        this.set('labels', [{ position: -20, attrs: { text: { dy: -8, text: value }}}]);
	    }
	});

	var erd = ({
		Entity: Entity,
		WeakEntity: WeakEntity,
		Relationship: Relationship,
		IdentifyingRelationship: IdentifyingRelationship,
		Attribute: Attribute,
		Multivalued: Multivalued,
		Derived: Derived,
		Key: Key,
		Normal: Normal,
		ISA: ISA,
		Line: Line$1
	});

	var State = Circle.define('fsa.State', {
	    attrs: {
	        circle: { 'stroke-width': 3 },
	        text: { 'font-weight': '800' }
	    }
	});

	var StartState = Element$1.define('fsa.StartState', {
	    size: { width: 20, height: 20 },
	    attrs: {
	        circle: {
	            transform: 'translate(10, 10)',
	            r: 10,
	            fill: '#000000'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><circle/></g></g>',
	});

	var EndState = Element$1.define('fsa.EndState', {
	    size: { width: 20, height: 20 },
	    attrs: {
	        '.outer': {
	            transform: 'translate(10, 10)',
	            r: 10,
	            fill: '#ffffff',
	            stroke: '#000000'
	        },

	        '.inner': {
	            transform: 'translate(10, 10)',
	            r: 6,
	            fill: '#000000'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
	});

	var Arrow = Link.define('fsa.Arrow', {
	    attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }},
	    smooth: true
	});

	var fsa = ({
		State: State,
		StartState: StartState,
		EndState: EndState,
		Arrow: Arrow
	});

	var Member = Element$1.define('org.Member', {
	    size: { width: 180, height: 70 },
	    attrs: {
	        rect: { width: 170, height: 60 },

	        '.card': {
	            fill: '#FFFFFF', stroke: '#000000', 'stroke-width': 2,
	            'pointer-events': 'visiblePainted', rx: 10, ry: 10
	        },

	        image: {
	            width: 48, height: 48,
	            ref: '.card', 'ref-x': 10, 'ref-y': 5
	        },

	        '.rank': {
	            'text-decoration': 'underline',
	            ref: '.card', 'ref-x': 0.9, 'ref-y': 0.2,
	            'font-family': 'Courier New', 'font-size': 14,
	            'text-anchor': 'end'
	        },

	        '.name': {
	            'font-weight': '800',
	            ref: '.card', 'ref-x': 0.9, 'ref-y': 0.6,
	            'font-family': 'Courier New', 'font-size': 14,
	            'text-anchor': 'end'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><rect class="card"/><image/></g><text class="rank"/><text class="name"/></g>',
	});

	var Arrow$1 = Link.define('org.Arrow', {
	    source: { selector: '.card' }, target: { selector: '.card' },
	    attrs: { '.connection': { stroke: '#585858', 'stroke-width': 3 }},
	    z: -1
	});

	var org = ({
		Member: Member,
		Arrow: Arrow$1
	});

	var Place = Generic.define('pn.Place', {
	    size: { width: 50, height: 50 },
	    attrs: {
	        '.root': {
	            r: 25,
	            fill: '#ffffff',
	            stroke: '#000000',
	            transform: 'translate(25, 25)'
	        },
	        '.label': {
	            'text-anchor': 'middle',
	            'ref-x': .5,
	            'ref-y': -20,
	            ref: '.root',
	            fill: '#000000',
	            'font-size': 12
	        },
	        '.tokens > circle': {
	            fill: '#000000',
	            r: 5
	        },
	        '.tokens.one > circle': { transform: 'translate(25, 25)' },

	        '.tokens.two > circle:nth-child(1)': { transform: 'translate(19, 25)' },
	        '.tokens.two > circle:nth-child(2)': { transform: 'translate(31, 25)' },

	        '.tokens.three > circle:nth-child(1)': { transform: 'translate(18, 29)' },
	        '.tokens.three > circle:nth-child(2)': { transform: 'translate(25, 19)' },
	        '.tokens.three > circle:nth-child(3)': { transform: 'translate(32, 29)' },

	        '.tokens.alot > text': {
	            transform: 'translate(25, 18)',
	            'text-anchor': 'middle',
	            fill: '#000000'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><circle class="root"/><g class="tokens" /></g><text class="label"/></g>',
	});

	var PlaceView = ElementView.extend({

	    presentationAttributes: ElementView.addPresentationAttributes({
	        tokens: ['TOKENS']
	    }),

	    initFlag: ElementView.prototype.initFlag.concat(['TOKENS']),

	    confirmUpdate: function() {
	        var ref;

	        var args = [], len = arguments.length;
	        while ( len-- ) args[ len ] = arguments[ len ];
	        var flags = (ref = ElementView.prototype.confirmUpdate).call.apply(ref, [ this ].concat( args ));
	        if (this.hasFlag(flags, 'TOKENS')) {
	            this.renderTokens();
	            this.update();
	            flags = this.removeFlag(flags, 'TOKENS');
	        }
	        return flags;
	    },

	    renderTokens: function() {

	        var vTokens = this.vel.findOne('.tokens').empty();
	        ['one', 'two', 'three', 'alot'].forEach(function(className) {
	            vTokens.removeClass(className);
	        });

	        var tokens = this.model.get('tokens');
	        if (!tokens) { return; }

	        switch (tokens) {

	            case 1:
	                vTokens.addClass('one');
	                vTokens.append(V('circle'));
	                break;

	            case 2:
	                vTokens.addClass('two');
	                vTokens.append([V('circle'), V('circle')]);
	                break;

	            case 3:
	                vTokens.addClass('three');
	                vTokens.append([V('circle'), V('circle'), V('circle')]);
	                break;

	            default:
	                vTokens.addClass('alot');
	                vTokens.append(V('text').text(tokens + ''));
	                break;
	        }
	    }
	});

	var Transition = Generic.define('pn.Transition', {
	    size: { width: 12, height: 50 },
	    attrs: {
	        'rect': {
	            width: 12,
	            height: 50,
	            fill: '#000000',
	            stroke: '#000000'
	        },
	        '.label': {
	            'text-anchor': 'middle',
	            'ref-x': .5,
	            'ref-y': -20,
	            ref: 'rect',
	            fill: '#000000',
	            'font-size': 12
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><rect class="root"/></g></g><text class="label"/>',
	});

	var Link$3 = Link.define('pn.Link', {
	    attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }}
	});

	var pn = ({
		Place: Place,
		PlaceView: PlaceView,
		Transition: Transition,
		Link: Link$3
	});

	var Class = Generic.define('uml.Class', {
	    attrs: {
	        rect: { 'width': 200 },

	        '.uml-class-name-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#3498db' },
	        '.uml-class-attrs-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' },
	        '.uml-class-methods-rect': { 'stroke': 'black', 'stroke-width': 2, 'fill': '#2980b9' },

	        '.uml-class-name-text': {
	            'ref': '.uml-class-name-rect',
	            'ref-y': .5,
	            'ref-x': .5,
	            'text-anchor': 'middle',
	            'y-alignment': 'middle',
	            'font-weight': 'bold',
	            'fill': 'black',
	            'font-size': 12,
	            'font-family': 'Times New Roman'
	        },
	        '.uml-class-attrs-text': {
	            'ref': '.uml-class-attrs-rect', 'ref-y': 5, 'ref-x': 5,
	            'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
	        },
	        '.uml-class-methods-text': {
	            'ref': '.uml-class-methods-rect', 'ref-y': 5, 'ref-x': 5,
	            'fill': 'black', 'font-size': 12, 'font-family': 'Times New Roman'
	        }
	    },

	    name: [],
	    attributes: [],
	    methods: []
	}, {
	    markup: [
	        '<g class="rotatable">',
	        '<g class="scalable">',
	        '<rect class="uml-class-name-rect"/><rect class="uml-class-attrs-rect"/><rect class="uml-class-methods-rect"/>',
	        '</g>',
	        '<text class="uml-class-name-text"/><text class="uml-class-attrs-text"/><text class="uml-class-methods-text"/>',
	        '</g>'
	    ].join(''),

	    initialize: function() {

	        this.on('change:name change:attributes change:methods', function() {
	            this.updateRectangles();
	            this.trigger('uml-update');
	        }, this);

	        this.updateRectangles();

	        Generic.prototype.initialize.apply(this, arguments);
	    },

	    getClassName: function() {
	        return this.get('name');
	    },

	    updateRectangles: function() {

	        var attrs = this.get('attrs');

	        var rects = [
	            { type: 'name', text: this.getClassName() },
	            { type: 'attrs', text: this.get('attributes') },
	            { type: 'methods', text: this.get('methods') }
	        ];

	        var offsetY = 0;

	        rects.forEach(function(rect) {

	            var lines = Array.isArray(rect.text) ? rect.text : [rect.text];
	            var rectHeight = lines.length * 20 + 20;

	            attrs['.uml-class-' + rect.type + '-text'].text = lines.join('\n');
	            attrs['.uml-class-' + rect.type + '-rect'].height = rectHeight;
	            attrs['.uml-class-' + rect.type + '-rect'].transform = 'translate(0,' + offsetY + ')';

	            offsetY += rectHeight;
	        });
	    }

	});

	var ClassView = ElementView.extend({

	    initialize: function() {

	        ElementView.prototype.initialize.apply(this, arguments);

	        this.listenTo(this.model, 'uml-update', function() {
	            this.update();
	            this.resize();
	        });
	    }
	});

	var Abstract = Class.define('uml.Abstract', {
	    attrs: {
	        '.uml-class-name-rect': { fill: '#e74c3c' },
	        '.uml-class-attrs-rect': { fill: '#c0392b' },
	        '.uml-class-methods-rect': { fill: '#c0392b' }
	    }
	}, {

	    getClassName: function() {
	        return ['<<Abstract>>', this.get('name')];
	    }

	});
	var AbstractView = ClassView;

	var Interface = Class.define('uml.Interface', {
	    attrs: {
	        '.uml-class-name-rect': { fill: '#f1c40f' },
	        '.uml-class-attrs-rect': { fill: '#f39c12' },
	        '.uml-class-methods-rect': { fill: '#f39c12' }
	    }
	}, {
	    getClassName: function() {
	        return ['<<Interface>>', this.get('name')];
	    }
	});
	var InterfaceView = ClassView;

	var Generalization = Link.define('uml.Generalization', {
	    attrs: { '.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' }}
	});

	var Implementation = Link.define('uml.Implementation', {
	    attrs: {
	        '.marker-target': { d: 'M 20 0 L 0 10 L 20 20 z', fill: 'white' },
	        '.connection': { 'stroke-dasharray': '3,3' }
	    }
	});

	var Aggregation = Link.define('uml.Aggregation', {
	    attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'white' }}
	});

	var Composition = Link.define('uml.Composition', {
	    attrs: { '.marker-target': { d: 'M 40 10 L 20 20 L 0 10 L 20 0 z', fill: 'black' }}
	});

	var Association = Link.define('uml.Association');

	// Statechart

	var State$1 = Generic.define('uml.State', {
	    attrs: {
	        '.uml-state-body': {
	            'width': 200, 'height': 200, 'rx': 10, 'ry': 10,
	            'fill': '#ecf0f1', 'stroke': '#bdc3c7', 'stroke-width': 3
	        },
	        '.uml-state-separator': {
	            'stroke': '#bdc3c7', 'stroke-width': 2
	        },
	        '.uml-state-name': {
	            'ref': '.uml-state-body', 'ref-x': .5, 'ref-y': 5, 'text-anchor': 'middle',
	            'fill': '#000000', 'font-family': 'Courier New', 'font-size': 14
	        },
	        '.uml-state-events': {
	            'ref': '.uml-state-separator', 'ref-x': 5, 'ref-y': 5,
	            'fill': '#000000', 'font-family': 'Courier New', 'font-size': 14
	        }
	    },

	    name: 'State',
	    events: []

	}, {
	    markup: [
	        '<g class="rotatable">',
	        '<g class="scalable">',
	        '<rect class="uml-state-body"/>',
	        '</g>',
	        '<path class="uml-state-separator"/>',
	        '<text class="uml-state-name"/>',
	        '<text class="uml-state-events"/>',
	        '</g>'
	    ].join(''),

	    initialize: function() {

	        this.on({
	            'change:name': this.updateName,
	            'change:events': this.updateEvents,
	            'change:size': this.updatePath
	        }, this);

	        this.updateName();
	        this.updateEvents();
	        this.updatePath();

	        Generic.prototype.initialize.apply(this, arguments);
	    },

	    updateName: function() {

	        this.attr('.uml-state-name/text', this.get('name'));
	    },

	    updateEvents: function() {

	        this.attr('.uml-state-events/text', this.get('events').join('\n'));
	    },

	    updatePath: function() {

	        var d = 'M 0 20 L ' + this.get('size').width + ' 20';

	        // We are using `silent: true` here because updatePath() is meant to be called
	        // on resize and there's no need to to update the element twice (`change:size`
	        // triggers also an update).
	        this.attr('.uml-state-separator/d', d, { silent: true });
	    }
	});

	var StartState$1 = Circle.define('uml.StartState', {
	    type: 'uml.StartState',
	    attrs: { circle: { 'fill': '#34495e', 'stroke': '#2c3e50', 'stroke-width': 2, 'rx': 1 }}
	});

	var EndState$1 = Generic.define('uml.EndState', {
	    size: { width: 20, height: 20 },
	    attrs: {
	        'circle.outer': {
	            transform: 'translate(10, 10)',
	            r: 10,
	            fill: '#ffffff',
	            stroke: '#2c3e50'
	        },

	        'circle.inner': {
	            transform: 'translate(10, 10)',
	            r: 6,
	            fill: '#34495e'
	        }
	    }
	}, {
	    markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
	});

	var Transition$1 = Link.define('uml.Transition', {
	    attrs: {
	        '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z', fill: '#34495e', stroke: '#2c3e50' },
	        '.connection': { stroke: '#2c3e50' }
	    }
	});

	var uml = ({
		Class: Class,
		ClassView: ClassView,
		Abstract: Abstract,
		AbstractView: AbstractView,
		Interface: Interface,
		InterfaceView: InterfaceView,
		Generalization: Generalization,
		Implementation: Implementation,
		Aggregation: Aggregation,
		Composition: Composition,
		Association: Association,
		State: State$1,
		StartState: StartState$1,
		EndState: EndState$1,
		Transition: Transition$1
	});



	var index$3 = ({
		basic: basic,
		standard: standard,
		devs: devs,
		logic: logic,
		chess: chess,
		erd: erd,
		fsa: fsa,
		org: org,
		pn: pn,
		uml: uml
	});

	function abs2rel(value, max) {

	    if (max === 0) { return '0%'; }
	    return Math.round(value / max * 100) + '%';
	}

	function pin(relative) {

	    return function(end, view, magnet, coords) {
	        var fn = (view.isNodeConnection(magnet)) ? pinnedLinkEnd : pinnedElementEnd;
	        return fn(relative, end, view, magnet, coords);
	    };
	}

	function pinnedElementEnd(relative, end, view, magnet, coords) {

	    var angle = view.model.angle();
	    var bbox = view.getNodeUnrotatedBBox(magnet);
	    var origin = view.model.getBBox().center();
	    coords.rotate(origin, angle);
	    var dx = coords.x - bbox.x;
	    var dy = coords.y - bbox.y;

	    if (relative) {
	        dx = abs2rel(dx, bbox.width);
	        dy = abs2rel(dy, bbox.height);
	    }

	    end.anchor = {
	        name: 'topLeft',
	        args: {
	            dx: dx,
	            dy: dy,
	            rotate: true
	        }
	    };

	    return end;
	}

	function pinnedLinkEnd(relative, end, view, _magnet, coords) {

	    var connection = view.getConnection();
	    if (!connection) { return end; }
	    var length = connection.closestPointLength(coords);
	    if (relative) {
	        var totalLength = connection.length();
	        end.anchor = {
	            name: 'connectionRatio',
	            args: {
	                ratio: length / totalLength
	            }
	        };
	    } else {
	        end.anchor = {
	            name: 'connectionLength',
	            args: {
	                length: length
	            }
	        };
	    }
	    return end;
	}

	var useDefaults = noop;
	var pinAbsolute = pin(false);
	var pinRelative = pin(true);

	var index$4 = ({
		useDefaults: useDefaults,
		pinAbsolute: pinAbsolute,
		pinRelative: pinRelative
	});

	function getAnchor(coords, view, magnet) {
	    // take advantage of an existing logic inside of the
	    // pin relative connection strategy
	    var end = pinRelative.call(
	        this.paper,
	        {},
	        view,
	        magnet,
	        coords,
	        this.model
	    );
	    return end.anchor;
	}

	function snapAnchor(coords, view, magnet, type, relatedView, toolView) {
	    var snapRadius = toolView.options.snapRadius;
	    var isSource = (type === 'source');
	    var refIndex = (isSource ? 0 : -1);
	    var ref = this.model.vertex(refIndex) || this.getEndAnchor(isSource ? 'target' : 'source');
	    if (ref) {
	        if (Math.abs(ref.x - coords.x) < snapRadius) { coords.x = ref.x; }
	        if (Math.abs(ref.y - coords.y) < snapRadius) { coords.y = ref.y; }
	    }
	    return coords;
	}

	function getViewBBox(view, useModelGeometry) {
	    var model = view.model;
	    if (useModelGeometry) { return model.getBBox(); }
	    return (model.isLink()) ? view.getConnection().bbox() : view.getNodeUnrotatedBBox(view.el);
	}

	// Vertex Handles
	var VertexHandle = View.extend({
	    tagName: 'circle',
	    svgElement: true,
	    className: 'marker-vertex',
	    events: {
	        mousedown: 'onPointerDown',
	        touchstart: 'onPointerDown',
	        dblclick: 'onDoubleClick'
	    },
	    documentEvents: {
	        mousemove: 'onPointerMove',
	        touchmove: 'onPointerMove',
	        mouseup: 'onPointerUp',
	        touchend: 'onPointerUp',
	        touchcancel: 'onPointerUp'
	    },
	    attributes: {
	        'r': 6,
	        'fill': '#33334F',
	        'stroke': '#FFFFFF',
	        'stroke-width': 2,
	        'cursor': 'move'
	    },
	    position: function(x, y) {
	        this.vel.attr({ cx: x, cy: y });
	    },
	    onPointerDown: function(evt) {
	        if (this.options.guard(evt)) { return; }
	        evt.stopPropagation();
	        evt.preventDefault();
	        this.options.paper.undelegateEvents();
	        this.delegateDocumentEvents(null, evt.data);
	        this.trigger('will-change', this, evt);
	    },
	    onPointerMove: function(evt) {
	        this.trigger('changing', this, evt);
	    },
	    onDoubleClick: function(evt) {
	        this.trigger('remove', this, evt);
	    },
	    onPointerUp: function(evt) {
	        this.trigger('changed', this, evt);
	        this.undelegateDocumentEvents();
	        this.options.paper.delegateEvents();
	    }
	});

	var Vertices = ToolView.extend({
	    name: 'vertices',
	    options: {
	        handleClass: VertexHandle,
	        snapRadius: 20,
	        redundancyRemoval: true,
	        vertexAdding: true,
	        stopPropagation: true
	    },
	    children: [{
	        tagName: 'path',
	        selector: 'connection',
	        className: 'joint-vertices-path',
	        attributes: {
	            'fill': 'none',
	            'stroke': 'transparent',
	            'stroke-width': 10,
	            'cursor': 'cell'
	        }
	    }],
	    handles: null,
	    events: {
	        'mousedown .joint-vertices-path': 'onPathPointerDown',
	        'touchstart .joint-vertices-path': 'onPathPointerDown'
	    },
	    onRender: function() {
	        if (this.options.vertexAdding) {
	            this.renderChildren();
	            this.updatePath();
	        }
	        this.resetHandles();
	        this.renderHandles();
	        return this;
	    },
	    update: function() {
	        var relatedView = this.relatedView;
	        var vertices = relatedView.model.vertices();
	        if (vertices.length === this.handles.length) {
	            this.updateHandles();
	        } else {
	            this.resetHandles();
	            this.renderHandles();
	        }
	        if (this.options.vertexAdding) {
	            this.updatePath();
	        }
	        return this;
	    },
	    resetHandles: function() {
	        var handles = this.handles;
	        this.handles = [];
	        this.stopListening();
	        if (!Array.isArray(handles)) { return; }
	        for (var i = 0, n = handles.length; i < n; i++) {
	            handles[i].remove();
	        }
	    },
	    renderHandles: function() {
	        var this$1 = this;

	        var relatedView = this.relatedView;
	        var vertices = relatedView.model.vertices();
	        for (var i = 0, n = vertices.length; i < n; i++) {
	            var vertex = vertices[i];
	            var handle = new (this.options.handleClass)({
	                index: i,
	                paper: this.paper,
	                guard: function (evt) { return this$1.guard(evt); }
	            });
	            handle.render();
	            handle.position(vertex.x, vertex.y);
	            this.simulateRelatedView(handle.el);
	            handle.vel.appendTo(this.el);
	            this.handles.push(handle);
	            this.startHandleListening(handle);
	        }
	    },
	    updateHandles: function() {
	        var relatedView = this.relatedView;
	        var vertices = relatedView.model.vertices();
	        for (var i = 0, n = vertices.length; i < n; i++) {
	            var vertex = vertices[i];
	            var handle = this.handles[i];
	            if (!handle) { return; }
	            handle.position(vertex.x, vertex.y);
	        }
	    },
	    updatePath: function() {
	        var connection = this.childNodes.connection;
	        if (connection) { connection.setAttribute('d', this.relatedView.getSerializedConnection()); }
	    },
	    startHandleListening: function(handle) {
	        var relatedView = this.relatedView;
	        if (relatedView.can('vertexMove')) {
	            this.listenTo(handle, 'will-change', this.onHandleWillChange);
	            this.listenTo(handle, 'changing', this.onHandleChanging);
	            this.listenTo(handle, 'changed', this.onHandleChanged);
	        }
	        if (relatedView.can('vertexRemove')) {
	            this.listenTo(handle, 'remove', this.onHandleRemove);
	        }
	    },
	    getNeighborPoints: function(index) {
	        var linkView = this.relatedView;
	        var vertices = linkView.model.vertices();
	        var prev = (index > 0) ? vertices[index - 1] : linkView.sourceAnchor;
	        var next = (index < vertices.length - 1) ? vertices[index + 1] : linkView.targetAnchor;
	        return {
	            prev: new Point(prev),
	            next: new Point(next)
	        };
	    },
	    onHandleWillChange: function(_handle, evt) {
	        this.focus();
	        var ref = this;
	        var relatedView = ref.relatedView;
	        var options = ref.options;
	        relatedView.model.startBatch('vertex-move', { ui: true, tool: this.cid });
	        if (!options.stopPropagation) { relatedView.notifyPointerdown.apply(relatedView, relatedView.paper.getPointerArgs(evt)); }
	    },
	    onHandleChanging: function(handle, evt) {
	        var ref = this;
	        var options = ref.options;
	        var linkView = ref.relatedView;
	        var index = handle.options.index;
	        var ref$1 = linkView.paper.getPointerArgs(evt);
	        var normalizedEvent = ref$1[0];
	        var x = ref$1[1];
	        var y = ref$1[2];
	        var vertex = { x: x, y: y };
	        this.snapVertex(vertex, index);
	        linkView.model.vertex(index, vertex, { ui: true, tool: this.cid });
	        handle.position(vertex.x, vertex.y);
	        if (!options.stopPropagation) { linkView.notifyPointermove(normalizedEvent, x, y); }
	    },
	    onHandleChanged: function(_handle, evt) {
	        var ref = this;
	        var options = ref.options;
	        var linkView = ref.relatedView;
	        if (options.vertexAdding) { this.updatePath(); }
	        if (!options.redundancyRemoval) { return; }
	        var verticesRemoved = linkView.removeRedundantLinearVertices({ ui: true, tool: this.cid });
	        if (verticesRemoved) { this.render(); }
	        this.blur();
	        linkView.model.stopBatch('vertex-move', { ui: true, tool: this.cid });
	        if (this.eventData(evt).vertexAdded) {
	            linkView.model.stopBatch('vertex-add', { ui: true, tool: this.cid });
	        }
	        var ref$1 = linkView.paper.getPointerArgs(evt);
	        var normalizedEvt = ref$1[0];
	        var x = ref$1[1];
	        var y = ref$1[2];
	        if (!options.stopPropagation) { linkView.notifyPointerup(normalizedEvt, x, y); }
	        linkView.checkMouseleave(normalizedEvt);
	    },
	    snapVertex: function(vertex, index) {
	        var snapRadius = this.options.snapRadius;
	        if (snapRadius > 0) {
	            var neighbors = this.getNeighborPoints(index);
	            var prev = neighbors.prev;
	            var next = neighbors.next;
	            if (Math.abs(vertex.x - prev.x) < snapRadius) {
	                vertex.x = prev.x;
	            } else if (Math.abs(vertex.x - next.x) < snapRadius) {
	                vertex.x = next.x;
	            }
	            if (Math.abs(vertex.y - prev.y) < snapRadius) {
	                vertex.y = neighbors.prev.y;
	            } else if (Math.abs(vertex.y - next.y) < snapRadius) {
	                vertex.y = next.y;
	            }
	        }
	    },
	    onHandleRemove: function(handle, evt) {
	        var index$1 = handle.options.index;
	        var linkView = this.relatedView;
	        linkView.model.removeVertex(index$1, { ui: true });
	        if (this.options.vertexAdding) { this.updatePath(); }
	        linkView.checkMouseleave(normalizeEvent(evt));
	    },
	    onPathPointerDown: function(evt) {
	        if (this.guard(evt)) { return; }
	        evt.stopPropagation();
	        evt.preventDefault();
	        var normalizedEvent = normalizeEvent(evt);
	        var vertex = this.paper.snapToGrid(normalizedEvent.clientX, normalizedEvent.clientY).toJSON();
	        var relatedView = this.relatedView;
	        relatedView.model.startBatch('vertex-add', { ui: true, tool: this.cid });
	        var index$1 = relatedView.getVertexIndex(vertex.x, vertex.y);
	        this.snapVertex(vertex, index$1);
	        relatedView.model.insertVertex(index$1, vertex, { ui: true, tool: this.cid });
	        this.render();
	        var handle = this.handles[index$1];
	        this.eventData(normalizedEvent, { vertexAdded: true });
	        handle.onPointerDown(normalizedEvent);
	    },
	    onRemove: function() {
	        this.resetHandles();
	    }
	}, {
	    VertexHandle: VertexHandle // keep as class property
	});

	var SegmentHandle = View.extend({
	    tagName: 'g',
	    svgElement: true,
	    className: 'marker-segment',
	    events: {
	        mousedown: 'onPointerDown',
	        touchstart: 'onPointerDown'
	    },
	    documentEvents: {
	        mousemove: 'onPointerMove',
	        touchmove: 'onPointerMove',
	        mouseup: 'onPointerUp',
	        touchend: 'onPointerUp',
	        touchcancel: 'onPointerUp'
	    },
	    children: [{
	        tagName: 'line',
	        selector: 'line',
	        attributes: {
	            'stroke': '#33334F',
	            'stroke-width': 2,
	            'fill': 'none',
	            'pointer-events': 'none'
	        }
	    }, {
	        tagName: 'rect',
	        selector: 'handle',
	        attributes: {
	            'width': 20,
	            'height': 8,
	            'x': -10,
	            'y': -4,
	            'rx': 4,
	            'ry': 4,
	            'fill': '#33334F',
	            'stroke': '#FFFFFF',
	            'stroke-width': 2
	        }
	    }],
	    onRender: function() {
	        this.renderChildren();
	    },
	    position: function(x, y, angle, view) {

	        var matrix = V.createSVGMatrix().translate(x, y).rotate(angle);
	        var handle = this.childNodes.handle;
	        handle.setAttribute('transform', V.matrixToTransformString(matrix));
	        handle.setAttribute('cursor', (angle % 180 === 0) ? 'row-resize' : 'col-resize');

	        var viewPoint = view.getClosestPoint(new Point(x, y));
	        var line = this.childNodes.line;
	        line.setAttribute('x1', x);
	        line.setAttribute('y1', y);
	        line.setAttribute('x2', viewPoint.x);
	        line.setAttribute('y2', viewPoint.y);
	    },
	    onPointerDown: function(evt) {
	        if (this.options.guard(evt)) { return; }
	        this.trigger('change:start', this, evt);
	        evt.stopPropagation();
	        evt.preventDefault();
	        this.options.paper.undelegateEvents();
	        this.delegateDocumentEvents(null, evt.data);
	    },
	    onPointerMove: function(evt) {
	        this.trigger('changing', this, evt);
	    },
	    onPointerUp: function(evt) {
	        this.undelegateDocumentEvents();
	        this.options.paper.delegateEvents();
	        this.trigger('change:end', this, evt);
	    },
	    show: function() {
	        this.el.style.display = '';
	    },
	    hide: function() {
	        this.el.style.display = 'none';
	    }
	});

	var Segments = ToolView.extend({
	    name: 'segments',
	    precision: .5,
	    options: {
	        handleClass: SegmentHandle,
	        segmentLengthThreshold: 40,
	        redundancyRemoval: true,
	        anchor: getAnchor,
	        snapRadius: 10,
	        snapHandle: true,
	        stopPropagation: true
	    },
	    handles: null,
	    onRender: function() {
	        this.resetHandles();
	        var relatedView = this.relatedView;
	        var vertices = relatedView.model.vertices();
	        vertices.unshift(relatedView.sourcePoint);
	        vertices.push(relatedView.targetPoint);
	        for (var i = 0, n = vertices.length; i < n - 1; i++) {
	            var vertex = vertices[i];
	            var nextVertex = vertices[i + 1];
	            var handle = this.renderHandle(vertex, nextVertex);
	            this.simulateRelatedView(handle.el);
	            this.handles.push(handle);
	            handle.options.index = i;
	        }
	        return this;
	    },
	    renderHandle: function(vertex, nextVertex) {
	        var this$1 = this;

	        var handle = new (this.options.handleClass)({
	            paper: this.paper,
	            guard: function (evt) { return this$1.guard(evt); }
	        });
	        handle.render();
	        this.updateHandle(handle, vertex, nextVertex);
	        handle.vel.appendTo(this.el);
	        this.startHandleListening(handle);
	        return handle;
	    },
	    update: function() {
	        this.render();
	        return this;
	    },
	    startHandleListening: function(handle) {
	        this.listenTo(handle, 'change:start', this.onHandleChangeStart);
	        this.listenTo(handle, 'changing', this.onHandleChanging);
	        this.listenTo(handle, 'change:end', this.onHandleChangeEnd);
	    },
	    resetHandles: function() {
	        var handles = this.handles;
	        this.handles = [];
	        this.stopListening();
	        if (!Array.isArray(handles)) { return; }
	        for (var i = 0, n = handles.length; i < n; i++) {
	            handles[i].remove();
	        }
	    },
	    shiftHandleIndexes: function(value) {
	        var handles = this.handles;
	        for (var i = 0, n = handles.length; i < n; i++) { handles[i].options.index += value; }
	    },
	    resetAnchor: function(type, anchor) {
	        var relatedModel = this.relatedView.model;
	        if (anchor) {
	            relatedModel.prop([type, 'anchor'], anchor, {
	                rewrite: true,
	                ui: true,
	                tool: this.cid
	            });
	        } else {
	            relatedModel.removeProp([type, 'anchor'], {
	                ui: true,
	                tool: this.cid
	            });
	        }
	    },
	    snapHandle: function(handle, position, data) {

	        var index = handle.options.index;
	        var linkView = this.relatedView;
	        var link = linkView.model;
	        var vertices = link.vertices();
	        var axis = handle.options.axis;
	        var prev = vertices[index - 2] || data.sourceAnchor;
	        var next = vertices[index + 1] || data.targetAnchor;
	        var snapRadius = this.options.snapRadius;
	        if (Math.abs(position[axis] - prev[axis]) < snapRadius) {
	            position[axis] = prev[axis];
	        } else if (Math.abs(position[axis] - next[axis]) < snapRadius) {
	            position[axis] = next[axis];
	        }
	        return position;
	    },

	    onHandleChanging: function(handle, evt) {

	        var ref = this;
	        var options = ref.options;
	        var data = this.eventData(evt);
	        var relatedView = this.relatedView;
	        var paper = relatedView.paper;
	        var index$1 = handle.options.index - 1;
	        var normalizedEvent = normalizeEvent(evt);
	        var coords = paper.snapToGrid(normalizedEvent.clientX, normalizedEvent.clientY);
	        var position = this.snapHandle(handle, coords.clone(), data);
	        var axis = handle.options.axis;
	        var offset = (this.options.snapHandle) ? 0 : (coords[axis] - position[axis]);
	        var link = relatedView.model;
	        var vertices = cloneDeep(link.vertices());
	        var vertex = vertices[index$1];
	        var nextVertex = vertices[index$1 + 1];
	        var anchorFn = this.options.anchor;
	        if (typeof anchorFn !== 'function') { anchorFn = null; }

	        // First Segment
	        var sourceView = relatedView.sourceView;
	        var sourceBBox = relatedView.sourceBBox;
	        var changeSourceAnchor = false;
	        var deleteSourceAnchor = false;
	        if (!vertex) {
	            vertex = relatedView.sourceAnchor.toJSON();
	            vertex[axis] = position[axis];
	            if (sourceBBox.containsPoint(vertex)) {
	                vertex[axis] = position[axis];
	                changeSourceAnchor = true;
	            } else {
	                // we left the area of the source magnet for the first time
	                vertices.unshift(vertex);
	                this.shiftHandleIndexes(1);
	                deleteSourceAnchor = true;
	            }
	        } else if (index$1 === 0) {
	            if (sourceBBox.containsPoint(vertex)) {
	                vertices.shift();
	                this.shiftHandleIndexes(-1);
	                changeSourceAnchor = true;
	            } else {
	                vertex[axis] = position[axis];
	                deleteSourceAnchor = true;
	            }
	        } else {
	            vertex[axis] = position[axis];
	        }

	        if (anchorFn && sourceView) {
	            if (changeSourceAnchor) {
	                var sourceAnchorPosition = data.sourceAnchor.clone();
	                sourceAnchorPosition[axis] = position[axis];
	                var sourceAnchor = anchorFn.call(relatedView, sourceAnchorPosition, sourceView, relatedView.sourceMagnet || sourceView.el, 'source', relatedView);
	                this.resetAnchor('source', sourceAnchor);
	            }
	            if (deleteSourceAnchor) {
	                this.resetAnchor('source', data.sourceAnchorDef);
	            }
	        }

	        // Last segment
	        var targetView = relatedView.targetView;
	        var targetBBox = relatedView.targetBBox;
	        var changeTargetAnchor = false;
	        var deleteTargetAnchor = false;
	        if (!nextVertex) {
	            nextVertex = relatedView.targetAnchor.toJSON();
	            nextVertex[axis] = position[axis];
	            if (targetBBox.containsPoint(nextVertex)) {
	                changeTargetAnchor = true;
	            } else {
	                // we left the area of the target magnet for the first time
	                vertices.push(nextVertex);
	                deleteTargetAnchor = true;
	            }
	        } else if (index$1 === vertices.length - 2) {
	            if (targetBBox.containsPoint(nextVertex)) {
	                vertices.pop();
	                changeTargetAnchor = true;
	            } else {
	                nextVertex[axis] = position[axis];
	                deleteTargetAnchor = true;
	            }
	        } else {
	            nextVertex[axis] = position[axis];
	        }

	        if (anchorFn && targetView) {
	            if (changeTargetAnchor) {
	                var targetAnchorPosition = data.targetAnchor.clone();
	                targetAnchorPosition[axis] = position[axis];
	                var targetAnchor = anchorFn.call(relatedView, targetAnchorPosition, targetView, relatedView.targetMagnet || targetView.el, 'target', relatedView);
	                this.resetAnchor('target', targetAnchor);
	            }
	            if (deleteTargetAnchor) {
	                this.resetAnchor('target', data.targetAnchorDef);
	            }
	        }

	        link.vertices(vertices, { ui: true, tool: this.cid });
	        this.updateHandle(handle, vertex, nextVertex, offset);
	        if (!options.stopPropagation) { relatedView.notifyPointermove(normalizedEvent, coords.x, coords.y); }
	    },
	    onHandleChangeStart: function(handle, evt) {
	        var ref = this;
	        var options = ref.options;
	        var handles = ref.handles;
	        var linkView = ref.relatedView;
	        var model = linkView.model;
	        var paper = linkView.paper;
	        var index$1 = handle.options.index;
	        if (!Array.isArray(handles)) { return; }
	        for (var i = 0, n = handles.length; i < n; i++) {
	            if (i !== index$1) { handles[i].hide(); }
	        }
	        this.focus();
	        this.eventData(evt, {
	            sourceAnchor: linkView.sourceAnchor.clone(),
	            targetAnchor: linkView.targetAnchor.clone(),
	            sourceAnchorDef: clone(model.prop(['source', 'anchor'])),
	            targetAnchorDef: clone(model.prop(['target', 'anchor']))
	        });
	        model.startBatch('segment-move', { ui: true, tool: this.cid });
	        if (!options.stopPropagation) { linkView.notifyPointerdown.apply(linkView, paper.getPointerArgs(evt)); }
	    },
	    onHandleChangeEnd: function(_handle, evt) {
	        var ref= this;
	        var options = ref.options;
	        var linkView = ref.relatedView;
	        var paper = linkView.paper;
	        var model = linkView.model;
	        if (options.redundancyRemoval) {
	            linkView.removeRedundantLinearVertices({ ui: true, tool: this.cid });
	        }
	        var normalizedEvent = normalizeEvent(evt);
	        var coords = paper.snapToGrid(normalizedEvent.clientX, normalizedEvent.clientY);
	        this.render();
	        this.blur();
	        model.stopBatch('segment-move', { ui: true, tool: this.cid });
	        if (!options.stopPropagation) { linkView.notifyPointerup(normalizedEvent, coords.x, coords.y); }
	        linkView.checkMouseleave(normalizedEvent);
	    },
	    updateHandle: function(handle, vertex, nextVertex, offset) {
	        var vertical = Math.abs(vertex.x - nextVertex.x) < this.precision;
	        var horizontal = Math.abs(vertex.y - nextVertex.y) < this.precision;
	        if (vertical || horizontal) {
	            var segmentLine = new Line(vertex, nextVertex);
	            var length = segmentLine.length();
	            if (length < this.options.segmentLengthThreshold) {
	                handle.hide();
	            } else {
	                var position = segmentLine.midpoint();
	                var axis = (vertical) ? 'x' : 'y';
	                position[axis] += offset || 0;
	                var angle = segmentLine.vector().vectorAngle(new Point(1, 0));
	                handle.position(position.x, position.y, angle, this.relatedView);
	                handle.show();
	                handle.options.axis = axis;
	            }
	        } else {
	            handle.hide();
	        }
	    },
	    onRemove: function() {
	        this.resetHandles();
	    }
	}, {
	    SegmentHandle: SegmentHandle // keep as class property
	});

	// End Markers
	var Arrowhead = ToolView.extend({
	    tagName: 'path',
	    xAxisVector: new Point(1, 0),
	    events: {
	        mousedown: 'onPointerDown',
	        touchstart: 'onPointerDown'
	    },
	    documentEvents: {
	        mousemove: 'onPointerMove',
	        touchmove: 'onPointerMove',
	        mouseup: 'onPointerUp',
	        touchend: 'onPointerUp',
	        touchcancel: 'onPointerUp'
	    },
	    onRender: function() {
	        this.update();
	    },
	    update: function() {
	        var ratio = this.ratio;
	        var view = this.relatedView;
	        var tangent = view.getTangentAtRatio(ratio);
	        var position, angle;
	        if (tangent) {
	            position = tangent.start;
	            angle = tangent.vector().vectorAngle(this.xAxisVector) || 0;
	        } else {
	            position = view.getPointAtRatio(ratio);
	            angle = 0;
	        }
	        if (!position) { return this; }
	        var matrix = V.createSVGMatrix().translate(position.x, position.y).rotate(angle);
	        this.vel.transform(matrix, { absolute: true });
	        return this;
	    },
	    onPointerDown: function(evt) {
	        if (this.guard(evt)) { return; }
	        evt.stopPropagation();
	        evt.preventDefault();
	        var relatedView = this.relatedView;
	        relatedView.model.startBatch('arrowhead-move', { ui: true, tool: this.cid });
	        if (relatedView.can('arrowheadMove')) {
	            relatedView.startArrowheadMove(this.arrowheadType);
	            this.delegateDocumentEvents();
	            relatedView.paper.undelegateEvents();
	        }
	        this.focus();
	        this.el.style.pointerEvents = 'none';
	    },
	    onPointerMove: function(evt) {
	        var normalizedEvent = normalizeEvent(evt);
	        var coords = this.paper.snapToGrid(normalizedEvent.clientX, normalizedEvent.clientY);
	        this.relatedView.pointermove(normalizedEvent, coords.x, coords.y);
	    },
	    onPointerUp: function(evt) {
	        this.undelegateDocumentEvents();
	        var relatedView = this.relatedView;
	        var paper = relatedView.paper;
	        var normalizedEvent = normalizeEvent(evt);
	        var coords = paper.snapToGrid(normalizedEvent.clientX, normalizedEvent.clientY);
	        relatedView.pointerup(normalizedEvent, coords.x, coords.y);
	        paper.delegateEvents();
	        this.blur();
	        this.el.style.pointerEvents = '';
	        relatedView.model.stopBatch('arrowhead-move', { ui: true, tool: this.cid });
	    }
	});

	var TargetArrowhead = Arrowhead.extend({
	    name: 'target-arrowhead',
	    ratio: 1,
	    arrowheadType: 'target',
	    attributes: {
	        'd': 'M -10 -8 10 0 -10 8 Z',
	        'fill': '#33334F',
	        'stroke': '#FFFFFF',
	        'stroke-width': 2,
	        'cursor': 'move',
	        'class': 'target-arrowhead'
	    }
	});

	var SourceArrowhead = Arrowhead.extend({
	    name: 'source-arrowhead',
	    ratio: 0,
	    arrowheadType: 'source',
	    attributes: {
	        'd': 'M 10 -8 -10 0 10 8 Z',
	        'fill': '#33334F',
	        'stroke': '#FFFFFF',
	        'stroke-width': 2,
	        'cursor': 'move',
	        'class': 'source-arrowhead'
	    }
	});

	var Button = ToolView.extend({
	    name: 'button',
	    events: {
	        'mousedown': 'onPointerDown',
	        'touchstart': 'onPointerDown'
	    },
	    options: {
	        distance: 0,
	        offset: 0,
	        rotate: false
	    },
	    onRender: function() {
	        this.renderChildren(this.options.markup);
	        this.update();
	    },
	    update: function() {
	        this.position();
	        return this;
	    },
	    position: function() {
	        var ref = this;
	        var view = ref.relatedView;
	        var vel = ref.vel;
	        var matrix = view.model.isLink() ? this.getLinkMatrix() : this.getElementMatrix();
	        vel.transform(matrix, { absolute: true });
	    },
	    getElementMatrix: function getElementMatrix() {
	        var ref = this;
	        var view = ref.relatedView;
	        var options = ref.options;
	        var x = options.x; if ( x === void 0 ) x = 0;
	        var y = options.y; if ( y === void 0 ) y = 0;
	        var offset = options.offset; if ( offset === void 0 ) offset = {};
	        var useModelGeometry = options.useModelGeometry;
	        var rotate = options.rotate;
	        var bbox = getViewBBox(view, useModelGeometry);
	        var angle = view.model.angle();
	        if (!rotate) { bbox = bbox.bbox(angle); }
	        var offsetX = offset.x; if ( offsetX === void 0 ) offsetX = 0;
	        var offsetY = offset.y; if ( offsetY === void 0 ) offsetY = 0;
	        if (isPercentage(x)) {
	            x = parseFloat(x) / 100 * bbox.width;
	        }
	        if (isPercentage(y)) {
	            y = parseFloat(y) / 100 * bbox.height;
	        }
	        var matrix = V.createSVGMatrix().translate(bbox.x + bbox.width / 2, bbox.y + bbox.height / 2);
	        if (rotate) { matrix = matrix.rotate(angle); }
	        matrix = matrix.translate(x + offsetX - bbox.width / 2, y + offsetY - bbox.height / 2);
	        return matrix;
	    },
	    getLinkMatrix: function getLinkMatrix() {
	        var ref = this;
	        var view = ref.relatedView;
	        var options = ref.options;
	        var offset = options.offset; if ( offset === void 0 ) offset = 0;
	        var distance = options.distance; if ( distance === void 0 ) distance = 0;
	        var rotate = options.rotate;
	        var tangent, position, angle;
	        if (isPercentage(distance)) {
	            tangent = view.getTangentAtRatio(parseFloat(distance) / 100);
	        } else {
	            tangent = view.getTangentAtLength(distance);
	        }
	        if (tangent) {
	            position = tangent.start;
	            angle = tangent.vector().vectorAngle(new Point(1, 0)) || 0;
	        } else {
	            position = view.getConnection().start;
	            angle = 0;
	        }
	        var matrix = V.createSVGMatrix()
	            .translate(position.x, position.y)
	            .rotate(angle)
	            .translate(0, offset);
	        if (!rotate) { matrix = matrix.rotate(-angle); }
	        return matrix;
	    },
	    onPointerDown: function(evt) {
	        if (this.guard(evt)) { return; }
	        evt.stopPropagation();
	        evt.preventDefault();
	        var actionFn = this.options.action;
	        if (typeof actionFn === 'function') {
	            actionFn.call(this.relatedView, evt, this.relatedView, this);
	        }
	    }
	});


	var Remove = Button.extend({
	    children: [{
	        tagName: 'circle',
	        selector: 'button',
	        attributes: {
	            'r': 7,
	            'fill': '#FF1D00',
	            'cursor': 'pointer'
	        }
	    }, {
	        tagName: 'path',
	        selector: 'icon',
	        attributes: {
	            'd': 'M -3 -3 3 3 M -3 3 3 -3',
	            'fill': 'none',
	            'stroke': '#FFFFFF',
	            'stroke-width': 2,
	            'pointer-events': 'none'
	        }
	    }],
	    options: {
	        distance: 60,
	        offset: 0,
	        action: function(evt, view, tool) {
	            view.model.remove({ ui: true, tool: tool.cid });
	        }
	    }
	});

	var Boundary = ToolView.extend({
	    name: 'boundary',
	    tagName: 'rect',
	    options: {
	        padding: 10,
	        useModelGeometry: false,
	    },
	    attributes: {
	        'fill': 'none',
	        'stroke': '#33334F',
	        'stroke-width': .5,
	        'stroke-dasharray': '5, 5',
	        'pointer-events': 'none'
	    },
	    onRender: function() {
	        this.update();
	    },
	    update: function() {
	        var ref = this;
	        var view = ref.relatedView;
	        var options = ref.options;
	        var vel = ref.vel;
	        var useModelGeometry = options.useModelGeometry;
	        var rotate = options.rotate;
	        var padding = normalizeSides(options.padding);
	        var bbox = getViewBBox(view, useModelGeometry).moveAndExpand({
	            x: -padding.left,
	            y: -padding.top,
	            width: padding.left + padding.right,
	            height: padding.top + padding.bottom
	        });
	        var model = view.model;
	        if (model.isElement()) {
	            var angle = model.angle();
	            if (angle) {
	                if (rotate) {
	                    var origin = model.getBBox().center();
	                    vel.rotate(angle, origin.x, origin.y, { absolute: true });
	                } else {
	                    bbox = bbox.bbox(angle);
	                }
	            }
	        }
	        vel.attr(bbox.toJSON());
	        return this;
	    }
	});

	var Anchor = ToolView.extend({
	    tagName: 'g',
	    type: null,
	    children: [{
	        tagName: 'circle',
	        selector: 'anchor',
	        attributes: {
	            'cursor': 'pointer'
	        }
	    }, {
	        tagName: 'rect',
	        selector: 'area',
	        attributes: {
	            'pointer-events': 'none',
	            'fill': 'none',
	            'stroke': '#33334F',
	            'stroke-dasharray': '2,4',
	            'rx': 5,
	            'ry': 5
	        }
	    }],
	    events: {
	        mousedown: 'onPointerDown',
	        touchstart: 'onPointerDown',
	        dblclick: 'onPointerDblClick'
	    },
	    documentEvents: {
	        mousemove: 'onPointerMove',
	        touchmove: 'onPointerMove',
	        mouseup: 'onPointerUp',
	        touchend: 'onPointerUp',
	        touchcancel: 'onPointerUp'
	    },
	    options: {
	        snap: snapAnchor,
	        anchor: getAnchor,
	        resetAnchor: true,
	        customAnchorAttributes: {
	            'stroke-width': 4,
	            'stroke': '#33334F',
	            'fill': '#FFFFFF',
	            'r': 5
	        },
	        defaultAnchorAttributes: {
	            'stroke-width': 2,
	            'stroke': '#FFFFFF',
	            'fill': '#33334F',
	            'r': 6
	        },
	        areaPadding: 6,
	        snapRadius: 10,
	        restrictArea: true,
	        redundancyRemoval: true
	    },
	    onRender: function() {
	        this.renderChildren();
	        this.toggleArea(false);
	        this.update();
	    },
	    update: function() {
	        var type = this.type;
	        var relatedView = this.relatedView;
	        var view = relatedView.getEndView(type);
	        if (view) {
	            this.updateAnchor();
	            this.updateArea();
	            this.el.style.display = '';
	        } else {
	            this.el.style.display = 'none';
	        }
	        return this;
	    },
	    updateAnchor: function() {
	        var childNodes = this.childNodes;
	        if (!childNodes) { return; }
	        var anchorNode = childNodes.anchor;
	        if (!anchorNode) { return; }
	        var relatedView = this.relatedView;
	        var type = this.type;
	        var position = relatedView.getEndAnchor(type);
	        var options = this.options;
	        var customAnchor = relatedView.model.prop([type, 'anchor']);
	        anchorNode.setAttribute('transform', 'translate(' + position.x + ',' + position.y + ')');
	        var anchorAttributes = (customAnchor) ? options.customAnchorAttributes : options.defaultAnchorAttributes;
	        for (var attrName in anchorAttributes) {
	            anchorNode.setAttribute(attrName, anchorAttributes[attrName]);
	        }
	    },
	    updateArea: function() {
	        var childNodes = this.childNodes;
	        if (!childNodes) { return; }
	        var areaNode = childNodes.area;
	        if (!areaNode) { return; }
	        var relatedView = this.relatedView;
	        var type = this.type;
	        var view = relatedView.getEndView(type);
	        var model = view.model;
	        var magnet = relatedView.getEndMagnet(type);
	        var padding = this.options.areaPadding;
	        if (!isFinite(padding)) { padding = 0; }
	        var bbox, angle, center;
	        if (view.isNodeConnection(magnet)) {
	            bbox = view.getBBox();
	            angle = 0;
	            center = bbox.center();
	        } else {
	            bbox = view.getNodeUnrotatedBBox(magnet);
	            angle = model.angle();
	            center = bbox.center();
	            if (angle) { center.rotate(model.getBBox().center(), -angle); }
	            // TODO: get the link's magnet rotation into account
	        }
	        bbox.inflate(padding);
	        areaNode.setAttribute('x', -bbox.width / 2);
	        areaNode.setAttribute('y', -bbox.height / 2);
	        areaNode.setAttribute('width', bbox.width);
	        areaNode.setAttribute('height', bbox.height);
	        areaNode.setAttribute('transform', 'translate(' + center.x + ',' + center.y + ') rotate(' + angle + ')');
	    },
	    toggleArea: function(visible) {
	        this.childNodes.area.style.display = (visible) ? '' : 'none';
	    },
	    onPointerDown: function(evt) {
	        if (this.guard(evt)) { return; }
	        evt.stopPropagation();
	        evt.preventDefault();
	        this.paper.undelegateEvents();
	        this.delegateDocumentEvents();
	        this.focus();
	        this.toggleArea(this.options.restrictArea);
	        this.relatedView.model.startBatch('anchor-move', { ui: true, tool: this.cid });
	    },
	    resetAnchor: function(anchor) {
	        var type = this.type;
	        var relatedModel = this.relatedView.model;
	        if (anchor) {
	            relatedModel.prop([type, 'anchor'], anchor, {
	                rewrite: true,
	                ui: true,
	                tool: this.cid
	            });
	        } else {
	            relatedModel.removeProp([type, 'anchor'], {
	                ui: true,
	                tool: this.cid
	            });
	        }
	    },
	    onPointerMove: function(evt) {

	        var relatedView = this.relatedView;
	        var type = this.type;
	        var view = relatedView.getEndView(type);
	        var model = view.model;
	        var magnet = relatedView.getEndMagnet(type);
	        var normalizedEvent = normalizeEvent(evt);
	        var coords = this.paper.clientToLocalPoint(normalizedEvent.clientX, normalizedEvent.clientY);
	        var snapFn = this.options.snap;
	        if (typeof snapFn === 'function') {
	            coords = snapFn.call(relatedView, coords, view, magnet, type, relatedView, this);
	            coords = new Point(coords);
	        }

	        if (this.options.restrictArea) {
	            if (view.isNodeConnection(magnet)) {
	                // snap coords to the link's connection
	                var pointAtConnection = view.getClosestPoint(coords);
	                if (pointAtConnection) { coords = pointAtConnection; }
	            } else {
	                // snap coords within node bbox
	                var bbox = view.getNodeUnrotatedBBox(magnet);
	                var angle = model.angle();
	                var origin = model.getBBox().center();
	                var rotatedCoords = coords.clone().rotate(origin, angle);
	                if (!bbox.containsPoint(rotatedCoords)) {
	                    coords = bbox.pointNearestToPoint(rotatedCoords).rotate(origin, -angle);
	                }
	            }
	        }

	        var anchor;
	        var anchorFn = this.options.anchor;
	        if (typeof anchorFn === 'function') {
	            anchor = anchorFn.call(relatedView, coords, view, magnet, type, relatedView);
	        }

	        this.resetAnchor(anchor);
	        this.update();
	    },

	    onPointerUp: function(evt) {
	        this.paper.delegateEvents();
	        this.undelegateDocumentEvents();
	        this.blur();
	        this.toggleArea(false);
	        var linkView = this.relatedView;
	        if (this.options.redundancyRemoval) { linkView.removeRedundantLinearVertices({ ui: true, tool: this.cid }); }
	        linkView.model.stopBatch('anchor-move', { ui: true, tool: this.cid });
	    },

	    onPointerDblClick: function() {
	        var anchor = this.options.resetAnchor;
	        if (anchor === false) { return; } // reset anchor disabled
	        if (anchor === true) { anchor = null; } // remove the current anchor
	        this.resetAnchor(cloneDeep(anchor));
	        this.update();
	    }
	});

	var SourceAnchor = Anchor.extend({
	    name: 'source-anchor',
	    type: 'source'
	});

	var TargetAnchor = Anchor.extend({
	    name: 'target-anchor',
	    type: 'target'
	});

	var index$5 = ({
		Vertices: Vertices,
		Segments: Segments,
		SourceArrowhead: SourceArrowhead,
		TargetArrowhead: TargetArrowhead,
		SourceAnchor: SourceAnchor,
		TargetAnchor: TargetAnchor,
		Button: Button,
		Remove: Remove,
		Boundary: Boundary
	});



	var index$6 = ({
		Button: Button,
		Remove: Remove,
		Boundary: Boundary
	});

	var version = "3.4.4";

	var Vectorizer = V;
	var layout = { PortLabel: PortLabel, Port: Port };
	var setTheme = function(theme, opt) {

	    opt = opt || {};

	    invoke(views, 'setTheme', theme, opt);

	    // Update the default theme on the view prototype.
	    View.prototype.defaultTheme = theme;
	};

	var layout$1 = { DirectedGraph: DirectedGraph, PortLabel: PortLabel, Port: Port };

	// export empty namespaces - backward compatibility
	var format$1 = {};
	var ui = {};

	exports.V = V;
	exports.Vectorizer = Vectorizer;
	exports.anchors = anchors;
	exports.config = config;
	exports.connectionPoints = connectionPoints;
	exports.connectionStrategies = index$4;
	exports.connectors = connectors;
	exports.dia = index$2;
	exports.elementTools = index$6;
	exports.env = env;
	exports.format = format$1;
	exports.g = g;
	exports.highlighters = highlighters;
	exports.layout = layout$1;
	exports.linkAnchors = linkAnchors;
	exports.linkTools = index$5;
	exports.mvc = index$1;
	exports.routers = routers;
	exports.setTheme = setTheme;
	exports.shapes = index$3;
	exports.ui = ui;
	exports.util = index;
	exports.version = version;

	Object.defineProperty(exports, '__esModule', { value: true });

}));
if (typeof joint !== 'undefined') { var g = joint.g, V = joint.V, Vectorizer = joint.V; }


/***/ }),

/***/ "./node_modules/jointjs/node_modules/backbone/backbone.js":
/*!****************************************************************!*\
  !*** ./node_modules/jointjs/node_modules/backbone/backbone.js ***!
  \****************************************************************/
/***/ ((module, exports, __webpack_require__) => {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;//     Backbone.js 1.4.0

//     (c) 2010-2019 Jeremy Ashkenas and DocumentCloud
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://backbonejs.org

(function(factory) {

  // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  // We use `self` instead of `window` for `WebWorker` support.
  var root = typeof self == 'object' && self.self === self && self ||
            typeof __webpack_require__.g == 'object' && __webpack_require__.g.global === __webpack_require__.g && __webpack_require__.g;

  // Set up Backbone appropriately for the environment. Start with AMD.
  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! underscore */ "./node_modules/underscore/underscore-umd.js"), __webpack_require__(/*! jquery */ "./node_modules/jquery/dist/jquery.js"), exports], __WEBPACK_AMD_DEFINE_RESULT__ = (function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));

  // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  } else { var _, $; }

})(function(root, Backbone, _, $) {

  // Initial Setup
  // -------------

  // Save the previous value of the `Backbone` variable, so that it can be
  // restored later on, if `noConflict` is used.
  var previousBackbone = root.Backbone;

  // Create a local reference to a common array method we'll want to use later.
  var slice = Array.prototype.slice;

  // Current version of the library. Keep in sync with `package.json`.
  Backbone.VERSION = '1.4.0';

  // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
  // the `$` variable.
  Backbone.$ = $;

  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  // to its previous owner. Returns a reference to this Backbone object.
  Backbone.noConflict = function() {
    root.Backbone = previousBackbone;
    return this;
  };

  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  // set a `X-Http-Method-Override` header.
  Backbone.emulateHTTP = false;

  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  // `application/json` requests ... this will encode the body as
  // `application/x-www-form-urlencoded` instead and will send the model in a
  // form param named `model`.
  Backbone.emulateJSON = false;

  // Backbone.Events
  // ---------------

  // A module that can be mixed in to *any object* in order to provide it with
  // a custom event channel. You may bind a callback to an event with `on` or
  // remove with `off`; `trigger`-ing an event fires all callbacks in
  // succession.
  //
  //     var object = {};
  //     _.extend(object, Backbone.Events);
  //     object.on('expand', function(){ alert('expanded'); });
  //     object.trigger('expand');
  //
  var Events = Backbone.Events = {};

  // Regular expression used to split event strings.
  var eventSplitter = /\s+/;

  // A private global variable to share between listeners and listenees.
  var _listening;

  // Iterates over the standard `event, callback` (as well as the fancy multiple
  // space-separated events `"change blur", callback` and jQuery-style event
  // maps `{event: callback}`).
  var eventsApi = function(iteratee, events, name, callback, opts) {
    var i = 0, names;
    if (name && typeof name === 'object') {
      // Handle event maps.
      if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
      for (names = _.keys(name); i < names.length ; i++) {
        events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
      }
    } else if (name && eventSplitter.test(name)) {
      // Handle space-separated event names by delegating them individually.
      for (names = name.split(eventSplitter); i < names.length; i++) {
        events = iteratee(events, names[i], callback, opts);
      }
    } else {
      // Finally, standard events.
      events = iteratee(events, name, callback, opts);
    }
    return events;
  };

  // Bind an event to a `callback` function. Passing `"all"` will bind
  // the callback to all events fired.
  Events.on = function(name, callback, context) {
    this._events = eventsApi(onApi, this._events || {}, name, callback, {
      context: context,
      ctx: this,
      listening: _listening
    });

    if (_listening) {
      var listeners = this._listeners || (this._listeners = {});
      listeners[_listening.id] = _listening;
      // Allow the listening to use a counter, instead of tracking
      // callbacks for library interop
      _listening.interop = false;
    }

    return this;
  };

  // Inversion-of-control versions of `on`. Tell *this* object to listen to
  // an event in another object... keeping track of what it's listening to
  // for easier unbinding later.
  Events.listenTo = function(obj, name, callback) {
    if (!obj) return this;
    var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
    var listeningTo = this._listeningTo || (this._listeningTo = {});
    var listening = _listening = listeningTo[id];

    // This object is not listening to any other events on `obj` yet.
    // Setup the necessary references to track the listening callbacks.
    if (!listening) {
      this._listenId || (this._listenId = _.uniqueId('l'));
      listening = _listening = listeningTo[id] = new Listening(this, obj);
    }

    // Bind callbacks on obj.
    var error = tryCatchOn(obj, name, callback, this);
    _listening = void 0;

    if (error) throw error;
    // If the target obj is not Backbone.Events, track events manually.
    if (listening.interop) listening.on(name, callback);

    return this;
  };

  // The reducing API that adds a callback to the `events` object.
  var onApi = function(events, name, callback, options) {
    if (callback) {
      var handlers = events[name] || (events[name] = []);
      var context = options.context, ctx = options.ctx, listening = options.listening;
      if (listening) listening.count++;

      handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
    }
    return events;
  };

  // An try-catch guarded #on function, to prevent poisoning the global
  // `_listening` variable.
  var tryCatchOn = function(obj, name, callback, context) {
    try {
      obj.on(name, callback, context);
    } catch (e) {
      return e;
    }
  };

  // Remove one or many callbacks. If `context` is null, removes all
  // callbacks with that function. If `callback` is null, removes all
  // callbacks for the event. If `name` is null, removes all bound
  // callbacks for all events.
  Events.off = function(name, callback, context) {
    if (!this._events) return this;
    this._events = eventsApi(offApi, this._events, name, callback, {
      context: context,
      listeners: this._listeners
    });

    return this;
  };

  // Tell this object to stop listening to either specific events ... or
  // to every object it's currently listening to.
  Events.stopListening = function(obj, name, callback) {
    var listeningTo = this._listeningTo;
    if (!listeningTo) return this;

    var ids = obj ? [obj._listenId] : _.keys(listeningTo);
    for (var i = 0; i < ids.length; i++) {
      var listening = listeningTo[ids[i]];

      // If listening doesn't exist, this object is not currently
      // listening to obj. Break out early.
      if (!listening) break;

      listening.obj.off(name, callback, this);
      if (listening.interop) listening.off(name, callback);
    }
    if (_.isEmpty(listeningTo)) this._listeningTo = void 0;

    return this;
  };

  // The reducing API that removes a callback from the `events` object.
  var offApi = function(events, name, callback, options) {
    if (!events) return;

    var context = options.context, listeners = options.listeners;
    var i = 0, names;

    // Delete all event listeners and "drop" events.
    if (!name && !context && !callback) {
      for (names = _.keys(listeners); i < names.length; i++) {
        listeners[names[i]].cleanup();
      }
      return;
    }

    names = name ? [name] : _.keys(events);
    for (; i < names.length; i++) {
      name = names[i];
      var handlers = events[name];

      // Bail out if there are no events stored.
      if (!handlers) break;

      // Find any remaining events.
      var remaining = [];
      for (var j = 0; j < handlers.length; j++) {
        var handler = handlers[j];
        if (
          callback && callback !== handler.callback &&
            callback !== handler.callback._callback ||
              context && context !== handler.context
        ) {
          remaining.push(handler);
        } else {
          var listening = handler.listening;
          if (listening) listening.off(name, callback);
        }
      }

      // Replace events if there are any remaining.  Otherwise, clean up.
      if (remaining.length) {
        events[name] = remaining;
      } else {
        delete events[name];
      }
    }

    return events;
  };

  // Bind an event to only be triggered a single time. After the first time
  // the callback is invoked, its listener will be removed. If multiple events
  // are passed in using the space-separated syntax, the handler will fire
  // once for each event, not once for a combination of all events.
  Events.once = function(name, callback, context) {
    // Map the event into a `{event: once}` object.
    var events = eventsApi(onceMap, {}, name, callback, this.off.bind(this));
    if (typeof name === 'string' && context == null) callback = void 0;
    return this.on(events, callback, context);
  };

  // Inversion-of-control versions of `once`.
  Events.listenToOnce = function(obj, name, callback) {
    // Map the event into a `{event: once}` object.
    var events = eventsApi(onceMap, {}, name, callback, this.stopListening.bind(this, obj));
    return this.listenTo(obj, events);
  };

  // Reduces the event callbacks into a map of `{event: onceWrapper}`.
  // `offer` unbinds the `onceWrapper` after it has been called.
  var onceMap = function(map, name, callback, offer) {
    if (callback) {
      var once = map[name] = _.once(function() {
        offer(name, once);
        callback.apply(this, arguments);
      });
      once._callback = callback;
    }
    return map;
  };

  // Trigger one or many events, firing all bound callbacks. Callbacks are
  // passed the same arguments as `trigger` is, apart from the event name
  // (unless you're listening on `"all"`, which will cause your callback to
  // receive the true name of the event as the first argument).
  Events.trigger = function(name) {
    if (!this._events) return this;

    var length = Math.max(0, arguments.length - 1);
    var args = Array(length);
    for (var i = 0; i < length; i++) args[i] = arguments[i + 1];

    eventsApi(triggerApi, this._events, name, void 0, args);
    return this;
  };

  // Handles triggering the appropriate event callbacks.
  var triggerApi = function(objEvents, name, callback, args) {
    if (objEvents) {
      var events = objEvents[name];
      var allEvents = objEvents.all;
      if (events && allEvents) allEvents = allEvents.slice();
      if (events) triggerEvents(events, args);
      if (allEvents) triggerEvents(allEvents, [name].concat(args));
    }
    return objEvents;
  };

  // A difficult-to-believe, but optimized internal dispatch function for
  // triggering events. Tries to keep the usual cases speedy (most internal
  // Backbone events have 3 arguments).
  var triggerEvents = function(events, args) {
    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
    switch (args.length) {
      case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
      case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
      case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
      case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
      default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
    }
  };

  // A listening class that tracks and cleans up memory bindings
  // when all callbacks have been offed.
  var Listening = function(listener, obj) {
    this.id = listener._listenId;
    this.listener = listener;
    this.obj = obj;
    this.interop = true;
    this.count = 0;
    this._events = void 0;
  };

  Listening.prototype.on = Events.on;

  // Offs a callback (or several).
  // Uses an optimized counter if the listenee uses Backbone.Events.
  // Otherwise, falls back to manual tracking to support events
  // library interop.
  Listening.prototype.off = function(name, callback) {
    var cleanup;
    if (this.interop) {
      this._events = eventsApi(offApi, this._events, name, callback, {
        context: void 0,
        listeners: void 0
      });
      cleanup = !this._events;
    } else {
      this.count--;
      cleanup = this.count === 0;
    }
    if (cleanup) this.cleanup();
  };

  // Cleans up memory bindings between the listener and the listenee.
  Listening.prototype.cleanup = function() {
    delete this.listener._listeningTo[this.obj._listenId];
    if (!this.interop) delete this.obj._listeners[this.id];
  };

  // Aliases for backwards compatibility.
  Events.bind   = Events.on;
  Events.unbind = Events.off;

  // Allow the `Backbone` object to serve as a global event bus, for folks who
  // want global "pubsub" in a convenient place.
  _.extend(Backbone, Events);

  // Backbone.Model
  // --------------

  // Backbone **Models** are the basic data object in the framework --
  // frequently representing a row in a table in a database on your server.
  // A discrete chunk of data and a bunch of useful, related methods for
  // performing computations and transformations on that data.

  // Create a new model with the specified attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  var Model = Backbone.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.preinitialize.apply(this, arguments);
    this.cid = _.uniqueId(this.cidPrefix);
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  };

  // Attach all inheritable methods to the Model prototype.
  _.extend(Model.prototype, Events, {

    // A hash of attributes whose current and previous value differ.
    changed: null,

    // The value returned during the last failed validation.
    validationError: null,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute: 'id',

    // The prefix is used to create the client id which is used to identify models locally.
    // You may want to override this if you're experiencing name clashes with model ids.
    cidPrefix: 'c',

    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the Model.
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Return a copy of the model's `attributes` object.
    toJSON: function(options) {
      return _.clone(this.attributes);
    },

    // Proxy `Backbone.sync` by default -- but override this if you need
    // custom syncing semantics for *this* particular model.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

    // Get the value of an attribute.
    get: function(attr) {
      return this.attributes[attr];
    },

    // Get the HTML-escaped value of an attribute.
    escape: function(attr) {
      return _.escape(this.get(attr));
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has: function(attr) {
      return this.get(attr) != null;
    },

    // Special-cased proxy to underscore's `_.matches` method.
    matches: function(attrs) {
      return !!_.iteratee(attrs, this)(this.attributes);
    },

    // Set a hash of model attributes on the object, firing `"change"`. This is
    // the core primitive operation of a model, updating the data and notifying
    // anyone who needs to know about the change in state. The heart of the beast.
    set: function(key, val, options) {
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options || (options = {});

      // Run validation.
      if (!this._validate(attrs, options)) return false;

      // Extract attributes and options.
      var unset      = options.unset;
      var silent     = options.silent;
      var changes    = [];
      var changing   = this._changing;
      this._changing = true;

      if (!changing) {
        this._previousAttributes = _.clone(this.attributes);
        this.changed = {};
      }

      var current = this.attributes;
      var changed = this.changed;
      var prev    = this._previousAttributes;

      // For each `set` attribute, update or delete the current value.
      for (var attr in attrs) {
        val = attrs[attr];
        if (!_.isEqual(current[attr], val)) changes.push(attr);
        if (!_.isEqual(prev[attr], val)) {
          changed[attr] = val;
        } else {
          delete changed[attr];
        }
        unset ? delete current[attr] : current[attr] = val;
      }

      // Update the `id`.
      if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);

      // Trigger all relevant attribute changes.
      if (!silent) {
        if (changes.length) this._pending = options;
        for (var i = 0; i < changes.length; i++) {
          this.trigger('change:' + changes[i], this, current[changes[i]], options);
        }
      }

      // You might be wondering why there's a `while` loop here. Changes can
      // be recursively nested within `"change"` events.
      if (changing) return this;
      if (!silent) {
        while (this._pending) {
          options = this._pending;
          this._pending = false;
          this.trigger('change', this, options);
        }
      }
      this._pending = false;
      this._changing = false;
      return this;
    },

    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
    // if the attribute doesn't exist.
    unset: function(attr, options) {
      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
    },

    // Clear all attributes on the model, firing `"change"`.
    clear: function(options) {
      var attrs = {};
      for (var key in this.attributes) attrs[key] = void 0;
      return this.set(attrs, _.extend({}, options, {unset: true}));
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged: function(attr) {
      if (attr == null) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    },

    // Return an object containing all the attributes that have changed, or
    // false if there are no changed attributes. Useful for determining what
    // parts of a view need to be updated and/or what attributes need to be
    // persisted to the server. Unset attributes will be set to undefined.
    // You can also pass an attributes object to diff against the model,
    // determining if there *would be* a change.
    changedAttributes: function(diff) {
      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
      var old = this._changing ? this._previousAttributes : this.attributes;
      var changed = {};
      var hasChanged;
      for (var attr in diff) {
        var val = diff[attr];
        if (_.isEqual(old[attr], val)) continue;
        changed[attr] = val;
        hasChanged = true;
      }
      return hasChanged ? changed : false;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous: function(attr) {
      if (attr == null || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes: function() {
      return _.clone(this._previousAttributes);
    },

    // Fetch the model from the server, merging the response with the model's
    // local attributes. Any changed attributes will trigger a "change" event.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (!model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save: function(key, val, options) {
      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (key == null || typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options = _.extend({validate: true, parse: true}, options);
      var wait = options.wait;

      // If we're not waiting and attributes exist, save acts as
      // `set(attr).save(null, opts)` with validation. Otherwise, check if
      // the model will be valid when the attributes, if any, are set.
      if (attrs && !wait) {
        if (!this.set(attrs, options)) return false;
      } else if (!this._validate(attrs, options)) {
        return false;
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      var model = this;
      var success = options.success;
      var attributes = this.attributes;
      options.success = function(resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
        if (serverAttrs && !model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);

      // Set temporary attributes if `{wait: true}` to properly find new ids.
      if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);

      var method = this.isNew() ? 'create' : options.patch ? 'patch' : 'update';
      if (method === 'patch' && !options.attrs) options.attrs = attrs;
      var xhr = this.sync(method, this, options);

      // Restore attributes.
      this.attributes = attributes;

      return xhr;
    },

    // Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;
      var wait = options.wait;

      var destroy = function() {
        model.stopListening();
        model.trigger('destroy', model, model.collection, options);
      };

      options.success = function(resp) {
        if (wait) destroy();
        if (success) success.call(options.context, model, resp, options);
        if (!model.isNew()) model.trigger('sync', model, resp, options);
      };

      var xhr = false;
      if (this.isNew()) {
        _.defer(options.success);
      } else {
        wrapError(this, options);
        xhr = this.sync('delete', this, options);
      }
      if (!wait) destroy();
      return xhr;
    },

    // Default URL for the model's representation on the server -- if you're
    // using Backbone's restful methods, override this to change the endpoint
    // that will be called.
    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      var id = this.get(this.idAttribute);
      return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new model with identical attributes to this one.
    clone: function() {
      return new this.constructor(this.attributes);
    },

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew: function() {
      return !this.has(this.idAttribute);
    },

    // Check if the model is currently in a valid state.
    isValid: function(options) {
      return this._validate({}, _.extend({}, options, {validate: true}));
    },

    // Run validation against the next complete set of model attributes,
    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    _validate: function(attrs, options) {
      if (!options.validate || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      var error = this.validationError = this.validate(attrs, options) || null;
      if (!error) return true;
      this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
      return false;
    }

  });

  // Backbone.Collection
  // -------------------

  // If models tend to represent a single row of data, a Backbone Collection is
  // more analogous to a table full of data ... or a small slice or page of that
  // table, or a collection of rows that belong together for a particular reason
  // -- all of the messages in this particular folder, all of the documents
  // belonging to this particular author, and so on. Collections maintain
  // indexes of their models, both in order, and for lookup by `id`.

  // Create a new **Collection**, perhaps to contain a specific type of `model`.
  // If a `comparator` is specified, the Collection will maintain
  // its models in sort order, as they're added and removed.
  var Collection = Backbone.Collection = function(models, options) {
    options || (options = {});
    this.preinitialize.apply(this, arguments);
    if (options.model) this.model = options.model;
    if (options.comparator !== void 0) this.comparator = options.comparator;
    this._reset();
    this.initialize.apply(this, arguments);
    if (models) this.reset(models, _.extend({silent: true}, options));
  };

  // Default options for `Collection#set`.
  var setOptions = {add: true, remove: true, merge: true};
  var addOptions = {add: true, remove: false};

  // Splices `insert` into `array` at index `at`.
  var splice = function(array, insert, at) {
    at = Math.min(Math.max(at, 0), array.length);
    var tail = Array(array.length - at);
    var length = insert.length;
    var i;
    for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
    for (i = 0; i < length; i++) array[i + at] = insert[i];
    for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
  };

  // Define the Collection's inheritable methods.
  _.extend(Collection.prototype, Events, {

    // The default model for a collection is just a **Backbone.Model**.
    // This should be overridden in most cases.
    model: Model,


    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the Collection.
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // The JSON representation of a Collection is an array of the
    // models' attributes.
    toJSON: function(options) {
      return this.map(function(model) { return model.toJSON(options); });
    },

    // Proxy `Backbone.sync` by default.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

    // Add a model, or list of models to the set. `models` may be Backbone
    // Models or raw JavaScript objects to be converted to Models, or any
    // combination of the two.
    add: function(models, options) {
      return this.set(models, _.extend({merge: false}, options, addOptions));
    },

    // Remove a model, or a list of models from the set.
    remove: function(models, options) {
      options = _.extend({}, options);
      var singular = !_.isArray(models);
      models = singular ? [models] : models.slice();
      var removed = this._removeModels(models, options);
      if (!options.silent && removed.length) {
        options.changes = {added: [], merged: [], removed: removed};
        this.trigger('update', this, options);
      }
      return singular ? removed[0] : removed;
    },

    // Update a collection by `set`-ing a new list of models, adding new ones,
    // removing models that are no longer present, and merging models that
    // already exist in the collection, as necessary. Similar to **Model#set**,
    // the core operation for updating the data contained by the collection.
    set: function(models, options) {
      if (models == null) return;

      options = _.extend({}, setOptions, options);
      if (options.parse && !this._isModel(models)) {
        models = this.parse(models, options) || [];
      }

      var singular = !_.isArray(models);
      models = singular ? [models] : models.slice();

      var at = options.at;
      if (at != null) at = +at;
      if (at > this.length) at = this.length;
      if (at < 0) at += this.length + 1;

      var set = [];
      var toAdd = [];
      var toMerge = [];
      var toRemove = [];
      var modelMap = {};

      var add = options.add;
      var merge = options.merge;
      var remove = options.remove;

      var sort = false;
      var sortable = this.comparator && at == null && options.sort !== false;
      var sortAttr = _.isString(this.comparator) ? this.comparator : null;

      // Turn bare objects into model references, and prevent invalid models
      // from being added.
      var model, i;
      for (i = 0; i < models.length; i++) {
        model = models[i];

        // If a duplicate is found, prevent it from being added and
        // optionally merge it into the existing model.
        var existing = this.get(model);
        if (existing) {
          if (merge && model !== existing) {
            var attrs = this._isModel(model) ? model.attributes : model;
            if (options.parse) attrs = existing.parse(attrs, options);
            existing.set(attrs, options);
            toMerge.push(existing);
            if (sortable && !sort) sort = existing.hasChanged(sortAttr);
          }
          if (!modelMap[existing.cid]) {
            modelMap[existing.cid] = true;
            set.push(existing);
          }
          models[i] = existing;

        // If this is a new, valid model, push it to the `toAdd` list.
        } else if (add) {
          model = models[i] = this._prepareModel(model, options);
          if (model) {
            toAdd.push(model);
            this._addReference(model, options);
            modelMap[model.cid] = true;
            set.push(model);
          }
        }
      }

      // Remove stale models.
      if (remove) {
        for (i = 0; i < this.length; i++) {
          model = this.models[i];
          if (!modelMap[model.cid]) toRemove.push(model);
        }
        if (toRemove.length) this._removeModels(toRemove, options);
      }

      // See if sorting is needed, update `length` and splice in new models.
      var orderChanged = false;
      var replace = !sortable && add && remove;
      if (set.length && replace) {
        orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
          return m !== set[index];
        });
        this.models.length = 0;
        splice(this.models, set, 0);
        this.length = this.models.length;
      } else if (toAdd.length) {
        if (sortable) sort = true;
        splice(this.models, toAdd, at == null ? this.length : at);
        this.length = this.models.length;
      }

      // Silently sort the collection if appropriate.
      if (sort) this.sort({silent: true});

      // Unless silenced, it's time to fire all appropriate add/sort/update events.
      if (!options.silent) {
        for (i = 0; i < toAdd.length; i++) {
          if (at != null) options.index = at + i;
          model = toAdd[i];
          model.trigger('add', model, this, options);
        }
        if (sort || orderChanged) this.trigger('sort', this, options);
        if (toAdd.length || toRemove.length || toMerge.length) {
          options.changes = {
            added: toAdd,
            removed: toRemove,
            merged: toMerge
          };
          this.trigger('update', this, options);
        }
      }

      // Return the added (or merged) model (or models).
      return singular ? models[0] : models;
    },

    // When you have more items than you want to add or remove individually,
    // you can reset the entire set with a new list of models, without firing
    // any granular `add` or `remove` events. Fires `reset` when finished.
    // Useful for bulk operations and optimizations.
    reset: function(models, options) {
      options = options ? _.clone(options) : {};
      for (var i = 0; i < this.models.length; i++) {
        this._removeReference(this.models[i], options);
      }
      options.previousModels = this.models;
      this._reset();
      models = this.add(models, _.extend({silent: true}, options));
      if (!options.silent) this.trigger('reset', this, options);
      return models;
    },

    // Add a model to the end of the collection.
    push: function(model, options) {
      return this.add(model, _.extend({at: this.length}, options));
    },

    // Remove a model from the end of the collection.
    pop: function(options) {
      var model = this.at(this.length - 1);
      return this.remove(model, options);
    },

    // Add a model to the beginning of the collection.
    unshift: function(model, options) {
      return this.add(model, _.extend({at: 0}, options));
    },

    // Remove a model from the beginning of the collection.
    shift: function(options) {
      var model = this.at(0);
      return this.remove(model, options);
    },

    // Slice out a sub-array of models from the collection.
    slice: function() {
      return slice.apply(this.models, arguments);
    },

    // Get a model from the set by id, cid, model object with id or cid
    // properties, or an attributes object that is transformed through modelId.
    get: function(obj) {
      if (obj == null) return void 0;
      return this._byId[obj] ||
        this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj)] ||
        obj.cid && this._byId[obj.cid];
    },

    // Returns `true` if the model is in the collection.
    has: function(obj) {
      return this.get(obj) != null;
    },

    // Get the model at the given index.
    at: function(index) {
      if (index < 0) index += this.length;
      return this.models[index];
    },

    // Return models with matching attributes. Useful for simple cases of
    // `filter`.
    where: function(attrs, first) {
      return this[first ? 'find' : 'filter'](attrs);
    },

    // Return the first model with matching attributes. Useful for simple cases
    // of `find`.
    findWhere: function(attrs) {
      return this.where(attrs, true);
    },

    // Force the collection to re-sort itself. You don't need to call this under
    // normal circumstances, as the set will maintain sort order as each item
    // is added.
    sort: function(options) {
      var comparator = this.comparator;
      if (!comparator) throw new Error('Cannot sort a set without a comparator');
      options || (options = {});

      var length = comparator.length;
      if (_.isFunction(comparator)) comparator = comparator.bind(this);

      // Run sort based on type of `comparator`.
      if (length === 1 || _.isString(comparator)) {
        this.models = this.sortBy(comparator);
      } else {
        this.models.sort(comparator);
      }
      if (!options.silent) this.trigger('sort', this, options);
      return this;
    },

    // Pluck an attribute from each model in the collection.
    pluck: function(attr) {
      return this.map(attr + '');
    },

    // Fetch the default set of models for this collection, resetting the
    // collection when they arrive. If `reset: true` is passed, the response
    // data will be passed through the `reset` method instead of `set`.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var success = options.success;
      var collection = this;
      options.success = function(resp) {
        var method = options.reset ? 'reset' : 'set';
        collection[method](resp, options);
        if (success) success.call(options.context, collection, resp, options);
        collection.trigger('sync', collection, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Create a new instance of a model in this collection. Add the model to the
    // collection immediately, unless `wait: true` is passed, in which case we
    // wait for the server to agree.
    create: function(model, options) {
      options = options ? _.clone(options) : {};
      var wait = options.wait;
      model = this._prepareModel(model, options);
      if (!model) return false;
      if (!wait) this.add(model, options);
      var collection = this;
      var success = options.success;
      options.success = function(m, resp, callbackOpts) {
        if (wait) collection.add(m, callbackOpts);
        if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
      };
      model.save(null, options);
      return model;
    },

    // **parse** converts a response into a list of models to be added to the
    // collection. The default implementation is just to pass it through.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new collection with an identical list of models as this one.
    clone: function() {
      return new this.constructor(this.models, {
        model: this.model,
        comparator: this.comparator
      });
    },

    // Define how to uniquely identify models in the collection.
    modelId: function(attrs) {
      return attrs[this.model.prototype.idAttribute || 'id'];
    },

    // Get an iterator of all models in this collection.
    values: function() {
      return new CollectionIterator(this, ITERATOR_VALUES);
    },

    // Get an iterator of all model IDs in this collection.
    keys: function() {
      return new CollectionIterator(this, ITERATOR_KEYS);
    },

    // Get an iterator of all [ID, model] tuples in this collection.
    entries: function() {
      return new CollectionIterator(this, ITERATOR_KEYSVALUES);
    },

    // Private method to reset all internal state. Called when the collection
    // is first initialized or reset.
    _reset: function() {
      this.length = 0;
      this.models = [];
      this._byId  = {};
    },

    // Prepare a hash of attributes (or other model) to be added to this
    // collection.
    _prepareModel: function(attrs, options) {
      if (this._isModel(attrs)) {
        if (!attrs.collection) attrs.collection = this;
        return attrs;
      }
      options = options ? _.clone(options) : {};
      options.collection = this;
      var model = new this.model(attrs, options);
      if (!model.validationError) return model;
      this.trigger('invalid', this, model.validationError, options);
      return false;
    },

    // Internal method called by both remove and set.
    _removeModels: function(models, options) {
      var removed = [];
      for (var i = 0; i < models.length; i++) {
        var model = this.get(models[i]);
        if (!model) continue;

        var index = this.indexOf(model);
        this.models.splice(index, 1);
        this.length--;

        // Remove references before triggering 'remove' event to prevent an
        // infinite loop. #3693
        delete this._byId[model.cid];
        var id = this.modelId(model.attributes);
        if (id != null) delete this._byId[id];

        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }

        removed.push(model);
        this._removeReference(model, options);
      }
      return removed;
    },

    // Method for checking whether an object should be considered a model for
    // the purposes of adding to the collection.
    _isModel: function(model) {
      return model instanceof Model;
    },

    // Internal method to create a model's ties to a collection.
    _addReference: function(model, options) {
      this._byId[model.cid] = model;
      var id = this.modelId(model.attributes);
      if (id != null) this._byId[id] = model;
      model.on('all', this._onModelEvent, this);
    },

    // Internal method to sever a model's ties to a collection.
    _removeReference: function(model, options) {
      delete this._byId[model.cid];
      var id = this.modelId(model.attributes);
      if (id != null) delete this._byId[id];
      if (this === model.collection) delete model.collection;
      model.off('all', this._onModelEvent, this);
    },

    // Internal method called every time a model in the set fires an event.
    // Sets need to update their indexes when models change ids. All other
    // events simply proxy through. "add" and "remove" events that originate
    // in other collections are ignored.
    _onModelEvent: function(event, model, collection, options) {
      if (model) {
        if ((event === 'add' || event === 'remove') && collection !== this) return;
        if (event === 'destroy') this.remove(model, options);
        if (event === 'change') {
          var prevId = this.modelId(model.previousAttributes());
          var id = this.modelId(model.attributes);
          if (prevId !== id) {
            if (prevId != null) delete this._byId[prevId];
            if (id != null) this._byId[id] = model;
          }
        }
      }
      this.trigger.apply(this, arguments);
    }

  });

  // Defining an @@iterator method implements JavaScript's Iterable protocol.
  // In modern ES2015 browsers, this value is found at Symbol.iterator.
  /* global Symbol */
  var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
  if ($$iterator) {
    Collection.prototype[$$iterator] = Collection.prototype.values;
  }

  // CollectionIterator
  // ------------------

  // A CollectionIterator implements JavaScript's Iterator protocol, allowing the
  // use of `for of` loops in modern browsers and interoperation between
  // Backbone.Collection and other JavaScript functions and third-party libraries
  // which can operate on Iterables.
  var CollectionIterator = function(collection, kind) {
    this._collection = collection;
    this._kind = kind;
    this._index = 0;
  };

  // This "enum" defines the three possible kinds of values which can be emitted
  // by a CollectionIterator that correspond to the values(), keys() and entries()
  // methods on Collection, respectively.
  var ITERATOR_VALUES = 1;
  var ITERATOR_KEYS = 2;
  var ITERATOR_KEYSVALUES = 3;

  // All Iterators should themselves be Iterable.
  if ($$iterator) {
    CollectionIterator.prototype[$$iterator] = function() {
      return this;
    };
  }

  CollectionIterator.prototype.next = function() {
    if (this._collection) {

      // Only continue iterating if the iterated collection is long enough.
      if (this._index < this._collection.length) {
        var model = this._collection.at(this._index);
        this._index++;

        // Construct a value depending on what kind of values should be iterated.
        var value;
        if (this._kind === ITERATOR_VALUES) {
          value = model;
        } else {
          var id = this._collection.modelId(model.attributes);
          if (this._kind === ITERATOR_KEYS) {
            value = id;
          } else { // ITERATOR_KEYSVALUES
            value = [id, model];
          }
        }
        return {value: value, done: false};
      }

      // Once exhausted, remove the reference to the collection so future
      // calls to the next method always return done.
      this._collection = void 0;
    }

    return {value: void 0, done: true};
  };

  // Backbone.View
  // -------------

  // Backbone Views are almost more convention than they are actual code. A View
  // is simply a JavaScript object that represents a logical chunk of UI in the
  // DOM. This might be a single item, an entire list, a sidebar or panel, or
  // even the surrounding frame which wraps your whole app. Defining a chunk of
  // UI as a **View** allows you to define your DOM events declaratively, without
  // having to worry about render order ... and makes it easy for the view to
  // react to specific changes in the state of your models.

  // Creating a Backbone.View creates its initial element outside of the DOM,
  // if an existing element is not provided...
  var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    this.preinitialize.apply(this, arguments);
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
  };

  // Cached regex to split keys for `delegate`.
  var delegateEventSplitter = /^(\S+)\s*(.*)$/;

  // List of view options to be set as properties.
  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

  // Set up all inheritable **Backbone.View** properties and methods.
  _.extend(View.prototype, Events, {

    // The default `tagName` of a View's element is `"div"`.
    tagName: 'div',

    // jQuery delegate for element lookup, scoped to DOM elements within the
    // current view. This should be preferred to global lookups where possible.
    $: function(selector) {
      return this.$el.find(selector);
    },

    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the View
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
    render: function() {
      return this;
    },

    // Remove this view by taking the element out of the DOM, and removing any
    // applicable Backbone.Events listeners.
    remove: function() {
      this._removeElement();
      this.stopListening();
      return this;
    },

    // Remove this view's element from the document and all event listeners
    // attached to it. Exposed for subclasses using an alternative DOM
    // manipulation API.
    _removeElement: function() {
      this.$el.remove();
    },

    // Change the view's element (`this.el` property) and re-delegate the
    // view's events on the new element.
    setElement: function(element) {
      this.undelegateEvents();
      this._setElement(element);
      this.delegateEvents();
      return this;
    },

    // Creates the `this.el` and `this.$el` references for this view using the
    // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
    // context or an element. Subclasses can override this to utilize an
    // alternative DOM manipulation API and are only required to set the
    // `this.el` property.
    _setElement: function(el) {
      this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
      this.el = this.$el[0];
    },

    // Set callbacks, where `this.events` is a hash of
    //
    // *{"event selector": "callback"}*
    //
    //     {
    //       'mousedown .title':  'edit',
    //       'click .button':     'save',
    //       'click .open':       function(e) { ... }
    //     }
    //
    // pairs. Callbacks will be bound to the view, with `this` set properly.
    // Uses event delegation for efficiency.
    // Omitting the selector binds the event to `this.el`.
    delegateEvents: function(events) {
      events || (events = _.result(this, 'events'));
      if (!events) return this;
      this.undelegateEvents();
      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[method];
        if (!method) continue;
        var match = key.match(delegateEventSplitter);
        this.delegate(match[1], match[2], method.bind(this));
      }
      return this;
    },

    // Add a single event listener to the view's element (or a child element
    // using `selector`). This only works for delegate-able events: not `focus`,
    // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
    delegate: function(eventName, selector, listener) {
      this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Clears all callbacks previously bound to the view by `delegateEvents`.
    // You usually don't need to use this, but may wish to if you have multiple
    // Backbone views attached to the same DOM element.
    undelegateEvents: function() {
      if (this.$el) this.$el.off('.delegateEvents' + this.cid);
      return this;
    },

    // A finer-grained `undelegateEvents` for removing a single delegated event.
    // `selector` and `listener` are both optional.
    undelegate: function(eventName, selector, listener) {
      this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Produces a DOM element to be assigned to your view. Exposed for
    // subclasses using an alternative DOM manipulation API.
    _createElement: function(tagName) {
      return document.createElement(tagName);
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function() {
      if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        this.setElement(this._createElement(_.result(this, 'tagName')));
        this._setAttributes(attrs);
      } else {
        this.setElement(_.result(this, 'el'));
      }
    },

    // Set attributes from a hash on this view's element.  Exposed for
    // subclasses using an alternative DOM manipulation API.
    _setAttributes: function(attributes) {
      this.$el.attr(attributes);
    }

  });

  // Proxy Backbone class methods to Underscore functions, wrapping the model's
  // `attributes` object or collection's `models` array behind the scenes.
  //
  // collection.filter(function(model) { return model.get('age') > 10 });
  // collection.each(this.addView);
  //
  // `Function#apply` can be slow so we use the method's arg count, if we know it.
  var addMethod = function(base, length, method, attribute) {
    switch (length) {
      case 1: return function() {
        return base[method](this[attribute]);
      };
      case 2: return function(value) {
        return base[method](this[attribute], value);
      };
      case 3: return function(iteratee, context) {
        return base[method](this[attribute], cb(iteratee, this), context);
      };
      case 4: return function(iteratee, defaultVal, context) {
        return base[method](this[attribute], cb(iteratee, this), defaultVal, context);
      };
      default: return function() {
        var args = slice.call(arguments);
        args.unshift(this[attribute]);
        return base[method].apply(base, args);
      };
    }
  };

  var addUnderscoreMethods = function(Class, base, methods, attribute) {
    _.each(methods, function(length, method) {
      if (base[method]) Class.prototype[method] = addMethod(base, length, method, attribute);
    });
  };

  // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
  var cb = function(iteratee, instance) {
    if (_.isFunction(iteratee)) return iteratee;
    if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
    if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
    return iteratee;
  };
  var modelMatcher = function(attrs) {
    var matcher = _.matches(attrs);
    return function(model) {
      return matcher(model.attributes);
    };
  };

  // Underscore methods that we want to implement on the Collection.
  // 90% of the core usefulness of Backbone Collections is actually implemented
  // right here:
  var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
    foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
    select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
    contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
    head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
    without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
    isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
    sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};


  // Underscore methods that we want to implement on the Model, mapped to the
  // number of arguments they take.
  var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
    omit: 0, chain: 1, isEmpty: 1};

  // Mix in each Underscore method as a proxy to `Collection#models`.

  _.each([
    [Collection, collectionMethods, 'models'],
    [Model, modelMethods, 'attributes']
  ], function(config) {
    var Base = config[0],
        methods = config[1],
        attribute = config[2];

    Base.mixin = function(obj) {
      var mappings = _.reduce(_.functions(obj), function(memo, name) {
        memo[name] = 0;
        return memo;
      }, {});
      addUnderscoreMethods(Base, obj, mappings, attribute);
    };

    addUnderscoreMethods(Base, _, methods, attribute);
  });

  // Backbone.sync
  // -------------

  // Override this function to change the manner in which Backbone persists
  // models to the server. You will be passed the type of request, and the
  // model in question. By default, makes a RESTful Ajax request
  // to the model's `url()`. Some possible customizations could be:
  //
  // * Use `setTimeout` to batch rapid-fire updates into a single request.
  // * Send up the models as XML instead of JSON.
  // * Persist models via WebSockets instead of Ajax.
  //
  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  // as `POST`, with a `_method` parameter containing the true HTTP method,
  // as well as all requests with the body as `application/x-www-form-urlencoded`
  // instead of `application/json` with the model in a param named `model`.
  // Useful when interfacing with server-side languages like **PHP** that make
  // it difficult to read the body of `PUT` requests.
  Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default options, unless specified.
    _.defaults(options || (options = {}), {
      emulateHTTP: Backbone.emulateHTTP,
      emulateJSON: Backbone.emulateJSON
    });

    // Default JSON-request options.
    var params = {type: type, dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(options.attrs || model.toJSON(options));
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (options.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data = params.data ? {model: params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
      params.type = 'POST';
      if (options.emulateJSON) params.data._method = type;
      var beforeSend = options.beforeSend;
      options.beforeSend = function(xhr) {
        xhr.setRequestHeader('X-HTTP-Method-Override', type);
        if (beforeSend) return beforeSend.apply(this, arguments);
      };
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !options.emulateJSON) {
      params.processData = false;
    }

    // Pass along `textStatus` and `errorThrown` from jQuery.
    var error = options.error;
    options.error = function(xhr, textStatus, errorThrown) {
      options.textStatus = textStatus;
      options.errorThrown = errorThrown;
      if (error) error.call(options.context, xhr, textStatus, errorThrown);
    };

    // Make the request, allowing the user to override any Ajax options.
    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
    model.trigger('request', model, xhr, options);
    return xhr;
  };

  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  var methodMap = {
    create: 'POST',
    update: 'PUT',
    patch: 'PATCH',
    delete: 'DELETE',
    read: 'GET'
  };

  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  // Override this if you'd like to use a different library.
  Backbone.ajax = function() {
    return Backbone.$.ajax.apply(Backbone.$, arguments);
  };

  // Backbone.Router
  // ---------------

  // Routers map faux-URLs to actions, and fire events when routes are
  // matched. Creating a new one sets its `routes` hash, if not set statically.
  var Router = Backbone.Router = function(options) {
    options || (options = {});
    this.preinitialize.apply(this, arguments);
    if (options.routes) this.routes = options.routes;
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

  // Cached regular expressions for matching named param parts and splatted
  // parts of route strings.
  var optionalParam = /\((.*?)\)/g;
  var namedParam    = /(\(\?)?:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;

  // Set up all inheritable **Backbone.Router** properties and methods.
  _.extend(Router.prototype, Events, {

    // preinitialize is an empty function by default. You can override it with a function
    // or object.  preinitialize will run before any instantiation logic is run in the Router.
    preinitialize: function(){},

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Manually bind a single named route to a callback. For example:
    //
    //     this.route('search/:query/p:num', 'search', function(query, num) {
    //       ...
    //     });
    //
    route: function(route, name, callback) {
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      if (_.isFunction(name)) {
        callback = name;
        name = '';
      }
      if (!callback) callback = this[name];
      var router = this;
      Backbone.history.route(route, function(fragment) {
        var args = router._extractParameters(route, fragment);
        if (router.execute(callback, args, name) !== false) {
          router.trigger.apply(router, ['route:' + name].concat(args));
          router.trigger('route', name, args);
          Backbone.history.trigger('route', router, name, args);
        }
      });
      return this;
    },

    // Execute a route handler with the provided parameters.  This is an
    // excellent place to do pre-route setup or post-route cleanup.
    execute: function(callback, args, name) {
      if (callback) callback.apply(this, args);
    },

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
      return this;
    },

    // Bind all defined routes to `Backbone.history`. We have to reverse the
    // order of the routes here to support behavior where the most general
    // routes can be defined at the bottom of the route map.
    _bindRoutes: function() {
      if (!this.routes) return;
      this.routes = _.result(this, 'routes');
      var route, routes = _.keys(this.routes);
      while ((route = routes.pop()) != null) {
        this.route(route, this.routes[route]);
      }
    },

    // Convert a route string into a regular expression, suitable for matching
    // against the current location hash.
    _routeToRegExp: function(route) {
      route = route.replace(escapeRegExp, '\\$&')
        .replace(optionalParam, '(?:$1)?')
        .replace(namedParam, function(match, optional) {
          return optional ? match : '([^/?]+)';
        })
        .replace(splatParam, '([^?]*?)');
      return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
    },

    // Given a route, and a URL fragment that it matches, return the array of
    // extracted decoded parameters. Empty or unmatched parameters will be
    // treated as `null` to normalize cross-browser behavior.
    _extractParameters: function(route, fragment) {
      var params = route.exec(fragment).slice(1);
      return _.map(params, function(param, i) {
        // Don't decode the search params.
        if (i === params.length - 1) return param || null;
        return param ? decodeURIComponent(param) : null;
      });
    }

  });

  // Backbone.History
  // ----------------

  // Handles cross-browser history management, based on either
  // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
  // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
  // and URL fragments. If the browser supports neither (old IE, natch),
  // falls back to polling.
  var History = Backbone.History = function() {
    this.handlers = [];
    this.checkUrl = this.checkUrl.bind(this);

    // Ensure that `History` can be used outside of the browser.
    if (typeof window !== 'undefined') {
      this.location = window.location;
      this.history = window.history;
    }
  };

  // Cached regex for stripping a leading hash/slash and trailing space.
  var routeStripper = /^[#\/]|\s+$/g;

  // Cached regex for stripping leading and trailing slashes.
  var rootStripper = /^\/+|\/+$/g;

  // Cached regex for stripping urls of hash.
  var pathStripper = /#.*$/;

  // Has the history handling already been started?
  History.started = false;

  // Set up all inheritable **Backbone.History** properties and methods.
  _.extend(History.prototype, Events, {

    // The default interval to poll for hash changes, if necessary, is
    // twenty times a second.
    interval: 50,

    // Are we at the app root?
    atRoot: function() {
      var path = this.location.pathname.replace(/[^\/]$/, '$&/');
      return path === this.root && !this.getSearch();
    },

    // Does the pathname match the root?
    matchRoot: function() {
      var path = this.decodeFragment(this.location.pathname);
      var rootPath = path.slice(0, this.root.length - 1) + '/';
      return rootPath === this.root;
    },

    // Unicode characters in `location.pathname` are percent encoded so they're
    // decoded for comparison. `%25` should not be decoded since it may be part
    // of an encoded parameter.
    decodeFragment: function(fragment) {
      return decodeURI(fragment.replace(/%25/g, '%2525'));
    },

    // In IE6, the hash fragment and search params are incorrect if the
    // fragment contains `?`.
    getSearch: function() {
      var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
      return match ? match[0] : '';
    },

    // Gets the true hash value. Cannot use location.hash directly due to bug
    // in Firefox where location.hash will always be decoded.
    getHash: function(window) {
      var match = (window || this).location.href.match(/#(.*)$/);
      return match ? match[1] : '';
    },

    // Get the pathname and search params, without the root.
    getPath: function() {
      var path = this.decodeFragment(
        this.location.pathname + this.getSearch()
      ).slice(this.root.length - 1);
      return path.charAt(0) === '/' ? path.slice(1) : path;
    },

    // Get the cross-browser normalized URL fragment from the path or hash.
    getFragment: function(fragment) {
      if (fragment == null) {
        if (this._usePushState || !this._wantsHashChange) {
          fragment = this.getPath();
        } else {
          fragment = this.getHash();
        }
      }
      return fragment.replace(routeStripper, '');
    },

    // Start the hash change handling, returning `true` if the current URL matches
    // an existing route, and `false` otherwise.
    start: function(options) {
      if (History.started) throw new Error('Backbone.history has already been started');
      History.started = true;

      // Figure out the initial configuration. Do we need an iframe?
      // Is pushState desired ... is it available?
      this.options          = _.extend({root: '/'}, this.options, options);
      this.root             = this.options.root;
      this._wantsHashChange = this.options.hashChange !== false;
      this._hasHashChange   = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
      this._useHashChange   = this._wantsHashChange && this._hasHashChange;
      this._wantsPushState  = !!this.options.pushState;
      this._hasPushState    = !!(this.history && this.history.pushState);
      this._usePushState    = this._wantsPushState && this._hasPushState;
      this.fragment         = this.getFragment();

      // Normalize root to always include a leading and trailing slash.
      this.root = ('/' + this.root + '/').replace(rootStripper, '/');

      // Transition from hashChange to pushState or vice versa if both are
      // requested.
      if (this._wantsHashChange && this._wantsPushState) {

        // If we've started off with a route from a `pushState`-enabled
        // browser, but we're currently in a browser that doesn't support it...
        if (!this._hasPushState && !this.atRoot()) {
          var rootPath = this.root.slice(0, -1) || '/';
          this.location.replace(rootPath + '#' + this.getPath());
          // Return immediately as browser will do redirect to new url
          return true;

        // Or if we've started out with a hash-based route, but we're currently
        // in a browser where it could be `pushState`-based instead...
        } else if (this._hasPushState && this.atRoot()) {
          this.navigate(this.getHash(), {replace: true});
        }

      }

      // Proxy an iframe to handle location events if the browser doesn't
      // support the `hashchange` event, HTML5 history, or the user wants
      // `hashChange` but not `pushState`.
      if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
        this.iframe = document.createElement('iframe');
        this.iframe.src = 'javascript:0';
        this.iframe.style.display = 'none';
        this.iframe.tabIndex = -1;
        var body = document.body;
        // Using `appendChild` will throw on IE < 9 if the document is not ready.
        var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
        iWindow.document.open();
        iWindow.document.close();
        iWindow.location.hash = '#' + this.fragment;
      }

      // Add a cross-platform `addEventListener` shim for older browsers.
      var addEventListener = window.addEventListener || function(eventName, listener) {
        return attachEvent('on' + eventName, listener);
      };

      // Depending on whether we're using pushState or hashes, and whether
      // 'onhashchange' is supported, determine how we check the URL state.
      if (this._usePushState) {
        addEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        addEventListener('hashchange', this.checkUrl, false);
      } else if (this._wantsHashChange) {
        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
      }

      if (!this.options.silent) return this.loadUrl();
    },

    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
    // but possibly useful for unit testing Routers.
    stop: function() {
      // Add a cross-platform `removeEventListener` shim for older browsers.
      var removeEventListener = window.removeEventListener || function(eventName, listener) {
        return detachEvent('on' + eventName, listener);
      };

      // Remove window listeners.
      if (this._usePushState) {
        removeEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        removeEventListener('hashchange', this.checkUrl, false);
      }

      // Clean up the iframe if necessary.
      if (this.iframe) {
        document.body.removeChild(this.iframe);
        this.iframe = null;
      }

      // Some environments will throw when clearing an undefined interval.
      if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
      History.started = false;
    },

    // Add a route to be tested when the fragment changes. Routes added later
    // may override previous routes.
    route: function(route, callback) {
      this.handlers.unshift({route: route, callback: callback});
    },

    // Checks the current URL to see if it has changed, and if it has,
    // calls `loadUrl`, normalizing across the hidden iframe.
    checkUrl: function(e) {
      var current = this.getFragment();

      // If the user pressed the back button, the iframe's hash will have
      // changed and we should use that for comparison.
      if (current === this.fragment && this.iframe) {
        current = this.getHash(this.iframe.contentWindow);
      }

      if (current === this.fragment) return false;
      if (this.iframe) this.navigate(current);
      this.loadUrl();
    },

    // Attempt to load the current URL fragment. If a route succeeds with a
    // match, returns `true`. If no defined routes matches the fragment,
    // returns `false`.
    loadUrl: function(fragment) {
      // If the root doesn't match, no routes can match either.
      if (!this.matchRoot()) return false;
      fragment = this.fragment = this.getFragment(fragment);
      return _.some(this.handlers, function(handler) {
        if (handler.route.test(fragment)) {
          handler.callback(fragment);
          return true;
        }
      });
    },

    // Save a fragment into the hash history, or replace the URL state if the
    // 'replace' option is passed. You are responsible for properly URL-encoding
    // the fragment in advance.
    //
    // The options object can contain `trigger: true` if you wish to have the
    // route callback be fired (not usually desirable), or `replace: true`, if
    // you wish to modify the current URL without adding an entry to the history.
    navigate: function(fragment, options) {
      if (!History.started) return false;
      if (!options || options === true) options = {trigger: !!options};

      // Normalize the fragment.
      fragment = this.getFragment(fragment || '');

      // Don't include a trailing slash on the root.
      var rootPath = this.root;
      if (fragment === '' || fragment.charAt(0) === '?') {
        rootPath = rootPath.slice(0, -1) || '/';
      }
      var url = rootPath + fragment;

      // Strip the fragment of the query and hash for matching.
      fragment = fragment.replace(pathStripper, '');

      // Decode for matching.
      var decodedFragment = this.decodeFragment(fragment);

      if (this.fragment === decodedFragment) return;
      this.fragment = decodedFragment;

      // If pushState is available, we use it to set the fragment as a real URL.
      if (this._usePushState) {
        this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);

      // If hash changes haven't been explicitly disabled, update the hash
      // fragment to store history.
      } else if (this._wantsHashChange) {
        this._updateHash(this.location, fragment, options.replace);
        if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
          var iWindow = this.iframe.contentWindow;

          // Opening and closing the iframe tricks IE7 and earlier to push a
          // history entry on hash-tag change.  When replace is true, we don't
          // want this.
          if (!options.replace) {
            iWindow.document.open();
            iWindow.document.close();
          }

          this._updateHash(iWindow.location, fragment, options.replace);
        }

      // If you've told us that you explicitly don't want fallback hashchange-
      // based history, then `navigate` becomes a page refresh.
      } else {
        return this.location.assign(url);
      }
      if (options.trigger) return this.loadUrl(fragment);
    },

    // Update the hash location, either replacing the current entry, or adding
    // a new one to the browser history.
    _updateHash: function(location, fragment, replace) {
      if (replace) {
        var href = location.href.replace(/(javascript:|#).*$/, '');
        location.replace(href + '#' + fragment);
      } else {
        // Some browsers require that `hash` contains a leading #.
        location.hash = '#' + fragment;
      }
    }

  });

  // Create the default Backbone.history.
  Backbone.history = new History;

  // Helpers
  // -------

  // Helper function to correctly set up the prototype chain for subclasses.
  // Similar to `goog.inherits`, but uses a hash of prototype properties and
  // class properties to be extended.
  var extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Add static properties to the constructor function, if supplied.
    _.extend(child, parent, staticProps);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function and add the prototype properties.
    child.prototype = _.create(parent.prototype, protoProps);
    child.prototype.constructor = child;

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
  };

  // Set up inheritance for the model, collection, router, view and history.
  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;

  // Throw an error when a URL is needed, and none is supplied.
  var urlError = function() {
    throw new Error('A "url" property or function must be specified');
  };

  // Wrap an optional error callback with a fallback error event.
  var wrapError = function(model, options) {
    var error = options.error;
    options.error = function(resp) {
      if (error) error.call(options.context, model, resp, options);
      model.trigger('error', model, resp, options);
    };
  };

  return Backbone;
});


/***/ }),

/***/ "./node_modules/jquery/dist/jquery.js":
/*!********************************************!*\
  !*** ./node_modules/jquery/dist/jquery.js ***!
  \********************************************/
/***/ (function(module, exports) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery JavaScript Library v3.6.0
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2021-03-02T17:08Z
 */
( function( global, factory ) {

	"use strict";

	if (  true && typeof module.exports === "object" ) {

		// For CommonJS and CommonJS-like environments where a proper `window`
		// is present, execute the factory and get jQuery.
		// For environments that do not have a `window` with a `document`
		// (such as Node.js), expose a factory as module.exports.
		// This accentuates the need for the creation of a real `window`.
		// e.g. var jQuery = require("jquery")(window);
		// See ticket #14549 for more info.
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "jQuery requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		factory( global );
	}

// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";

var arr = [];

var getProto = Object.getPrototypeOf;

var slice = arr.slice;

var flat = arr.flat ? function( array ) {
	return arr.flat.call( array );
} : function( array ) {
	return arr.concat.apply( [], array );
};


var push = arr.push;

var indexOf = arr.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var fnToString = hasOwn.toString;

var ObjectFunctionString = fnToString.call( Object );

var support = {};

var isFunction = function isFunction( obj ) {

		// Support: Chrome <=57, Firefox <=52
		// In some browsers, typeof returns "function" for HTML <object> elements
		// (i.e., `typeof document.createElement( "object" ) === "function"`).
		// We don't want to classify *any* DOM node as a function.
		// Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5
		// Plus for old WebKit, typeof returns "function" for HTML collections
		// (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
		return typeof obj === "function" && typeof obj.nodeType !== "number" &&
			typeof obj.item !== "function";
	};


var isWindow = function isWindow( obj ) {
		return obj != null && obj === obj.window;
	};


var document = window.document;



	var preservedScriptAttributes = {
		type: true,
		src: true,
		nonce: true,
		noModule: true
	};

	function DOMEval( code, node, doc ) {
		doc = doc || document;

		var i, val,
			script = doc.createElement( "script" );

		script.text = code;
		if ( node ) {
			for ( i in preservedScriptAttributes ) {

				// Support: Firefox 64+, Edge 18+
				// Some browsers don't support the "nonce" property on scripts.
				// On the other hand, just using `getAttribute` is not enough as
				// the `nonce` attribute is reset to an empty string whenever it
				// becomes browsing-context connected.
				// See https://github.com/whatwg/html/issues/2369
				// See https://html.spec.whatwg.org/#nonce-attributes
				// The `node.getAttribute` check was added for the sake of
				// `jQuery.globalEval` so that it can fake a nonce-containing node
				// via an object.
				val = node[ i ] || node.getAttribute && node.getAttribute( i );
				if ( val ) {
					script.setAttribute( i, val );
				}
			}
		}
		doc.head.appendChild( script ).parentNode.removeChild( script );
	}


function toType( obj ) {
	if ( obj == null ) {
		return obj + "";
	}

	// Support: Android <=2.3 only (functionish RegExp)
	return typeof obj === "object" || typeof obj === "function" ?
		class2type[ toString.call( obj ) ] || "object" :
		typeof obj;
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module



var
	version = "3.6.0",

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {

		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init( selector, context );
	};

jQuery.fn = jQuery.prototype = {

	// The current version of jQuery being used
	jquery: version,

	constructor: jQuery,

	// The default length of a jQuery object is 0
	length: 0,

	toArray: function() {
		return slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {

		// Return all the elements in a clean array
		if ( num == null ) {
			return slice.call( this );
		}

		// Return just the one element from the set
		return num < 0 ? this[ num + this.length ] : this[ num ];
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	each: function( callback ) {
		return jQuery.each( this, callback );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map( this, function( elem, i ) {
			return callback.call( elem, i, elem );
		} ) );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ) );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	even: function() {
		return this.pushStack( jQuery.grep( this, function( _elem, i ) {
			return ( i + 1 ) % 2;
		} ) );
	},

	odd: function() {
		return this.pushStack( jQuery.grep( this, function( _elem, i ) {
			return i % 2;
		} ) );
	},

	eq: function( i ) {
		var len = this.length,
			j = +i + ( i < 0 ? len : 0 );
		return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
	},

	end: function() {
		return this.prevObject || this.constructor();
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: arr.sort,
	splice: arr.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;

		// Skip the boolean and the target
		target = arguments[ i ] || {};
		i++;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !isFunction( target ) ) {
		target = {};
	}

	// Extend jQuery itself if only one argument is passed
	if ( i === length ) {
		target = this;
		i--;
	}

	for ( ; i < length; i++ ) {

		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) {

			// Extend the base object
			for ( name in options ) {
				copy = options[ name ];

				// Prevent Object.prototype pollution
				// Prevent never-ending loop
				if ( name === "__proto__" || target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = Array.isArray( copy ) ) ) ) {
					src = target[ name ];

					// Ensure proper type for the source value
					if ( copyIsArray && !Array.isArray( src ) ) {
						clone = [];
					} else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
						clone = {};
					} else {
						clone = src;
					}
					copyIsArray = false;

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend( {

	// Unique for each copy of jQuery on the page
	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),

	// Assume jQuery is ready without the ready module
	isReady: true,

	error: function( msg ) {
		throw new Error( msg );
	},

	noop: function() {},

	isPlainObject: function( obj ) {
		var proto, Ctor;

		// Detect obvious negatives
		// Use toString instead of jQuery.type to catch host objects
		if ( !obj || toString.call( obj ) !== "[object Object]" ) {
			return false;
		}

		proto = getProto( obj );

		// Objects with no prototype (e.g., `Object.create( null )`) are plain
		if ( !proto ) {
			return true;
		}

		// Objects with prototype are plain iff they were constructed by a global Object function
		Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
		return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
	},

	isEmptyObject: function( obj ) {
		var name;

		for ( name in obj ) {
			return false;
		}
		return true;
	},

	// Evaluates a script in a provided context; falls back to the global one
	// if not specified.
	globalEval: function( code, options, doc ) {
		DOMEval( code, { nonce: options && options.nonce }, doc );
	},

	each: function( obj, callback ) {
		var length, i = 0;

		if ( isArrayLike( obj ) ) {
			length = obj.length;
			for ( ; i < length; i++ ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		} else {
			for ( i in obj ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		}

		return obj;
	},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArrayLike( Object( arr ) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
						[ arr ] : arr
				);
			} else {
				push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		return arr == null ? -1 : indexOf.call( arr, elem, i );
	},

	// Support: Android <=4.0 only, PhantomJS 1 only
	// push.apply(_, arraylike) throws on ancient WebKit
	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		for ( ; j < len; j++ ) {
			first[ i++ ] = second[ j ];
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, invert ) {
		var callbackInverse,
			matches = [],
			i = 0,
			length = elems.length,
			callbackExpect = !invert;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			callbackInverse = !callback( elems[ i ], i );
			if ( callbackInverse !== callbackExpect ) {
				matches.push( elems[ i ] );
			}
		}

		return matches;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return flat( ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// jQuery.support is not used in Core but other projects attach their
	// properties to it so it needs to exist.
	support: support
} );

if ( typeof Symbol === "function" ) {
	jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
	function( _i, name ) {
		class2type[ "[object " + name + "]" ] = name.toLowerCase();
	} );

function isArrayLike( obj ) {

	// Support: real iOS 8.2 only (not reproducible in simulator)
	// `in` check used to prevent JIT error (gh-2145)
	// hasOwn isn't used here due to false negatives
	// regarding Nodelist length in IE
	var length = !!obj && "length" in obj && obj.length,
		type = toType( obj );

	if ( isFunction( obj ) || isWindow( obj ) ) {
		return false;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
 * Sizzle CSS Selector Engine v2.3.6
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://js.foundation/
 *
 * Date: 2021-02-16
 */
( function( window ) {
var i,
	support,
	Expr,
	getText,
	isXML,
	tokenize,
	compile,
	select,
	outermostContext,
	sortInput,
	hasDuplicate,

	// Local document vars
	setDocument,
	document,
	docElem,
	documentIsHTML,
	rbuggyQSA,
	rbuggyMatches,
	matches,
	contains,

	// Instance-specific data
	expando = "sizzle" + 1 * new Date(),
	preferredDoc = window.document,
	dirruns = 0,
	done = 0,
	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),
	nonnativeSelectorCache = createCache(),
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
		}
		return 0;
	},

	// Instance methods
	hasOwn = ( {} ).hasOwnProperty,
	arr = [],
	pop = arr.pop,
	pushNative = arr.push,
	push = arr.push,
	slice = arr.slice,

	// Use a stripped-down indexOf as it's faster than native
	// https://jsperf.com/thor-indexof-vs-for/5
	indexOf = function( list, elem ) {
		var i = 0,
			len = list.length;
		for ( ; i < len; i++ ) {
			if ( list[ i ] === elem ) {
				return i;
			}
		}
		return -1;
	},

	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" +
		"ismap|loop|multiple|open|readonly|required|scoped",

	// Regular expressions

	// http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",

	// https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
	identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace +
		"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",

	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +

		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +

		// "Attribute values must be CSS identifiers [capture 5]
		// or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" +
		whitespace + "*\\]",

	pseudos = ":(" + identifier + ")(?:\\((" +

		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
		// 1. quoted (capture 3; capture 4 or capture 5)
		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +

		// 2. simple (capture 6)
		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +

		// 3. anything else (capture 2)
		".*" +
		")\\)|)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rwhitespace = new RegExp( whitespace + "+", "g" ),
	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" +
		whitespace + "+$", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace +
		"*" ),
	rdescend = new RegExp( whitespace + "|>" ),

	rpseudo = new RegExp( pseudos ),
	ridentifier = new RegExp( "^" + identifier + "$" ),

	matchExpr = {
		"ID": new RegExp( "^#(" + identifier + ")" ),
		"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
		"TAG": new RegExp( "^(" + identifier + "|[*])" ),
		"ATTR": new RegExp( "^" + attributes ),
		"PSEUDO": new RegExp( "^" + pseudos ),
		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" +
			whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" +
			whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),

		// For use in libraries implementing .is()
		// We use this for POS matching in `select`
		"needsContext": new RegExp( "^" + whitespace +
			"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
			"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
	},

	rhtml = /HTML$/i,
	rinputs = /^(?:input|select|textarea|button)$/i,
	rheader = /^h\d$/i,

	rnative = /^[^{]+\{\s*\[native \w/,

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

	rsibling = /[+~]/,

	// CSS escapes
	// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
	runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ),
	funescape = function( escape, nonHex ) {
		var high = "0x" + escape.slice( 1 ) - 0x10000;

		return nonHex ?

			// Strip the backslash prefix from a non-hex escape sequence
			nonHex :

			// Replace a hexadecimal escape sequence with the encoded Unicode code point
			// Support: IE <=11+
			// For values outside the Basic Multilingual Plane (BMP), manually construct a
			// surrogate pair
			high < 0 ?
				String.fromCharCode( high + 0x10000 ) :
				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
	},

	// CSS string/identifier serialization
	// https://drafts.csswg.org/cssom/#common-serializing-idioms
	rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
	fcssescape = function( ch, asCodePoint ) {
		if ( asCodePoint ) {

			// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
			if ( ch === "\0" ) {
				return "\uFFFD";
			}

			// Control characters and (dependent upon position) numbers get escaped as code points
			return ch.slice( 0, -1 ) + "\\" +
				ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
		}

		// Other potentially-special ASCII characters get backslash-escaped
		return "\\" + ch;
	},

	// Used for iframes
	// See setDocument()
	// Removing the function wrapper causes a "Permission Denied"
	// error in IE
	unloadHandler = function() {
		setDocument();
	},

	inDisabledFieldset = addCombinator(
		function( elem ) {
			return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
		},
		{ dir: "parentNode", next: "legend" }
	);

// Optimize for push.apply( _, NodeList )
try {
	push.apply(
		( arr = slice.call( preferredDoc.childNodes ) ),
		preferredDoc.childNodes
	);

	// Support: Android<4.0
	// Detect silently failing push.apply
	// eslint-disable-next-line no-unused-expressions
	arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
	push = { apply: arr.length ?

		// Leverage slice if possible
		function( target, els ) {
			pushNative.apply( target, slice.call( els ) );
		} :

		// Support: IE<9
		// Otherwise append directly
		function( target, els ) {
			var j = target.length,
				i = 0;

			// Can't trust NodeList.length
			while ( ( target[ j++ ] = els[ i++ ] ) ) {}
			target.length = j - 1;
		}
	};
}

function Sizzle( selector, context, results, seed ) {
	var m, i, elem, nid, match, groups, newSelector,
		newContext = context && context.ownerDocument,

		// nodeType defaults to 9, since context defaults to document
		nodeType = context ? context.nodeType : 9;

	results = results || [];

	// Return early from calls with invalid selector or context
	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {

		return results;
	}

	// Try to shortcut find operations (as opposed to filters) in HTML documents
	if ( !seed ) {
		setDocument( context );
		context = context || document;

		if ( documentIsHTML ) {

			// If the selector is sufficiently simple, try using a "get*By*" DOM method
			// (excepting DocumentFragment context, where the methods don't exist)
			if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) {

				// ID selector
				if ( ( m = match[ 1 ] ) ) {

					// Document context
					if ( nodeType === 9 ) {
						if ( ( elem = context.getElementById( m ) ) ) {

							// Support: IE, Opera, Webkit
							// TODO: identify versions
							// getElementById can match elements by name instead of ID
							if ( elem.id === m ) {
								results.push( elem );
								return results;
							}
						} else {
							return results;
						}

					// Element context
					} else {

						// Support: IE, Opera, Webkit
						// TODO: identify versions
						// getElementById can match elements by name instead of ID
						if ( newContext && ( elem = newContext.getElementById( m ) ) &&
							contains( context, elem ) &&
							elem.id === m ) {

							results.push( elem );
							return results;
						}
					}

				// Type selector
				} else if ( match[ 2 ] ) {
					push.apply( results, context.getElementsByTagName( selector ) );
					return results;

				// Class selector
				} else if ( ( m = match[ 3 ] ) && support.getElementsByClassName &&
					context.getElementsByClassName ) {

					push.apply( results, context.getElementsByClassName( m ) );
					return results;
				}
			}

			// Take advantage of querySelectorAll
			if ( support.qsa &&
				!nonnativeSelectorCache[ selector + " " ] &&
				( !rbuggyQSA || !rbuggyQSA.test( selector ) ) &&

				// Support: IE 8 only
				// Exclude object elements
				( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) {

				newSelector = selector;
				newContext = context;

				// qSA considers elements outside a scoping root when evaluating child or
				// descendant combinators, which is not what we want.
				// In such cases, we work around the behavior by prefixing every selector in the
				// list with an ID selector referencing the scope context.
				// The technique has to be used as well when a leading combinator is used
				// as such selectors are not recognized by querySelectorAll.
				// Thanks to Andrew Dupont for this technique.
				if ( nodeType === 1 &&
					( rdescend.test( selector ) || rcombinators.test( selector ) ) ) {

					// Expand context for sibling selectors
					newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
						context;

					// We can use :scope instead of the ID hack if the browser
					// supports it & if we're not changing the context.
					if ( newContext !== context || !support.scope ) {

						// Capture the context ID, setting it first if necessary
						if ( ( nid = context.getAttribute( "id" ) ) ) {
							nid = nid.replace( rcssescape, fcssescape );
						} else {
							context.setAttribute( "id", ( nid = expando ) );
						}
					}

					// Prefix every selector in the list
					groups = tokenize( selector );
					i = groups.length;
					while ( i-- ) {
						groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " +
							toSelector( groups[ i ] );
					}
					newSelector = groups.join( "," );
				}

				try {
					push.apply( results,
						newContext.querySelectorAll( newSelector )
					);
					return results;
				} catch ( qsaError ) {
					nonnativeSelectorCache( selector, true );
				} finally {
					if ( nid === expando ) {
						context.removeAttribute( "id" );
					}
				}
			}
		}
	}

	// All others
	return select( selector.replace( rtrim, "$1" ), context, results, seed );
}

/**
 * Create key-value caches of limited size
 * @returns {function(string, object)} Returns the Object data after storing it on itself with
 *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
 *	deleting the oldest entry
 */
function createCache() {
	var keys = [];

	function cache( key, value ) {

		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
		if ( keys.push( key + " " ) > Expr.cacheLength ) {

			// Only keep the most recent entries
			delete cache[ keys.shift() ];
		}
		return ( cache[ key + " " ] = value );
	}
	return cache;
}

/**
 * Mark a function for special use by Sizzle
 * @param {Function} fn The function to mark
 */
function markFunction( fn ) {
	fn[ expando ] = true;
	return fn;
}

/**
 * Support testing using an element
 * @param {Function} fn Passed the created element and returns a boolean result
 */
function assert( fn ) {
	var el = document.createElement( "fieldset" );

	try {
		return !!fn( el );
	} catch ( e ) {
		return false;
	} finally {

		// Remove from its parent by default
		if ( el.parentNode ) {
			el.parentNode.removeChild( el );
		}

		// release memory in IE
		el = null;
	}
}

/**
 * Adds the same handler for all of the specified attrs
 * @param {String} attrs Pipe-separated list of attributes
 * @param {Function} handler The method that will be applied
 */
function addHandle( attrs, handler ) {
	var arr = attrs.split( "|" ),
		i = arr.length;

	while ( i-- ) {
		Expr.attrHandle[ arr[ i ] ] = handler;
	}
}

/**
 * Checks document order of two siblings
 * @param {Element} a
 * @param {Element} b
 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
 */
function siblingCheck( a, b ) {
	var cur = b && a,
		diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
			a.sourceIndex - b.sourceIndex;

	// Use IE sourceIndex if available on both nodes
	if ( diff ) {
		return diff;
	}

	// Check if b follows a
	if ( cur ) {
		while ( ( cur = cur.nextSibling ) ) {
			if ( cur === b ) {
				return -1;
			}
		}
	}

	return a ? 1 : -1;
}

/**
 * Returns a function to use in pseudos for input types
 * @param {String} type
 */
function createInputPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return name === "input" && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for buttons
 * @param {String} type
 */
function createButtonPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return ( name === "input" || name === "button" ) && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for :enabled/:disabled
 * @param {Boolean} disabled true for :disabled; false for :enabled
 */
function createDisabledPseudo( disabled ) {

	// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
	return function( elem ) {

		// Only certain elements can match :enabled or :disabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
		if ( "form" in elem ) {

			// Check for inherited disabledness on relevant non-disabled elements:
			// * listed form-associated elements in a disabled fieldset
			//   https://html.spec.whatwg.org/multipage/forms.html#category-listed
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
			// * option elements in a disabled optgroup
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
			// All such elements have a "form" property.
			if ( elem.parentNode && elem.disabled === false ) {

				// Option elements defer to a parent optgroup if present
				if ( "label" in elem ) {
					if ( "label" in elem.parentNode ) {
						return elem.parentNode.disabled === disabled;
					} else {
						return elem.disabled === disabled;
					}
				}

				// Support: IE 6 - 11
				// Use the isDisabled shortcut property to check for disabled fieldset ancestors
				return elem.isDisabled === disabled ||

					// Where there is no isDisabled, check manually
					/* jshint -W018 */
					elem.isDisabled !== !disabled &&
					inDisabledFieldset( elem ) === disabled;
			}

			return elem.disabled === disabled;

		// Try to winnow out elements that can't be disabled before trusting the disabled property.
		// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
		// even exist on them, let alone have a boolean value.
		} else if ( "label" in elem ) {
			return elem.disabled === disabled;
		}

		// Remaining elements are neither :enabled nor :disabled
		return false;
	};
}

/**
 * Returns a function to use in pseudos for positionals
 * @param {Function} fn
 */
function createPositionalPseudo( fn ) {
	return markFunction( function( argument ) {
		argument = +argument;
		return markFunction( function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ ( j = matchIndexes[ i ] ) ] ) {
					seed[ j ] = !( matches[ j ] = seed[ j ] );
				}
			}
		} );
	} );
}

/**
 * Checks a node for validity as a Sizzle context
 * @param {Element|Object=} context
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */
function testContext( context ) {
	return context && typeof context.getElementsByTagName !== "undefined" && context;
}

// Expose support vars for convenience
support = Sizzle.support = {};

/**
 * Detects XML nodes
 * @param {Element|Object} elem An element or a document
 * @returns {Boolean} True iff elem is a non-HTML XML node
 */
isXML = Sizzle.isXML = function( elem ) {
	var namespace = elem && elem.namespaceURI,
		docElem = elem && ( elem.ownerDocument || elem ).documentElement;

	// Support: IE <=8
	// Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
	// https://bugs.jquery.com/ticket/4833
	return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" );
};

/**
 * Sets document-related variables once based on the current document
 * @param {Element|Object} [doc] An element or document object to use to set the document
 * @returns {Object} Returns the current document
 */
setDocument = Sizzle.setDocument = function( node ) {
	var hasCompare, subWindow,
		doc = node ? node.ownerDocument || node : preferredDoc;

	// Return early if doc is invalid or already selected
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Update global variables
	document = doc;
	docElem = document.documentElement;
	documentIsHTML = !isXML( document );

	// Support: IE 9 - 11+, Edge 12 - 18+
	// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( preferredDoc != document &&
		( subWindow = document.defaultView ) && subWindow.top !== subWindow ) {

		// Support: IE 11, Edge
		if ( subWindow.addEventListener ) {
			subWindow.addEventListener( "unload", unloadHandler, false );

		// Support: IE 9 - 10 only
		} else if ( subWindow.attachEvent ) {
			subWindow.attachEvent( "onunload", unloadHandler );
		}
	}

	// Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only,
	// Safari 4 - 5 only, Opera <=11.6 - 12.x only
	// IE/Edge & older browsers don't support the :scope pseudo-class.
	// Support: Safari 6.0 only
	// Safari 6.0 supports :scope but it's an alias of :root there.
	support.scope = assert( function( el ) {
		docElem.appendChild( el ).appendChild( document.createElement( "div" ) );
		return typeof el.querySelectorAll !== "undefined" &&
			!el.querySelectorAll( ":scope fieldset div" ).length;
	} );

	/* Attributes
	---------------------------------------------------------------------- */

	// Support: IE<8
	// Verify that getAttribute really returns attributes and not properties
	// (excepting IE8 booleans)
	support.attributes = assert( function( el ) {
		el.className = "i";
		return !el.getAttribute( "className" );
	} );

	/* getElement(s)By*
	---------------------------------------------------------------------- */

	// Check if getElementsByTagName("*") returns only elements
	support.getElementsByTagName = assert( function( el ) {
		el.appendChild( document.createComment( "" ) );
		return !el.getElementsByTagName( "*" ).length;
	} );

	// Support: IE<9
	support.getElementsByClassName = rnative.test( document.getElementsByClassName );

	// Support: IE<10
	// Check if getElementById returns elements by name
	// The broken getElementById methods don't pick up programmatically-set names,
	// so use a roundabout getElementsByName test
	support.getById = assert( function( el ) {
		docElem.appendChild( el ).id = expando;
		return !document.getElementsByName || !document.getElementsByName( expando ).length;
	} );

	// ID filter and find
	if ( support.getById ) {
		Expr.filter[ "ID" ] = function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				return elem.getAttribute( "id" ) === attrId;
			};
		};
		Expr.find[ "ID" ] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var elem = context.getElementById( id );
				return elem ? [ elem ] : [];
			}
		};
	} else {
		Expr.filter[ "ID" ] =  function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				var node = typeof elem.getAttributeNode !== "undefined" &&
					elem.getAttributeNode( "id" );
				return node && node.value === attrId;
			};
		};

		// Support: IE 6 - 7 only
		// getElementById is not reliable as a find shortcut
		Expr.find[ "ID" ] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var node, i, elems,
					elem = context.getElementById( id );

				if ( elem ) {

					// Verify the id attribute
					node = elem.getAttributeNode( "id" );
					if ( node && node.value === id ) {
						return [ elem ];
					}

					// Fall back on getElementsByName
					elems = context.getElementsByName( id );
					i = 0;
					while ( ( elem = elems[ i++ ] ) ) {
						node = elem.getAttributeNode( "id" );
						if ( node && node.value === id ) {
							return [ elem ];
						}
					}
				}

				return [];
			}
		};
	}

	// Tag
	Expr.find[ "TAG" ] = support.getElementsByTagName ?
		function( tag, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( tag );

			// DocumentFragment nodes don't have gEBTN
			} else if ( support.qsa ) {
				return context.querySelectorAll( tag );
			}
		} :

		function( tag, context ) {
			var elem,
				tmp = [],
				i = 0,

				// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
				results = context.getElementsByTagName( tag );

			// Filter out possible comments
			if ( tag === "*" ) {
				while ( ( elem = results[ i++ ] ) ) {
					if ( elem.nodeType === 1 ) {
						tmp.push( elem );
					}
				}

				return tmp;
			}
			return results;
		};

	// Class
	Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) {
		if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
			return context.getElementsByClassName( className );
		}
	};

	/* QSA/matchesSelector
	---------------------------------------------------------------------- */

	// QSA and matchesSelector support

	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
	rbuggyMatches = [];

	// qSa(:focus) reports false when true (Chrome 21)
	// We allow this because of a bug in IE8/9 that throws an error
	// whenever `document.activeElement` is accessed on an iframe
	// So, we allow :focus to pass through QSA all the time to avoid the IE error
	// See https://bugs.jquery.com/ticket/13378
	rbuggyQSA = [];

	if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) {

		// Build QSA regex
		// Regex strategy adopted from Diego Perini
		assert( function( el ) {

			var input;

			// Select is set to empty string on purpose
			// This is to test IE's treatment of not explicitly
			// setting a boolean content attribute,
			// since its presence should be enough
			// https://bugs.jquery.com/ticket/12359
			docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
				"<select id='" + expando + "-\r\\' msallowcapture=''>" +
				"<option selected=''></option></select>";

			// Support: IE8, Opera 11-12.16
			// Nothing should be selected when empty strings follow ^= or $= or *=
			// The test attribute must be unknown in Opera but "safe" for WinRT
			// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
			if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
			}

			// Support: IE8
			// Boolean attributes and "value" are not treated correctly
			if ( !el.querySelectorAll( "[selected]" ).length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
			}

			// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
			if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
				rbuggyQSA.push( "~=" );
			}

			// Support: IE 11+, Edge 15 - 18+
			// IE 11/Edge don't find elements on a `[name='']` query in some cases.
			// Adding a temporary attribute to the document before the selection works
			// around the issue.
			// Interestingly, IE 10 & older don't seem to have the issue.
			input = document.createElement( "input" );
			input.setAttribute( "name", "" );
			el.appendChild( input );
			if ( !el.querySelectorAll( "[name='']" ).length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" +
					whitespace + "*(?:''|\"\")" );
			}

			// Webkit/Opera - :checked should return selected option elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			// IE8 throws error here and will not see later tests
			if ( !el.querySelectorAll( ":checked" ).length ) {
				rbuggyQSA.push( ":checked" );
			}

			// Support: Safari 8+, iOS 8+
			// https://bugs.webkit.org/show_bug.cgi?id=136851
			// In-page `selector#id sibling-combinator selector` fails
			if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
				rbuggyQSA.push( ".#.+[+~]" );
			}

			// Support: Firefox <=3.6 - 5 only
			// Old Firefox doesn't throw on a badly-escaped identifier.
			el.querySelectorAll( "\\\f" );
			rbuggyQSA.push( "[\\r\\n\\f]" );
		} );

		assert( function( el ) {
			el.innerHTML = "<a href='' disabled='disabled'></a>" +
				"<select disabled='disabled'><option/></select>";

			// Support: Windows 8 Native Apps
			// The type and name attributes are restricted during .innerHTML assignment
			var input = document.createElement( "input" );
			input.setAttribute( "type", "hidden" );
			el.appendChild( input ).setAttribute( "name", "D" );

			// Support: IE8
			// Enforce case-sensitivity of name attribute
			if ( el.querySelectorAll( "[name=d]" ).length ) {
				rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
			}

			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
			// IE8 throws error here and will not see later tests
			if ( el.querySelectorAll( ":enabled" ).length !== 2 ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Support: IE9-11+
			// IE's :disabled selector does not pick up the children of disabled fieldsets
			docElem.appendChild( el ).disabled = true;
			if ( el.querySelectorAll( ":disabled" ).length !== 2 ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Support: Opera 10 - 11 only
			// Opera 10-11 does not throw on post-comma invalid pseudos
			el.querySelectorAll( "*,:x" );
			rbuggyQSA.push( ",.*:" );
		} );
	}

	if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches ||
		docElem.webkitMatchesSelector ||
		docElem.mozMatchesSelector ||
		docElem.oMatchesSelector ||
		docElem.msMatchesSelector ) ) ) ) {

		assert( function( el ) {

			// Check to see if it's possible to do matchesSelector
			// on a disconnected node (IE 9)
			support.disconnectedMatch = matches.call( el, "*" );

			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( el, "[s!='']:x" );
			rbuggyMatches.push( "!=", pseudos );
		} );
	}

	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) );
	rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) );

	/* Contains
	---------------------------------------------------------------------- */
	hasCompare = rnative.test( docElem.compareDocumentPosition );

	// Element contains another
	// Purposefully self-exclusive
	// As in, an element does not contain itself
	contains = hasCompare || rnative.test( docElem.contains ) ?
		function( a, b ) {
			var adown = a.nodeType === 9 ? a.documentElement : a,
				bup = b && b.parentNode;
			return a === bup || !!( bup && bup.nodeType === 1 && (
				adown.contains ?
					adown.contains( bup ) :
					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
			) );
		} :
		function( a, b ) {
			if ( b ) {
				while ( ( b = b.parentNode ) ) {
					if ( b === a ) {
						return true;
					}
				}
			}
			return false;
		};

	/* Sorting
	---------------------------------------------------------------------- */

	// Document order sorting
	sortOrder = hasCompare ?
	function( a, b ) {

		// Flag for duplicate removal
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		// Sort on method existence if only one input has compareDocumentPosition
		var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
		if ( compare ) {
			return compare;
		}

		// Calculate position if both inputs belong to the same document
		// Support: IE 11+, Edge 17 - 18+
		// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
		// two documents; shallow comparisons work.
		// eslint-disable-next-line eqeqeq
		compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ?
			a.compareDocumentPosition( b ) :

			// Otherwise we know they are disconnected
			1;

		// Disconnected nodes
		if ( compare & 1 ||
			( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) {

			// Choose the first element that is related to our preferred document
			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			// eslint-disable-next-line eqeqeq
			if ( a == document || a.ownerDocument == preferredDoc &&
				contains( preferredDoc, a ) ) {
				return -1;
			}

			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			// eslint-disable-next-line eqeqeq
			if ( b == document || b.ownerDocument == preferredDoc &&
				contains( preferredDoc, b ) ) {
				return 1;
			}

			// Maintain original order
			return sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;
		}

		return compare & 4 ? -1 : 1;
	} :
	function( a, b ) {

		// Exit early if the nodes are identical
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		var cur,
			i = 0,
			aup = a.parentNode,
			bup = b.parentNode,
			ap = [ a ],
			bp = [ b ];

		// Parentless nodes are either documents or disconnected
		if ( !aup || !bup ) {

			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			/* eslint-disable eqeqeq */
			return a == document ? -1 :
				b == document ? 1 :
				/* eslint-enable eqeqeq */
				aup ? -1 :
				bup ? 1 :
				sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;

		// If the nodes are siblings, we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );
		}

		// Otherwise we need full lists of their ancestors for comparison
		cur = a;
		while ( ( cur = cur.parentNode ) ) {
			ap.unshift( cur );
		}
		cur = b;
		while ( ( cur = cur.parentNode ) ) {
			bp.unshift( cur );
		}

		// Walk down the tree looking for a discrepancy
		while ( ap[ i ] === bp[ i ] ) {
			i++;
		}

		return i ?

			// Do a sibling check if the nodes have a common ancestor
			siblingCheck( ap[ i ], bp[ i ] ) :

			// Otherwise nodes in our document sort first
			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			/* eslint-disable eqeqeq */
			ap[ i ] == preferredDoc ? -1 :
			bp[ i ] == preferredDoc ? 1 :
			/* eslint-enable eqeqeq */
			0;
	};

	return document;
};

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	setDocument( elem );

	if ( support.matchesSelector && documentIsHTML &&
		!nonnativeSelectorCache[ expr + " " ] &&
		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {

		try {
			var ret = matches.call( elem, expr );

			// IE 9's matchesSelector returns false on disconnected nodes
			if ( ret || support.disconnectedMatch ||

				// As well, disconnected nodes are said to be in a document
				// fragment in IE 9
				elem.document && elem.document.nodeType !== 11 ) {
				return ret;
			}
		} catch ( e ) {
			nonnativeSelectorCache( expr, true );
		}
	}

	return Sizzle( expr, document, null, [ elem ] ).length > 0;
};

Sizzle.contains = function( context, elem ) {

	// Set document vars if needed
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( ( context.ownerDocument || context ) != document ) {
		setDocument( context );
	}
	return contains( context, elem );
};

Sizzle.attr = function( elem, name ) {

	// Set document vars if needed
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( ( elem.ownerDocument || elem ) != document ) {
		setDocument( elem );
	}

	var fn = Expr.attrHandle[ name.toLowerCase() ],

		// Don't get fooled by Object.prototype properties (jQuery #13807)
		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
			fn( elem, name, !documentIsHTML ) :
			undefined;

	return val !== undefined ?
		val :
		support.attributes || !documentIsHTML ?
			elem.getAttribute( name ) :
			( val = elem.getAttributeNode( name ) ) && val.specified ?
				val.value :
				null;
};

Sizzle.escape = function( sel ) {
	return ( sel + "" ).replace( rcssescape, fcssescape );
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

/**
 * Document sorting and removing duplicates
 * @param {ArrayLike} results
 */
Sizzle.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		j = 0,
		i = 0;

	// Unless we *know* we can detect duplicates, assume their presence
	hasDuplicate = !support.detectDuplicates;
	sortInput = !support.sortStable && results.slice( 0 );
	results.sort( sortOrder );

	if ( hasDuplicate ) {
		while ( ( elem = results[ i++ ] ) ) {
			if ( elem === results[ i ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			results.splice( duplicates[ j ], 1 );
		}
	}

	// Clear input after sorting to release objects
	// See https://github.com/jquery/sizzle/pull/225
	sortInput = null;

	return results;
};

/**
 * Utility function for retrieving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
getText = Sizzle.getText = function( elem ) {
	var node,
		ret = "",
		i = 0,
		nodeType = elem.nodeType;

	if ( !nodeType ) {

		// If no nodeType, this is expected to be an array
		while ( ( node = elem[ i++ ] ) ) {

			// Do not traverse comment nodes
			ret += getText( node );
		}
	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {

		// Use textContent for elements
		// innerText usage removed for consistency of new lines (jQuery #11153)
		if ( typeof elem.textContent === "string" ) {
			return elem.textContent;
		} else {

			// Traverse its children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				ret += getText( elem );
			}
		}
	} else if ( nodeType === 3 || nodeType === 4 ) {
		return elem.nodeValue;
	}

	// Do not include comment or processing instruction nodes

	return ret;
};

Expr = Sizzle.selectors = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	attrHandle: {},

	find: {},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		"ATTR": function( match ) {
			match[ 1 ] = match[ 1 ].replace( runescape, funescape );

			// Move the given value to match[3] whether quoted or unquoted
			match[ 3 ] = ( match[ 3 ] || match[ 4 ] ||
				match[ 5 ] || "" ).replace( runescape, funescape );

			if ( match[ 2 ] === "~=" ) {
				match[ 3 ] = " " + match[ 3 ] + " ";
			}

			return match.slice( 0, 4 );
		},

		"CHILD": function( match ) {

			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 what (child|of-type)
				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				4 xn-component of xn+y argument ([+-]?\d*n|)
				5 sign of xn-component
				6 x of xn-component
				7 sign of y-component
				8 y of y-component
			*/
			match[ 1 ] = match[ 1 ].toLowerCase();

			if ( match[ 1 ].slice( 0, 3 ) === "nth" ) {

				// nth-* requires argument
				if ( !match[ 3 ] ) {
					Sizzle.error( match[ 0 ] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[ 4 ] = +( match[ 4 ] ?
					match[ 5 ] + ( match[ 6 ] || 1 ) :
					2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) );
				match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" );

				// other types prohibit arguments
			} else if ( match[ 3 ] ) {
				Sizzle.error( match[ 0 ] );
			}

			return match;
		},

		"PSEUDO": function( match ) {
			var excess,
				unquoted = !match[ 6 ] && match[ 2 ];

			if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) {
				return null;
			}

			// Accept quoted arguments as-is
			if ( match[ 3 ] ) {
				match[ 2 ] = match[ 4 ] || match[ 5 ] || "";

			// Strip excess characters from unquoted arguments
			} else if ( unquoted && rpseudo.test( unquoted ) &&

				// Get excess from tokenize (recursively)
				( excess = tokenize( unquoted, true ) ) &&

				// advance to the next closing parenthesis
				( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) {

				// excess is a negative index
				match[ 0 ] = match[ 0 ].slice( 0, excess );
				match[ 2 ] = unquoted.slice( 0, excess );
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {

		"TAG": function( nodeNameSelector ) {
			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
			return nodeNameSelector === "*" ?
				function() {
					return true;
				} :
				function( elem ) {
					return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
				};
		},

		"CLASS": function( className ) {
			var pattern = classCache[ className + " " ];

			return pattern ||
				( pattern = new RegExp( "(^|" + whitespace +
					")" + className + "(" + whitespace + "|$)" ) ) && classCache(
						className, function( elem ) {
							return pattern.test(
								typeof elem.className === "string" && elem.className ||
								typeof elem.getAttribute !== "undefined" &&
									elem.getAttribute( "class" ) ||
								""
							);
				} );
		},

		"ATTR": function( name, operator, check ) {
			return function( elem ) {
				var result = Sizzle.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				/* eslint-disable max-len */

				return operator === "=" ? result === check :
					operator === "!=" ? result !== check :
					operator === "^=" ? check && result.indexOf( check ) === 0 :
					operator === "*=" ? check && result.indexOf( check ) > -1 :
					operator === "$=" ? check && result.slice( -check.length ) === check :
					operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
					false;
				/* eslint-enable max-len */

			};
		},

		"CHILD": function( type, what, _argument, first, last ) {
			var simple = type.slice( 0, 3 ) !== "nth",
				forward = type.slice( -4 ) !== "last",
				ofType = what === "of-type";

			return first === 1 && last === 0 ?

				// Shortcut for :nth-*(n)
				function( elem ) {
					return !!elem.parentNode;
				} :

				function( elem, _context, xml ) {
					var cache, uniqueCache, outerCache, node, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType,
						diff = false;

					if ( parent ) {

						// :(first|last|only)-(child|of-type)
						if ( simple ) {
							while ( dir ) {
								node = elem;
								while ( ( node = node[ dir ] ) ) {
									if ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) {

										return false;
									}
								}

								// Reverse direction for :only-* (if we haven't yet done so)
								start = dir = type === "only" && !start && "nextSibling";
							}
							return true;
						}

						start = [ forward ? parent.firstChild : parent.lastChild ];

						// non-xml :nth-child(...) stores cache data on `parent`
						if ( forward && useCache ) {

							// Seek `elem` from a previously-cached index

							// ...in a gzip-friendly way
							node = parent;
							outerCache = node[ expando ] || ( node[ expando ] = {} );

							// Support: IE <9 only
							// Defend against cloned attroperties (jQuery gh-1709)
							uniqueCache = outerCache[ node.uniqueID ] ||
								( outerCache[ node.uniqueID ] = {} );

							cache = uniqueCache[ type ] || [];
							nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
							diff = nodeIndex && cache[ 2 ];
							node = nodeIndex && parent.childNodes[ nodeIndex ];

							while ( ( node = ++nodeIndex && node && node[ dir ] ||

								// Fallback to seeking `elem` from the start
								( diff = nodeIndex = 0 ) || start.pop() ) ) {

								// When found, cache indexes on `parent` and break
								if ( node.nodeType === 1 && ++diff && node === elem ) {
									uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						} else {

							// Use previously-cached element index if available
							if ( useCache ) {

								// ...in a gzip-friendly way
								node = elem;
								outerCache = node[ expando ] || ( node[ expando ] = {} );

								// Support: IE <9 only
								// Defend against cloned attroperties (jQuery gh-1709)
								uniqueCache = outerCache[ node.uniqueID ] ||
									( outerCache[ node.uniqueID ] = {} );

								cache = uniqueCache[ type ] || [];
								nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
								diff = nodeIndex;
							}

							// xml :nth-child(...)
							// or :nth-last-child(...) or :nth(-last)?-of-type(...)
							if ( diff === false ) {

								// Use the same loop as above to seek `elem` from the start
								while ( ( node = ++nodeIndex && node && node[ dir ] ||
									( diff = nodeIndex = 0 ) || start.pop() ) ) {

									if ( ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) &&
										++diff ) {

										// Cache the index of each encountered element
										if ( useCache ) {
											outerCache = node[ expando ] ||
												( node[ expando ] = {} );

											// Support: IE <9 only
											// Defend against cloned attroperties (jQuery gh-1709)
											uniqueCache = outerCache[ node.uniqueID ] ||
												( outerCache[ node.uniqueID ] = {} );

											uniqueCache[ type ] = [ dirruns, diff ];
										}

										if ( node === elem ) {
											break;
										}
									}
								}
							}
						}

						// Incorporate the offset, then check against cycle size
						diff -= last;
						return diff === first || ( diff % first === 0 && diff / first >= 0 );
					}
				};
		},

		"PSEUDO": function( pseudo, argument ) {

			// pseudo-class names are case-insensitive
			// http://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					Sizzle.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as Sizzle does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length > 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction( function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf( seed, matched[ i ] );
							seed[ idx ] = !( matches[ idx ] = matched[ i ] );
						}
					} ) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {

		// Potentially complex pseudos
		"not": markFunction( function( selector ) {

			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrim, "$1" ) );

			return matcher[ expando ] ?
				markFunction( function( seed, matches, _context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( ( elem = unmatched[ i ] ) ) {
							seed[ i ] = !( matches[ i ] = elem );
						}
					}
				} ) :
				function( elem, _context, xml ) {
					input[ 0 ] = elem;
					matcher( input, null, xml, results );

					// Don't keep the element (issue #299)
					input[ 0 ] = null;
					return !results.pop();
				};
		} ),

		"has": markFunction( function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length > 0;
			};
		} ),

		"contains": markFunction( function( text ) {
			text = text.replace( runescape, funescape );
			return function( elem ) {
				return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1;
			};
		} ),

		// "Whether an element is represented by a :lang() selector
		// is based solely on the element's language value
		// being equal to the identifier C,
		// or beginning with the identifier C immediately followed by "-".
		// The matching of C against the element's language value is performed case-insensitively.
		// The identifier C does not have to be a valid language name."
		// http://www.w3.org/TR/selectors/#lang-pseudo
		"lang": markFunction( function( lang ) {

			// lang value must be a valid identifier
			if ( !ridentifier.test( lang || "" ) ) {
				Sizzle.error( "unsupported lang: " + lang );
			}
			lang = lang.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				var elemLang;
				do {
					if ( ( elemLang = documentIsHTML ?
						elem.lang :
						elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {

						elemLang = elemLang.toLowerCase();
						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
					}
				} while ( ( elem = elem.parentNode ) && elem.nodeType === 1 );
				return false;
			};
		} ),

		// Miscellaneous
		"target": function( elem ) {
			var hash = window.location && window.location.hash;
			return hash && hash.slice( 1 ) === elem.id;
		},

		"root": function( elem ) {
			return elem === docElem;
		},

		"focus": function( elem ) {
			return elem === document.activeElement &&
				( !document.hasFocus || document.hasFocus() ) &&
				!!( elem.type || elem.href || ~elem.tabIndex );
		},

		// Boolean properties
		"enabled": createDisabledPseudo( false ),
		"disabled": createDisabledPseudo( true ),

		"checked": function( elem ) {

			// In CSS3, :checked should return both checked and selected elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			var nodeName = elem.nodeName.toLowerCase();
			return ( nodeName === "input" && !!elem.checked ) ||
				( nodeName === "option" && !!elem.selected );
		},

		"selected": function( elem ) {

			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				// eslint-disable-next-line no-unused-expressions
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		// Contents
		"empty": function( elem ) {

			// http://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
			//   but not by others (comment: 8; processing instruction: 7; etc.)
			// nodeType < 6 works because attributes (2) do not appear as children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				if ( elem.nodeType < 6 ) {
					return false;
				}
			}
			return true;
		},

		"parent": function( elem ) {
			return !Expr.pseudos[ "empty" ]( elem );
		},

		// Element/input types
		"header": function( elem ) {
			return rheader.test( elem.nodeName );
		},

		"input": function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		"button": function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && elem.type === "button" || name === "button";
		},

		"text": function( elem ) {
			var attr;
			return elem.nodeName.toLowerCase() === "input" &&
				elem.type === "text" &&

				// Support: IE<8
				// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
				( ( attr = elem.getAttribute( "type" ) ) == null ||
					attr.toLowerCase() === "text" );
		},

		// Position-in-collection
		"first": createPositionalPseudo( function() {
			return [ 0 ];
		} ),

		"last": createPositionalPseudo( function( _matchIndexes, length ) {
			return [ length - 1 ];
		} ),

		"eq": createPositionalPseudo( function( _matchIndexes, length, argument ) {
			return [ argument < 0 ? argument + length : argument ];
		} ),

		"even": createPositionalPseudo( function( matchIndexes, length ) {
			var i = 0;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		"odd": createPositionalPseudo( function( matchIndexes, length ) {
			var i = 1;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		"lt": createPositionalPseudo( function( matchIndexes, length, argument ) {
			var i = argument < 0 ?
				argument + length :
				argument > length ?
					length :
					argument;
			for ( ; --i >= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		"gt": createPositionalPseudo( function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; ++i < length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} )
	}
};

Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ];

// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
	Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
	Expr.pseudos[ i ] = createButtonPseudo( i );
}

// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();

tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || ( match = rcomma.exec( soFar ) ) ) {
			if ( match ) {

				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[ 0 ].length ) || soFar;
			}
			groups.push( ( tokens = [] ) );
		}

		matched = false;

		// Combinators
		if ( ( match = rcombinators.exec( soFar ) ) ) {
			matched = match.shift();
			tokens.push( {
				value: matched,

				// Cast descendant combinators to space
				type: match[ 0 ].replace( rtrim, " " )
			} );
			soFar = soFar.slice( matched.length );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] ||
				( match = preFilters[ type ]( match ) ) ) ) {
				matched = match.shift();
				tokens.push( {
					value: matched,
					type: type,
					matches: match
				} );
				soFar = soFar.slice( matched.length );
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	return parseOnly ?
		soFar.length :
		soFar ?
			Sizzle.error( selector ) :

			// Cache the tokens
			tokenCache( selector, groups ).slice( 0 );
};

function toSelector( tokens ) {
	var i = 0,
		len = tokens.length,
		selector = "";
	for ( ; i < len; i++ ) {
		selector += tokens[ i ].value;
	}
	return selector;
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		skip = combinator.next,
		key = skip || dir,
		checkNonElements = base && key === "parentNode",
		doneName = done++;

	return combinator.first ?

		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( ( elem = elem[ dir ] ) ) {
				if ( elem.nodeType === 1 || checkNonElements ) {
					return matcher( elem, context, xml );
				}
			}
			return false;
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			var oldCache, uniqueCache, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
			if ( xml ) {
				while ( ( elem = elem[ dir ] ) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						if ( matcher( elem, context, xml ) ) {
							return true;
						}
					}
				}
			} else {
				while ( ( elem = elem[ dir ] ) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						outerCache = elem[ expando ] || ( elem[ expando ] = {} );

						// Support: IE <9 only
						// Defend against cloned attroperties (jQuery gh-1709)
						uniqueCache = outerCache[ elem.uniqueID ] ||
							( outerCache[ elem.uniqueID ] = {} );

						if ( skip && skip === elem.nodeName.toLowerCase() ) {
							elem = elem[ dir ] || elem;
						} else if ( ( oldCache = uniqueCache[ key ] ) &&
							oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {

							// Assign to newCache so results back-propagate to previous elements
							return ( newCache[ 2 ] = oldCache[ 2 ] );
						} else {

							// Reuse newcache so results back-propagate to previous elements
							uniqueCache[ key ] = newCache;

							// A match means we're done; a fail means we have to keep checking
							if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {
								return true;
							}
						}
					}
				}
			}
			return false;
		};
}

function elementMatcher( matchers ) {
	return matchers.length > 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[ i ]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[ 0 ];
}

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i < len; i++ ) {
		Sizzle( selector, contexts[ i ], results );
	}
	return results;
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i < len; i++ ) {
		if ( ( elem = unmatched[ i ] ) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter && !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder && !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction( function( seed, results, context, xml ) {
		var temp, i, elem,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed || multipleContexts(
				selector || "*",
				context.nodeType ? [ context ] : context,
				[]
			),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter && ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems,

			matcherOut = matcher ?

				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

					// ...intermediate processing is necessary
					[] :

					// ...otherwise use results directly
					results :
				matcherIn;

		// Find primary matches
		if ( matcher ) {
			matcher( matcherIn, matcherOut, context, xml );
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( ( elem = temp[ i ] ) ) {
					matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {

					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( ( elem = matcherOut[ i ] ) ) {

							// Restore matcherIn since elem is not yet a final match
							temp.push( ( matcherIn[ i ] = elem ) );
						}
					}
					postFinder( null, ( matcherOut = [] ), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( ( elem = matcherOut[ i ] ) &&
						( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) {

						seed[ temp ] = !( results[ temp ] = elem );
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	} );
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[ 0 ].type ],
		implicitRelative = leadingRelative || Expr.relative[ " " ],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
				( checkContext = context ).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );

			// Avoid hanging onto element (issue #299)
			checkContext = null;
			return ret;
		} ];

	for ( ; i < len; i++ ) {
		if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) {
			matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
		} else {
			matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {

				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j < len; j++ ) {
					if ( Expr.relative[ tokens[ j ].type ] ) {
						break;
					}
				}
				return setMatcher(
					i > 1 && elementMatcher( matchers ),
					i > 1 && toSelector(

					// If the preceding token was a descendant combinator, insert an implicit any-element `*`
					tokens
						.slice( 0, i - 1 )
						.concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )
					).replace( rtrim, "$1" ),
					matcher,
					i < j && matcherFromTokens( tokens.slice( i, j ) ),
					j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ),
					j < len && toSelector( tokens )
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	var bySet = setMatchers.length > 0,
		byElement = elementMatchers.length > 0,
		superMatcher = function( seed, context, xml, results, outermost ) {
			var elem, j, matcher,
				matchedCount = 0,
				i = "0",
				unmatched = seed && [],
				setMatched = [],
				contextBackup = outermostContext,

				// We must always have either seed elements or outermost context
				elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ),

				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ),
				len = elems.length;

			if ( outermost ) {

				// Support: IE 11+, Edge 17 - 18+
				// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
				// two documents; shallow comparisons work.
				// eslint-disable-next-line eqeqeq
				outermostContext = context == document || context || outermost;
			}

			// Add elements passing elementMatchers directly to results
			// Support: IE<9, Safari
			// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
			for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) {
				if ( byElement && elem ) {
					j = 0;

					// Support: IE 11+, Edge 17 - 18+
					// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
					// two documents; shallow comparisons work.
					// eslint-disable-next-line eqeqeq
					if ( !context && elem.ownerDocument != document ) {
						setDocument( elem );
						xml = !documentIsHTML;
					}
					while ( ( matcher = elementMatchers[ j++ ] ) ) {
						if ( matcher( elem, context || document, xml ) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {

					// They will have gone through all possible matchers
					if ( ( elem = !matcher && elem ) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// `i` is now the count of elements visited above, and adding it to `matchedCount`
			// makes the latter nonnegative.
			matchedCount += i;

			// Apply set filters to unmatched elements
			// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
			// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
			// no element matchers and no seed.
			// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
			// case, which will result in a "00" `matchedCount` that differs from `i` but is also
			// numerically zero.
			if ( bySet && i !== matchedCount ) {
				j = 0;
				while ( ( matcher = setMatchers[ j++ ] ) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {

					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !( unmatched[ i ] || setMatched[ i ] ) ) {
								setMatched[ i ] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {

		// Generate a function of recursive functions that can be used to check each element
		if ( !match ) {
			match = tokenize( selector );
		}
		i = match.length;
		while ( i-- ) {
			cached = matcherFromTokens( match[ i ] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache(
			selector,
			matcherFromGroupMatchers( elementMatchers, setMatchers )
		);

		// Save selector and tokenization
		cached.selector = selector;
	}
	return cached;
};

/**
 * A low-level selection function that works with Sizzle's compiled
 *  selector functions
 * @param {String|Function} selector A selector or a pre-compiled
 *  selector function built with Sizzle.compile
 * @param {Element} context
 * @param {Array} [results]
 * @param {Array} [seed] A set of elements to match against
 */
select = Sizzle.select = function( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		compiled = typeof selector === "function" && selector,
		match = !seed && tokenize( ( selector = compiled.selector || selector ) );

	results = results || [];

	// Try to minimize operations if there is only one selector in the list and no seed
	// (the latter of which guarantees us context)
	if ( match.length === 1 ) {

		// Reduce context if the leading compound selector is an ID
		tokens = match[ 0 ] = match[ 0 ].slice( 0 );
		if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" &&
			context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) {

			context = ( Expr.find[ "ID" ]( token.matches[ 0 ]
				.replace( runescape, funescape ), context ) || [] )[ 0 ];
			if ( !context ) {
				return results;

			// Precompiled matchers will still verify ancestry, so step up a level
			} else if ( compiled ) {
				context = context.parentNode;
			}

			selector = selector.slice( tokens.shift().value.length );
		}

		// Fetch a seed set for right-to-left matching
		i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length;
		while ( i-- ) {
			token = tokens[ i ];

			// Abort if we hit a combinator
			if ( Expr.relative[ ( type = token.type ) ] ) {
				break;
			}
			if ( ( find = Expr.find[ type ] ) ) {

				// Search, expanding context for leading sibling combinators
				if ( ( seed = find(
					token.matches[ 0 ].replace( runescape, funescape ),
					rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) ||
						context
				) ) ) {

					// If seed is empty or no tokens remain, we can return early
					tokens.splice( i, 1 );
					selector = seed.length && toSelector( tokens );
					if ( !selector ) {
						push.apply( results, seed );
						return results;
					}

					break;
				}
			}
		}
	}

	// Compile and execute a filtering function if one is not provided
	// Provide `match` to avoid retokenization if we modified the selector above
	( compiled || compile( selector, match ) )(
		seed,
		context,
		!documentIsHTML,
		results,
		!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
	);
	return results;
};

// One-time assignments

// Sort stability
support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando;

// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;

// Initialize against the default document
setDocument();

// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert( function( el ) {

	// Should return 1, but returns 4 (following)
	return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1;
} );

// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert( function( el ) {
	el.innerHTML = "<a href='#'></a>";
	return el.firstChild.getAttribute( "href" ) === "#";
} ) ) {
	addHandle( "type|href|height|width", function( elem, name, isXML ) {
		if ( !isXML ) {
			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
		}
	} );
}

// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert( function( el ) {
	el.innerHTML = "<input/>";
	el.firstChild.setAttribute( "value", "" );
	return el.firstChild.getAttribute( "value" ) === "";
} ) ) {
	addHandle( "value", function( elem, _name, isXML ) {
		if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
			return elem.defaultValue;
		}
	} );
}

// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert( function( el ) {
	return el.getAttribute( "disabled" ) == null;
} ) ) {
	addHandle( booleans, function( elem, name, isXML ) {
		var val;
		if ( !isXML ) {
			return elem[ name ] === true ? name.toLowerCase() :
				( val = elem.getAttributeNode( name ) ) && val.specified ?
					val.value :
					null;
		}
	} );
}

return Sizzle;

} )( window );



jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;

// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;




var dir = function( elem, dir, until ) {
	var matched = [],
		truncate = until !== undefined;

	while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
		if ( elem.nodeType === 1 ) {
			if ( truncate && jQuery( elem ).is( until ) ) {
				break;
			}
			matched.push( elem );
		}
	}
	return matched;
};


var siblings = function( n, elem ) {
	var matched = [];

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

	return matched;
};


var rneedsContext = jQuery.expr.match.needsContext;



function nodeName( elem, name ) {

	return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();

}
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );



// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			return !!qualifier.call( elem, i, elem ) !== not;
		} );
	}

	// Single element
	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		} );
	}

	// Arraylike of elements (jQuery, arguments, Array)
	if ( typeof qualifier !== "string" ) {
		return jQuery.grep( elements, function( elem ) {
			return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
		} );
	}

	// Filtered directly for both simple and complex selectors
	return jQuery.filter( qualifier, elements, not );
}

jQuery.filter = function( expr, elems, not ) {
	var elem = elems[ 0 ];

	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	if ( elems.length === 1 && elem.nodeType === 1 ) {
		return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
	}

	return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
		return elem.nodeType === 1;
	} ) );
};

jQuery.fn.extend( {
	find: function( selector ) {
		var i, ret,
			len = this.length,
			self = this;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter( function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			} ) );
		}

		ret = this.pushStack( [] );

		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		return len > 1 ? jQuery.uniqueSort( ret ) : ret;
	},
	filter: function( selector ) {
		return this.pushStack( winnow( this, selector || [], false ) );
	},
	not: function( selector ) {
		return this.pushStack( winnow( this, selector || [], true ) );
	},
	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	}
} );


// Initialize a jQuery object


// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	// Strict HTML recognition (#11290: must start with <)
	// Shortcut simple #id case for speed
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,

	init = jQuery.fn.init = function( selector, context, root ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Method init() accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector[ 0 ] === "<" &&
				selector[ selector.length - 1 ] === ">" &&
				selector.length >= 3 ) {

				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match && ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( isFunction( this[ match ] ) ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					if ( elem ) {

						// Inject the element directly into the jQuery object
						this[ 0 ] = elem;
						this.length = 1;
					}
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || root ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(DOMElement)
		} else if ( selector.nodeType ) {
			this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( isFunction( selector ) ) {
			return root.ready !== undefined ?
				root.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );
		}

		return jQuery.makeArray( selector, this );
	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );


var rparentsprev = /^(?:parents|prev(?:Until|All))/,

	// Methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend( {
	has: function( target ) {
		var targets = jQuery( target, this ),
			l = targets.length;

		return this.filter( function() {
			var i = 0;
			for ( ; i < l; i++ ) {
				if ( jQuery.contains( this, targets[ i ] ) ) {
					return true;
				}
			}
		} );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			targets = typeof selectors !== "string" && jQuery( selectors );

		// Positional selectors never match, since there's no _selection_ context
		if ( !rneedsContext.test( selectors ) ) {
			for ( ; i < l; i++ ) {
				for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {

					// Always skip document fragments
					if ( cur.nodeType < 11 && ( targets ?
						targets.index( cur ) > -1 :

						// Don't pass non-elements to Sizzle
						cur.nodeType === 1 &&
							jQuery.find.matchesSelector( cur, selectors ) ) ) {

						matched.push( cur );
						break;
					}
				}
			}
		}

		return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
	},

	// Determine the position of an element within the set
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// Index in selector
		if ( typeof elem === "string" ) {
			return indexOf.call( jQuery( elem ), this[ 0 ] );
		}

		// Locate the position of the desired element
		return indexOf.call( this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem
		);
	},

	add: function( selector, context ) {
		return this.pushStack(
			jQuery.uniqueSort(
				jQuery.merge( this.get(), jQuery( selector, context ) )
			)
		);
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	}
} );

function sibling( cur, dir ) {
	while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
	return cur;
}

jQuery.each( {
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, _i, until ) {
		return dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, _i, until ) {
		return dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, _i, until ) {
		return dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return siblings( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return siblings( elem.firstChild );
	},
	contents: function( elem ) {
		if ( elem.contentDocument != null &&

			// Support: IE 11+
			// <object> elements with no `data` attribute has an object
			// `contentDocument` with a `null` prototype.
			getProto( elem.contentDocument ) ) {

			return elem.contentDocument;
		}

		// Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
		// Treat the template element as a regular one in browsers that
		// don't support it.
		if ( nodeName( elem, "template" ) ) {
			elem = elem.content || elem;
		}

		return jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var matched = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			matched = jQuery.filter( selector, matched );
		}

		if ( this.length > 1 ) {

			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				jQuery.uniqueSort( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );



// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
	var object = {};
	jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
		object[ flag ] = true;
	} );
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		createOptions( options ) :
		jQuery.extend( {}, options );

	var // Flag to know if list is currently firing
		firing,

		// Last fire value for non-forgettable lists
		memory,

		// Flag to know if list was already fired
		fired,

		// Flag to prevent firing
		locked,

		// Actual callback list
		list = [],

		// Queue of execution data for repeatable lists
		queue = [],

		// Index of currently firing callback (modified by add/remove as needed)
		firingIndex = -1,

		// Fire callbacks
		fire = function() {

			// Enforce single-firing
			locked = locked || options.once;

			// Execute callbacks for all pending executions,
			// respecting firingIndex overrides and runtime changes
			fired = firing = true;
			for ( ; queue.length; firingIndex = -1 ) {
				memory = queue.shift();
				while ( ++firingIndex < list.length ) {

					// Run callback and check for early termination
					if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
						options.stopOnFalse ) {

						// Jump to end and forget the data so .add doesn't re-fire
						firingIndex = list.length;
						memory = false;
					}
				}
			}

			// Forget the data if we're done with it
			if ( !options.memory ) {
				memory = false;
			}

			firing = false;

			// Clean up if we're done firing for good
			if ( locked ) {

				// Keep an empty list if we have data for future add calls
				if ( memory ) {
					list = [];

				// Otherwise, this object is spent
				} else {
					list = "";
				}
			}
		},

		// Actual Callbacks object
		self = {

			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {

					// If we have memory from a past run, we should fire after adding
					if ( memory && !firing ) {
						firingIndex = list.length - 1;
						queue.push( memory );
					}

					( function add( args ) {
						jQuery.each( args, function( _, arg ) {
							if ( isFunction( arg ) ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && toType( arg ) !== "string" ) {

								// Inspect recursively
								add( arg );
							}
						} );
					} )( arguments );

					if ( memory && !firing ) {
						fire();
					}
				}
				return this;
			},

			// Remove a callback from the list
			remove: function() {
				jQuery.each( arguments, function( _, arg ) {
					var index;
					while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
						list.splice( index, 1 );

						// Handle firing indexes
						if ( index <= firingIndex ) {
							firingIndex--;
						}
					}
				} );
				return this;
			},

			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function( fn ) {
				return fn ?
					jQuery.inArray( fn, list ) > -1 :
					list.length > 0;
			},

			// Remove all callbacks from the list
			empty: function() {
				if ( list ) {
					list = [];
				}
				return this;
			},

			// Disable .fire and .add
			// Abort any current/pending executions
			// Clear all callbacks and values
			disable: function() {
				locked = queue = [];
				list = memory = "";
				return this;
			},
			disabled: function() {
				return !list;
			},

			// Disable .fire
			// Also disable .add unless we have memory (since it would have no effect)
			// Abort any pending executions
			lock: function() {
				locked = queue = [];
				if ( !memory && !firing ) {
					list = memory = "";
				}
				return this;
			},
			locked: function() {
				return !!locked;
			},

			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( !locked ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					queue.push( args );
					if ( !firing ) {
						fire();
					}
				}
				return this;
			},

			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},

			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};


function Identity( v ) {
	return v;
}
function Thrower( ex ) {
	throw ex;
}

function adoptValue( value, resolve, reject, noValue ) {
	var method;

	try {

		// Check for promise aspect first to privilege synchronous behavior
		if ( value && isFunction( ( method = value.promise ) ) ) {
			method.call( value ).done( resolve ).fail( reject );

		// Other thenables
		} else if ( value && isFunction( ( method = value.then ) ) ) {
			method.call( value, resolve, reject );

		// Other non-thenables
		} else {

			// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
			// * false: [ value ].slice( 0 ) => resolve( value )
			// * true: [ value ].slice( 1 ) => resolve()
			resolve.apply( undefined, [ value ].slice( noValue ) );
		}

	// For Promises/A+, convert exceptions into rejections
	// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
	// Deferred#then to conditionally suppress rejection.
	} catch ( value ) {

		// Support: Android 4.0 only
		// Strict mode functions invoked without .call/.apply get global-object context
		reject.apply( undefined, [ value ] );
	}
}

jQuery.extend( {

	Deferred: function( func ) {
		var tuples = [

				// action, add listener, callbacks,
				// ... .then handlers, argument index, [final state]
				[ "notify", "progress", jQuery.Callbacks( "memory" ),
					jQuery.Callbacks( "memory" ), 2 ],
				[ "resolve", "done", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 0, "resolved" ],
				[ "reject", "fail", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 1, "rejected" ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				"catch": function( fn ) {
					return promise.then( null, fn );
				},

				// Keep pipe for back-compat
				pipe: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;

					return jQuery.Deferred( function( newDefer ) {
						jQuery.each( tuples, function( _i, tuple ) {

							// Map tuples (progress, done, fail) to arguments (done, fail, progress)
							var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];

							// deferred.progress(function() { bind to newDefer or newDefer.notify })
							// deferred.done(function() { bind to newDefer or newDefer.resolve })
							// deferred.fail(function() { bind to newDefer or newDefer.reject })
							deferred[ tuple[ 1 ] ]( function() {
								var returned = fn && fn.apply( this, arguments );
								if ( returned && isFunction( returned.promise ) ) {
									returned.promise()
										.progress( newDefer.notify )
										.done( newDefer.resolve )
										.fail( newDefer.reject );
								} else {
									newDefer[ tuple[ 0 ] + "With" ](
										this,
										fn ? [ returned ] : arguments
									);
								}
							} );
						} );
						fns = null;
					} ).promise();
				},
				then: function( onFulfilled, onRejected, onProgress ) {
					var maxDepth = 0;
					function resolve( depth, deferred, handler, special ) {
						return function() {
							var that = this,
								args = arguments,
								mightThrow = function() {
									var returned, then;

									// Support: Promises/A+ section 2.3.3.3.3
									// https://promisesaplus.com/#point-59
									// Ignore double-resolution attempts
									if ( depth < maxDepth ) {
										return;
									}

									returned = handler.apply( that, args );

									// Support: Promises/A+ section 2.3.1
									// https://promisesaplus.com/#point-48
									if ( returned === deferred.promise() ) {
										throw new TypeError( "Thenable self-resolution" );
									}

									// Support: Promises/A+ sections 2.3.3.1, 3.5
									// https://promisesaplus.com/#point-54
									// https://promisesaplus.com/#point-75
									// Retrieve `then` only once
									then = returned &&

										// Support: Promises/A+ section 2.3.4
										// https://promisesaplus.com/#point-64
										// Only check objects and functions for thenability
										( typeof returned === "object" ||
											typeof returned === "function" ) &&
										returned.then;

									// Handle a returned thenable
									if ( isFunction( then ) ) {

										// Special processors (notify) just wait for resolution
										if ( special ) {
											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special )
											);

										// Normal processors (resolve) also hook into progress
										} else {

											// ...and disregard older resolution values
											maxDepth++;

											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special ),
												resolve( maxDepth, deferred, Identity,
													deferred.notifyWith )
											);
										}

									// Handle all other returned values
									} else {

										// Only substitute handlers pass on context
										// and multiple values (non-spec behavior)
										if ( handler !== Identity ) {
											that = undefined;
											args = [ returned ];
										}

										// Process the value(s)
										// Default process is resolve
										( special || deferred.resolveWith )( that, args );
									}
								},

								// Only normal processors (resolve) catch and reject exceptions
								process = special ?
									mightThrow :
									function() {
										try {
											mightThrow();
										} catch ( e ) {

											if ( jQuery.Deferred.exceptionHook ) {
												jQuery.Deferred.exceptionHook( e,
													process.stackTrace );
											}

											// Support: Promises/A+ section 2.3.3.3.4.1
											// https://promisesaplus.com/#point-61
											// Ignore post-resolution exceptions
											if ( depth + 1 >= maxDepth ) {

												// Only substitute handlers pass on context
												// and multiple values (non-spec behavior)
												if ( handler !== Thrower ) {
													that = undefined;
													args = [ e ];
												}

												deferred.rejectWith( that, args );
											}
										}
									};

							// Support: Promises/A+ section 2.3.3.3.1
							// https://promisesaplus.com/#point-57
							// Re-resolve promises immediately to dodge false rejection from
							// subsequent errors
							if ( depth ) {
								process();
							} else {

								// Call an optional hook to record the stack, in case of exception
								// since it's otherwise lost when execution goes async
								if ( jQuery.Deferred.getStackHook ) {
									process.stackTrace = jQuery.Deferred.getStackHook();
								}
								window.setTimeout( process );
							}
						};
					}

					return jQuery.Deferred( function( newDefer ) {

						// progress_handlers.add( ... )
						tuples[ 0 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onProgress ) ?
									onProgress :
									Identity,
								newDefer.notifyWith
							)
						);

						// fulfilled_handlers.add( ... )
						tuples[ 1 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onFulfilled ) ?
									onFulfilled :
									Identity
							)
						);

						// rejected_handlers.add( ... )
						tuples[ 2 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onRejected ) ?
									onRejected :
									Thrower
							)
						);
					} ).promise();
				},

				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 5 ];

			// promise.progress = list.add
			// promise.done = list.add
			// promise.fail = list.add
			promise[ tuple[ 1 ] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add(
					function() {

						// state = "resolved" (i.e., fulfilled)
						// state = "rejected"
						state = stateString;
					},

					// rejected_callbacks.disable
					// fulfilled_callbacks.disable
					tuples[ 3 - i ][ 2 ].disable,

					// rejected_handlers.disable
					// fulfilled_handlers.disable
					tuples[ 3 - i ][ 3 ].disable,

					// progress_callbacks.lock
					tuples[ 0 ][ 2 ].lock,

					// progress_handlers.lock
					tuples[ 0 ][ 3 ].lock
				);
			}

			// progress_handlers.fire
			// fulfilled_handlers.fire
			// rejected_handlers.fire
			list.add( tuple[ 3 ].fire );

			// deferred.notify = function() { deferred.notifyWith(...) }
			// deferred.resolve = function() { deferred.resolveWith(...) }
			// deferred.reject = function() { deferred.rejectWith(...) }
			deferred[ tuple[ 0 ] ] = function() {
				deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
				return this;
			};

			// deferred.notifyWith = list.fireWith
			// deferred.resolveWith = list.fireWith
			// deferred.rejectWith = list.fireWith
			deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
		} );

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( singleValue ) {
		var

			// count of uncompleted subordinates
			remaining = arguments.length,

			// count of unprocessed arguments
			i = remaining,

			// subordinate fulfillment data
			resolveContexts = Array( i ),
			resolveValues = slice.call( arguments ),

			// the primary Deferred
			primary = jQuery.Deferred(),

			// subordinate callback factory
			updateFunc = function( i ) {
				return function( value ) {
					resolveContexts[ i ] = this;
					resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
					if ( !( --remaining ) ) {
						primary.resolveWith( resolveContexts, resolveValues );
					}
				};
			};

		// Single- and empty arguments are adopted like Promise.resolve
		if ( remaining <= 1 ) {
			adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject,
				!remaining );

			// Use .then() to unwrap secondary thenables (cf. gh-3000)
			if ( primary.state() === "pending" ||
				isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {

				return primary.then();
			}
		}

		// Multiple arguments are aggregated like Promise.all array elements
		while ( i-- ) {
			adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject );
		}

		return primary.promise();
	}
} );


// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;

jQuery.Deferred.exceptionHook = function( error, stack ) {

	// Support: IE 8 - 9 only
	// Console exists when dev tools are open, which can happen at any time
	if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
		window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
	}
};




jQuery.readyException = function( error ) {
	window.setTimeout( function() {
		throw error;
	} );
};




// The deferred used on DOM ready
var readyList = jQuery.Deferred();

jQuery.fn.ready = function( fn ) {

	readyList
		.then( fn )

		// Wrap jQuery.readyException in a function so that the lookup
		// happens at the time of error handling instead of callback
		// registration.
		.catch( function( error ) {
			jQuery.readyException( error );
		} );

	return this;
};

jQuery.extend( {

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Remember that the DOM is ready
		jQuery.isReady = true;

		// If a normal DOM Ready event fired, decrement, and wait if need be
		if ( wait !== true && --jQuery.readyWait > 0 ) {
			return;
		}

		// If there are functions bound, to execute
		readyList.resolveWith( document, [ jQuery ] );
	}
} );

jQuery.ready.then = readyList.then;

// The ready event handler and self cleanup method
function completed() {
	document.removeEventListener( "DOMContentLoaded", completed );
	window.removeEventListener( "load", completed );
	jQuery.ready();
}

// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
	( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {

	// Handle it asynchronously to allow scripts the opportunity to delay ready
	window.setTimeout( jQuery.ready );

} else {

	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", completed );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", completed );
}




// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
	var i = 0,
		len = elems.length,
		bulk = key == null;

	// Sets many values
	if ( toType( key ) === "object" ) {
		chainable = true;
		for ( i in key ) {
			access( elems, fn, i, key[ i ], true, emptyGet, raw );
		}

	// Sets one value
	} else if ( value !== undefined ) {
		chainable = true;

		if ( !isFunction( value ) ) {
			raw = true;
		}

		if ( bulk ) {

			// Bulk operations run against the entire set
			if ( raw ) {
				fn.call( elems, value );
				fn = null;

			// ...except when executing function values
			} else {
				bulk = fn;
				fn = function( elem, _key, value ) {
					return bulk.call( jQuery( elem ), value );
				};
			}
		}

		if ( fn ) {
			for ( ; i < len; i++ ) {
				fn(
					elems[ i ], key, raw ?
						value :
						value.call( elems[ i ], i, fn( elems[ i ], key ) )
				);
			}
		}
	}

	if ( chainable ) {
		return elems;
	}

	// Gets
	if ( bulk ) {
		return fn.call( elems );
	}

	return len ? fn( elems[ 0 ], key ) : emptyGet;
};


// Matches dashed string for camelizing
var rmsPrefix = /^-ms-/,
	rdashAlpha = /-([a-z])/g;

// Used by camelCase as callback to replace()
function fcamelCase( _all, letter ) {
	return letter.toUpperCase();
}

// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 15
// Microsoft forgot to hump their vendor prefix (#9572)
function camelCase( string ) {
	return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
}
var acceptData = function( owner ) {

	// Accepts only:
	//  - Node
	//    - Node.ELEMENT_NODE
	//    - Node.DOCUMENT_NODE
	//  - Object
	//    - Any
	return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};




function Data() {
	this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;

Data.prototype = {

	cache: function( owner ) {

		// Check if the owner object already has a cache
		var value = owner[ this.expando ];

		// If not, create one
		if ( !value ) {
			value = {};

			// We can accept data for non-element nodes in modern browsers,
			// but we should not, see #8335.
			// Always return an empty object.
			if ( acceptData( owner ) ) {

				// If it is a node unlikely to be stringify-ed or looped over
				// use plain assignment
				if ( owner.nodeType ) {
					owner[ this.expando ] = value;

				// Otherwise secure it in a non-enumerable property
				// configurable must be true to allow the property to be
				// deleted when data is removed
				} else {
					Object.defineProperty( owner, this.expando, {
						value: value,
						configurable: true
					} );
				}
			}
		}

		return value;
	},
	set: function( owner, data, value ) {
		var prop,
			cache = this.cache( owner );

		// Handle: [ owner, key, value ] args
		// Always use camelCase key (gh-2257)
		if ( typeof data === "string" ) {
			cache[ camelCase( data ) ] = value;

		// Handle: [ owner, { properties } ] args
		} else {

			// Copy the properties one-by-one to the cache object
			for ( prop in data ) {
				cache[ camelCase( prop ) ] = data[ prop ];
			}
		}
		return cache;
	},
	get: function( owner, key ) {
		return key === undefined ?
			this.cache( owner ) :

			// Always use camelCase key (gh-2257)
			owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ];
	},
	access: function( owner, key, value ) {

		// In cases where either:
		//
		//   1. No key was specified
		//   2. A string key was specified, but no value provided
		//
		// Take the "read" path and allow the get method to determine
		// which value to return, respectively either:
		//
		//   1. The entire cache object
		//   2. The data stored at the key
		//
		if ( key === undefined ||
				( ( key && typeof key === "string" ) && value === undefined ) ) {

			return this.get( owner, key );
		}

		// When the key is not a string, or both a key and value
		// are specified, set or extend (existing objects) with either:
		//
		//   1. An object of properties
		//   2. A key and value
		//
		this.set( owner, key, value );

		// Since the "set" path can have two possible entry points
		// return the expected data based on which path was taken[*]
		return value !== undefined ? value : key;
	},
	remove: function( owner, key ) {
		var i,
			cache = owner[ this.expando ];

		if ( cache === undefined ) {
			return;
		}

		if ( key !== undefined ) {

			// Support array or space separated string of keys
			if ( Array.isArray( key ) ) {

				// If key is an array of keys...
				// We always set camelCase keys, so remove that.
				key = key.map( camelCase );
			} else {
				key = camelCase( key );

				// If a key with the spaces exists, use it.
				// Otherwise, create an array by matching non-whitespace
				key = key in cache ?
					[ key ] :
					( key.match( rnothtmlwhite ) || [] );
			}

			i = key.length;

			while ( i-- ) {
				delete cache[ key[ i ] ];
			}
		}

		// Remove the expando if there's no more data
		if ( key === undefined || jQuery.isEmptyObject( cache ) ) {

			// Support: Chrome <=35 - 45
			// Webkit & Blink performance suffers when deleting properties
			// from DOM nodes, so set to undefined instead
			// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
			if ( owner.nodeType ) {
				owner[ this.expando ] = undefined;
			} else {
				delete owner[ this.expando ];
			}
		}
	},
	hasData: function( owner ) {
		var cache = owner[ this.expando ];
		return cache !== undefined && !jQuery.isEmptyObject( cache );
	}
};
var dataPriv = new Data();

var dataUser = new Data();



//	Implementation Summary
//
//	1. Enforce API surface and semantic compatibility with 1.9.x branch
//	2. Improve the module's maintainability by reducing the storage
//		paths to a single mechanism.
//	3. Use the same single mechanism to support "private" and "user" data.
//	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
//	5. Avoid exposing implementation details on user objects (eg. expando properties)
//	6. Provide a clear path for implementation upgrade to WeakMap in 2014

var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	rmultiDash = /[A-Z]/g;

function getData( data ) {
	if ( data === "true" ) {
		return true;
	}

	if ( data === "false" ) {
		return false;
	}

	if ( data === "null" ) {
		return null;
	}

	// Only convert to a number if it doesn't change the string
	if ( data === +data + "" ) {
		return +data;
	}

	if ( rbrace.test( data ) ) {
		return JSON.parse( data );
	}

	return data;
}

function dataAttr( elem, key, data ) {
	var name;

	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {
		name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = getData( data );
			} catch ( e ) {}

			// Make sure we set the data so it isn't changed later
			dataUser.set( elem, key, data );
		} else {
			data = undefined;
		}
	}
	return data;
}

jQuery.extend( {
	hasData: function( elem ) {
		return dataUser.hasData( elem ) || dataPriv.hasData( elem );
	},

	data: function( elem, name, data ) {
		return dataUser.access( elem, name, data );
	},

	removeData: function( elem, name ) {
		dataUser.remove( elem, name );
	},

	// TODO: Now that all calls to _data and _removeData have been replaced
	// with direct calls to dataPriv methods, these can be deprecated.
	_data: function( elem, name, data ) {
		return dataPriv.access( elem, name, data );
	},

	_removeData: function( elem, name ) {
		dataPriv.remove( elem, name );
	}
} );

jQuery.fn.extend( {
	data: function( key, value ) {
		var i, name, data,
			elem = this[ 0 ],
			attrs = elem && elem.attributes;

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = dataUser.get( elem );

				if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
					i = attrs.length;
					while ( i-- ) {

						// Support: IE 11 only
						// The attrs elements can be null (#14894)
						if ( attrs[ i ] ) {
							name = attrs[ i ].name;
							if ( name.indexOf( "data-" ) === 0 ) {
								name = camelCase( name.slice( 5 ) );
								dataAttr( elem, name, data[ name ] );
							}
						}
					}
					dataPriv.set( elem, "hasDataAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each( function() {
				dataUser.set( this, key );
			} );
		}

		return access( this, function( value ) {
			var data;

			// The calling jQuery object (element matches) is not empty
			// (and therefore has an element appears at this[ 0 ]) and the
			// `value` parameter was not undefined. An empty jQuery object
			// will result in `undefined` for elem = this[ 0 ] which will
			// throw an exception if an attempt to read a data cache is made.
			if ( elem && value === undefined ) {

				// Attempt to get data from the cache
				// The key will always be camelCased in Data
				data = dataUser.get( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// Attempt to "discover" the data in
				// HTML5 custom data-* attrs
				data = dataAttr( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// We tried really hard, but the data doesn't exist.
				return;
			}

			// Set the data...
			this.each( function() {

				// We always store the camelCased key
				dataUser.set( this, key, value );
			} );
		}, null, value, arguments.length > 1, null, true );
	},

	removeData: function( key ) {
		return this.each( function() {
			dataUser.remove( this, key );
		} );
	}
} );


jQuery.extend( {
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = dataPriv.get( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || Array.isArray( data ) ) {
					queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
				} else {
					queue.push( data );
				}
			}
			return queue || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			startLength = queue.length,
			fn = queue.shift(),
			hooks = jQuery._queueHooks( elem, type ),
			next = function() {
				jQuery.dequeue( elem, type );
			};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
			startLength--;
		}

		if ( fn ) {

			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			// Clear up the last queue stop function
			delete hooks.stop;
			fn.call( elem, next, hooks );
		}

		if ( !startLength && hooks ) {
			hooks.empty.fire();
		}
	},

	// Not public - generate a queueHooks object, or return the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
			empty: jQuery.Callbacks( "once memory" ).add( function() {
				dataPriv.remove( elem, [ type + "queue", key ] );
			} )
		} );
	}
} );

jQuery.fn.extend( {
	queue: function( type, data ) {
		var setter = 2;

		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
			setter--;
		}

		if ( arguments.length < setter ) {
			return jQuery.queue( this[ 0 ], type );
		}

		return data === undefined ?
			this :
			this.each( function() {
				var queue = jQuery.queue( this, type, data );

				// Ensure a hooks for this queue
				jQuery._queueHooks( this, type );

				if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
					jQuery.dequeue( this, type );
				}
			} );
	},
	dequeue: function( type ) {
		return this.each( function() {
			jQuery.dequeue( this, type );
		} );
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},

	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, obj ) {
		var tmp,
			count = 1,
			defer = jQuery.Deferred(),
			elements = this,
			i = this.length,
			resolve = function() {
				if ( !( --count ) ) {
					defer.resolveWith( elements, [ elements ] );
				}
			};

		if ( typeof type !== "string" ) {
			obj = type;
			type = undefined;
		}
		type = type || "fx";

		while ( i-- ) {
			tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
			if ( tmp && tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;

var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );


var cssExpand = [ "Top", "Right", "Bottom", "Left" ];

var documentElement = document.documentElement;



	var isAttached = function( elem ) {
			return jQuery.contains( elem.ownerDocument, elem );
		},
		composed = { composed: true };

	// Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only
	// Check attachment across shadow DOM boundaries when possible (gh-3504)
	// Support: iOS 10.0-10.2 only
	// Early iOS 10 versions support `attachShadow` but not `getRootNode`,
	// leading to errors. We need to check for `getRootNode`.
	if ( documentElement.getRootNode ) {
		isAttached = function( elem ) {
			return jQuery.contains( elem.ownerDocument, elem ) ||
				elem.getRootNode( composed ) === elem.ownerDocument;
		};
	}
var isHiddenWithinTree = function( elem, el ) {

		// isHiddenWithinTree might be called from jQuery#filter function;
		// in that case, element will be second argument
		elem = el || elem;

		// Inline style trumps all
		return elem.style.display === "none" ||
			elem.style.display === "" &&

			// Otherwise, check computed style
			// Support: Firefox <=43 - 45
			// Disconnected elements can have computed display: none, so first confirm that elem is
			// in the document.
			isAttached( elem ) &&

			jQuery.css( elem, "display" ) === "none";
	};



function adjustCSS( elem, prop, valueParts, tween ) {
	var adjusted, scale,
		maxIterations = 20,
		currentValue = tween ?
			function() {
				return tween.cur();
			} :
			function() {
				return jQuery.css( elem, prop, "" );
			},
		initial = currentValue(),
		unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),

		// Starting value computation is required for potential unit mismatches
		initialInUnit = elem.nodeType &&
			( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
			rcssNum.exec( jQuery.css( elem, prop ) );

	if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {

		// Support: Firefox <=54
		// Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
		initial = initial / 2;

		// Trust units reported by jQuery.css
		unit = unit || initialInUnit[ 3 ];

		// Iteratively approximate from a nonzero starting point
		initialInUnit = +initial || 1;

		while ( maxIterations-- ) {

			// Evaluate and update our best guess (doubling guesses that zero out).
			// Finish if the scale equals or crosses 1 (making the old*new product non-positive).
			jQuery.style( elem, prop, initialInUnit + unit );
			if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) {
				maxIterations = 0;
			}
			initialInUnit = initialInUnit / scale;

		}

		initialInUnit = initialInUnit * 2;
		jQuery.style( elem, prop, initialInUnit + unit );

		// Make sure we update the tween properties later on
		valueParts = valueParts || [];
	}

	if ( valueParts ) {
		initialInUnit = +initialInUnit || +initial || 0;

		// Apply relative offset (+=/-=) if specified
		adjusted = valueParts[ 1 ] ?
			initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
			+valueParts[ 2 ];
		if ( tween ) {
			tween.unit = unit;
			tween.start = initialInUnit;
			tween.end = adjusted;
		}
	}
	return adjusted;
}


var defaultDisplayMap = {};

function getDefaultDisplay( elem ) {
	var temp,
		doc = elem.ownerDocument,
		nodeName = elem.nodeName,
		display = defaultDisplayMap[ nodeName ];

	if ( display ) {
		return display;
	}

	temp = doc.body.appendChild( doc.createElement( nodeName ) );
	display = jQuery.css( temp, "display" );

	temp.parentNode.removeChild( temp );

	if ( display === "none" ) {
		display = "block";
	}
	defaultDisplayMap[ nodeName ] = display;

	return display;
}

function showHide( elements, show ) {
	var display, elem,
		values = [],
		index = 0,
		length = elements.length;

	// Determine new display value for elements that need to change
	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		display = elem.style.display;
		if ( show ) {

			// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
			// check is required in this first loop unless we have a nonempty display value (either
			// inline or about-to-be-restored)
			if ( display === "none" ) {
				values[ index ] = dataPriv.get( elem, "display" ) || null;
				if ( !values[ index ] ) {
					elem.style.display = "";
				}
			}
			if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
				values[ index ] = getDefaultDisplay( elem );
			}
		} else {
			if ( display !== "none" ) {
				values[ index ] = "none";

				// Remember what we're overwriting
				dataPriv.set( elem, "display", display );
			}
		}
	}

	// Set the display of the elements in a second loop to avoid constant reflow
	for ( index = 0; index < length; index++ ) {
		if ( values[ index ] != null ) {
			elements[ index ].style.display = values[ index ];
		}
	}

	return elements;
}

jQuery.fn.extend( {
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state ) {
		if ( typeof state === "boolean" ) {
			return state ? this.show() : this.hide();
		}

		return this.each( function() {
			if ( isHiddenWithinTree( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		} );
	}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );

var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i );

var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );



( function() {
	var fragment = document.createDocumentFragment(),
		div = fragment.appendChild( document.createElement( "div" ) ),
		input = document.createElement( "input" );

	// Support: Android 4.0 - 4.3 only
	// Check state lost if the name is set (#11217)
	// Support: Windows Web Apps (WWA)
	// `name` and `type` must use .setAttribute for WWA (#14901)
	input.setAttribute( "type", "radio" );
	input.setAttribute( "checked", "checked" );
	input.setAttribute( "name", "t" );

	div.appendChild( input );

	// Support: Android <=4.1 only
	// Older WebKit doesn't clone checked state correctly in fragments
	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE <=11 only
	// Make sure textarea (and checkbox) defaultValue is properly cloned
	div.innerHTML = "<textarea>x</textarea>";
	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;

	// Support: IE <=9 only
	// IE <=9 replaces <option> tags with their contents when inserted outside of
	// the select element.
	div.innerHTML = "<option></option>";
	support.option = !!div.lastChild;
} )();


// We have to close these tags to support XHTML (#13200)
var wrapMap = {

	// XHTML parsers do not magically insert elements in the
	// same way that tag soup parsers do. So we cannot shorten
	// this by omitting <tbody> or other required elements.
	thead: [ 1, "<table>", "</table>" ],
	col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
	tr: [ 2, "<table><tbody>", "</tbody></table>" ],
	td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

	_default: [ 0, "", "" ]
};

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

// Support: IE <=9 only
if ( !support.option ) {
	wrapMap.optgroup = wrapMap.option = [ 1, "<select multiple='multiple'>", "</select>" ];
}


function getAll( context, tag ) {

	// Support: IE <=9 - 11 only
	// Use typeof to avoid zero-argument method invocation on host objects (#15151)
	var ret;

	if ( typeof context.getElementsByTagName !== "undefined" ) {
		ret = context.getElementsByTagName( tag || "*" );

	} else if ( typeof context.querySelectorAll !== "undefined" ) {
		ret = context.querySelectorAll( tag || "*" );

	} else {
		ret = [];
	}

	if ( tag === undefined || tag && nodeName( context, tag ) ) {
		return jQuery.merge( [ context ], ret );
	}

	return ret;
}


// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		dataPriv.set(
			elems[ i ],
			"globalEval",
			!refElements || dataPriv.get( refElements[ i ], "globalEval" )
		);
	}
}


var rhtml = /<|&#?\w+;/;

function buildFragment( elems, context, scripts, selection, ignored ) {
	var elem, tmp, tag, wrap, attached, j,
		fragment = context.createDocumentFragment(),
		nodes = [],
		i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		elem = elems[ i ];

		if ( elem || elem === 0 ) {

			// Add nodes directly
			if ( toType( elem ) === "object" ) {

				// Support: Android <=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );

			// Convert non-html into a text node
			} else if ( !rhtml.test( elem ) ) {
				nodes.push( context.createTextNode( elem ) );

			// Convert html into DOM nodes
			} else {
				tmp = tmp || fragment.appendChild( context.createElement( "div" ) );

				// Deserialize a standard representation
				tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
				wrap = wrapMap[ tag ] || wrapMap._default;
				tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];

				// Descend through wrappers to the right content
				j = wrap[ 0 ];
				while ( j-- ) {
					tmp = tmp.lastChild;
				}

				// Support: Android <=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, tmp.childNodes );

				// Remember the top-level container
				tmp = fragment.firstChild;

				// Ensure the created nodes are orphaned (#12392)
				tmp.textContent = "";
			}
		}
	}

	// Remove wrapper from fragment
	fragment.textContent = "";

	i = 0;
	while ( ( elem = nodes[ i++ ] ) ) {

		// Skip elements already in the context collection (trac-4087)
		if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
			if ( ignored ) {
				ignored.push( elem );
			}
			continue;
		}

		attached = isAttached( elem );

		// Append to fragment
		tmp = getAll( fragment.appendChild( elem ), "script" );

		// Preserve script evaluation history
		if ( attached ) {
			setGlobalEval( tmp );
		}

		// Capture executables
		if ( scripts ) {
			j = 0;
			while ( ( elem = tmp[ j++ ] ) ) {
				if ( rscriptType.test( elem.type || "" ) ) {
					scripts.push( elem );
				}
			}
		}
	}

	return fragment;
}


var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

// Support: IE <=9 - 11+
// focus() and blur() are asynchronous, except when they are no-op.
// So expect focus to be synchronous when the element is already active,
// and blur to be synchronous when the element is not already active.
// (focus and blur are always synchronous in other supported browsers,
// this just defines when we can count on it).
function expectSync( elem, type ) {
	return ( elem === safeActiveElement() ) === ( type === "focus" );
}

// Support: IE <=9 only
// Accessing document.activeElement can throw unexpectedly
// https://bugs.jquery.com/ticket/13393
function safeActiveElement() {
	try {
		return document.activeElement;
	} catch ( err ) { }
}

function on( elem, types, selector, data, fn, one ) {
	var origFn, type;

	// Types can be a map of types/handlers
	if ( typeof types === "object" ) {

		// ( types-Object, selector, data )
		if ( typeof selector !== "string" ) {

			// ( types-Object, data )
			data = data || selector;
			selector = undefined;
		}
		for ( type in types ) {
			on( elem, type, selector, data, types[ type ], one );
		}
		return elem;
	}

	if ( data == null && fn == null ) {

		// ( types, fn )
		fn = selector;
		data = selector = undefined;
	} else if ( fn == null ) {
		if ( typeof selector === "string" ) {

			// ( types, selector, fn )
			fn = data;
			data = undefined;
		} else {

			// ( types, data, fn )
			fn = data;
			data = selector;
			selector = undefined;
		}
	}
	if ( fn === false ) {
		fn = returnFalse;
	} else if ( !fn ) {
		return elem;
	}

	if ( one === 1 ) {
		origFn = fn;
		fn = function( event ) {

			// Can use an empty set, since event contains the info
			jQuery().off( event );
			return origFn.apply( this, arguments );
		};

		// Use same guid so caller can remove using origFn
		fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
	}
	return elem.each( function() {
		jQuery.event.add( this, types, fn, data, selector );
	} );
}

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	global: {},

	add: function( elem, types, handler, data, selector ) {

		var handleObjIn, eventHandle, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.get( elem );

		// Only attach events to objects that accept data
		if ( !acceptData( elem ) ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
			selector = handleObjIn.selector;
		}

		// Ensure that invalid selectors throw exceptions at attach time
		// Evaluate against documentElement in case elem is a non-element node (e.g., document)
		if ( selector ) {
			jQuery.find.matchesSelector( documentElement, selector );
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		if ( !( events = elemData.events ) ) {
			events = elemData.events = Object.create( null );
		}
		if ( !( eventHandle = elemData.handle ) ) {
			eventHandle = elemData.handle = function( e ) {

				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
					jQuery.event.dispatch.apply( elem, arguments ) : undefined;
			};
		}

		// Handle multiple events separated by a space
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// There *must* be a type, no attaching namespace-only handlers
			if ( !type ) {
				continue;
			}

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend( {
				type: type,
				origType: origType,
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
				namespace: namespaces.join( "." )
			}, handleObjIn );

			// Init the event handler queue if we're the first
			if ( !( handlers = events[ type ] ) ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener if the special events handler returns false
				if ( !special.setup ||
					special.setup.call( elem, data, namespaces, eventHandle ) === false ) {

					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {

		var j, origCount, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );

		if ( !elemData || !( events = elemData.events ) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector ? special.delegateType : special.bindType ) || type;
			handlers = events[ type ] || [];
			tmp = tmp[ 2 ] &&
				new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );

			// Remove matching events
			origCount = j = handlers.length;
			while ( j-- ) {
				handleObj = handlers[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &&
					( !handler || handler.guid === handleObj.guid ) &&
					( !tmp || tmp.test( handleObj.namespace ) ) &&
					( !selector || selector === handleObj.selector ||
						selector === "**" && handleObj.selector ) ) {
					handlers.splice( j, 1 );

					if ( handleObj.selector ) {
						handlers.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( origCount && !handlers.length ) {
				if ( !special.teardown ||
					special.teardown.call( elem, namespaces, elemData.handle ) === false ) {

					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove data and the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			dataPriv.remove( elem, "handle events" );
		}
	},

	dispatch: function( nativeEvent ) {

		var i, j, ret, matched, handleObj, handlerQueue,
			args = new Array( arguments.length ),

			// Make a writable jQuery.Event from the native event object
			event = jQuery.event.fix( nativeEvent ),

			handlers = (
				dataPriv.get( this, "events" ) || Object.create( null )
			)[ event.type ] || [],
			special = jQuery.event.special[ event.type ] || {};

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[ 0 ] = event;

		for ( i = 1; i < arguments.length; i++ ) {
			args[ i ] = arguments[ i ];
		}

		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers
		handlerQueue = jQuery.event.handlers.call( this, event, handlers );

		// Run delegates first; they may want to stop propagation beneath us
		i = 0;
		while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
			event.currentTarget = matched.elem;

			j = 0;
			while ( ( handleObj = matched.handlers[ j++ ] ) &&
				!event.isImmediatePropagationStopped() ) {

				// If the event is namespaced, then each handler is only invoked if it is
				// specially universal or its namespaces are a superset of the event's.
				if ( !event.rnamespace || handleObj.namespace === false ||
					event.rnamespace.test( handleObj.namespace ) ) {

					event.handleObj = handleObj;
					event.data = handleObj.data;

					ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
						handleObj.handler ).apply( matched.elem, args );

					if ( ret !== undefined ) {
						if ( ( event.result = ret ) === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	handlers: function( event, handlers ) {
		var i, handleObj, sel, matchedHandlers, matchedSelectors,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Find delegate handlers
		if ( delegateCount &&

			// Support: IE <=9
			// Black-hole SVG <use> instance trees (trac-13180)
			cur.nodeType &&

			// Support: Firefox <=42
			// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
			// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
			// Support: IE 11 only
			// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
			!( event.type === "click" && event.button >= 1 ) ) {

			for ( ; cur !== this; cur = cur.parentNode || this ) {

				// Don't check non-elements (#13208)
				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
				if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
					matchedHandlers = [];
					matchedSelectors = {};
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (#13203)
						sel = handleObj.selector + " ";

						if ( matchedSelectors[ sel ] === undefined ) {
							matchedSelectors[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) > -1 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matchedSelectors[ sel ] ) {
							matchedHandlers.push( handleObj );
						}
					}
					if ( matchedHandlers.length ) {
						handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		cur = this;
		if ( delegateCount < handlers.length ) {
			handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
		}

		return handlerQueue;
	},

	addProp: function( name, hook ) {
		Object.defineProperty( jQuery.Event.prototype, name, {
			enumerable: true,
			configurable: true,

			get: isFunction( hook ) ?
				function() {
					if ( this.originalEvent ) {
						return hook( this.originalEvent );
					}
				} :
				function() {
					if ( this.originalEvent ) {
						return this.originalEvent[ name ];
					}
				},

			set: function( value ) {
				Object.defineProperty( this, name, {
					enumerable: true,
					configurable: true,
					writable: true,
					value: value
				} );
			}
		} );
	},

	fix: function( originalEvent ) {
		return originalEvent[ jQuery.expando ] ?
			originalEvent :
			new jQuery.Event( originalEvent );
	},

	special: {
		load: {

			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		click: {

			// Utilize native event to ensure correct state for checkable inputs
			setup: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Claim the first handler
				if ( rcheckableType.test( el.type ) &&
					el.click && nodeName( el, "input" ) ) {

					// dataPriv.set( el, "click", ... )
					leverageNative( el, "click", returnTrue );
				}

				// Return false to allow normal processing in the caller
				return false;
			},
			trigger: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Force setup before triggering a click
				if ( rcheckableType.test( el.type ) &&
					el.click && nodeName( el, "input" ) ) {

					leverageNative( el, "click" );
				}

				// Return non-false to allow normal event-path propagation
				return true;
			},

			// For cross-browser consistency, suppress native .click() on links
			// Also prevent it if we're currently inside a leveraged native-event stack
			_default: function( event ) {
				var target = event.target;
				return rcheckableType.test( target.type ) &&
					target.click && nodeName( target, "input" ) &&
					dataPriv.get( target, "click" ) ||
					nodeName( target, "a" );
			}
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Support: Firefox 20+
				// Firefox doesn't alert if the returnValue field is not set.
				if ( event.result !== undefined && event.originalEvent ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	}
};

// Ensure the presence of an event listener that handles manually-triggered
// synthetic events by interrupting progress until reinvoked in response to
// *native* events that it fires directly, ensuring that state changes have
// already occurred before other listeners are invoked.
function leverageNative( el, type, expectSync ) {

	// Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add
	if ( !expectSync ) {
		if ( dataPriv.get( el, type ) === undefined ) {
			jQuery.event.add( el, type, returnTrue );
		}
		return;
	}

	// Register the controller as a special universal handler for all event namespaces
	dataPriv.set( el, type, false );
	jQuery.event.add( el, type, {
		namespace: false,
		handler: function( event ) {
			var notAsync, result,
				saved = dataPriv.get( this, type );

			if ( ( event.isTrigger & 1 ) && this[ type ] ) {

				// Interrupt processing of the outer synthetic .trigger()ed event
				// Saved data should be false in such cases, but might be a leftover capture object
				// from an async native handler (gh-4350)
				if ( !saved.length ) {

					// Store arguments for use when handling the inner native event
					// There will always be at least one argument (an event object), so this array
					// will not be confused with a leftover capture object.
					saved = slice.call( arguments );
					dataPriv.set( this, type, saved );

					// Trigger the native event and capture its result
					// Support: IE <=9 - 11+
					// focus() and blur() are asynchronous
					notAsync = expectSync( this, type );
					this[ type ]();
					result = dataPriv.get( this, type );
					if ( saved !== result || notAsync ) {
						dataPriv.set( this, type, false );
					} else {
						result = {};
					}
					if ( saved !== result ) {

						// Cancel the outer synthetic event
						event.stopImmediatePropagation();
						event.preventDefault();

						// Support: Chrome 86+
						// In Chrome, if an element having a focusout handler is blurred by
						// clicking outside of it, it invokes the handler synchronously. If
						// that handler calls `.remove()` on the element, the data is cleared,
						// leaving `result` undefined. We need to guard against this.
						return result && result.value;
					}

				// If this is an inner synthetic event for an event with a bubbling surrogate
				// (focus or blur), assume that the surrogate already propagated from triggering the
				// native event and prevent that from happening again here.
				// This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the
				// bubbling surrogate propagates *after* the non-bubbling base), but that seems
				// less bad than duplication.
				} else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) {
					event.stopPropagation();
				}

			// If this is a native event triggered above, everything is now in order
			// Fire an inner synthetic event with the original arguments
			} else if ( saved.length ) {

				// ...and capture the result
				dataPriv.set( this, type, {
					value: jQuery.event.trigger(

						// Support: IE <=9 - 11+
						// Extend with the prototype to reset the above stopImmediatePropagation()
						jQuery.extend( saved[ 0 ], jQuery.Event.prototype ),
						saved.slice( 1 ),
						this
					)
				} );

				// Abort handling of the native event
				event.stopImmediatePropagation();
			}
		}
	} );
}

jQuery.removeEvent = function( elem, type, handle ) {

	// This "if" is needed for plain objects
	if ( elem.removeEventListener ) {
		elem.removeEventListener( type, handle );
	}
};

jQuery.Event = function( src, props ) {

	// Allow instantiation without the 'new' keyword
	if ( !( this instanceof jQuery.Event ) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &&

				// Support: Android <=2.3 only
				src.returnValue === false ?
			returnTrue :
			returnFalse;

		// Create target properties
		// Support: Safari <=6 - 7 only
		// Target should not be a text node (#504, #13143)
		this.target = ( src.target && src.target.nodeType === 3 ) ?
			src.target.parentNode :
			src.target;

		this.currentTarget = src.currentTarget;
		this.relatedTarget = src.relatedTarget;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || Date.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	constructor: jQuery.Event,
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,
	isSimulated: false,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;

		if ( e && !this.isSimulated ) {
			e.preventDefault();
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopPropagation();
		}
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
	altKey: true,
	bubbles: true,
	cancelable: true,
	changedTouches: true,
	ctrlKey: true,
	detail: true,
	eventPhase: true,
	metaKey: true,
	pageX: true,
	pageY: true,
	shiftKey: true,
	view: true,
	"char": true,
	code: true,
	charCode: true,
	key: true,
	keyCode: true,
	button: true,
	buttons: true,
	clientX: true,
	clientY: true,
	offsetX: true,
	offsetY: true,
	pointerId: true,
	pointerType: true,
	screenX: true,
	screenY: true,
	targetTouches: true,
	toElement: true,
	touches: true,
	which: true
}, jQuery.event.addProp );

jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {
	jQuery.event.special[ type ] = {

		// Utilize native event if possible so blur/focus sequence is correct
		setup: function() {

			// Claim the first handler
			// dataPriv.set( this, "focus", ... )
			// dataPriv.set( this, "blur", ... )
			leverageNative( this, type, expectSync );

			// Return false to allow normal processing in the caller
			return false;
		},
		trigger: function() {

			// Force setup before trigger
			leverageNative( this, type );

			// Return non-false to allow normal event-path propagation
			return true;
		},

		// Suppress native focus or blur as it's already being fired
		// in leverageNative.
		_default: function() {
			return true;
		},

		delegateType: delegateType
	};
} );

// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
	mouseenter: "mouseover",
	mouseleave: "mouseout",
	pointerenter: "pointerover",
	pointerleave: "pointerout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mouseenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
} );

jQuery.fn.extend( {

	on: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn );
	},
	one: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {

			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ?
					handleObj.origType + "." + handleObj.namespace :
					handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {

			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {

			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each( function() {
			jQuery.event.remove( this, types, fn, selector );
		} );
	}
} );


var

	// Support: IE <=10 - 11, Edge 12 - 13 only
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /<script|<style|<link/i,

	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;

// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
	if ( nodeName( elem, "table" ) &&
		nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {

		return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
	}

	return elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
		elem.type = elem.type.slice( 5 );
	} else {
		elem.removeAttribute( "type" );
	}

	return elem;
}

function cloneCopyEvent( src, dest ) {
	var i, l, type, pdataOld, udataOld, udataCur, events;

	if ( dest.nodeType !== 1 ) {
		return;
	}

	// 1. Copy private data: events, handlers, etc.
	if ( dataPriv.hasData( src ) ) {
		pdataOld = dataPriv.get( src );
		events = pdataOld.events;

		if ( events ) {
			dataPriv.remove( dest, "handle events" );

			for ( type in events ) {
				for ( i = 0, l = events[ type ].length; i < l; i++ ) {
					jQuery.event.add( dest, type, events[ type ][ i ] );
				}
			}
		}
	}

	// 2. Copy user data
	if ( dataUser.hasData( src ) ) {
		udataOld = dataUser.access( src );
		udataCur = jQuery.extend( {}, udataOld );

		dataUser.set( dest, udataCur );
	}
}

// Fix IE bugs, see support tests
function fixInput( src, dest ) {
	var nodeName = dest.nodeName.toLowerCase();

	// Fails to persist the checked state of a cloned checkbox or radio button.
	if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		dest.checked = src.checked;

	// Fails to return the selected option to the default selected state when cloning options
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = flat( args );

	var fragment, first, scripts, hasScripts, node, doc,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[ 0 ],
		valueIsFunction = isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( valueIsFunction ||
			( l > 1 && typeof value === "string" &&
				!support.checkClone && rchecked.test( value ) ) ) {
		return collection.each( function( index ) {
			var self = collection.eq( index );
			if ( valueIsFunction ) {
				args[ 0 ] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		} );
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (#8070).
			for ( ; i < l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {

						// Support: Android <=4.0 only, PhantomJS 1 only
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[ i ], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Reenable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i < hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &&
						!dataPriv.access( node, "globalEval" ) &&
						jQuery.contains( doc, node ) ) {

						if ( node.src && ( node.type || "" ).toLowerCase()  !== "module" ) {

							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl && !node.noModule ) {
								jQuery._evalUrl( node.src, {
									nonce: node.nonce || node.getAttribute( "nonce" )
								}, doc );
							}
						} else {
							DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc );
						}
					}
				}
			}
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		nodes = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; ( node = nodes[ i ] ) != null; i++ ) {
		if ( !keepData && node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData && isAttached( node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html;
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var i, l, srcElements, destElements,
			clone = elem.cloneNode( true ),
			inPage = isAttached( elem );

		// Fix IE cloning issues
		if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
				!jQuery.isXMLDoc( elem ) ) {

			// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			for ( i = 0, l = srcElements.length; i < l; i++ ) {
				fixInput( srcElements[ i ], destElements[ i ] );
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0, l = srcElements.length; i < l; i++ ) {
					cloneCopyEvent( srcElements[ i ], destElements[ i ] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems ) {
		var data, elem, type,
			special = jQuery.event.special,
			i = 0;

		for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
			if ( acceptData( elem ) ) {
				if ( ( data = elem[ dataPriv.expando ] ) ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataPriv.expando ] = undefined;
				}
				if ( elem[ dataUser.expando ] ) {

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataUser.expando ] = undefined;
				}
			}
		}
	}
} );

jQuery.fn.extend( {
	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().each( function() {
					if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
						this.textContent = value;
					}
				} );
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		} );
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		} );
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		} );
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		} );
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; ( elem = this[ i ] ) != null; i++ ) {
			if ( elem.nodeType === 1 ) {

				// Prevent memory leaks
				jQuery.cleanData( getAll( elem, false ) );

				// Remove any remaining nodes
				elem.textContent = "";
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		} );
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined && elem.nodeType === 1 ) {
				return elem.innerHTML;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for ( ; i < l; i++ ) {
						elem = this[ i ] || {};

						// Remove element nodes and prevent memory leaks
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) < 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
} );

jQuery.each( {
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1,
			i = 0;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone( true );
			jQuery( insert[ i ] )[ original ]( elems );

			// Support: Android <=4.0 only, PhantomJS 1 only
			// .get() because push.apply(_, arraylike) throws on ancient WebKit
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
} );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );

var getStyles = function( elem ) {

		// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if ( !view || !view.opener ) {
			view = window;
		}

		return view.getComputedStyle( elem );
	};

var swap = function( elem, options, callback ) {
	var ret, name,
		old = {};

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.call( elem );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};


var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );



( function() {

	// Executing both pixelPosition & boxSizingReliable tests require only one layout
	// so they're executed at the same time to save the second computation.
	function computeStyleTests() {

		// This is a singleton, we need to execute it only once
		if ( !div ) {
			return;
		}

		container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
			"margin-top:1px;padding:0;border:0";
		div.style.cssText =
			"position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
			"margin:auto;border:1px;padding:1px;" +
			"width:60%;top:1%";
		documentElement.appendChild( container ).appendChild( div );

		var divStyle = window.getComputedStyle( div );
		pixelPositionVal = divStyle.top !== "1%";

		// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
		reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;

		// Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
		// Some styles come back with percentage values, even though they shouldn't
		div.style.right = "60%";
		pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;

		// Support: IE 9 - 11 only
		// Detect misreporting of content dimensions for box-sizing:border-box elements
		boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;

		// Support: IE 9 only
		// Detect overflow:scroll screwiness (gh-3699)
		// Support: Chrome <=64
		// Don't get tricked when zoom affects offsetWidth (gh-4029)
		div.style.position = "absolute";
		scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;

		documentElement.removeChild( container );

		// Nullify the div so it wouldn't be stored in the memory and
		// it will also be a sign that checks already performed
		div = null;
	}

	function roundPixelMeasures( measure ) {
		return Math.round( parseFloat( measure ) );
	}

	var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,
		reliableTrDimensionsVal, reliableMarginLeftVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	// Support: IE <=9 - 11 only
	// Style of cloned element affects source element cloned (#8908)
	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	jQuery.extend( support, {
		boxSizingReliable: function() {
			computeStyleTests();
			return boxSizingReliableVal;
		},
		pixelBoxStyles: function() {
			computeStyleTests();
			return pixelBoxStylesVal;
		},
		pixelPosition: function() {
			computeStyleTests();
			return pixelPositionVal;
		},
		reliableMarginLeft: function() {
			computeStyleTests();
			return reliableMarginLeftVal;
		},
		scrollboxSize: function() {
			computeStyleTests();
			return scrollboxSizeVal;
		},

		// Support: IE 9 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Behavior in IE 9 is more subtle than in newer versions & it passes
		// some versions of this test; make sure not to make it pass there!
		//
		// Support: Firefox 70+
		// Only Firefox includes border widths
		// in computed dimensions. (gh-4529)
		reliableTrDimensions: function() {
			var table, tr, trChild, trStyle;
			if ( reliableTrDimensionsVal == null ) {
				table = document.createElement( "table" );
				tr = document.createElement( "tr" );
				trChild = document.createElement( "div" );

				table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
				tr.style.cssText = "border:1px solid";

				// Support: Chrome 86+
				// Height set through cssText does not get applied.
				// Computed height then comes back as 0.
				tr.style.height = "1px";
				trChild.style.height = "9px";

				// Support: Android 8 Chrome 86+
				// In our bodyBackground.html iframe,
				// display for all div elements is set to "inline",
				// which causes a problem only in Android 8 Chrome 86.
				// Ensuring the div is display: block
				// gets around this issue.
				trChild.style.display = "block";

				documentElement
					.appendChild( table )
					.appendChild( tr )
					.appendChild( trChild );

				trStyle = window.getComputedStyle( tr );
				reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) +
					parseInt( trStyle.borderTopWidth, 10 ) +
					parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight;

				documentElement.removeChild( table );
			}
			return reliableTrDimensionsVal;
		}
	} );
} )();


function curCSS( elem, name, computed ) {
	var width, minWidth, maxWidth, ret,

		// Support: Firefox 51+
		// Retrieving style before computed somehow
		// fixes an issue with getting wrong values
		// on detached elements
		style = elem.style;

	computed = computed || getStyles( elem );

	// getPropertyValue is needed for:
	//   .css('filter') (IE 9 only, #12537)
	//   .css('--customProperty) (#3144)
	if ( computed ) {
		ret = computed.getPropertyValue( name ) || computed[ name ];

		if ( ret === "" && !isAttached( elem ) ) {
			ret = jQuery.style( elem, name );
		}

		// A tribute to the "awesome hack by Dean Edwards"
		// Android Browser returns percentage for some values,
		// but width seems to be reliably pixels.
		// This is against the CSSOM draft spec:
		// https://drafts.csswg.org/cssom/#resolved-values
		if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) {

			// Remember the original values
			width = style.width;
			minWidth = style.minWidth;
			maxWidth = style.maxWidth;

			// Put in the new values to get a computed value out
			style.minWidth = style.maxWidth = style.width = ret;
			ret = computed.width;

			// Revert the changed values
			style.width = width;
			style.minWidth = minWidth;
			style.maxWidth = maxWidth;
		}
	}

	return ret !== undefined ?

		// Support: IE <=9 - 11 only
		// IE returns zIndex value as an integer.
		ret + "" :
		ret;
}


function addGetHookIf( conditionFn, hookFn ) {

	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			if ( conditionFn() ) {

				// Hook not needed (or it's not possible to use it due
				// to missing dependency), remove it.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.
			return ( this.get = hookFn ).apply( this, arguments );
		}
	};
}


var cssPrefixes = [ "Webkit", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style,
	vendorProps = {};

// Return a vendor-prefixed property or undefined
function vendorPropName( name ) {

	// Check for vendor prefixed names
	var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in emptyStyle ) {
			return name;
		}
	}
}

// Return a potentially-mapped jQuery.cssProps or vendor prefixed property
function finalPropName( name ) {
	var final = jQuery.cssProps[ name ] || vendorProps[ name ];

	if ( final ) {
		return final;
	}
	if ( name in emptyStyle ) {
		return name;
	}
	return vendorProps[ name ] = vendorPropName( name ) || name;
}


var

	// Swappable if display is none or starts with table
	// except "table", "table-cell", or "table-caption"
	// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	rcustomProp = /^--/,
	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	};

function setPositiveNumber( _elem, value, subtract ) {

	// Any relative (+/-) values have already been
	// normalized at this point
	var matches = rcssNum.exec( value );
	return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
		value;
}

function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) {
	var i = dimension === "width" ? 1 : 0,
		extra = 0,
		delta = 0;

	// Adjustment may not be necessary
	if ( box === ( isBorderBox ? "border" : "content" ) ) {
		return 0;
	}

	for ( ; i < 4; i += 2 ) {

		// Both box models exclude margin
		if ( box === "margin" ) {
			delta += jQuery.css( elem, box + cssExpand[ i ], true, styles );
		}

		// If we get here with a content-box, we're seeking "padding" or "border" or "margin"
		if ( !isBorderBox ) {

			// Add padding
			delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// For "border" or "margin", add border
			if ( box !== "padding" ) {
				delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );

			// But still keep track of it otherwise
			} else {
				extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}

		// If we get here with a border-box (content + padding + border), we're seeking "content" or
		// "padding" or "margin"
		} else {

			// For "content", subtract padding
			if ( box === "content" ) {
				delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// For "content" or "padding", subtract border
			if ( box !== "margin" ) {
				delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	// Account for positive content-box scroll gutter when requested by providing computedVal
	if ( !isBorderBox && computedVal >= 0 ) {

		// offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
		// Assuming integer scroll gutter, subtract the rest and round down
		delta += Math.max( 0, Math.ceil(
			elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
			computedVal -
			delta -
			extra -
			0.5

		// If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter
		// Use an explicit zero to avoid NaN (gh-3964)
		) ) || 0;
	}

	return delta;
}

function getWidthOrHeight( elem, dimension, extra ) {

	// Start with computed style
	var styles = getStyles( elem ),

		// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).
		// Fake content-box until we know it's needed to know the true value.
		boxSizingNeeded = !support.boxSizingReliable() || extra,
		isBorderBox = boxSizingNeeded &&
			jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
		valueIsBorderBox = isBorderBox,

		val = curCSS( elem, dimension, styles ),
		offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 );

	// Support: Firefox <=54
	// Return a confounding non-pixel value or feign ignorance, as appropriate.
	if ( rnumnonpx.test( val ) ) {
		if ( !extra ) {
			return val;
		}
		val = "auto";
	}


	// Support: IE 9 - 11 only
	// Use offsetWidth/offsetHeight for when box sizing is unreliable.
	// In those cases, the computed value can be trusted to be border-box.
	if ( ( !support.boxSizingReliable() && isBorderBox ||

		// Support: IE 10 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Interestingly, in some cases IE 9 doesn't suffer from this issue.
		!support.reliableTrDimensions() && nodeName( elem, "tr" ) ||

		// Fall back to offsetWidth/offsetHeight when value is "auto"
		// This happens for inline elements with no explicit setting (gh-3571)
		val === "auto" ||

		// Support: Android <=4.1 - 4.3 only
		// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
		!parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) &&

		// Make sure the element is visible & connected
		elem.getClientRects().length ) {

		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

		// Where available, offsetWidth/offsetHeight approximate border box dimensions.
		// Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
		// retrieved value as a content box dimension.
		valueIsBorderBox = offsetProp in elem;
		if ( valueIsBorderBox ) {
			val = elem[ offsetProp ];
		}
	}

	// Normalize "" and auto
	val = parseFloat( val ) || 0;

	// Adjust for the element's box model
	return ( val +
		boxModelAdjustment(
			elem,
			dimension,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles,

			// Provide the current computed size to request scroll gutter calculation (gh-3589)
			val
		)
	) + "px";
}

jQuery.extend( {

	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {

					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Don't automatically add "px" to these possibly-unitless properties
	cssNumber: {
		"animationIterationCount": true,
		"columnCount": true,
		"fillOpacity": true,
		"flexGrow": true,
		"flexShrink": true,
		"fontWeight": true,
		"gridArea": true,
		"gridColumn": true,
		"gridColumnEnd": true,
		"gridColumnStart": true,
		"gridRow": true,
		"gridRowEnd": true,
		"gridRowStart": true,
		"lineHeight": true,
		"opacity": true,
		"order": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {

		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name ),
			style = elem.style;

		// Make sure that we're working with the right name. We don't
		// want to query the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Gets hook for the prefixed version, then unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Convert "+=" or "-=" to relative numbers (#7345)
			if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
				value = adjustCSS( elem, name, ret );

				// Fixes bug #9237
				type = "number";
			}

			// Make sure that null and NaN values aren't set (#7116)
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add the unit (except for certain CSS properties)
			// The isCustomProp check can be removed in jQuery 4.0 when we only auto-append
			// "px" to a few hardcoded values.
			if ( type === "number" && !isCustomProp ) {
				value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
			}

			// background-* props affect original clone's values
			if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !( "set" in hooks ) ||
				( value = hooks.set( elem, value, extra ) ) !== undefined ) {

				if ( isCustomProp ) {
					style.setProperty( name, value );
				} else {
					style[ name ] = value;
				}
			}

		} else {

			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks &&
				( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var val, num, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name );

		// Make sure that we're working with the right name. We don't
		// want to modify the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Try prefixed name followed by the unprefixed name
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		// Convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Make numeric if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || isFinite( num ) ? num || 0 : val;
		}

		return val;
	}
} );

jQuery.each( [ "height", "width" ], function( _i, dimension ) {
	jQuery.cssHooks[ dimension ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// Certain elements can have dimension info if we invisibly show them
				// but it must have a current display style that would benefit
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&

					// Support: Safari 8+
					// Table columns in Safari have non-zero offsetWidth & zero
					// getBoundingClientRect().width unless display is changed.
					// Support: IE <=11 only
					// Running getBoundingClientRect on a disconnected node
					// in IE throws an error.
					( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
					swap( elem, cssShow, function() {
						return getWidthOrHeight( elem, dimension, extra );
					} ) :
					getWidthOrHeight( elem, dimension, extra );
			}
		},

		set: function( elem, value, extra ) {
			var matches,
				styles = getStyles( elem ),

				// Only read styles.position if the test has a chance to fail
				// to avoid forcing a reflow.
				scrollboxSizeBuggy = !support.scrollboxSize() &&
					styles.position === "absolute",

				// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
				boxSizingNeeded = scrollboxSizeBuggy || extra,
				isBorderBox = boxSizingNeeded &&
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
				subtract = extra ?
					boxModelAdjustment(
						elem,
						dimension,
						extra,
						isBorderBox,
						styles
					) :
					0;

			// Account for unreliable border-box dimensions by comparing offset* to computed and
			// faking a content-box to get border and padding (gh-3699)
			if ( isBorderBox && scrollboxSizeBuggy ) {
				subtract -= Math.ceil(
					elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
					parseFloat( styles[ dimension ] ) -
					boxModelAdjustment( elem, dimension, "border", false, styles ) -
					0.5
				);
			}

			// Convert to pixels if value adjustment is needed
			if ( subtract && ( matches = rcssNum.exec( value ) ) &&
				( matches[ 3 ] || "px" ) !== "px" ) {

				elem.style[ dimension ] = value;
				value = jQuery.css( elem, dimension );
			}

			return setPositiveNumber( elem, value, subtract );
		}
	};
} );

jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
	function( elem, computed ) {
		if ( computed ) {
			return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
				elem.getBoundingClientRect().left -
					swap( elem, { marginLeft: 0 }, function() {
						return elem.getBoundingClientRect().left;
					} )
			) + "px";
		}
	}
);

// These hooks are used by animate to expand properties
jQuery.each( {
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// Assumes a single number if not a string
				parts = typeof value === "string" ? value.split( " " ) : [ value ];

			for ( ; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( prefix !== "margin" ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
} );

jQuery.fn.extend( {
	css: function( name, value ) {
		return access( this, function( elem, name, value ) {
			var styles, len,
				map = {},
				i = 0;

			if ( Array.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i < len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	}
} );


function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || jQuery.easing._default;
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			// Use a property on the element directly when it is not a DOM element,
			// or when there is no matching style property that exists.
			if ( tween.elem.nodeType !== 1 ||
				tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
				return tween.elem[ tween.prop ];
			}

			// Passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails.
			// Simple values such as "10px" are parsed to Float;
			// complex values such as "rotate(1rad)" are returned as-is.
			result = jQuery.css( tween.elem, tween.prop, "" );

			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {

			// Use step hook for back compat.
			// Use cssHook if its there.
			// Use .style if available and use plain properties where available.
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.nodeType === 1 && (
				jQuery.cssHooks[ tween.prop ] ||
					tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p * Math.PI ) / 2;
	},
	_default: "swing"
};

jQuery.fx = Tween.prototype.init;

// Back compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, inProgress,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rrun = /queueHooks$/;

function schedule() {
	if ( inProgress ) {
		if ( document.hidden === false && window.requestAnimationFrame ) {
			window.requestAnimationFrame( schedule );
		} else {
			window.setTimeout( schedule, jQuery.fx.interval );
		}

		jQuery.fx.tick();
	}
}

// Animations created synchronously will run synchronously
function createFxNow() {
	window.setTimeout( function() {
		fxNow = undefined;
	} );
	return ( fxNow = Date.now() );
}

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		i = 0,
		attrs = { height: type };

	// If we include width, step value is 1 to do all cssExpand values,
	// otherwise step value is 2 to skip over Left and Right
	includeWidth = includeWidth ? 1 : 0;
	for ( ; i < 4; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

function createTween( value, prop, animation ) {
	var tween,
		collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
		index = 0,
		length = collection.length;
	for ( ; index < length; index++ ) {
		if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {

			// We're done with this property
			return tween;
		}
	}
}

function defaultPrefilter( elem, props, opts ) {
	var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
		isBox = "width" in props || "height" in props,
		anim = this,
		orig = {},
		style = elem.style,
		hidden = elem.nodeType && isHiddenWithinTree( elem ),
		dataShow = dataPriv.get( elem, "fxshow" );

	// Queue-skipping animations hijack the fx hooks
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always( function() {

			// Ensure the complete handler is called before this completes
			anim.always( function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			} );
		} );
	}

	// Detect show/hide animations
	for ( prop in props ) {
		value = props[ prop ];
		if ( rfxtypes.test( value ) ) {
			delete props[ prop ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {

				// Pretend to be hidden if this is a "show" and
				// there is still data from a stopped show/hide
				if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
					hidden = true;

				// Ignore all other no-op show/hide data
				} else {
					continue;
				}
			}
			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
		}
	}

	// Bail out if this is a no-op like .hide().hide()
	propTween = !jQuery.isEmptyObject( props );
	if ( !propTween && jQuery.isEmptyObject( orig ) ) {
		return;
	}

	// Restrict "overflow" and "display" styles during box animations
	if ( isBox && elem.nodeType === 1 ) {

		// Support: IE <=9 - 11, Edge 12 - 15
		// Record all 3 overflow attributes because IE does not infer the shorthand
		// from identically-valued overflowX and overflowY and Edge just mirrors
		// the overflowX value there.
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Identify a display type, preferring old show/hide data over the CSS cascade
		restoreDisplay = dataShow && dataShow.display;
		if ( restoreDisplay == null ) {
			restoreDisplay = dataPriv.get( elem, "display" );
		}
		display = jQuery.css( elem, "display" );
		if ( display === "none" ) {
			if ( restoreDisplay ) {
				display = restoreDisplay;
			} else {

				// Get nonempty value(s) by temporarily forcing visibility
				showHide( [ elem ], true );
				restoreDisplay = elem.style.display || restoreDisplay;
				display = jQuery.css( elem, "display" );
				showHide( [ elem ] );
			}
		}

		// Animate inline elements as inline-block
		if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
			if ( jQuery.css( elem, "float" ) === "none" ) {

				// Restore the original display value at the end of pure show/hide animations
				if ( !propTween ) {
					anim.done( function() {
						style.display = restoreDisplay;
					} );
					if ( restoreDisplay == null ) {
						display = style.display;
						restoreDisplay = display === "none" ? "" : display;
					}
				}
				style.display = "inline-block";
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		anim.always( function() {
			style.overflow = opts.overflow[ 0 ];
			style.overflowX = opts.overflow[ 1 ];
			style.overflowY = opts.overflow[ 2 ];
		} );
	}

	// Implement show/hide animations
	propTween = false;
	for ( prop in orig ) {

		// General show/hide setup for this element animation
		if ( !propTween ) {
			if ( dataShow ) {
				if ( "hidden" in dataShow ) {
					hidden = dataShow.hidden;
				}
			} else {
				dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
			}

			// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
			if ( toggle ) {
				dataShow.hidden = !hidden;
			}

			// Show elements before animating them
			if ( hidden ) {
				showHide( [ elem ], true );
			}

			/* eslint-disable no-loop-func */

			anim.done( function() {

				/* eslint-enable no-loop-func */

				// The final step of a "hide" animation is actually hiding the element
				if ( !hidden ) {
					showHide( [ elem ] );
				}
				dataPriv.remove( elem, "fxshow" );
				for ( prop in orig ) {
					jQuery.style( elem, prop, orig[ prop ] );
				}
			} );
		}

		// Per-property setup
		propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
		if ( !( prop in dataShow ) ) {
			dataShow[ prop ] = propTween.start;
			if ( hidden ) {
				propTween.end = propTween.start;
				propTween.start = 0;
			}
		}
	}
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( Array.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// Not quite $.extend, this won't overwrite existing keys.
			// Reusing 'index' because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = Animation.prefilters.length,
		deferred = jQuery.Deferred().always( function() {

			// Don't match elem in the :animated selector
			delete tick.elem;
		} ),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),

				// Support: Android 2.3 only
				// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ] );

			// If there's more to do, yield
			if ( percent < 1 && length ) {
				return remaining;
			}

			// If this was an empty animation, synthesize a final progress notification
			if ( !length ) {
				deferred.notifyWith( elem, [ animation, 1, 0 ] );
			}

			// Resolve the animation and report its conclusion
			deferred.resolveWith( elem, [ animation ] );
			return false;
		},
		animation = deferred.promise( {
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
					animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,

					// If we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index < length; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// Resolve when we played the last frame; otherwise, reject
				if ( gotoEnd ) {
					deferred.notifyWith( elem, [ animation, 1, 0 ] );
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		} ),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length; index++ ) {
		result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			if ( isFunction( result.stop ) ) {
				jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
					result.stop.bind( result );
			}
			return result;
		}
	}

	jQuery.map( props, createTween, animation );

	if ( isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	// Attach callbacks from options
	animation
		.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		} )
	);

	return animation;
}

jQuery.Animation = jQuery.extend( Animation, {

	tweeners: {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value );
			adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
			return tween;
		} ]
	},

	tweener: function( props, callback ) {
		if ( isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.match( rnothtmlwhite );
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length; index++ ) {
			prop = props[ index ];
			Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
			Animation.tweeners[ prop ].unshift( callback );
		}
	},

	prefilters: [ defaultPrefilter ],

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			Animation.prefilters.unshift( callback );
		} else {
			Animation.prefilters.push( callback );
		}
	}
} );

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !isFunction( easing ) && easing
	};

	// Go to the end state if fx are off
	if ( jQuery.fx.off ) {
		opt.duration = 0;

	} else {
		if ( typeof opt.duration !== "number" ) {
			if ( opt.duration in jQuery.fx.speeds ) {
				opt.duration = jQuery.fx.speeds[ opt.duration ];

			} else {
				opt.duration = jQuery.fx.speeds._default;
			}
		}
	}

	// Normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.fn.extend( {
	fadeTo: function( speed, to, easing, callback ) {

		// Show any hidden elements after setting opacity to 0
		return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()

			// Animate to the value specified
			.end().animate( { opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations, or finishing resolves immediately
				if ( empty || dataPriv.get( this, "finish" ) ) {
					anim.stop( true );
				}
			};

		doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue ) {
			this.queue( type || "fx", [] );
		}

		return this.each( function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = dataPriv.get( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &&
					( type == null || timers[ index ].queue === type ) ) {

					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// Start the next in the queue if the last step wasn't forced.
			// Timers currently will call their complete callbacks, which
			// will dequeue but only if they were gotoEnd.
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		} );
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each( function() {
			var index,
				data = dataPriv.get( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// Enable finishing flag on private data
			data.finish = true;

			// Empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks && hooks.stop ) {
				hooks.stop.call( this, true );
			}

			// Look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// Look for any animations in the old queue and finish them
			for ( index = 0; index < length; index++ ) {
				if ( queue[ index ] && queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// Turn off finishing flag
			delete data.finish;
		} );
	}
} );

jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
} );

// Generate shortcuts for custom animations
jQuery.each( {
	slideDown: genFx( "show" ),
	slideUp: genFx( "hide" ),
	slideToggle: genFx( "toggle" ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
} );

jQuery.timers = [];
jQuery.fx.tick = function() {
	var timer,
		i = 0,
		timers = jQuery.timers;

	fxNow = Date.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];

		// Run the timer and safely remove it when done (allowing for external removal)
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	jQuery.timers.push( timer );
	jQuery.fx.start();
};

jQuery.fx.interval = 13;
jQuery.fx.start = function() {
	if ( inProgress ) {
		return;
	}

	inProgress = true;
	schedule();
};

jQuery.fx.stop = function() {
	inProgress = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,

	// Default speed
	_default: 400
};


// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
	type = type || "fx";

	return this.queue( type, function( next, hooks ) {
		var timeout = window.setTimeout( next, time );
		hooks.stop = function() {
			window.clearTimeout( timeout );
		};
	} );
};


( function() {
	var input = document.createElement( "input" ),
		select = document.createElement( "select" ),
		opt = select.appendChild( document.createElement( "option" ) );

	input.type = "checkbox";

	// Support: Android <=4.3 only
	// Default value for a checkbox should be "on"
	support.checkOn = input.value !== "";

	// Support: IE <=11 only
	// Must access selectedIndex to make default options select
	support.optSelected = opt.selected;

	// Support: IE <=11 only
	// An input loses its value after becoming a radio
	input = document.createElement( "input" );
	input.value = "t";
	input.type = "radio";
	support.radioValue = input.value === "t";
} )();


var boolHook,
	attrHandle = jQuery.expr.attrHandle;

jQuery.fn.extend( {
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each( function() {
			jQuery.removeAttr( this, name );
		} );
	}
} );

jQuery.extend( {
	attr: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set attributes on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		// Attribute hooks are determined by the lowercase version
		// Grab necessary hook if one is defined
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
		}

		if ( value !== undefined ) {
			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;
			}

			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			elem.setAttribute( name, value + "" );
			return value;
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		ret = jQuery.find.attr( elem, name );

		// Non-existent attributes return null, we normalize to undefined
		return ret == null ? undefined : ret;
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue && value === "radio" &&
					nodeName( elem, "input" ) ) {
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	removeAttr: function( elem, value ) {
		var name,
			i = 0,

			// Attribute names can contain non-HTML whitespace characters
			// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
			attrNames = value && value.match( rnothtmlwhite );

		if ( attrNames && elem.nodeType === 1 ) {
			while ( ( name = attrNames[ i++ ] ) ) {
				elem.removeAttribute( name );
			}
		}
	}
} );

// Hooks for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {

			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			elem.setAttribute( name, name );
		}
		return name;
	}
};

jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) {
	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = function( elem, name, isXML ) {
		var ret, handle,
			lowercaseName = name.toLowerCase();

		if ( !isXML ) {

			// Avoid an infinite loop by temporarily removing this function from the getter
			handle = attrHandle[ lowercaseName ];
			attrHandle[ lowercaseName ] = ret;
			ret = getter( elem, name, isXML ) != null ?
				lowercaseName :
				null;
			attrHandle[ lowercaseName ] = handle;
		}
		return ret;
	};
} );




var rfocusable = /^(?:input|select|textarea|button)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend( {
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		return this.each( function() {
			delete this[ jQuery.propFix[ name ] || name ];
		} );
	}
} );

jQuery.extend( {
	prop: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {

			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			return ( elem[ name ] = value );
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		return elem[ name ];
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {

				// Support: IE <=9 - 11 only
				// elem.tabIndex doesn't always return the
				// correct value when it hasn't been explicitly set
				// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				// Use proper attribute retrieval(#12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				if ( tabindex ) {
					return parseInt( tabindex, 10 );
				}

				if (
					rfocusable.test( elem.nodeName ) ||
					rclickable.test( elem.nodeName ) &&
					elem.href
				) {
					return 0;
				}

				return -1;
			}
		}
	},

	propFix: {
		"for": "htmlFor",
		"class": "className"
	}
} );

// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent && parent.parentNode ) {
				parent.parentNode.selectedIndex;
			}
			return null;
		},
		set: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent ) {
				parent.selectedIndex;

				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	};
}

jQuery.each( [
	"tabIndex",
	"readOnly",
	"maxLength",
	"cellSpacing",
	"cellPadding",
	"rowSpan",
	"colSpan",
	"useMap",
	"frameBorder",
	"contentEditable"
], function() {
	jQuery.propFix[ this.toLowerCase() ] = this;
} );




	// Strip and collapse whitespace according to HTML spec
	// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
	function stripAndCollapse( value ) {
		var tokens = value.match( rnothtmlwhite ) || [];
		return tokens.join( " " );
	}


function getClass( elem ) {
	return elem.getAttribute && elem.getAttribute( "class" ) || "";
}

function classesToArray( value ) {
	if ( Array.isArray( value ) ) {
		return value;
	}
	if ( typeof value === "string" ) {
		return value.match( rnothtmlwhite ) || [];
	}
	return [];
}

jQuery.fn.extend( {
	addClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		classes = classesToArray( value );

		if ( classes.length ) {
			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );
				cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {
						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
							cur += clazz + " ";
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( !arguments.length ) {
			return this.attr( "class", "" );
		}

		classes = classesToArray( value );

		if ( classes.length ) {
			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );

				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {

						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value,
			isValidValue = type === "string" || Array.isArray( value );

		if ( typeof stateVal === "boolean" && isValidValue ) {
			return stateVal ? this.addClass( value ) : this.removeClass( value );
		}

		if ( isFunction( value ) ) {
			return this.each( function( i ) {
				jQuery( this ).toggleClass(
					value.call( this, i, getClass( this ), stateVal ),
					stateVal
				);
			} );
		}

		return this.each( function() {
			var className, i, self, classNames;

			if ( isValidValue ) {

				// Toggle individual class names
				i = 0;
				self = jQuery( this );
				classNames = classesToArray( value );

				while ( ( className = classNames[ i++ ] ) ) {

					// Check each className given, space separated list
					if ( self.hasClass( className ) ) {
						self.removeClass( className );
					} else {
						self.addClass( className );
					}
				}

			// Toggle whole class name
			} else if ( value === undefined || type === "boolean" ) {
				className = getClass( this );
				if ( className ) {

					// Store className if set
					dataPriv.set( this, "__className__", className );
				}

				// If the element has a class name or if we're passed `false`,
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				if ( this.setAttribute ) {
					this.setAttribute( "class",
						className || value === false ?
							"" :
							dataPriv.get( this, "__className__" ) || ""
					);
				}
			}
		} );
	},

	hasClass: function( selector ) {
		var className, elem,
			i = 0;

		className = " " + selector + " ";
		while ( ( elem = this[ i++ ] ) ) {
			if ( elem.nodeType === 1 &&
				( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
				return true;
			}
		}

		return false;
	}
} );




var rreturn = /\r/g;

jQuery.fn.extend( {
	val: function( value ) {
		var hooks, ret, valueIsFunction,
			elem = this[ 0 ];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] ||
					jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks &&
					"get" in hooks &&
					( ret = hooks.get( elem, "value" ) ) !== undefined
				) {
					return ret;
				}

				ret = elem.value;

				// Handle most common string cases
				if ( typeof ret === "string" ) {
					return ret.replace( rreturn, "" );
				}

				// Handle cases where value is null/undef or number
				return ret == null ? "" : ret;
			}

			return;
		}

		valueIsFunction = isFunction( value );

		return this.each( function( i ) {
			var val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( valueIsFunction ) {
				val = value.call( this, i, jQuery( this ).val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";

			} else if ( typeof val === "number" ) {
				val += "";

			} else if ( Array.isArray( val ) ) {
				val = jQuery.map( val, function( value ) {
					return value == null ? "" : value + "";
				} );
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		} );
	}
} );

jQuery.extend( {
	valHooks: {
		option: {
			get: function( elem ) {

				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :

					// Support: IE <=10 - 11 only
					// option.text throws exceptions (#14686, #14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					stripAndCollapse( jQuery.text( elem ) );
			}
		},
		select: {
			get: function( elem ) {
				var value, option, i,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one",
					values = one ? null : [],
					max = one ? index + 1 : options.length;

				if ( index < 0 ) {
					i = max;

				} else {
					i = one ? index : 0;
				}

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// Support: IE <=9 only
					// IE8-9 doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&

							// Don't return options that are disabled or in a disabled optgroup
							!option.disabled &&
							( !option.parentNode.disabled ||
								!nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					/* eslint-disable no-cond-assign */

					if ( option.selected =
						jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
					) {
						optionSet = true;
					}

					/* eslint-enable no-cond-assign */
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	}
} );

// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = {
		set: function( elem, value ) {
			if ( Array.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute( "value" ) === null ? "on" : elem.value;
		};
	}
} );




// Return jQuery for attributes-only inclusion


support.focusin = "onfocusin" in window;


var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	stopPropagationCallback = function( e ) {
		e.stopPropagation();
	};

jQuery.extend( jQuery.event, {

	trigger: function( event, data, elem, onlyHandlers ) {

		var i, cur, tmp, bubbleType, ontype, handle, special, lastElement,
			eventPath = [ elem || document ],
			type = hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];

		cur = lastElement = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "." ) > -1 ) {

			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split( "." );
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf( ":" ) < 0 && "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" && event );

		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
		event.isTrigger = onlyHandlers ? 2 : 3;
		event.namespace = namespaces.join( "." );
		event.rnamespace = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === ( elem.ownerDocument || document ) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
			lastElement = cur;
			event.type = i > 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] &&
				dataPriv.get( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && handle.apply && acceptData( cur ) ) {
				event.result = handle.apply( cur, data );
				if ( event.result === false ) {
					event.preventDefault();
				}
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( ( !special._default ||
				special._default.apply( eventPath.pop(), data ) === false ) &&
				acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name as the event.
				// Don't do default actions on window, that's where global variables be (#6170)
				if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;

					if ( event.isPropagationStopped() ) {
						lastElement.addEventListener( type, stopPropagationCallback );
					}

					elem[ type ]();

					if ( event.isPropagationStopped() ) {
						lastElement.removeEventListener( type, stopPropagationCallback );
					}

					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	// Piggyback on a donor event to simulate a different one
	// Used only for `focus(in | out)` events
	simulate: function( type, elem, event ) {
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true
			}
		);

		jQuery.event.trigger( e, null, elem );
	}

} );

jQuery.fn.extend( {

	trigger: function( type, data ) {
		return this.each( function() {
			jQuery.event.trigger( type, data, this );
		} );
	},
	triggerHandler: function( type, data ) {
		var elem = this[ 0 ];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
} );


// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
	jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler on the document while someone wants focusin/focusout
		var handler = function( event ) {
			jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
		};

		jQuery.event.special[ fix ] = {
			setup: function() {

				// Handle: regular nodes (via `this.ownerDocument`), window
				// (via `this.document`) & document (via `this`).
				var doc = this.ownerDocument || this.document || this,
					attaches = dataPriv.access( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this.document || this,
					attaches = dataPriv.access( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					dataPriv.remove( doc, fix );

				} else {
					dataPriv.access( doc, fix, attaches );
				}
			}
		};
	} );
}
var location = window.location;

var nonce = { guid: Date.now() };

var rquery = ( /\?/ );



// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml, parserErrorElem;
	if ( !data || typeof data !== "string" ) {
		return null;
	}

	// Support: IE 9 - 11 only
	// IE throws on parseFromString with invalid input.
	try {
		xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
	} catch ( e ) {}

	parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ];
	if ( !xml || parserErrorElem ) {
		jQuery.error( "Invalid XML: " + (
			parserErrorElem ?
				jQuery.map( parserErrorElem.childNodes, function( el ) {
					return el.textContent;
				} ).join( "\n" ) :
				data
		) );
	}
	return xml;
};


var
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( Array.isArray( obj ) ) {

		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {

				// Treat each array item as a scalar.
				add( prefix, v );

			} else {

				// Item is non-scalar (array or object), encode its numeric index.
				buildParams(
					prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
					v,
					traditional,
					add
				);
			}
		} );

	} else if ( !traditional && toType( obj ) === "object" ) {

		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {

		// Serialize scalar item.
		add( prefix, obj );
	}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, valueOrFunction ) {

			// If value is a function, invoke it and use its return value
			var value = isFunction( valueOrFunction ) ?
				valueOrFunction() :
				valueOrFunction;

			s[ s.length ] = encodeURIComponent( key ) + "=" +
				encodeURIComponent( value == null ? "" : value );
		};

	if ( a == null ) {
		return "";
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {

		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		} );

	} else {

		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" );
};

jQuery.fn.extend( {
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} ).filter( function() {
			var type = this.type;

			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} ).map( function( _i, elem ) {
			var val = jQuery( this ).val();

			if ( val == null ) {
				return null;
			}

			if ( Array.isArray( val ) ) {
				return jQuery.map( val, function( val ) {
					return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
				} );
			}

			return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
} );


var
	r20 = /%20/g,
	rhash = /#.*$/,
	rantiCache = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,

	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = "*/".concat( "*" ),

	// Anchor tag for parsing the document origin
	originAnchor = document.createElement( "a" );

originAnchor.href = location.href;

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];

		if ( isFunction( func ) ) {

			// For each dataType in the dataTypeExpression
			while ( ( dataType = dataTypes[ i++ ] ) ) {

				// Prepend if requested
				if ( dataType[ 0 ] === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );

				// Otherwise append
				} else {
					( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if ( typeof dataTypeOrTransport === "string" &&
				!seekingTransport && !inspected[ dataTypeOrTransport ] ) {

				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		} );
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

/* Handles responses to an ajax request:
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var ct, type, finalDataType, firstDataType,
		contents = s.contents,
		dataTypes = s.dataTypes;

	// Remove auto dataType and get content-type in the process
	while ( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {

		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}

		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

/* Chain conversions given the request and the original response
 * Also sets the responseXXX fields on the jqXHR instance
 */
function ajaxConvert( s, response, jqXHR, isSuccess ) {
	var conv2, current, conv, tmp, prev,
		converters = {},

		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	current = dataTypes.shift();

	// Convert to each sequential dataType
	while ( current ) {

		if ( s.responseFields[ current ] ) {
			jqXHR[ s.responseFields[ current ] ] = response;
		}

		// Apply the dataFilter if provided
		if ( !prev && isSuccess && s.dataFilter ) {
			response = s.dataFilter( response, s.dataType );
		}

		prev = current;
		current = dataTypes.shift();

		if ( current ) {

			// There's only work to do if current dataType is non-auto
			if ( current === "*" ) {

				current = prev;

			// Convert response if prev dataType is non-auto and differs from current
			} else if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split( " " );
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {

								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.unshift( tmp[ 1 ] );
								}
								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s.throws ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return {
								state: "parsererror",
								error: conv ? e : "No conversion from " + prev + " to " + current
							};
						}
					}
				}
			}
		}
	}

	return { state: "success", data: response };
}

jQuery.extend( {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: location.href,
		type: "GET",
		isLocal: rlocalProtocol.test( location.protocol ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",

		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /\bxml\b/,
			html: /\bhtml/,
			json: /\bjson\b/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText",
			json: "responseJSON"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": JSON.parse,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var transport,

			// URL without anti-cache param
			cacheURL,

			// Response headers
			responseHeadersString,
			responseHeaders,

			// timeout handle
			timeoutTimer,

			// Url cleanup var
			urlAnchor,

			// Request state (becomes false upon send and true upon completion)
			completed,

			// To know if global events are to be dispatched
			fireGlobals,

			// Loop variable
			i,

			// uncached part of the url
			uncached,

			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),

			// Callbacks context
			callbackContext = s.context || s,

			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context &&
				( callbackContext.nodeType || callbackContext.jquery ) ?
				jQuery( callbackContext ) :
				jQuery.event,

			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),

			// Status-dependent callbacks
			statusCode = s.statusCode || {},

			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},

			// Default abort message
			strAbort = "canceled",

			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( completed ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[ 1 ].toLowerCase() + " " ] =
									( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] )
										.concat( match[ 2 ] );
							}
						}
						match = responseHeaders[ key.toLowerCase() + " " ];
					}
					return match == null ? null : match.join( ", " );
				},

				// Raw string
				getAllResponseHeaders: function() {
					return completed ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( completed == null ) {
						name = requestHeadersNames[ name.toLowerCase() ] =
							requestHeadersNames[ name.toLowerCase() ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( completed == null ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( completed ) {

							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						} else {

							// Lazy-add the new callbacks in a way that preserves old ones
							for ( code in map ) {
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR );

		// Add protocol if not provided (prefilters might expect it)
		// Handle falsy url in the settings object (#10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || location.href ) + "" )
			.replace( rprotocol, location.protocol + "//" );

		// Alias method option to type as per ticket #12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];

		// A cross-domain request is in order when the origin doesn't match the current origin.
		if ( s.crossDomain == null ) {
			urlAnchor = document.createElement( "a" );

			// Support: IE <=8 - 11, Edge 12 - 15
			// IE throws exception on accessing the href property if url is malformed,
			// e.g. http://example.com:80x/
			try {
				urlAnchor.href = s.url;

				// Support: IE <=8 - 11 only
				// Anchor's host property isn't correctly set when s.url is relative
				urlAnchor.href = urlAnchor.href;
				s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
					urlAnchor.protocol + "//" + urlAnchor.host;
			} catch ( e ) {

				// If there is an error parsing the URL, assume it is crossDomain,
				// it can be rejected by the transport if it is invalid
				s.crossDomain = true;
			}
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( completed ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
		fireGlobals = jQuery.event && s.global;

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		// Remove hash to simplify url manipulation
		cacheURL = s.url.replace( rhash, "" );

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// Remember the hash so we can put it back
			uncached = s.url.slice( cacheURL.length );

			// If data is available and should be processed, append data to url
			if ( s.data && ( s.processData || typeof s.data === "string" ) ) {
				cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;

				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add or update anti-cache param if needed
			if ( s.cache === false ) {
				cacheURL = cacheURL.replace( rantiCache, "$1" );
				uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) +
					uncached;
			}

			// Put hash and anti-cache on the URL that will be requested (gh-1732)
			s.url = cacheURL + uncached;

		// Change '%20' to '+' if this is encoded form body content (gh-2658)
		} else if ( s.data && s.processData &&
			( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
			s.data = s.data.replace( r20, "+" );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
				s.accepts[ s.dataTypes[ 0 ] ] +
					( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend &&
			( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {

			// Abort if not done already and return
			return jqXHR.abort();
		}

		// Aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		completeDeferred.add( s.complete );
		jqXHR.done( s.success );
		jqXHR.fail( s.error );

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}

			// If request was aborted inside ajaxSend, stop there
			if ( completed ) {
				return jqXHR;
			}

			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = window.setTimeout( function() {
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				completed = false;
				transport.send( requestHeaders, done );
			} catch ( e ) {

				// Rethrow post-completion exceptions
				if ( completed ) {
					throw e;
				}

				// Propagate others as results
				done( -1, e );
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Ignore repeat invocations
			if ( completed ) {
				return;
			}

			completed = true;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				window.clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Determine if successful
			isSuccess = status >= 200 && status < 300 || status === 304;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// Use a noop converter for missing script but not if jsonp
			if ( !isSuccess &&
				jQuery.inArray( "script", s.dataTypes ) > -1 &&
				jQuery.inArray( "json", s.dataTypes ) < 0 ) {
				s.converters[ "text script" ] = function() {};
			}

			// Convert no matter what (that way responseXXX fields are always set)
			response = ajaxConvert( s, response, jqXHR, isSuccess );

			// If successful, handle type chaining
			if ( isSuccess ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader( "Last-Modified" );
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader( "etag" );
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 || s.type === "HEAD" ) {
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					statusText = response.state;
					success = response.data;
					error = response.error;
					isSuccess = !error;
				}
			} else {

				// Extract error from statusText and normalize for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );

				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		return jqXHR;
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	}
} );

jQuery.each( [ "get", "post" ], function( _i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );

jQuery.ajaxPrefilter( function( s ) {
	var i;
	for ( i in s.headers ) {
		if ( i.toLowerCase() === "content-type" ) {
			s.contentType = s.headers[ i ] || "";
		}
	}
} );


jQuery._evalUrl = function( url, options, doc ) {
	return jQuery.ajax( {
		url: url,

		// Make this explicit, since user can override this through ajaxSetup (#11264)
		type: "GET",
		dataType: "script",
		cache: true,
		async: false,
		global: false,

		// Only evaluate the response if it is successful (gh-4126)
		// dataFilter is not invoked for failure responses, so using it instead
		// of the default converter is kludgy but it works.
		converters: {
			"text script": function() {}
		},
		dataFilter: function( response ) {
			jQuery.globalEval( response, options, doc );
		}
	} );
};


jQuery.fn.extend( {
	wrapAll: function( html ) {
		var wrap;

		if ( this[ 0 ] ) {
			if ( isFunction( html ) ) {
				html = html.call( this[ 0 ] );
			}

			// The elements to wrap the target around
			wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

			if ( this[ 0 ].parentNode ) {
				wrap.insertBefore( this[ 0 ] );
			}

			wrap.map( function() {
				var elem = this;

				while ( elem.firstElementChild ) {
					elem = elem.firstElementChild;
				}

				return elem;
			} ).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapInner( html.call( this, i ) );
			} );
		}

		return this.each( function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		} );
	},

	wrap: function( html ) {
		var htmlIsFunction = isFunction( html );

		return this.each( function( i ) {
			jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html );
		} );
	},

	unwrap: function( selector ) {
		this.parent( selector ).not( "body" ).each( function() {
			jQuery( this ).replaceWith( this.childNodes );
		} );
		return this;
	}
} );


jQuery.expr.pseudos.hidden = function( elem ) {
	return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
	return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};




jQuery.ajaxSettings.xhr = function() {
	try {
		return new window.XMLHttpRequest();
	} catch ( e ) {}
};

var xhrSuccessStatus = {

		// File protocol always yields status code 0, assume 200
		0: 200,

		// Support: IE <=9 only
		// #1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
	xhrSupported = jQuery.ajaxSettings.xhr();

support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;

jQuery.ajaxTransport( function( options ) {
	var callback, errorCallback;

	// Cross domain only allowed if supported through XMLHttpRequest
	if ( support.cors || xhrSupported && !options.crossDomain ) {
		return {
			send: function( headers, complete ) {
				var i,
					xhr = options.xhr();

				xhr.open(
					options.type,
					options.url,
					options.async,
					options.username,
					options.password
				);

				// Apply custom fields if provided
				if ( options.xhrFields ) {
					for ( i in options.xhrFields ) {
						xhr[ i ] = options.xhrFields[ i ];
					}
				}

				// Override mime type if needed
				if ( options.mimeType && xhr.overrideMimeType ) {
					xhr.overrideMimeType( options.mimeType );
				}

				// X-Requested-With header
				// For cross-domain requests, seeing as conditions for a preflight are
				// akin to a jigsaw puzzle, we simply never set it to be sure.
				// (it can always be set on a per-request basis or even using ajaxSetup)
				// For same-domain requests, won't change header if already provided.
				if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
					headers[ "X-Requested-With" ] = "XMLHttpRequest";
				}

				// Set headers
				for ( i in headers ) {
					xhr.setRequestHeader( i, headers[ i ] );
				}

				// Callback
				callback = function( type ) {
					return function() {
						if ( callback ) {
							callback = errorCallback = xhr.onload =
								xhr.onerror = xhr.onabort = xhr.ontimeout =
									xhr.onreadystatechange = null;

							if ( type === "abort" ) {
								xhr.abort();
							} else if ( type === "error" ) {

								// Support: IE <=9 only
								// On a manual native abort, IE9 throws
								// errors on any property access that is not readyState
								if ( typeof xhr.status !== "number" ) {
									complete( 0, "error" );
								} else {
									complete(

										// File: protocol always yields status 0; see #8605, #14207
										xhr.status,
										xhr.statusText
									);
								}
							} else {
								complete(
									xhrSuccessStatus[ xhr.status ] || xhr.status,
									xhr.statusText,

									// Support: IE <=9 only
									// IE9 has no XHR2 but throws on binary (trac-11426)
									// For XHR2 non-text, let the caller handle it (gh-2498)
									( xhr.responseType || "text" ) !== "text"  ||
									typeof xhr.responseText !== "string" ?
										{ binary: xhr.response } :
										{ text: xhr.responseText },
									xhr.getAllResponseHeaders()
								);
							}
						}
					};
				};

				// Listen to events
				xhr.onload = callback();
				errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" );

				// Support: IE 9 only
				// Use onreadystatechange to replace onabort
				// to handle uncaught aborts
				if ( xhr.onabort !== undefined ) {
					xhr.onabort = errorCallback;
				} else {
					xhr.onreadystatechange = function() {

						// Check readyState before timeout as it changes
						if ( xhr.readyState === 4 ) {

							// Allow onerror to be called first,
							// but that will not handle a native abort
							// Also, save errorCallback to a variable
							// as xhr.onerror cannot be accessed
							window.setTimeout( function() {
								if ( callback ) {
									errorCallback();
								}
							} );
						}
					};
				}

				// Create the abort callback
				callback = callback( "abort" );

				try {

					// Do send the request (this may raise an exception)
					xhr.send( options.hasContent && options.data || null );
				} catch ( e ) {

					// #14683: Only rethrow if this hasn't been notified as an error yet
					if ( callback ) {
						throw e;
					}
				}
			},

			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
	if ( s.crossDomain ) {
		s.contents.script = false;
	}
} );

// Install script dataType
jQuery.ajaxSetup( {
	accepts: {
		script: "text/javascript, application/javascript, " +
			"application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /\b(?:java|ecma)script\b/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
} );

// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
	}
} );

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {

	// This transport only deals with cross domain or forced-by-attrs requests
	if ( s.crossDomain || s.scriptAttrs ) {
		var script, callback;
		return {
			send: function( _, complete ) {
				script = jQuery( "<script>" )
					.attr( s.scriptAttrs || {} )
					.prop( { charset: s.scriptCharset, src: s.url } )
					.on( "load error", callback = function( evt ) {
						script.remove();
						callback = null;
						if ( evt ) {
							complete( evt.type === "error" ? 404 : 200, evt.type );
						}
					} );

				// Use native DOM manipulation to avoid our domManip AJAX trickery
				document.head.appendChild( script[ 0 ] );
			},
			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &&
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
				rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// Force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// Make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// Save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );




// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
	var body = document.implementation.createHTMLDocument( "" ).body;
	body.innerHTML = "<form></form><form></form>";
	return body.childNodes.length === 2;
} )();


// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
	if ( typeof data !== "string" ) {
		return [];
	}
	if ( typeof context === "boolean" ) {
		keepScripts = context;
		context = false;
	}

	var base, parsed, scripts;

	if ( !context ) {

		// Stop scripts or inline event handlers from being executed immediately
		// by using document.implementation
		if ( support.createHTMLDocument ) {
			context = document.implementation.createHTMLDocument( "" );

			// Set the base href for the created document
			// so any parsed elements with URLs
			// are based on the document's URL (gh-2965)
			base = context.createElement( "base" );
			base.href = document.location.href;
			context.head.appendChild( base );
		} else {
			context = document;
		}
	}

	parsed = rsingleTag.exec( data );
	scripts = !keepScripts && [];

	// Single tag
	if ( parsed ) {
		return [ context.createElement( parsed[ 1 ] ) ];
	}

	parsed = buildFragment( [ data ], context, scripts );

	if ( scripts && scripts.length ) {
		jQuery( scripts ).remove();
	}

	return jQuery.merge( [], parsed.childNodes );
};


/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
	var selector, type, response,
		self = this,
		off = url.indexOf( " " );

	if ( off > -1 ) {
		selector = stripAndCollapse( url.slice( off ) );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length > 0 ) {
		jQuery.ajax( {
			url: url,

			// If "type" variable is undefined, then "GET" method will be used.
			// Make value of this field explicit since
			// user can override it through ajaxSetup method
			type: type || "GET",
			dataType: "html",
			data: params
		} ).done( function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		// If the request succeeds, this function gets "data", "status", "jqXHR"
		// but they are ignored because response was set above.
		// If it fails, this function gets "jqXHR", "status", "error"
		} ).always( callback && function( jqXHR, status ) {
			self.each( function() {
				callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
			} );
		} );
	}

	return this;
};




jQuery.expr.pseudos.animated = function( elem ) {
	return jQuery.grep( jQuery.timers, function( fn ) {
		return elem === fn.elem;
	} ).length;
};




jQuery.offset = {
	setOffset: function( elem, options, i ) {
		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
			position = jQuery.css( elem, "position" ),
			curElem = jQuery( elem ),
			props = {};

		// Set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		curOffset = curElem.offset();
		curCSSTop = jQuery.css( elem, "top" );
		curCSSLeft = jQuery.css( elem, "left" );
		calculatePosition = ( position === "absolute" || position === "fixed" ) &&
			( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;

		// Need to be able to calculate position if either
		// top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;

		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( isFunction( options ) ) {

			// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
			options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );

		} else {
			curElem.css( props );
		}
	}
};

jQuery.fn.extend( {

	// offset() relates an element's border box to the document origin
	offset: function( options ) {

		// Preserve chaining for setter
		if ( arguments.length ) {
			return options === undefined ?
				this :
				this.each( function( i ) {
					jQuery.offset.setOffset( this, options, i );
				} );
		}

		var rect, win,
			elem = this[ 0 ];

		if ( !elem ) {
			return;
		}

		// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
		// Support: IE <=11 only
		// Running getBoundingClientRect on a
		// disconnected node in IE throws an error
		if ( !elem.getClientRects().length ) {
			return { top: 0, left: 0 };
		}

		// Get document-relative position by adding viewport scroll to viewport-relative gBCR
		rect = elem.getBoundingClientRect();
		win = elem.ownerDocument.defaultView;
		return {
			top: rect.top + win.pageYOffset,
			left: rect.left + win.pageXOffset
		};
	},

	// position() relates an element's margin box to its offset parent's padding box
	// This corresponds to the behavior of CSS absolute positioning
	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset, doc,
			elem = this[ 0 ],
			parentOffset = { top: 0, left: 0 };

		// position:fixed elements are offset from the viewport, which itself always has zero offset
		if ( jQuery.css( elem, "position" ) === "fixed" ) {

			// Assume position:fixed implies availability of getBoundingClientRect
			offset = elem.getBoundingClientRect();

		} else {
			offset = this.offset();

			// Account for the *real* offset parent, which can be the document or its root element
			// when a statically positioned element is identified
			doc = elem.ownerDocument;
			offsetParent = elem.offsetParent || doc.documentElement;
			while ( offsetParent &&
				( offsetParent === doc.body || offsetParent === doc.documentElement ) &&
				jQuery.css( offsetParent, "position" ) === "static" ) {

				offsetParent = offsetParent.parentNode;
			}
			if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) {

				// Incorporate borders into its offset, since they are outside its content origin
				parentOffset = jQuery( offsetParent ).offset();
				parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true );
				parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true );
			}
		}

		// Subtract parent offsets and element margins
		return {
			top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
		};
	},

	// This method will return documentElement in the following cases:
	// 1) For the element inside the iframe without offsetParent, this method will return
	//    documentElement of the parent window
	// 2) For the hidden or detached element
	// 3) For body or html element, i.e. in case of the html node - it will return itself
	//
	// but those exceptions were never presented as a real life use-cases
	// and might be considered as more preferable results.
	//
	// This logic, however, is not guaranteed and can change at any point in the future
	offsetParent: function() {
		return this.map( function() {
			var offsetParent = this.offsetParent;

			while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
				offsetParent = offsetParent.offsetParent;
			}

			return offsetParent || documentElement;
		} );
	}
} );

// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
	var top = "pageYOffset" === prop;

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {

			// Coalesce documents and windows
			var win;
			if ( isWindow( elem ) ) {
				win = elem;
			} else if ( elem.nodeType === 9 ) {
				win = elem.defaultView;
			}

			if ( val === undefined ) {
				return win ? win[ prop ] : elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : win.pageXOffset,
					top ? val : win.pageYOffset
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length );
	};
} );

// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( _i, prop ) {
	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
		function( elem, computed ) {
			if ( computed ) {
				computed = curCSS( elem, prop );

				// If curCSS returns percentage, fallback to offset
				return rnumnonpx.test( computed ) ?
					jQuery( elem ).position()[ prop ] + "px" :
					computed;
			}
		}
	);
} );


// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( {
		padding: "inner" + name,
		content: type,
		"": "outer" + name
	}, function( defaultExtra, funcName ) {

		// Margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return access( this, function( elem, type, value ) {
				var doc;

				if ( isWindow( elem ) ) {

					// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
					return funcName.indexOf( "outer" ) === 0 ?
						elem[ "inner" + name ] :
						elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
					// whichever is greatest
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable );
		};
	} );
} );


jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( _i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {

		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	},

	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
} );

jQuery.each(
	( "blur focus focusin focusout resize scroll click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup contextmenu" ).split( " " ),
	function( _i, name ) {

		// Handle event binding
		jQuery.fn[ name ] = function( data, fn ) {
			return arguments.length > 0 ?
				this.on( name, null, data, fn ) :
				this.trigger( name );
		};
	}
);




// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

// Bind a function to a context, optionally partially applying any
// arguments.
// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
// However, it is not slated for removal any time soon
jQuery.proxy = function( fn, context ) {
	var tmp, args, proxy;

	if ( typeof context === "string" ) {
		tmp = fn[ context ];
		context = fn;
		fn = tmp;
	}

	// Quick check to determine if target is callable, in the spec
	// this throws a TypeError, but we will just return undefined.
	if ( !isFunction( fn ) ) {
		return undefined;
	}

	// Simulated bind
	args = slice.call( arguments, 2 );
	proxy = function() {
		return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
	};

	// Set the guid of unique handler to the same of original handler, so it can be removed
	proxy.guid = fn.guid = fn.guid || jQuery.guid++;

	return proxy;
};

jQuery.holdReady = function( hold ) {
	if ( hold ) {
		jQuery.readyWait++;
	} else {
		jQuery.ready( true );
	}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
jQuery.isFunction = isFunction;
jQuery.isWindow = isWindow;
jQuery.camelCase = camelCase;
jQuery.type = toType;

jQuery.now = Date.now;

jQuery.isNumeric = function( obj ) {

	// As of jQuery 3.0, isNumeric is limited to
	// strings and numbers (primitives or objects)
	// that can be coerced to finite numbers (gh-2662)
	var type = jQuery.type( obj );
	return ( type === "number" || type === "string" ) &&

		// parseFloat NaNs numeric-cast false positives ("")
		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
		// subtraction forces infinities to NaN
		!isNaN( obj - parseFloat( obj ) );
};

jQuery.trim = function( text ) {
	return text == null ?
		"" :
		( text + "" ).replace( rtrim, "" );
};



// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( true ) {
	!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
		return jQuery;
	}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}




var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$;

jQuery.noConflict = function( deep ) {
	if ( window.$ === jQuery ) {
		window.$ = _$;
	}

	if ( deep && window.jQuery === jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === "undefined" ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;
} );


/***/ }),

/***/ "./node_modules/lodash/_assignMergeValue.js":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_assignMergeValue.js ***!
  \**************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseAssignValue = __webpack_require__(/*! ./_baseAssignValue */ "./node_modules/lodash/_baseAssignValue.js"),
    eq = __webpack_require__(/*! ./eq */ "./node_modules/lodash/eq.js");

/**
 * This function is like `assignValue` except that it doesn't assign
 * `undefined` values.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignMergeValue(object, key, value) {
  if ((value !== undefined && !eq(object[key], value)) ||
      (value === undefined && !(key in object))) {
    baseAssignValue(object, key, value);
  }
}

module.exports = assignMergeValue;


/***/ }),

/***/ "./node_modules/lodash/_baseExtremum.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/_baseExtremum.js ***!
  \**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js");

/**
 * The base implementation of methods like `_.max` and `_.min` which accepts a
 * `comparator` to determine the extremum value.
 *
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} iteratee The iteratee invoked per iteration.
 * @param {Function} comparator The comparator used to compare values.
 * @returns {*} Returns the extremum value.
 */
function baseExtremum(array, iteratee, comparator) {
  var index = -1,
      length = array.length;

  while (++index < length) {
    var value = array[index],
        current = iteratee(value);

    if (current != null && (computed === undefined
          ? (current === current && !isSymbol(current))
          : comparator(current, computed)
        )) {
      var computed = current,
          result = value;
    }
  }
  return result;
}

module.exports = baseExtremum;


/***/ }),

/***/ "./node_modules/lodash/_baseGt.js":
/*!****************************************!*\
  !*** ./node_modules/lodash/_baseGt.js ***!
  \****************************************/
/***/ ((module) => {

/**
 * The base implementation of `_.gt` which doesn't coerce arguments.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if `value` is greater than `other`,
 *  else `false`.
 */
function baseGt(value, other) {
  return value > other;
}

module.exports = baseGt;


/***/ }),

/***/ "./node_modules/lodash/_baseLt.js":
/*!****************************************!*\
  !*** ./node_modules/lodash/_baseLt.js ***!
  \****************************************/
/***/ ((module) => {

/**
 * The base implementation of `_.lt` which doesn't coerce arguments.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if `value` is less than `other`,
 *  else `false`.
 */
function baseLt(value, other) {
  return value < other;
}

module.exports = baseLt;


/***/ }),

/***/ "./node_modules/lodash/_baseMerge.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseMerge.js ***!
  \*******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Stack = __webpack_require__(/*! ./_Stack */ "./node_modules/lodash/_Stack.js"),
    assignMergeValue = __webpack_require__(/*! ./_assignMergeValue */ "./node_modules/lodash/_assignMergeValue.js"),
    baseFor = __webpack_require__(/*! ./_baseFor */ "./node_modules/lodash/_baseFor.js"),
    baseMergeDeep = __webpack_require__(/*! ./_baseMergeDeep */ "./node_modules/lodash/_baseMergeDeep.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js"),
    keysIn = __webpack_require__(/*! ./keysIn */ "./node_modules/lodash/keysIn.js"),
    safeGet = __webpack_require__(/*! ./_safeGet */ "./node_modules/lodash/_safeGet.js");

/**
 * The base implementation of `_.merge` without support for multiple sources.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @param {number} srcIndex The index of `source`.
 * @param {Function} [customizer] The function to customize merged values.
 * @param {Object} [stack] Tracks traversed source values and their merged
 *  counterparts.
 */
function baseMerge(object, source, srcIndex, customizer, stack) {
  if (object === source) {
    return;
  }
  baseFor(source, function(srcValue, key) {
    stack || (stack = new Stack);
    if (isObject(srcValue)) {
      baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
    }
    else {
      var newValue = customizer
        ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
        : undefined;

      if (newValue === undefined) {
        newValue = srcValue;
      }
      assignMergeValue(object, key, newValue);
    }
  }, keysIn);
}

module.exports = baseMerge;


/***/ }),

/***/ "./node_modules/lodash/_baseMergeDeep.js":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_baseMergeDeep.js ***!
  \***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var assignMergeValue = __webpack_require__(/*! ./_assignMergeValue */ "./node_modules/lodash/_assignMergeValue.js"),
    cloneBuffer = __webpack_require__(/*! ./_cloneBuffer */ "./node_modules/lodash/_cloneBuffer.js"),
    cloneTypedArray = __webpack_require__(/*! ./_cloneTypedArray */ "./node_modules/lodash/_cloneTypedArray.js"),
    copyArray = __webpack_require__(/*! ./_copyArray */ "./node_modules/lodash/_copyArray.js"),
    initCloneObject = __webpack_require__(/*! ./_initCloneObject */ "./node_modules/lodash/_initCloneObject.js"),
    isArguments = __webpack_require__(/*! ./isArguments */ "./node_modules/lodash/isArguments.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js"),
    isArrayLikeObject = __webpack_require__(/*! ./isArrayLikeObject */ "./node_modules/lodash/isArrayLikeObject.js"),
    isBuffer = __webpack_require__(/*! ./isBuffer */ "./node_modules/lodash/isBuffer.js"),
    isFunction = __webpack_require__(/*! ./isFunction */ "./node_modules/lodash/isFunction.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js"),
    isPlainObject = __webpack_require__(/*! ./isPlainObject */ "./node_modules/lodash/isPlainObject.js"),
    isTypedArray = __webpack_require__(/*! ./isTypedArray */ "./node_modules/lodash/isTypedArray.js"),
    safeGet = __webpack_require__(/*! ./_safeGet */ "./node_modules/lodash/_safeGet.js"),
    toPlainObject = __webpack_require__(/*! ./toPlainObject */ "./node_modules/lodash/toPlainObject.js");

/**
 * A specialized version of `baseMerge` for arrays and objects which performs
 * deep merges and tracks traversed objects enabling objects with circular
 * references to be merged.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @param {string} key The key of the value to merge.
 * @param {number} srcIndex The index of `source`.
 * @param {Function} mergeFunc The function to merge values.
 * @param {Function} [customizer] The function to customize assigned values.
 * @param {Object} [stack] Tracks traversed source values and their merged
 *  counterparts.
 */
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
  var objValue = safeGet(object, key),
      srcValue = safeGet(source, key),
      stacked = stack.get(srcValue);

  if (stacked) {
    assignMergeValue(object, key, stacked);
    return;
  }
  var newValue = customizer
    ? customizer(objValue, srcValue, (key + ''), object, source, stack)
    : undefined;

  var isCommon = newValue === undefined;

  if (isCommon) {
    var isArr = isArray(srcValue),
        isBuff = !isArr && isBuffer(srcValue),
        isTyped = !isArr && !isBuff && isTypedArray(srcValue);

    newValue = srcValue;
    if (isArr || isBuff || isTyped) {
      if (isArray(objValue)) {
        newValue = objValue;
      }
      else if (isArrayLikeObject(objValue)) {
        newValue = copyArray(objValue);
      }
      else if (isBuff) {
        isCommon = false;
        newValue = cloneBuffer(srcValue, true);
      }
      else if (isTyped) {
        isCommon = false;
        newValue = cloneTypedArray(srcValue, true);
      }
      else {
        newValue = [];
      }
    }
    else if (isPlainObject(srcValue) || isArguments(srcValue)) {
      newValue = objValue;
      if (isArguments(objValue)) {
        newValue = toPlainObject(objValue);
      }
      else if (!isObject(objValue) || isFunction(objValue)) {
        newValue = initCloneObject(srcValue);
      }
    }
    else {
      isCommon = false;
    }
  }
  if (isCommon) {
    // Recursively merge objects and arrays (susceptible to call stack limits).
    stack.set(srcValue, newValue);
    mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
    stack['delete'](srcValue);
  }
  assignMergeValue(object, key, newValue);
}

module.exports = baseMergeDeep;


/***/ }),

/***/ "./node_modules/lodash/_baseOrderBy.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_baseOrderBy.js ***!
  \*********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var arrayMap = __webpack_require__(/*! ./_arrayMap */ "./node_modules/lodash/_arrayMap.js"),
    baseGet = __webpack_require__(/*! ./_baseGet */ "./node_modules/lodash/_baseGet.js"),
    baseIteratee = __webpack_require__(/*! ./_baseIteratee */ "./node_modules/lodash/_baseIteratee.js"),
    baseMap = __webpack_require__(/*! ./_baseMap */ "./node_modules/lodash/_baseMap.js"),
    baseSortBy = __webpack_require__(/*! ./_baseSortBy */ "./node_modules/lodash/_baseSortBy.js"),
    baseUnary = __webpack_require__(/*! ./_baseUnary */ "./node_modules/lodash/_baseUnary.js"),
    compareMultiple = __webpack_require__(/*! ./_compareMultiple */ "./node_modules/lodash/_compareMultiple.js"),
    identity = __webpack_require__(/*! ./identity */ "./node_modules/lodash/identity.js"),
    isArray = __webpack_require__(/*! ./isArray */ "./node_modules/lodash/isArray.js");

/**
 * The base implementation of `_.orderBy` without param guards.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
 * @param {string[]} orders The sort orders of `iteratees`.
 * @returns {Array} Returns the new sorted array.
 */
function baseOrderBy(collection, iteratees, orders) {
  if (iteratees.length) {
    iteratees = arrayMap(iteratees, function(iteratee) {
      if (isArray(iteratee)) {
        return function(value) {
          return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
        }
      }
      return iteratee;
    });
  } else {
    iteratees = [identity];
  }

  var index = -1;
  iteratees = arrayMap(iteratees, baseUnary(baseIteratee));

  var result = baseMap(collection, function(value, key, collection) {
    var criteria = arrayMap(iteratees, function(iteratee) {
      return iteratee(value);
    });
    return { 'criteria': criteria, 'index': ++index, 'value': value };
  });

  return baseSortBy(result, function(object, other) {
    return compareMultiple(object, other, orders);
  });
}

module.exports = baseOrderBy;


/***/ }),

/***/ "./node_modules/lodash/_basePick.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_basePick.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var basePickBy = __webpack_require__(/*! ./_basePickBy */ "./node_modules/lodash/_basePickBy.js"),
    hasIn = __webpack_require__(/*! ./hasIn */ "./node_modules/lodash/hasIn.js");

/**
 * The base implementation of `_.pick` without support for individual
 * property identifiers.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @returns {Object} Returns the new object.
 */
function basePick(object, paths) {
  return basePickBy(object, paths, function(value, path) {
    return hasIn(object, path);
  });
}

module.exports = basePick;


/***/ }),

/***/ "./node_modules/lodash/_basePickBy.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_basePickBy.js ***!
  \********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseGet = __webpack_require__(/*! ./_baseGet */ "./node_modules/lodash/_baseGet.js"),
    baseSet = __webpack_require__(/*! ./_baseSet */ "./node_modules/lodash/_baseSet.js"),
    castPath = __webpack_require__(/*! ./_castPath */ "./node_modules/lodash/_castPath.js");

/**
 * The base implementation of  `_.pickBy` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @param {Function} predicate The function invoked per property.
 * @returns {Object} Returns the new object.
 */
function basePickBy(object, paths, predicate) {
  var index = -1,
      length = paths.length,
      result = {};

  while (++index < length) {
    var path = paths[index],
        value = baseGet(object, path);

    if (predicate(value, path)) {
      baseSet(result, castPath(path, object), value);
    }
  }
  return result;
}

module.exports = basePickBy;


/***/ }),

/***/ "./node_modules/lodash/_baseRange.js":
/*!*******************************************!*\
  !*** ./node_modules/lodash/_baseRange.js ***!
  \*******************************************/
/***/ ((module) => {

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
    nativeMax = Math.max;

/**
 * The base implementation of `_.range` and `_.rangeRight` which doesn't
 * coerce arguments.
 *
 * @private
 * @param {number} start The start of the range.
 * @param {number} end The end of the range.
 * @param {number} step The value to increment or decrement by.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Array} Returns the range of numbers.
 */
function baseRange(start, end, step, fromRight) {
  var index = -1,
      length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
      result = Array(length);

  while (length--) {
    result[fromRight ? length : ++index] = start;
    start += step;
  }
  return result;
}

module.exports = baseRange;


/***/ }),

/***/ "./node_modules/lodash/_baseSet.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_baseSet.js ***!
  \*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var assignValue = __webpack_require__(/*! ./_assignValue */ "./node_modules/lodash/_assignValue.js"),
    castPath = __webpack_require__(/*! ./_castPath */ "./node_modules/lodash/_castPath.js"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "./node_modules/lodash/_isIndex.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js"),
    toKey = __webpack_require__(/*! ./_toKey */ "./node_modules/lodash/_toKey.js");

/**
 * The base implementation of `_.set`.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {Array|string} path The path of the property to set.
 * @param {*} value The value to set.
 * @param {Function} [customizer] The function to customize path creation.
 * @returns {Object} Returns `object`.
 */
function baseSet(object, path, value, customizer) {
  if (!isObject(object)) {
    return object;
  }
  path = castPath(path, object);

  var index = -1,
      length = path.length,
      lastIndex = length - 1,
      nested = object;

  while (nested != null && ++index < length) {
    var key = toKey(path[index]),
        newValue = value;

    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
      return object;
    }

    if (index != lastIndex) {
      var objValue = nested[key];
      newValue = customizer ? customizer(objValue, key, nested) : undefined;
      if (newValue === undefined) {
        newValue = isObject(objValue)
          ? objValue
          : (isIndex(path[index + 1]) ? [] : {});
      }
    }
    assignValue(nested, key, newValue);
    nested = nested[key];
  }
  return object;
}

module.exports = baseSet;


/***/ }),

/***/ "./node_modules/lodash/_baseSortBy.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_baseSortBy.js ***!
  \********************************************/
/***/ ((module) => {

/**
 * The base implementation of `_.sortBy` which uses `comparer` to define the
 * sort order of `array` and replaces criteria objects with their corresponding
 * values.
 *
 * @private
 * @param {Array} array The array to sort.
 * @param {Function} comparer The function to define sort order.
 * @returns {Array} Returns `array`.
 */
function baseSortBy(array, comparer) {
  var length = array.length;

  array.sort(comparer);
  while (length--) {
    array[length] = array[length].value;
  }
  return array;
}

module.exports = baseSortBy;


/***/ }),

/***/ "./node_modules/lodash/_baseTrim.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_baseTrim.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var trimmedEndIndex = __webpack_require__(/*! ./_trimmedEndIndex */ "./node_modules/lodash/_trimmedEndIndex.js");

/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;

/**
 * The base implementation of `_.trim`.
 *
 * @private
 * @param {string} string The string to trim.
 * @returns {string} Returns the trimmed string.
 */
function baseTrim(string) {
  return string
    ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
    : string;
}

module.exports = baseTrim;


/***/ }),

/***/ "./node_modules/lodash/_baseZipObject.js":
/*!***********************************************!*\
  !*** ./node_modules/lodash/_baseZipObject.js ***!
  \***********************************************/
/***/ ((module) => {

/**
 * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
 *
 * @private
 * @param {Array} props The property identifiers.
 * @param {Array} values The property values.
 * @param {Function} assignFunc The function to assign values.
 * @returns {Object} Returns the new object.
 */
function baseZipObject(props, values, assignFunc) {
  var index = -1,
      length = props.length,
      valsLength = values.length,
      result = {};

  while (++index < length) {
    var value = index < valsLength ? values[index] : undefined;
    assignFunc(result, props[index], value);
  }
  return result;
}

module.exports = baseZipObject;


/***/ }),

/***/ "./node_modules/lodash/_compareAscending.js":
/*!**************************************************!*\
  !*** ./node_modules/lodash/_compareAscending.js ***!
  \**************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js");

/**
 * Compares values to sort them in ascending order.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {number} Returns the sort order indicator for `value`.
 */
function compareAscending(value, other) {
  if (value !== other) {
    var valIsDefined = value !== undefined,
        valIsNull = value === null,
        valIsReflexive = value === value,
        valIsSymbol = isSymbol(value);

    var othIsDefined = other !== undefined,
        othIsNull = other === null,
        othIsReflexive = other === other,
        othIsSymbol = isSymbol(other);

    if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
        (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
        (valIsNull && othIsDefined && othIsReflexive) ||
        (!valIsDefined && othIsReflexive) ||
        !valIsReflexive) {
      return 1;
    }
    if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
        (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
        (othIsNull && valIsDefined && valIsReflexive) ||
        (!othIsDefined && valIsReflexive) ||
        !othIsReflexive) {
      return -1;
    }
  }
  return 0;
}

module.exports = compareAscending;


/***/ }),

/***/ "./node_modules/lodash/_compareMultiple.js":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_compareMultiple.js ***!
  \*************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var compareAscending = __webpack_require__(/*! ./_compareAscending */ "./node_modules/lodash/_compareAscending.js");

/**
 * Used by `_.orderBy` to compare multiple properties of a value to another
 * and stable sort them.
 *
 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
 * specify an order of "desc" for descending or "asc" for ascending sort order
 * of corresponding values.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {boolean[]|string[]} orders The order to sort by for each property.
 * @returns {number} Returns the sort order indicator for `object`.
 */
function compareMultiple(object, other, orders) {
  var index = -1,
      objCriteria = object.criteria,
      othCriteria = other.criteria,
      length = objCriteria.length,
      ordersLength = orders.length;

  while (++index < length) {
    var result = compareAscending(objCriteria[index], othCriteria[index]);
    if (result) {
      if (index >= ordersLength) {
        return result;
      }
      var order = orders[index];
      return result * (order == 'desc' ? -1 : 1);
    }
  }
  // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
  // that causes it, under certain circumstances, to provide the same value for
  // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
  // for more details.
  //
  // This also ensures a stable sort in V8 and other engines.
  // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
  return object.index - other.index;
}

module.exports = compareMultiple;


/***/ }),

/***/ "./node_modules/lodash/_createAssigner.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_createAssigner.js ***!
  \************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseRest = __webpack_require__(/*! ./_baseRest */ "./node_modules/lodash/_baseRest.js"),
    isIterateeCall = __webpack_require__(/*! ./_isIterateeCall */ "./node_modules/lodash/_isIterateeCall.js");

/**
 * Creates a function like `_.assign`.
 *
 * @private
 * @param {Function} assigner The function to assign values.
 * @returns {Function} Returns the new assigner function.
 */
function createAssigner(assigner) {
  return baseRest(function(object, sources) {
    var index = -1,
        length = sources.length,
        customizer = length > 1 ? sources[length - 1] : undefined,
        guard = length > 2 ? sources[2] : undefined;

    customizer = (assigner.length > 3 && typeof customizer == 'function')
      ? (length--, customizer)
      : undefined;

    if (guard && isIterateeCall(sources[0], sources[1], guard)) {
      customizer = length < 3 ? undefined : customizer;
      length = 1;
    }
    object = Object(object);
    while (++index < length) {
      var source = sources[index];
      if (source) {
        assigner(object, source, index, customizer);
      }
    }
    return object;
  });
}

module.exports = createAssigner;


/***/ }),

/***/ "./node_modules/lodash/_createFind.js":
/*!********************************************!*\
  !*** ./node_modules/lodash/_createFind.js ***!
  \********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseIteratee = __webpack_require__(/*! ./_baseIteratee */ "./node_modules/lodash/_baseIteratee.js"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "./node_modules/lodash/isArrayLike.js"),
    keys = __webpack_require__(/*! ./keys */ "./node_modules/lodash/keys.js");

/**
 * Creates a `_.find` or `_.findLast` function.
 *
 * @private
 * @param {Function} findIndexFunc The function to find the collection index.
 * @returns {Function} Returns the new find function.
 */
function createFind(findIndexFunc) {
  return function(collection, predicate, fromIndex) {
    var iterable = Object(collection);
    if (!isArrayLike(collection)) {
      var iteratee = baseIteratee(predicate, 3);
      collection = keys(collection);
      predicate = function(key) { return iteratee(iterable[key], key, iterable); };
    }
    var index = findIndexFunc(collection, predicate, fromIndex);
    return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
  };
}

module.exports = createFind;


/***/ }),

/***/ "./node_modules/lodash/_createRange.js":
/*!*********************************************!*\
  !*** ./node_modules/lodash/_createRange.js ***!
  \*********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseRange = __webpack_require__(/*! ./_baseRange */ "./node_modules/lodash/_baseRange.js"),
    isIterateeCall = __webpack_require__(/*! ./_isIterateeCall */ "./node_modules/lodash/_isIterateeCall.js"),
    toFinite = __webpack_require__(/*! ./toFinite */ "./node_modules/lodash/toFinite.js");

/**
 * Creates a `_.range` or `_.rangeRight` function.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new range function.
 */
function createRange(fromRight) {
  return function(start, end, step) {
    if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
      end = step = undefined;
    }
    // Ensure the sign of `-0` is preserved.
    start = toFinite(start);
    if (end === undefined) {
      end = start;
      start = 0;
    } else {
      end = toFinite(end);
    }
    step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
    return baseRange(start, end, step, fromRight);
  };
}

module.exports = createRange;


/***/ }),

/***/ "./node_modules/lodash/_flatRest.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/_flatRest.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var flatten = __webpack_require__(/*! ./flatten */ "./node_modules/lodash/flatten.js"),
    overRest = __webpack_require__(/*! ./_overRest */ "./node_modules/lodash/_overRest.js"),
    setToString = __webpack_require__(/*! ./_setToString */ "./node_modules/lodash/_setToString.js");

/**
 * A specialized version of `baseRest` which flattens the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @returns {Function} Returns the new function.
 */
function flatRest(func) {
  return setToString(overRest(func, undefined, flatten), func + '');
}

module.exports = flatRest;


/***/ }),

/***/ "./node_modules/lodash/_isIterateeCall.js":
/*!************************************************!*\
  !*** ./node_modules/lodash/_isIterateeCall.js ***!
  \************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var eq = __webpack_require__(/*! ./eq */ "./node_modules/lodash/eq.js"),
    isArrayLike = __webpack_require__(/*! ./isArrayLike */ "./node_modules/lodash/isArrayLike.js"),
    isIndex = __webpack_require__(/*! ./_isIndex */ "./node_modules/lodash/_isIndex.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js");

/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */
function isIterateeCall(value, index, object) {
  if (!isObject(object)) {
    return false;
  }
  var type = typeof index;
  if (type == 'number'
        ? (isArrayLike(object) && isIndex(index, object.length))
        : (type == 'string' && index in object)
      ) {
    return eq(object[index], value);
  }
  return false;
}

module.exports = isIterateeCall;


/***/ }),

/***/ "./node_modules/lodash/_safeGet.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/_safeGet.js ***!
  \*****************************************/
/***/ ((module) => {

/**
 * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function safeGet(object, key) {
  if (key === 'constructor' && typeof object[key] === 'function') {
    return;
  }

  if (key == '__proto__') {
    return;
  }

  return object[key];
}

module.exports = safeGet;


/***/ }),

/***/ "./node_modules/lodash/_trimmedEndIndex.js":
/*!*************************************************!*\
  !*** ./node_modules/lodash/_trimmedEndIndex.js ***!
  \*************************************************/
/***/ ((module) => {

/** Used to match a single whitespace character. */
var reWhitespace = /\s/;

/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
 * character of `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the index of the last non-whitespace character.
 */
function trimmedEndIndex(string) {
  var index = string.length;

  while (index-- && reWhitespace.test(string.charAt(index))) {}
  return index;
}

module.exports = trimmedEndIndex;


/***/ }),

/***/ "./node_modules/lodash/cloneDeep.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/cloneDeep.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseClone = __webpack_require__(/*! ./_baseClone */ "./node_modules/lodash/_baseClone.js");

/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
    CLONE_SYMBOLS_FLAG = 4;

/**
 * This method is like `_.clone` except that it recursively clones `value`.
 *
 * @static
 * @memberOf _
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see _.clone
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var deep = _.cloneDeep(objects);
 * console.log(deep[0] === objects[0]);
 * // => false
 */
function cloneDeep(value) {
  return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}

module.exports = cloneDeep;


/***/ }),

/***/ "./node_modules/lodash/defaults.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/defaults.js ***!
  \*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseRest = __webpack_require__(/*! ./_baseRest */ "./node_modules/lodash/_baseRest.js"),
    eq = __webpack_require__(/*! ./eq */ "./node_modules/lodash/eq.js"),
    isIterateeCall = __webpack_require__(/*! ./_isIterateeCall */ "./node_modules/lodash/_isIterateeCall.js"),
    keysIn = __webpack_require__(/*! ./keysIn */ "./node_modules/lodash/keysIn.js");

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Assigns own and inherited enumerable string keyed properties of source
 * objects to the destination object for all destination properties that
 * resolve to `undefined`. Source objects are applied from left to right.
 * Once a property is set, additional values of the same property are ignored.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.defaultsDeep
 * @example
 *
 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
 * // => { 'a': 1, 'b': 2 }
 */
var defaults = baseRest(function(object, sources) {
  object = Object(object);

  var index = -1;
  var length = sources.length;
  var guard = length > 2 ? sources[2] : undefined;

  if (guard && isIterateeCall(sources[0], sources[1], guard)) {
    length = 1;
  }

  while (++index < length) {
    var source = sources[index];
    var props = keysIn(source);
    var propsIndex = -1;
    var propsLength = props.length;

    while (++propsIndex < propsLength) {
      var key = props[propsIndex];
      var value = object[key];

      if (value === undefined ||
          (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
        object[key] = source[key];
      }
    }
  }

  return object;
});

module.exports = defaults;


/***/ }),

/***/ "./node_modules/lodash/find.js":
/*!*************************************!*\
  !*** ./node_modules/lodash/find.js ***!
  \*************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var createFind = __webpack_require__(/*! ./_createFind */ "./node_modules/lodash/_createFind.js"),
    findIndex = __webpack_require__(/*! ./findIndex */ "./node_modules/lodash/findIndex.js");

/**
 * Iterates over elements of `collection`, returning the first element
 * `predicate` returns truthy for. The predicate is invoked with three
 * arguments: (value, index|key, collection).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to inspect.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {*} Returns the matched element, else `undefined`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'age': 36, 'active': true },
 *   { 'user': 'fred',    'age': 40, 'active': false },
 *   { 'user': 'pebbles', 'age': 1,  'active': true }
 * ];
 *
 * _.find(users, function(o) { return o.age < 40; });
 * // => object for 'barney'
 *
 * // The `_.matches` iteratee shorthand.
 * _.find(users, { 'age': 1, 'active': true });
 * // => object for 'pebbles'
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.find(users, ['active', false]);
 * // => object for 'fred'
 *
 * // The `_.property` iteratee shorthand.
 * _.find(users, 'active');
 * // => object for 'barney'
 */
var find = createFind(findIndex);

module.exports = find;


/***/ }),

/***/ "./node_modules/lodash/findIndex.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/findIndex.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseFindIndex = __webpack_require__(/*! ./_baseFindIndex */ "./node_modules/lodash/_baseFindIndex.js"),
    baseIteratee = __webpack_require__(/*! ./_baseIteratee */ "./node_modules/lodash/_baseIteratee.js"),
    toInteger = __webpack_require__(/*! ./toInteger */ "./node_modules/lodash/toInteger.js");

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * This method is like `_.find` except that it returns the index of the first
 * element `predicate` returns truthy for instead of the element itself.
 *
 * @static
 * @memberOf _
 * @since 1.1.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param {number} [fromIndex=0] The index to search from.
 * @returns {number} Returns the index of the found element, else `-1`.
 * @example
 *
 * var users = [
 *   { 'user': 'barney',  'active': false },
 *   { 'user': 'fred',    'active': false },
 *   { 'user': 'pebbles', 'active': true }
 * ];
 *
 * _.findIndex(users, function(o) { return o.user == 'barney'; });
 * // => 0
 *
 * // The `_.matches` iteratee shorthand.
 * _.findIndex(users, { 'user': 'fred', 'active': false });
 * // => 1
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.findIndex(users, ['active', false]);
 * // => 0
 *
 * // The `_.property` iteratee shorthand.
 * _.findIndex(users, 'active');
 * // => 2
 */
function findIndex(array, predicate, fromIndex) {
  var length = array == null ? 0 : array.length;
  if (!length) {
    return -1;
  }
  var index = fromIndex == null ? 0 : toInteger(fromIndex);
  if (index < 0) {
    index = nativeMax(length + index, 0);
  }
  return baseFindIndex(array, baseIteratee(predicate, 3), index);
}

module.exports = findIndex;


/***/ }),

/***/ "./node_modules/lodash/flatten.js":
/*!****************************************!*\
  !*** ./node_modules/lodash/flatten.js ***!
  \****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseFlatten = __webpack_require__(/*! ./_baseFlatten */ "./node_modules/lodash/_baseFlatten.js");

/**
 * Flattens `array` a single level deep.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to flatten.
 * @returns {Array} Returns the new flattened array.
 * @example
 *
 * _.flatten([1, [2, [3, [4]], 5]]);
 * // => [1, 2, [3, [4]], 5]
 */
function flatten(array) {
  var length = array == null ? 0 : array.length;
  return length ? baseFlatten(array, 1) : [];
}

module.exports = flatten;


/***/ }),

/***/ "./node_modules/lodash/forIn.js":
/*!**************************************!*\
  !*** ./node_modules/lodash/forIn.js ***!
  \**************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseFor = __webpack_require__(/*! ./_baseFor */ "./node_modules/lodash/_baseFor.js"),
    castFunction = __webpack_require__(/*! ./_castFunction */ "./node_modules/lodash/_castFunction.js"),
    keysIn = __webpack_require__(/*! ./keysIn */ "./node_modules/lodash/keysIn.js");

/**
 * Iterates over own and inherited enumerable string keyed properties of an
 * object and invokes `iteratee` for each property. The iteratee is invoked
 * with three arguments: (value, key, object). Iteratee functions may exit
 * iteration early by explicitly returning `false`.
 *
 * @static
 * @memberOf _
 * @since 0.3.0
 * @category Object
 * @param {Object} object The object to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Object} Returns `object`.
 * @see _.forInRight
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.forIn(new Foo, function(value, key) {
 *   console.log(key);
 * });
 * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
 */
function forIn(object, iteratee) {
  return object == null
    ? object
    : baseFor(object, castFunction(iteratee), keysIn);
}

module.exports = forIn;


/***/ }),

/***/ "./node_modules/lodash/isPlainObject.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/isPlainObject.js ***!
  \**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "./node_modules/lodash/_baseGetTag.js"),
    getPrototype = __webpack_require__(/*! ./_getPrototype */ "./node_modules/lodash/_getPrototype.js"),
    isObjectLike = __webpack_require__(/*! ./isObjectLike */ "./node_modules/lodash/isObjectLike.js");

/** `Object#toString` result references. */
var objectTag = '[object Object]';

/** Used for built-in method references. */
var funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);

/**
 * Checks if `value` is a plain object, that is, an object created by the
 * `Object` constructor or one with a `[[Prototype]]` of `null`.
 *
 * @static
 * @memberOf _
 * @since 0.8.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * _.isPlainObject(new Foo);
 * // => false
 *
 * _.isPlainObject([1, 2, 3]);
 * // => false
 *
 * _.isPlainObject({ 'x': 0, 'y': 0 });
 * // => true
 *
 * _.isPlainObject(Object.create(null));
 * // => true
 */
function isPlainObject(value) {
  if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
    return false;
  }
  var proto = getPrototype(value);
  if (proto === null) {
    return true;
  }
  var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  return typeof Ctor == 'function' && Ctor instanceof Ctor &&
    funcToString.call(Ctor) == objectCtorString;
}

module.exports = isPlainObject;


/***/ }),

/***/ "./node_modules/lodash/last.js":
/*!*************************************!*\
  !*** ./node_modules/lodash/last.js ***!
  \*************************************/
/***/ ((module) => {

/**
 * Gets the last element of `array`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to query.
 * @returns {*} Returns the last element of `array`.
 * @example
 *
 * _.last([1, 2, 3]);
 * // => 3
 */
function last(array) {
  var length = array == null ? 0 : array.length;
  return length ? array[length - 1] : undefined;
}

module.exports = last;


/***/ }),

/***/ "./node_modules/lodash/lodash.js":
/*!***************************************!*\
  !*** ./node_modules/lodash/lodash.js ***!
  \***************************************/
/***/ (function(module, exports, __webpack_require__) {

/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_RESULT__;/**
 * @license
 * Lodash <https://lodash.com/>
 * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */
;(function() {

  /** Used as a safe reference for `undefined` in pre-ES5 environments. */
  var undefined;

  /** Used as the semantic version number. */
  var VERSION = '4.17.21';

  /** Used as the size to enable large array optimizations. */
  var LARGE_ARRAY_SIZE = 200;

  /** Error message constants. */
  var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
      FUNC_ERROR_TEXT = 'Expected a function',
      INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';

  /** Used to stand-in for `undefined` hash values. */
  var HASH_UNDEFINED = '__lodash_hash_undefined__';

  /** Used as the maximum memoize cache size. */
  var MAX_MEMOIZE_SIZE = 500;

  /** Used as the internal argument placeholder. */
  var PLACEHOLDER = '__lodash_placeholder__';

  /** Used to compose bitmasks for cloning. */
  var CLONE_DEEP_FLAG = 1,
      CLONE_FLAT_FLAG = 2,
      CLONE_SYMBOLS_FLAG = 4;

  /** Used to compose bitmasks for value comparisons. */
  var COMPARE_PARTIAL_FLAG = 1,
      COMPARE_UNORDERED_FLAG = 2;

  /** Used to compose bitmasks for function metadata. */
  var WRAP_BIND_FLAG = 1,
      WRAP_BIND_KEY_FLAG = 2,
      WRAP_CURRY_BOUND_FLAG = 4,
      WRAP_CURRY_FLAG = 8,
      WRAP_CURRY_RIGHT_FLAG = 16,
      WRAP_PARTIAL_FLAG = 32,
      WRAP_PARTIAL_RIGHT_FLAG = 64,
      WRAP_ARY_FLAG = 128,
      WRAP_REARG_FLAG = 256,
      WRAP_FLIP_FLAG = 512;

  /** Used as default options for `_.truncate`. */
  var DEFAULT_TRUNC_LENGTH = 30,
      DEFAULT_TRUNC_OMISSION = '...';

  /** Used to detect hot functions by number of calls within a span of milliseconds. */
  var HOT_COUNT = 800,
      HOT_SPAN = 16;

  /** Used to indicate the type of lazy iteratees. */
  var LAZY_FILTER_FLAG = 1,
      LAZY_MAP_FLAG = 2,
      LAZY_WHILE_FLAG = 3;

  /** Used as references for various `Number` constants. */
  var INFINITY = 1 / 0,
      MAX_SAFE_INTEGER = 9007199254740991,
      MAX_INTEGER = 1.7976931348623157e+308,
      NAN = 0 / 0;

  /** Used as references for the maximum length and index of an array. */
  var MAX_ARRAY_LENGTH = 4294967295,
      MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
      HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;

  /** Used to associate wrap methods with their bit flags. */
  var wrapFlags = [
    ['ary', WRAP_ARY_FLAG],
    ['bind', WRAP_BIND_FLAG],
    ['bindKey', WRAP_BIND_KEY_FLAG],
    ['curry', WRAP_CURRY_FLAG],
    ['curryRight', WRAP_CURRY_RIGHT_FLAG],
    ['flip', WRAP_FLIP_FLAG],
    ['partial', WRAP_PARTIAL_FLAG],
    ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
    ['rearg', WRAP_REARG_FLAG]
  ];

  /** `Object#toString` result references. */
  var argsTag = '[object Arguments]',
      arrayTag = '[object Array]',
      asyncTag = '[object AsyncFunction]',
      boolTag = '[object Boolean]',
      dateTag = '[object Date]',
      domExcTag = '[object DOMException]',
      errorTag = '[object Error]',
      funcTag = '[object Function]',
      genTag = '[object GeneratorFunction]',
      mapTag = '[object Map]',
      numberTag = '[object Number]',
      nullTag = '[object Null]',
      objectTag = '[object Object]',
      promiseTag = '[object Promise]',
      proxyTag = '[object Proxy]',
      regexpTag = '[object RegExp]',
      setTag = '[object Set]',
      stringTag = '[object String]',
      symbolTag = '[object Symbol]',
      undefinedTag = '[object Undefined]',
      weakMapTag = '[object WeakMap]',
      weakSetTag = '[object WeakSet]';

  var arrayBufferTag = '[object ArrayBuffer]',
      dataViewTag = '[object DataView]',
      float32Tag = '[object Float32Array]',
      float64Tag = '[object Float64Array]',
      int8Tag = '[object Int8Array]',
      int16Tag = '[object Int16Array]',
      int32Tag = '[object Int32Array]',
      uint8Tag = '[object Uint8Array]',
      uint8ClampedTag = '[object Uint8ClampedArray]',
      uint16Tag = '[object Uint16Array]',
      uint32Tag = '[object Uint32Array]';

  /** Used to match empty string literals in compiled template source. */
  var reEmptyStringLeading = /\b__p \+= '';/g,
      reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
      reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;

  /** Used to match HTML entities and HTML characters. */
  var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
      reUnescapedHtml = /[&<>"']/g,
      reHasEscapedHtml = RegExp(reEscapedHtml.source),
      reHasUnescapedHtml = RegExp(reUnescapedHtml.source);

  /** Used to match template delimiters. */
  var reEscape = /<%-([\s\S]+?)%>/g,
      reEvaluate = /<%([\s\S]+?)%>/g,
      reInterpolate = /<%=([\s\S]+?)%>/g;

  /** Used to match property names within property paths. */
  var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
      reIsPlainProp = /^\w*$/,
      rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

  /**
   * Used to match `RegExp`
   * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
   */
  var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
      reHasRegExpChar = RegExp(reRegExpChar.source);

  /** Used to match leading whitespace. */
  var reTrimStart = /^\s+/;

  /** Used to match a single whitespace character. */
  var reWhitespace = /\s/;

  /** Used to match wrap detail comments. */
  var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
      reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
      reSplitDetails = /,? & /;

  /** Used to match words composed of alphanumeric characters. */
  var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;

  /**
   * Used to validate the `validate` option in `_.template` variable.
   *
   * Forbids characters which could potentially change the meaning of the function argument definition:
   * - "()," (modification of function parameters)
   * - "=" (default value)
   * - "[]{}" (destructuring of function parameters)
   * - "/" (beginning of a comment)
   * - whitespace
   */
  var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;

  /** Used to match backslashes in property paths. */
  var reEscapeChar = /\\(\\)?/g;

  /**
   * Used to match
   * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
   */
  var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;

  /** Used to match `RegExp` flags from their coerced string values. */
  var reFlags = /\w*$/;

  /** Used to detect bad signed hexadecimal string values. */
  var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

  /** Used to detect binary string values. */
  var reIsBinary = /^0b[01]+$/i;

  /** Used to detect host constructors (Safari). */
  var reIsHostCtor = /^\[object .+?Constructor\]$/;

  /** Used to detect octal string values. */
  var reIsOctal = /^0o[0-7]+$/i;

  /** Used to detect unsigned integer values. */
  var reIsUint = /^(?:0|[1-9]\d*)$/;

  /** Used to match Latin Unicode letters (excluding mathematical operators). */
  var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;

  /** Used to ensure capturing order of template delimiters. */
  var reNoMatch = /($^)/;

  /** Used to match unescaped characters in compiled string literals. */
  var reUnescapedString = /['\n\r\u2028\u2029\\]/g;

  /** Used to compose unicode character classes. */
  var rsAstralRange = '\\ud800-\\udfff',
      rsComboMarksRange = '\\u0300-\\u036f',
      reComboHalfMarksRange = '\\ufe20-\\ufe2f',
      rsComboSymbolsRange = '\\u20d0-\\u20ff',
      rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
      rsDingbatRange = '\\u2700-\\u27bf',
      rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
      rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
      rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
      rsPunctuationRange = '\\u2000-\\u206f',
      rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
      rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
      rsVarRange = '\\ufe0e\\ufe0f',
      rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;

  /** Used to compose unicode capture groups. */
  var rsApos = "['\u2019]",
      rsAstral = '[' + rsAstralRange + ']',
      rsBreak = '[' + rsBreakRange + ']',
      rsCombo = '[' + rsComboRange + ']',
      rsDigits = '\\d+',
      rsDingbat = '[' + rsDingbatRange + ']',
      rsLower = '[' + rsLowerRange + ']',
      rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
      rsFitz = '\\ud83c[\\udffb-\\udfff]',
      rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
      rsNonAstral = '[^' + rsAstralRange + ']',
      rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
      rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
      rsUpper = '[' + rsUpperRange + ']',
      rsZWJ = '\\u200d';

  /** Used to compose unicode regexes. */
  var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
      rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
      rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
      rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
      reOptMod = rsModifier + '?',
      rsOptVar = '[' + rsVarRange + ']?',
      rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
      rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
      rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
      rsSeq = rsOptVar + reOptMod + rsOptJoin,
      rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
      rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';

  /** Used to match apostrophes. */
  var reApos = RegExp(rsApos, 'g');

  /**
   * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
   * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
   */
  var reComboMark = RegExp(rsCombo, 'g');

  /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');

  /** Used to match complex or compound words. */
  var reUnicodeWord = RegExp([
    rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
    rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
    rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
    rsUpper + '+' + rsOptContrUpper,
    rsOrdUpper,
    rsOrdLower,
    rsDigits,
    rsEmoji
  ].join('|'), 'g');

  /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange  + rsComboRange + rsVarRange + ']');

  /** Used to detect strings that need a more robust regexp to match words. */
  var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;

  /** Used to assign default `context` object properties. */
  var contextProps = [
    'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
    'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
    'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
    'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
    '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
  ];

  /** Used to make template sourceURLs easier to identify. */
  var templateCounter = -1;

  /** Used to identify `toStringTag` values of typed arrays. */
  var typedArrayTags = {};
  typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  typedArrayTags[uint32Tag] = true;
  typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  typedArrayTags[errorTag] = typedArrayTags[funcTag] =
  typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
  typedArrayTags[setTag] = typedArrayTags[stringTag] =
  typedArrayTags[weakMapTag] = false;

  /** Used to identify `toStringTag` values supported by `_.clone`. */
  var cloneableTags = {};
  cloneableTags[argsTag] = cloneableTags[arrayTag] =
  cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
  cloneableTags[boolTag] = cloneableTags[dateTag] =
  cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  cloneableTags[int32Tag] = cloneableTags[mapTag] =
  cloneableTags[numberTag] = cloneableTags[objectTag] =
  cloneableTags[regexpTag] = cloneableTags[setTag] =
  cloneableTags[stringTag] = cloneableTags[symbolTag] =
  cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  cloneableTags[errorTag] = cloneableTags[funcTag] =
  cloneableTags[weakMapTag] = false;

  /** Used to map Latin Unicode letters to basic Latin letters. */
  var deburredLetters = {
    // Latin-1 Supplement block.
    '\xc0': 'A',  '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
    '\xe0': 'a',  '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
    '\xc7': 'C',  '\xe7': 'c',
    '\xd0': 'D',  '\xf0': 'd',
    '\xc8': 'E',  '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
    '\xe8': 'e',  '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
    '\xcc': 'I',  '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
    '\xec': 'i',  '\xed': 'i', '\xee': 'i', '\xef': 'i',
    '\xd1': 'N',  '\xf1': 'n',
    '\xd2': 'O',  '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
    '\xf2': 'o',  '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
    '\xd9': 'U',  '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
    '\xf9': 'u',  '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
    '\xdd': 'Y',  '\xfd': 'y', '\xff': 'y',
    '\xc6': 'Ae', '\xe6': 'ae',
    '\xde': 'Th', '\xfe': 'th',
    '\xdf': 'ss',
    // Latin Extended-A block.
    '\u0100': 'A',  '\u0102': 'A', '\u0104': 'A',
    '\u0101': 'a',  '\u0103': 'a', '\u0105': 'a',
    '\u0106': 'C',  '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
    '\u0107': 'c',  '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
    '\u010e': 'D',  '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
    '\u0112': 'E',  '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
    '\u0113': 'e',  '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
    '\u011c': 'G',  '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
    '\u011d': 'g',  '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
    '\u0124': 'H',  '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
    '\u0128': 'I',  '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
    '\u0129': 'i',  '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
    '\u0134': 'J',  '\u0135': 'j',
    '\u0136': 'K',  '\u0137': 'k', '\u0138': 'k',
    '\u0139': 'L',  '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
    '\u013a': 'l',  '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
    '\u0143': 'N',  '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
    '\u0144': 'n',  '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
    '\u014c': 'O',  '\u014e': 'O', '\u0150': 'O',
    '\u014d': 'o',  '\u014f': 'o', '\u0151': 'o',
    '\u0154': 'R',  '\u0156': 'R', '\u0158': 'R',
    '\u0155': 'r',  '\u0157': 'r', '\u0159': 'r',
    '\u015a': 'S',  '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
    '\u015b': 's',  '\u015d': 's', '\u015f': 's', '\u0161': 's',
    '\u0162': 'T',  '\u0164': 'T', '\u0166': 'T',
    '\u0163': 't',  '\u0165': 't', '\u0167': 't',
    '\u0168': 'U',  '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
    '\u0169': 'u',  '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
    '\u0174': 'W',  '\u0175': 'w',
    '\u0176': 'Y',  '\u0177': 'y', '\u0178': 'Y',
    '\u0179': 'Z',  '\u017b': 'Z', '\u017d': 'Z',
    '\u017a': 'z',  '\u017c': 'z', '\u017e': 'z',
    '\u0132': 'IJ', '\u0133': 'ij',
    '\u0152': 'Oe', '\u0153': 'oe',
    '\u0149': "'n", '\u017f': 's'
  };

  /** Used to map characters to HTML entities. */
  var htmlEscapes = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };

  /** Used to map HTML entities to characters. */
  var htmlUnescapes = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&#39;': "'"
  };

  /** Used to escape characters for inclusion in compiled string literals. */
  var stringEscapes = {
    '\\': '\\',
    "'": "'",
    '\n': 'n',
    '\r': 'r',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  /** Built-in method references without a dependency on `root`. */
  var freeParseFloat = parseFloat,
      freeParseInt = parseInt;

  /** Detect free variable `global` from Node.js. */
  var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g;

  /** Detect free variable `self`. */
  var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

  /** Used as a reference to the global object. */
  var root = freeGlobal || freeSelf || Function('return this')();

  /** Detect free variable `exports`. */
  var freeExports =  true && exports && !exports.nodeType && exports;

  /** Detect free variable `module`. */
  var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module;

  /** Detect the popular CommonJS extension `module.exports`. */
  var moduleExports = freeModule && freeModule.exports === freeExports;

  /** Detect free variable `process` from Node.js. */
  var freeProcess = moduleExports && freeGlobal.process;

  /** Used to access faster Node.js helpers. */
  var nodeUtil = (function() {
    try {
      // Use `util.types` for Node.js 10+.
      var types = freeModule && freeModule.require && freeModule.require('util').types;

      if (types) {
        return types;
      }

      // Legacy `process.binding('util')` for Node.js < 10.
      return freeProcess && freeProcess.binding && freeProcess.binding('util');
    } catch (e) {}
  }());

  /* Node.js helper references. */
  var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
      nodeIsDate = nodeUtil && nodeUtil.isDate,
      nodeIsMap = nodeUtil && nodeUtil.isMap,
      nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
      nodeIsSet = nodeUtil && nodeUtil.isSet,
      nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;

  /*--------------------------------------------------------------------------*/

  /**
   * A faster alternative to `Function#apply`, this function invokes `func`
   * with the `this` binding of `thisArg` and the arguments of `args`.
   *
   * @private
   * @param {Function} func The function to invoke.
   * @param {*} thisArg The `this` binding of `func`.
   * @param {Array} args The arguments to invoke `func` with.
   * @returns {*} Returns the result of `func`.
   */
  function apply(func, thisArg, args) {
    switch (args.length) {
      case 0: return func.call(thisArg);
      case 1: return func.call(thisArg, args[0]);
      case 2: return func.call(thisArg, args[0], args[1]);
      case 3: return func.call(thisArg, args[0], args[1], args[2]);
    }
    return func.apply(thisArg, args);
  }

  /**
   * A specialized version of `baseAggregator` for arrays.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} setter The function to set `accumulator` values.
   * @param {Function} iteratee The iteratee to transform keys.
   * @param {Object} accumulator The initial aggregated object.
   * @returns {Function} Returns `accumulator`.
   */
  function arrayAggregator(array, setter, iteratee, accumulator) {
    var index = -1,
        length = array == null ? 0 : array.length;

    while (++index < length) {
      var value = array[index];
      setter(accumulator, value, iteratee(value), array);
    }
    return accumulator;
  }

  /**
   * A specialized version of `_.forEach` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns `array`.
   */
  function arrayEach(array, iteratee) {
    var index = -1,
        length = array == null ? 0 : array.length;

    while (++index < length) {
      if (iteratee(array[index], index, array) === false) {
        break;
      }
    }
    return array;
  }

  /**
   * A specialized version of `_.forEachRight` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns `array`.
   */
  function arrayEachRight(array, iteratee) {
    var length = array == null ? 0 : array.length;

    while (length--) {
      if (iteratee(array[length], length, array) === false) {
        break;
      }
    }
    return array;
  }

  /**
   * A specialized version of `_.every` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} predicate The function invoked per iteration.
   * @returns {boolean} Returns `true` if all elements pass the predicate check,
   *  else `false`.
   */
  function arrayEvery(array, predicate) {
    var index = -1,
        length = array == null ? 0 : array.length;

    while (++index < length) {
      if (!predicate(array[index], index, array)) {
        return false;
      }
    }
    return true;
  }

  /**
   * A specialized version of `_.filter` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} predicate The function invoked per iteration.
   * @returns {Array} Returns the new filtered array.
   */
  function arrayFilter(array, predicate) {
    var index = -1,
        length = array == null ? 0 : array.length,
        resIndex = 0,
        result = [];

    while (++index < length) {
      var value = array[index];
      if (predicate(value, index, array)) {
        result[resIndex++] = value;
      }
    }
    return result;
  }

  /**
   * A specialized version of `_.includes` for arrays without support for
   * specifying an index to search from.
   *
   * @private
   * @param {Array} [array] The array to inspect.
   * @param {*} target The value to search for.
   * @returns {boolean} Returns `true` if `target` is found, else `false`.
   */
  function arrayIncludes(array, value) {
    var length = array == null ? 0 : array.length;
    return !!length && baseIndexOf(array, value, 0) > -1;
  }

  /**
   * This function is like `arrayIncludes` except that it accepts a comparator.
   *
   * @private
   * @param {Array} [array] The array to inspect.
   * @param {*} target The value to search for.
   * @param {Function} comparator The comparator invoked per element.
   * @returns {boolean} Returns `true` if `target` is found, else `false`.
   */
  function arrayIncludesWith(array, value, comparator) {
    var index = -1,
        length = array == null ? 0 : array.length;

    while (++index < length) {
      if (comparator(value, array[index])) {
        return true;
      }
    }
    return false;
  }

  /**
   * A specialized version of `_.map` for arrays without support for iteratee
   * shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns the new mapped array.
   */
  function arrayMap(array, iteratee) {
    var index = -1,
        length = array == null ? 0 : array.length,
        result = Array(length);

    while (++index < length) {
      result[index] = iteratee(array[index], index, array);
    }
    return result;
  }

  /**
   * Appends the elements of `values` to `array`.
   *
   * @private
   * @param {Array} array The array to modify.
   * @param {Array} values The values to append.
   * @returns {Array} Returns `array`.
   */
  function arrayPush(array, values) {
    var index = -1,
        length = values.length,
        offset = array.length;

    while (++index < length) {
      array[offset + index] = values[index];
    }
    return array;
  }

  /**
   * A specialized version of `_.reduce` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @param {*} [accumulator] The initial value.
   * @param {boolean} [initAccum] Specify using the first element of `array` as
   *  the initial value.
   * @returns {*} Returns the accumulated value.
   */
  function arrayReduce(array, iteratee, accumulator, initAccum) {
    var index = -1,
        length = array == null ? 0 : array.length;

    if (initAccum && length) {
      accumulator = array[++index];
    }
    while (++index < length) {
      accumulator = iteratee(accumulator, array[index], index, array);
    }
    return accumulator;
  }

  /**
   * A specialized version of `_.reduceRight` for arrays without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @param {*} [accumulator] The initial value.
   * @param {boolean} [initAccum] Specify using the last element of `array` as
   *  the initial value.
   * @returns {*} Returns the accumulated value.
   */
  function arrayReduceRight(array, iteratee, accumulator, initAccum) {
    var length = array == null ? 0 : array.length;
    if (initAccum && length) {
      accumulator = array[--length];
    }
    while (length--) {
      accumulator = iteratee(accumulator, array[length], length, array);
    }
    return accumulator;
  }

  /**
   * A specialized version of `_.some` for arrays without support for iteratee
   * shorthands.
   *
   * @private
   * @param {Array} [array] The array to iterate over.
   * @param {Function} predicate The function invoked per iteration.
   * @returns {boolean} Returns `true` if any element passes the predicate check,
   *  else `false`.
   */
  function arraySome(array, predicate) {
    var index = -1,
        length = array == null ? 0 : array.length;

    while (++index < length) {
      if (predicate(array[index], index, array)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Gets the size of an ASCII `string`.
   *
   * @private
   * @param {string} string The string inspect.
   * @returns {number} Returns the string size.
   */
  var asciiSize = baseProperty('length');

  /**
   * Converts an ASCII `string` to an array.
   *
   * @private
   * @param {string} string The string to convert.
   * @returns {Array} Returns the converted array.
   */
  function asciiToArray(string) {
    return string.split('');
  }

  /**
   * Splits an ASCII `string` into an array of its words.
   *
   * @private
   * @param {string} The string to inspect.
   * @returns {Array} Returns the words of `string`.
   */
  function asciiWords(string) {
    return string.match(reAsciiWord) || [];
  }

  /**
   * The base implementation of methods like `_.findKey` and `_.findLastKey`,
   * without support for iteratee shorthands, which iterates over `collection`
   * using `eachFunc`.
   *
   * @private
   * @param {Array|Object} collection The collection to inspect.
   * @param {Function} predicate The function invoked per iteration.
   * @param {Function} eachFunc The function to iterate over `collection`.
   * @returns {*} Returns the found element or its key, else `undefined`.
   */
  function baseFindKey(collection, predicate, eachFunc) {
    var result;
    eachFunc(collection, function(value, key, collection) {
      if (predicate(value, key, collection)) {
        result = key;
        return false;
      }
    });
    return result;
  }

  /**
   * The base implementation of `_.findIndex` and `_.findLastIndex` without
   * support for iteratee shorthands.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {Function} predicate The function invoked per iteration.
   * @param {number} fromIndex The index to search from.
   * @param {boolean} [fromRight] Specify iterating from right to left.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */
  function baseFindIndex(array, predicate, fromIndex, fromRight) {
    var length = array.length,
        index = fromIndex + (fromRight ? 1 : -1);

    while ((fromRight ? index-- : ++index < length)) {
      if (predicate(array[index], index, array)) {
        return index;
      }
    }
    return -1;
  }

  /**
   * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */
  function baseIndexOf(array, value, fromIndex) {
    return value === value
      ? strictIndexOf(array, value, fromIndex)
      : baseFindIndex(array, baseIsNaN, fromIndex);
  }

  /**
   * This function is like `baseIndexOf` except that it accepts a comparator.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @param {Function} comparator The comparator invoked per element.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */
  function baseIndexOfWith(array, value, fromIndex, comparator) {
    var index = fromIndex - 1,
        length = array.length;

    while (++index < length) {
      if (comparator(array[index], value)) {
        return index;
      }
    }
    return -1;
  }

  /**
   * The base implementation of `_.isNaN` without support for number objects.
   *
   * @private
   * @param {*} value The value to check.
   * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
   */
  function baseIsNaN(value) {
    return value !== value;
  }

  /**
   * The base implementation of `_.mean` and `_.meanBy` without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} array The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {number} Returns the mean.
   */
  function baseMean(array, iteratee) {
    var length = array == null ? 0 : array.length;
    return length ? (baseSum(array, iteratee) / length) : NAN;
  }

  /**
   * The base implementation of `_.property` without support for deep paths.
   *
   * @private
   * @param {string} key The key of the property to get.
   * @returns {Function} Returns the new accessor function.
   */
  function baseProperty(key) {
    return function(object) {
      return object == null ? undefined : object[key];
    };
  }

  /**
   * The base implementation of `_.propertyOf` without support for deep paths.
   *
   * @private
   * @param {Object} object The object to query.
   * @returns {Function} Returns the new accessor function.
   */
  function basePropertyOf(object) {
    return function(key) {
      return object == null ? undefined : object[key];
    };
  }

  /**
   * The base implementation of `_.reduce` and `_.reduceRight`, without support
   * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
   *
   * @private
   * @param {Array|Object} collection The collection to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @param {*} accumulator The initial value.
   * @param {boolean} initAccum Specify using the first or last element of
   *  `collection` as the initial value.
   * @param {Function} eachFunc The function to iterate over `collection`.
   * @returns {*} Returns the accumulated value.
   */
  function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
    eachFunc(collection, function(value, index, collection) {
      accumulator = initAccum
        ? (initAccum = false, value)
        : iteratee(accumulator, value, index, collection);
    });
    return accumulator;
  }

  /**
   * The base implementation of `_.sortBy` which uses `comparer` to define the
   * sort order of `array` and replaces criteria objects with their corresponding
   * values.
   *
   * @private
   * @param {Array} array The array to sort.
   * @param {Function} comparer The function to define sort order.
   * @returns {Array} Returns `array`.
   */
  function baseSortBy(array, comparer) {
    var length = array.length;

    array.sort(comparer);
    while (length--) {
      array[length] = array[length].value;
    }
    return array;
  }

  /**
   * The base implementation of `_.sum` and `_.sumBy` without support for
   * iteratee shorthands.
   *
   * @private
   * @param {Array} array The array to iterate over.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {number} Returns the sum.
   */
  function baseSum(array, iteratee) {
    var result,
        index = -1,
        length = array.length;

    while (++index < length) {
      var current = iteratee(array[index]);
      if (current !== undefined) {
        result = result === undefined ? current : (result + current);
      }
    }
    return result;
  }

  /**
   * The base implementation of `_.times` without support for iteratee shorthands
   * or max array length checks.
   *
   * @private
   * @param {number} n The number of times to invoke `iteratee`.
   * @param {Function} iteratee The function invoked per iteration.
   * @returns {Array} Returns the array of results.
   */
  function baseTimes(n, iteratee) {
    var index = -1,
        result = Array(n);

    while (++index < n) {
      result[index] = iteratee(index);
    }
    return result;
  }

  /**
   * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
   * of key-value pairs for `object` corresponding to the property names of `props`.
   *
   * @private
   * @param {Object} object The object to query.
   * @param {Array} props The property names to get values for.
   * @returns {Object} Returns the key-value pairs.
   */
  function baseToPairs(object, props) {
    return arrayMap(props, function(key) {
      return [key, object[key]];
    });
  }

  /**
   * The base implementation of `_.trim`.
   *
   * @private
   * @param {string} string The string to trim.
   * @returns {string} Returns the trimmed string.
   */
  function baseTrim(string) {
    return string
      ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
      : string;
  }

  /**
   * The base implementation of `_.unary` without support for storing metadata.
   *
   * @private
   * @param {Function} func The function to cap arguments for.
   * @returns {Function} Returns the new capped function.
   */
  function baseUnary(func) {
    return function(value) {
      return func(value);
    };
  }

  /**
   * The base implementation of `_.values` and `_.valuesIn` which creates an
   * array of `object` property values corresponding to the property names
   * of `props`.
   *
   * @private
   * @param {Object} object The object to query.
   * @param {Array} props The property names to get values for.
   * @returns {Object} Returns the array of property values.
   */
  function baseValues(object, props) {
    return arrayMap(props, function(key) {
      return object[key];
    });
  }

  /**
   * Checks if a `cache` value for `key` exists.
   *
   * @private
   * @param {Object} cache The cache to query.
   * @param {string} key The key of the entry to check.
   * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
   */
  function cacheHas(cache, key) {
    return cache.has(key);
  }

  /**
   * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
   * that is not found in the character symbols.
   *
   * @private
   * @param {Array} strSymbols The string symbols to inspect.
   * @param {Array} chrSymbols The character symbols to find.
   * @returns {number} Returns the index of the first unmatched string symbol.
   */
  function charsStartIndex(strSymbols, chrSymbols) {
    var index = -1,
        length = strSymbols.length;

    while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
    return index;
  }

  /**
   * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
   * that is not found in the character symbols.
   *
   * @private
   * @param {Array} strSymbols The string symbols to inspect.
   * @param {Array} chrSymbols The character symbols to find.
   * @returns {number} Returns the index of the last unmatched string symbol.
   */
  function charsEndIndex(strSymbols, chrSymbols) {
    var index = strSymbols.length;

    while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
    return index;
  }

  /**
   * Gets the number of `placeholder` occurrences in `array`.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} placeholder The placeholder to search for.
   * @returns {number} Returns the placeholder count.
   */
  function countHolders(array, placeholder) {
    var length = array.length,
        result = 0;

    while (length--) {
      if (array[length] === placeholder) {
        ++result;
      }
    }
    return result;
  }

  /**
   * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
   * letters to basic Latin letters.
   *
   * @private
   * @param {string} letter The matched letter to deburr.
   * @returns {string} Returns the deburred letter.
   */
  var deburrLetter = basePropertyOf(deburredLetters);

  /**
   * Used by `_.escape` to convert characters to HTML entities.
   *
   * @private
   * @param {string} chr The matched character to escape.
   * @returns {string} Returns the escaped character.
   */
  var escapeHtmlChar = basePropertyOf(htmlEscapes);

  /**
   * Used by `_.template` to escape characters for inclusion in compiled string literals.
   *
   * @private
   * @param {string} chr The matched character to escape.
   * @returns {string} Returns the escaped character.
   */
  function escapeStringChar(chr) {
    return '\\' + stringEscapes[chr];
  }

  /**
   * Gets the value at `key` of `object`.
   *
   * @private
   * @param {Object} [object] The object to query.
   * @param {string} key The key of the property to get.
   * @returns {*} Returns the property value.
   */
  function getValue(object, key) {
    return object == null ? undefined : object[key];
  }

  /**
   * Checks if `string` contains Unicode symbols.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {boolean} Returns `true` if a symbol is found, else `false`.
   */
  function hasUnicode(string) {
    return reHasUnicode.test(string);
  }

  /**
   * Checks if `string` contains a word composed of Unicode symbols.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {boolean} Returns `true` if a word is found, else `false`.
   */
  function hasUnicodeWord(string) {
    return reHasUnicodeWord.test(string);
  }

  /**
   * Converts `iterator` to an array.
   *
   * @private
   * @param {Object} iterator The iterator to convert.
   * @returns {Array} Returns the converted array.
   */
  function iteratorToArray(iterator) {
    var data,
        result = [];

    while (!(data = iterator.next()).done) {
      result.push(data.value);
    }
    return result;
  }

  /**
   * Converts `map` to its key-value pairs.
   *
   * @private
   * @param {Object} map The map to convert.
   * @returns {Array} Returns the key-value pairs.
   */
  function mapToArray(map) {
    var index = -1,
        result = Array(map.size);

    map.forEach(function(value, key) {
      result[++index] = [key, value];
    });
    return result;
  }

  /**
   * Creates a unary function that invokes `func` with its argument transformed.
   *
   * @private
   * @param {Function} func The function to wrap.
   * @param {Function} transform The argument transform.
   * @returns {Function} Returns the new function.
   */
  function overArg(func, transform) {
    return function(arg) {
      return func(transform(arg));
    };
  }

  /**
   * Replaces all `placeholder` elements in `array` with an internal placeholder
   * and returns an array of their indexes.
   *
   * @private
   * @param {Array} array The array to modify.
   * @param {*} placeholder The placeholder to replace.
   * @returns {Array} Returns the new array of placeholder indexes.
   */
  function replaceHolders(array, placeholder) {
    var index = -1,
        length = array.length,
        resIndex = 0,
        result = [];

    while (++index < length) {
      var value = array[index];
      if (value === placeholder || value === PLACEHOLDER) {
        array[index] = PLACEHOLDER;
        result[resIndex++] = index;
      }
    }
    return result;
  }

  /**
   * Converts `set` to an array of its values.
   *
   * @private
   * @param {Object} set The set to convert.
   * @returns {Array} Returns the values.
   */
  function setToArray(set) {
    var index = -1,
        result = Array(set.size);

    set.forEach(function(value) {
      result[++index] = value;
    });
    return result;
  }

  /**
   * Converts `set` to its value-value pairs.
   *
   * @private
   * @param {Object} set The set to convert.
   * @returns {Array} Returns the value-value pairs.
   */
  function setToPairs(set) {
    var index = -1,
        result = Array(set.size);

    set.forEach(function(value) {
      result[++index] = [value, value];
    });
    return result;
  }

  /**
   * A specialized version of `_.indexOf` which performs strict equality
   * comparisons of values, i.e. `===`.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */
  function strictIndexOf(array, value, fromIndex) {
    var index = fromIndex - 1,
        length = array.length;

    while (++index < length) {
      if (array[index] === value) {
        return index;
      }
    }
    return -1;
  }

  /**
   * A specialized version of `_.lastIndexOf` which performs strict equality
   * comparisons of values, i.e. `===`.
   *
   * @private
   * @param {Array} array The array to inspect.
   * @param {*} value The value to search for.
   * @param {number} fromIndex The index to search from.
   * @returns {number} Returns the index of the matched value, else `-1`.
   */
  function strictLastIndexOf(array, value, fromIndex) {
    var index = fromIndex + 1;
    while (index--) {
      if (array[index] === value) {
        return index;
      }
    }
    return index;
  }

  /**
   * Gets the number of symbols in `string`.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {number} Returns the string size.
   */
  function stringSize(string) {
    return hasUnicode(string)
      ? unicodeSize(string)
      : asciiSize(string);
  }

  /**
   * Converts `string` to an array.
   *
   * @private
   * @param {string} string The string to convert.
   * @returns {Array} Returns the converted array.
   */
  function stringToArray(string) {
    return hasUnicode(string)
      ? unicodeToArray(string)
      : asciiToArray(string);
  }

  /**
   * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
   * character of `string`.
   *
   * @private
   * @param {string} string The string to inspect.
   * @returns {number} Returns the index of the last non-whitespace character.
   */
  function trimmedEndIndex(string) {
    var index = string.length;

    while (index-- && reWhitespace.test(string.charAt(index))) {}
    return index;
  }

  /**
   * Used by `_.unescape` to convert HTML entities to characters.
   *
   * @private
   * @param {string} chr The matched character to unescape.
   * @returns {string} Returns the unescaped character.
   */
  var unescapeHtmlChar = basePropertyOf(htmlUnescapes);

  /**
   * Gets the size of a Unicode `string`.
   *
   * @private
   * @param {string} string The string inspect.
   * @returns {number} Returns the string size.
   */
  function unicodeSize(string) {
    var result = reUnicode.lastIndex = 0;
    while (reUnicode.test(string)) {
      ++result;
    }
    return result;
  }

  /**
   * Converts a Unicode `string` to an array.
   *
   * @private
   * @param {string} string The string to convert.
   * @returns {Array} Returns the converted array.
   */
  function unicodeToArray(string) {
    return string.match(reUnicode) || [];
  }

  /**
   * Splits a Unicode `string` into an array of its words.
   *
   * @private
   * @param {string} The string to inspect.
   * @returns {Array} Returns the words of `string`.
   */
  function unicodeWords(string) {
    return string.match(reUnicodeWord) || [];
  }

  /*--------------------------------------------------------------------------*/

  /**
   * Create a new pristine `lodash` function using the `context` object.
   *
   * @static
   * @memberOf _
   * @since 1.1.0
   * @category Util
   * @param {Object} [context=root] The context object.
   * @returns {Function} Returns a new `lodash` function.
   * @example
   *
   * _.mixin({ 'foo': _.constant('foo') });
   *
   * var lodash = _.runInContext();
   * lodash.mixin({ 'bar': lodash.constant('bar') });
   *
   * _.isFunction(_.foo);
   * // => true
   * _.isFunction(_.bar);
   * // => false
   *
   * lodash.isFunction(lodash.foo);
   * // => false
   * lodash.isFunction(lodash.bar);
   * // => true
   *
   * // Create a suped-up `defer` in Node.js.
   * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
   */
  var runInContext = (function runInContext(context) {
    context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));

    /** Built-in constructor references. */
    var Array = context.Array,
        Date = context.Date,
        Error = context.Error,
        Function = context.Function,
        Math = context.Math,
        Object = context.Object,
        RegExp = context.RegExp,
        String = context.String,
        TypeError = context.TypeError;

    /** Used for built-in method references. */
    var arrayProto = Array.prototype,
        funcProto = Function.prototype,
        objectProto = Object.prototype;

    /** Used to detect overreaching core-js shims. */
    var coreJsData = context['__core-js_shared__'];

    /** Used to resolve the decompiled source of functions. */
    var funcToString = funcProto.toString;

    /** Used to check objects for own properties. */
    var hasOwnProperty = objectProto.hasOwnProperty;

    /** Used to generate unique IDs. */
    var idCounter = 0;

    /** Used to detect methods masquerading as native. */
    var maskSrcKey = (function() {
      var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
      return uid ? ('Symbol(src)_1.' + uid) : '';
    }());

    /**
     * Used to resolve the
     * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
     * of values.
     */
    var nativeObjectToString = objectProto.toString;

    /** Used to infer the `Object` constructor. */
    var objectCtorString = funcToString.call(Object);

    /** Used to restore the original `_` reference in `_.noConflict`. */
    var oldDash = root._;

    /** Used to detect if a method is native. */
    var reIsNative = RegExp('^' +
      funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
      .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
    );

    /** Built-in value references. */
    var Buffer = moduleExports ? context.Buffer : undefined,
        Symbol = context.Symbol,
        Uint8Array = context.Uint8Array,
        allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
        getPrototype = overArg(Object.getPrototypeOf, Object),
        objectCreate = Object.create,
        propertyIsEnumerable = objectProto.propertyIsEnumerable,
        splice = arrayProto.splice,
        spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
        symIterator = Symbol ? Symbol.iterator : undefined,
        symToStringTag = Symbol ? Symbol.toStringTag : undefined;

    var defineProperty = (function() {
      try {
        var func = getNative(Object, 'defineProperty');
        func({}, '', {});
        return func;
      } catch (e) {}
    }());

    /** Mocked built-ins. */
    var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
        ctxNow = Date && Date.now !== root.Date.now && Date.now,
        ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;

    /* Built-in method references for those with the same name as other `lodash` methods. */
    var nativeCeil = Math.ceil,
        nativeFloor = Math.floor,
        nativeGetSymbols = Object.getOwnPropertySymbols,
        nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
        nativeIsFinite = context.isFinite,
        nativeJoin = arrayProto.join,
        nativeKeys = overArg(Object.keys, Object),
        nativeMax = Math.max,
        nativeMin = Math.min,
        nativeNow = Date.now,
        nativeParseInt = context.parseInt,
        nativeRandom = Math.random,
        nativeReverse = arrayProto.reverse;

    /* Built-in method references that are verified to be native. */
    var DataView = getNative(context, 'DataView'),
        Map = getNative(context, 'Map'),
        Promise = getNative(context, 'Promise'),
        Set = getNative(context, 'Set'),
        WeakMap = getNative(context, 'WeakMap'),
        nativeCreate = getNative(Object, 'create');

    /** Used to store function metadata. */
    var metaMap = WeakMap && new WeakMap;

    /** Used to lookup unminified function names. */
    var realNames = {};

    /** Used to detect maps, sets, and weakmaps. */
    var dataViewCtorString = toSource(DataView),
        mapCtorString = toSource(Map),
        promiseCtorString = toSource(Promise),
        setCtorString = toSource(Set),
        weakMapCtorString = toSource(WeakMap);

    /** Used to convert symbols to primitives and strings. */
    var symbolProto = Symbol ? Symbol.prototype : undefined,
        symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
        symbolToString = symbolProto ? symbolProto.toString : undefined;

    /*------------------------------------------------------------------------*/

    /**
     * Creates a `lodash` object which wraps `value` to enable implicit method
     * chain sequences. Methods that operate on and return arrays, collections,
     * and functions can be chained together. Methods that retrieve a single value
     * or may return a primitive value will automatically end the chain sequence
     * and return the unwrapped value. Otherwise, the value must be unwrapped
     * with `_#value`.
     *
     * Explicit chain sequences, which must be unwrapped with `_#value`, may be
     * enabled using `_.chain`.
     *
     * The execution of chained methods is lazy, that is, it's deferred until
     * `_#value` is implicitly or explicitly called.
     *
     * Lazy evaluation allows several methods to support shortcut fusion.
     * Shortcut fusion is an optimization to merge iteratee calls; this avoids
     * the creation of intermediate arrays and can greatly reduce the number of
     * iteratee executions. Sections of a chain sequence qualify for shortcut
     * fusion if the section is applied to an array and iteratees accept only
     * one argument. The heuristic for whether a section qualifies for shortcut
     * fusion is subject to change.
     *
     * Chaining is supported in custom builds as long as the `_#value` method is
     * directly or indirectly included in the build.
     *
     * In addition to lodash methods, wrappers have `Array` and `String` methods.
     *
     * The wrapper `Array` methods are:
     * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
     *
     * The wrapper `String` methods are:
     * `replace` and `split`
     *
     * The wrapper methods that support shortcut fusion are:
     * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
     * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
     * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
     *
     * The chainable wrapper methods are:
     * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
     * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
     * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
     * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
     * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
     * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
     * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
     * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
     * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
     * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
     * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
     * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
     * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
     * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
     * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
     * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
     * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
     * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
     * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
     * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
     * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
     * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
     * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
     * `zipObject`, `zipObjectDeep`, and `zipWith`
     *
     * The wrapper methods that are **not** chainable by default are:
     * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
     * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
     * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
     * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
     * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
     * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
     * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
     * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
     * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
     * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
     * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
     * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
     * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
     * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
     * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
     * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
     * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
     * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
     * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
     * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
     * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
     * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
     * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
     * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
     * `upperFirst`, `value`, and `words`
     *
     * @name _
     * @constructor
     * @category Seq
     * @param {*} value The value to wrap in a `lodash` instance.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var wrapped = _([1, 2, 3]);
     *
     * // Returns an unwrapped value.
     * wrapped.reduce(_.add);
     * // => 6
     *
     * // Returns a wrapped value.
     * var squares = wrapped.map(square);
     *
     * _.isArray(squares);
     * // => false
     *
     * _.isArray(squares.value());
     * // => true
     */
    function lodash(value) {
      if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
        if (value instanceof LodashWrapper) {
          return value;
        }
        if (hasOwnProperty.call(value, '__wrapped__')) {
          return wrapperClone(value);
        }
      }
      return new LodashWrapper(value);
    }

    /**
     * The base implementation of `_.create` without support for assigning
     * properties to the created object.
     *
     * @private
     * @param {Object} proto The object to inherit from.
     * @returns {Object} Returns the new object.
     */
    var baseCreate = (function() {
      function object() {}
      return function(proto) {
        if (!isObject(proto)) {
          return {};
        }
        if (objectCreate) {
          return objectCreate(proto);
        }
        object.prototype = proto;
        var result = new object;
        object.prototype = undefined;
        return result;
      };
    }());

    /**
     * The function whose prototype chain sequence wrappers inherit from.
     *
     * @private
     */
    function baseLodash() {
      // No operation performed.
    }

    /**
     * The base constructor for creating `lodash` wrapper objects.
     *
     * @private
     * @param {*} value The value to wrap.
     * @param {boolean} [chainAll] Enable explicit method chain sequences.
     */
    function LodashWrapper(value, chainAll) {
      this.__wrapped__ = value;
      this.__actions__ = [];
      this.__chain__ = !!chainAll;
      this.__index__ = 0;
      this.__values__ = undefined;
    }

    /**
     * By default, the template delimiters used by lodash are like those in
     * embedded Ruby (ERB) as well as ES2015 template strings. Change the
     * following template settings to use alternative delimiters.
     *
     * @static
     * @memberOf _
     * @type {Object}
     */
    lodash.templateSettings = {

      /**
       * Used to detect `data` property values to be HTML-escaped.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */
      'escape': reEscape,

      /**
       * Used to detect code to be evaluated.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */
      'evaluate': reEvaluate,

      /**
       * Used to detect `data` property values to inject.
       *
       * @memberOf _.templateSettings
       * @type {RegExp}
       */
      'interpolate': reInterpolate,

      /**
       * Used to reference the data object in the template text.
       *
       * @memberOf _.templateSettings
       * @type {string}
       */
      'variable': '',

      /**
       * Used to import variables into the compiled template.
       *
       * @memberOf _.templateSettings
       * @type {Object}
       */
      'imports': {

        /**
         * A reference to the `lodash` function.
         *
         * @memberOf _.templateSettings.imports
         * @type {Function}
         */
        '_': lodash
      }
    };

    // Ensure wrappers are instances of `baseLodash`.
    lodash.prototype = baseLodash.prototype;
    lodash.prototype.constructor = lodash;

    LodashWrapper.prototype = baseCreate(baseLodash.prototype);
    LodashWrapper.prototype.constructor = LodashWrapper;

    /*------------------------------------------------------------------------*/

    /**
     * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
     *
     * @private
     * @constructor
     * @param {*} value The value to wrap.
     */
    function LazyWrapper(value) {
      this.__wrapped__ = value;
      this.__actions__ = [];
      this.__dir__ = 1;
      this.__filtered__ = false;
      this.__iteratees__ = [];
      this.__takeCount__ = MAX_ARRAY_LENGTH;
      this.__views__ = [];
    }

    /**
     * Creates a clone of the lazy wrapper object.
     *
     * @private
     * @name clone
     * @memberOf LazyWrapper
     * @returns {Object} Returns the cloned `LazyWrapper` object.
     */
    function lazyClone() {
      var result = new LazyWrapper(this.__wrapped__);
      result.__actions__ = copyArray(this.__actions__);
      result.__dir__ = this.__dir__;
      result.__filtered__ = this.__filtered__;
      result.__iteratees__ = copyArray(this.__iteratees__);
      result.__takeCount__ = this.__takeCount__;
      result.__views__ = copyArray(this.__views__);
      return result;
    }

    /**
     * Reverses the direction of lazy iteration.
     *
     * @private
     * @name reverse
     * @memberOf LazyWrapper
     * @returns {Object} Returns the new reversed `LazyWrapper` object.
     */
    function lazyReverse() {
      if (this.__filtered__) {
        var result = new LazyWrapper(this);
        result.__dir__ = -1;
        result.__filtered__ = true;
      } else {
        result = this.clone();
        result.__dir__ *= -1;
      }
      return result;
    }

    /**
     * Extracts the unwrapped value from its lazy wrapper.
     *
     * @private
     * @name value
     * @memberOf LazyWrapper
     * @returns {*} Returns the unwrapped value.
     */
    function lazyValue() {
      var array = this.__wrapped__.value(),
          dir = this.__dir__,
          isArr = isArray(array),
          isRight = dir < 0,
          arrLength = isArr ? array.length : 0,
          view = getView(0, arrLength, this.__views__),
          start = view.start,
          end = view.end,
          length = end - start,
          index = isRight ? end : (start - 1),
          iteratees = this.__iteratees__,
          iterLength = iteratees.length,
          resIndex = 0,
          takeCount = nativeMin(length, this.__takeCount__);

      if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
        return baseWrapperValue(array, this.__actions__);
      }
      var result = [];

      outer:
      while (length-- && resIndex < takeCount) {
        index += dir;

        var iterIndex = -1,
            value = array[index];

        while (++iterIndex < iterLength) {
          var data = iteratees[iterIndex],
              iteratee = data.iteratee,
              type = data.type,
              computed = iteratee(value);

          if (type == LAZY_MAP_FLAG) {
            value = computed;
          } else if (!computed) {
            if (type == LAZY_FILTER_FLAG) {
              continue outer;
            } else {
              break outer;
            }
          }
        }
        result[resIndex++] = value;
      }
      return result;
    }

    // Ensure `LazyWrapper` is an instance of `baseLodash`.
    LazyWrapper.prototype = baseCreate(baseLodash.prototype);
    LazyWrapper.prototype.constructor = LazyWrapper;

    /*------------------------------------------------------------------------*/

    /**
     * Creates a hash object.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */
    function Hash(entries) {
      var index = -1,
          length = entries == null ? 0 : entries.length;

      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }

    /**
     * Removes all key-value entries from the hash.
     *
     * @private
     * @name clear
     * @memberOf Hash
     */
    function hashClear() {
      this.__data__ = nativeCreate ? nativeCreate(null) : {};
      this.size = 0;
    }

    /**
     * Removes `key` and its value from the hash.
     *
     * @private
     * @name delete
     * @memberOf Hash
     * @param {Object} hash The hash to modify.
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */
    function hashDelete(key) {
      var result = this.has(key) && delete this.__data__[key];
      this.size -= result ? 1 : 0;
      return result;
    }

    /**
     * Gets the hash value for `key`.
     *
     * @private
     * @name get
     * @memberOf Hash
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */
    function hashGet(key) {
      var data = this.__data__;
      if (nativeCreate) {
        var result = data[key];
        return result === HASH_UNDEFINED ? undefined : result;
      }
      return hasOwnProperty.call(data, key) ? data[key] : undefined;
    }

    /**
     * Checks if a hash value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf Hash
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */
    function hashHas(key) {
      var data = this.__data__;
      return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
    }

    /**
     * Sets the hash `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf Hash
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the hash instance.
     */
    function hashSet(key, value) {
      var data = this.__data__;
      this.size += this.has(key) ? 0 : 1;
      data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
      return this;
    }

    // Add methods to `Hash`.
    Hash.prototype.clear = hashClear;
    Hash.prototype['delete'] = hashDelete;
    Hash.prototype.get = hashGet;
    Hash.prototype.has = hashHas;
    Hash.prototype.set = hashSet;

    /*------------------------------------------------------------------------*/

    /**
     * Creates an list cache object.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */
    function ListCache(entries) {
      var index = -1,
          length = entries == null ? 0 : entries.length;

      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }

    /**
     * Removes all key-value entries from the list cache.
     *
     * @private
     * @name clear
     * @memberOf ListCache
     */
    function listCacheClear() {
      this.__data__ = [];
      this.size = 0;
    }

    /**
     * Removes `key` and its value from the list cache.
     *
     * @private
     * @name delete
     * @memberOf ListCache
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */
    function listCacheDelete(key) {
      var data = this.__data__,
          index = assocIndexOf(data, key);

      if (index < 0) {
        return false;
      }
      var lastIndex = data.length - 1;
      if (index == lastIndex) {
        data.pop();
      } else {
        splice.call(data, index, 1);
      }
      --this.size;
      return true;
    }

    /**
     * Gets the list cache value for `key`.
     *
     * @private
     * @name get
     * @memberOf ListCache
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */
    function listCacheGet(key) {
      var data = this.__data__,
          index = assocIndexOf(data, key);

      return index < 0 ? undefined : data[index][1];
    }

    /**
     * Checks if a list cache value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf ListCache
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */
    function listCacheHas(key) {
      return assocIndexOf(this.__data__, key) > -1;
    }

    /**
     * Sets the list cache `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf ListCache
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the list cache instance.
     */
    function listCacheSet(key, value) {
      var data = this.__data__,
          index = assocIndexOf(data, key);

      if (index < 0) {
        ++this.size;
        data.push([key, value]);
      } else {
        data[index][1] = value;
      }
      return this;
    }

    // Add methods to `ListCache`.
    ListCache.prototype.clear = listCacheClear;
    ListCache.prototype['delete'] = listCacheDelete;
    ListCache.prototype.get = listCacheGet;
    ListCache.prototype.has = listCacheHas;
    ListCache.prototype.set = listCacheSet;

    /*------------------------------------------------------------------------*/

    /**
     * Creates a map cache object to store key-value pairs.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */
    function MapCache(entries) {
      var index = -1,
          length = entries == null ? 0 : entries.length;

      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }

    /**
     * Removes all key-value entries from the map.
     *
     * @private
     * @name clear
     * @memberOf MapCache
     */
    function mapCacheClear() {
      this.size = 0;
      this.__data__ = {
        'hash': new Hash,
        'map': new (Map || ListCache),
        'string': new Hash
      };
    }

    /**
     * Removes `key` and its value from the map.
     *
     * @private
     * @name delete
     * @memberOf MapCache
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */
    function mapCacheDelete(key) {
      var result = getMapData(this, key)['delete'](key);
      this.size -= result ? 1 : 0;
      return result;
    }

    /**
     * Gets the map value for `key`.
     *
     * @private
     * @name get
     * @memberOf MapCache
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */
    function mapCacheGet(key) {
      return getMapData(this, key).get(key);
    }

    /**
     * Checks if a map value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf MapCache
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */
    function mapCacheHas(key) {
      return getMapData(this, key).has(key);
    }

    /**
     * Sets the map `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf MapCache
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the map cache instance.
     */
    function mapCacheSet(key, value) {
      var data = getMapData(this, key),
          size = data.size;

      data.set(key, value);
      this.size += data.size == size ? 0 : 1;
      return this;
    }

    // Add methods to `MapCache`.
    MapCache.prototype.clear = mapCacheClear;
    MapCache.prototype['delete'] = mapCacheDelete;
    MapCache.prototype.get = mapCacheGet;
    MapCache.prototype.has = mapCacheHas;
    MapCache.prototype.set = mapCacheSet;

    /*------------------------------------------------------------------------*/

    /**
     *
     * Creates an array cache object to store unique values.
     *
     * @private
     * @constructor
     * @param {Array} [values] The values to cache.
     */
    function SetCache(values) {
      var index = -1,
          length = values == null ? 0 : values.length;

      this.__data__ = new MapCache;
      while (++index < length) {
        this.add(values[index]);
      }
    }

    /**
     * Adds `value` to the array cache.
     *
     * @private
     * @name add
     * @memberOf SetCache
     * @alias push
     * @param {*} value The value to cache.
     * @returns {Object} Returns the cache instance.
     */
    function setCacheAdd(value) {
      this.__data__.set(value, HASH_UNDEFINED);
      return this;
    }

    /**
     * Checks if `value` is in the array cache.
     *
     * @private
     * @name has
     * @memberOf SetCache
     * @param {*} value The value to search for.
     * @returns {number} Returns `true` if `value` is found, else `false`.
     */
    function setCacheHas(value) {
      return this.__data__.has(value);
    }

    // Add methods to `SetCache`.
    SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
    SetCache.prototype.has = setCacheHas;

    /*------------------------------------------------------------------------*/

    /**
     * Creates a stack cache object to store key-value pairs.
     *
     * @private
     * @constructor
     * @param {Array} [entries] The key-value pairs to cache.
     */
    function Stack(entries) {
      var data = this.__data__ = new ListCache(entries);
      this.size = data.size;
    }

    /**
     * Removes all key-value entries from the stack.
     *
     * @private
     * @name clear
     * @memberOf Stack
     */
    function stackClear() {
      this.__data__ = new ListCache;
      this.size = 0;
    }

    /**
     * Removes `key` and its value from the stack.
     *
     * @private
     * @name delete
     * @memberOf Stack
     * @param {string} key The key of the value to remove.
     * @returns {boolean} Returns `true` if the entry was removed, else `false`.
     */
    function stackDelete(key) {
      var data = this.__data__,
          result = data['delete'](key);

      this.size = data.size;
      return result;
    }

    /**
     * Gets the stack value for `key`.
     *
     * @private
     * @name get
     * @memberOf Stack
     * @param {string} key The key of the value to get.
     * @returns {*} Returns the entry value.
     */
    function stackGet(key) {
      return this.__data__.get(key);
    }

    /**
     * Checks if a stack value for `key` exists.
     *
     * @private
     * @name has
     * @memberOf Stack
     * @param {string} key The key of the entry to check.
     * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
     */
    function stackHas(key) {
      return this.__data__.has(key);
    }

    /**
     * Sets the stack `key` to `value`.
     *
     * @private
     * @name set
     * @memberOf Stack
     * @param {string} key The key of the value to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns the stack cache instance.
     */
    function stackSet(key, value) {
      var data = this.__data__;
      if (data instanceof ListCache) {
        var pairs = data.__data__;
        if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
          pairs.push([key, value]);
          this.size = ++data.size;
          return this;
        }
        data = this.__data__ = new MapCache(pairs);
      }
      data.set(key, value);
      this.size = data.size;
      return this;
    }

    // Add methods to `Stack`.
    Stack.prototype.clear = stackClear;
    Stack.prototype['delete'] = stackDelete;
    Stack.prototype.get = stackGet;
    Stack.prototype.has = stackHas;
    Stack.prototype.set = stackSet;

    /*------------------------------------------------------------------------*/

    /**
     * Creates an array of the enumerable property names of the array-like `value`.
     *
     * @private
     * @param {*} value The value to query.
     * @param {boolean} inherited Specify returning inherited property names.
     * @returns {Array} Returns the array of property names.
     */
    function arrayLikeKeys(value, inherited) {
      var isArr = isArray(value),
          isArg = !isArr && isArguments(value),
          isBuff = !isArr && !isArg && isBuffer(value),
          isType = !isArr && !isArg && !isBuff && isTypedArray(value),
          skipIndexes = isArr || isArg || isBuff || isType,
          result = skipIndexes ? baseTimes(value.length, String) : [],
          length = result.length;

      for (var key in value) {
        if ((inherited || hasOwnProperty.call(value, key)) &&
            !(skipIndexes && (
               // Safari 9 has enumerable `arguments.length` in strict mode.
               key == 'length' ||
               // Node.js 0.10 has enumerable non-index properties on buffers.
               (isBuff && (key == 'offset' || key == 'parent')) ||
               // PhantomJS 2 has enumerable non-index properties on typed arrays.
               (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
               // Skip index properties.
               isIndex(key, length)
            ))) {
          result.push(key);
        }
      }
      return result;
    }

    /**
     * A specialized version of `_.sample` for arrays.
     *
     * @private
     * @param {Array} array The array to sample.
     * @returns {*} Returns the random element.
     */
    function arraySample(array) {
      var length = array.length;
      return length ? array[baseRandom(0, length - 1)] : undefined;
    }

    /**
     * A specialized version of `_.sampleSize` for arrays.
     *
     * @private
     * @param {Array} array The array to sample.
     * @param {number} n The number of elements to sample.
     * @returns {Array} Returns the random elements.
     */
    function arraySampleSize(array, n) {
      return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
    }

    /**
     * A specialized version of `_.shuffle` for arrays.
     *
     * @private
     * @param {Array} array The array to shuffle.
     * @returns {Array} Returns the new shuffled array.
     */
    function arrayShuffle(array) {
      return shuffleSelf(copyArray(array));
    }

    /**
     * This function is like `assignValue` except that it doesn't assign
     * `undefined` values.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {string} key The key of the property to assign.
     * @param {*} value The value to assign.
     */
    function assignMergeValue(object, key, value) {
      if ((value !== undefined && !eq(object[key], value)) ||
          (value === undefined && !(key in object))) {
        baseAssignValue(object, key, value);
      }
    }

    /**
     * Assigns `value` to `key` of `object` if the existing value is not equivalent
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {string} key The key of the property to assign.
     * @param {*} value The value to assign.
     */
    function assignValue(object, key, value) {
      var objValue = object[key];
      if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
          (value === undefined && !(key in object))) {
        baseAssignValue(object, key, value);
      }
    }

    /**
     * Gets the index at which the `key` is found in `array` of key-value pairs.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {*} key The key to search for.
     * @returns {number} Returns the index of the matched value, else `-1`.
     */
    function assocIndexOf(array, key) {
      var length = array.length;
      while (length--) {
        if (eq(array[length][0], key)) {
          return length;
        }
      }
      return -1;
    }

    /**
     * Aggregates elements of `collection` on `accumulator` with keys transformed
     * by `iteratee` and values set by `setter`.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} setter The function to set `accumulator` values.
     * @param {Function} iteratee The iteratee to transform keys.
     * @param {Object} accumulator The initial aggregated object.
     * @returns {Function} Returns `accumulator`.
     */
    function baseAggregator(collection, setter, iteratee, accumulator) {
      baseEach(collection, function(value, key, collection) {
        setter(accumulator, value, iteratee(value), collection);
      });
      return accumulator;
    }

    /**
     * The base implementation of `_.assign` without support for multiple sources
     * or `customizer` functions.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @returns {Object} Returns `object`.
     */
    function baseAssign(object, source) {
      return object && copyObject(source, keys(source), object);
    }

    /**
     * The base implementation of `_.assignIn` without support for multiple sources
     * or `customizer` functions.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @returns {Object} Returns `object`.
     */
    function baseAssignIn(object, source) {
      return object && copyObject(source, keysIn(source), object);
    }

    /**
     * The base implementation of `assignValue` and `assignMergeValue` without
     * value checks.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {string} key The key of the property to assign.
     * @param {*} value The value to assign.
     */
    function baseAssignValue(object, key, value) {
      if (key == '__proto__' && defineProperty) {
        defineProperty(object, key, {
          'configurable': true,
          'enumerable': true,
          'value': value,
          'writable': true
        });
      } else {
        object[key] = value;
      }
    }

    /**
     * The base implementation of `_.at` without support for individual paths.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {string[]} paths The property paths to pick.
     * @returns {Array} Returns the picked elements.
     */
    function baseAt(object, paths) {
      var index = -1,
          length = paths.length,
          result = Array(length),
          skip = object == null;

      while (++index < length) {
        result[index] = skip ? undefined : get(object, paths[index]);
      }
      return result;
    }

    /**
     * The base implementation of `_.clamp` which doesn't coerce arguments.
     *
     * @private
     * @param {number} number The number to clamp.
     * @param {number} [lower] The lower bound.
     * @param {number} upper The upper bound.
     * @returns {number} Returns the clamped number.
     */
    function baseClamp(number, lower, upper) {
      if (number === number) {
        if (upper !== undefined) {
          number = number <= upper ? number : upper;
        }
        if (lower !== undefined) {
          number = number >= lower ? number : lower;
        }
      }
      return number;
    }

    /**
     * The base implementation of `_.clone` and `_.cloneDeep` which tracks
     * traversed objects.
     *
     * @private
     * @param {*} value The value to clone.
     * @param {boolean} bitmask The bitmask flags.
     *  1 - Deep clone
     *  2 - Flatten inherited properties
     *  4 - Clone symbols
     * @param {Function} [customizer] The function to customize cloning.
     * @param {string} [key] The key of `value`.
     * @param {Object} [object] The parent object of `value`.
     * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
     * @returns {*} Returns the cloned value.
     */
    function baseClone(value, bitmask, customizer, key, object, stack) {
      var result,
          isDeep = bitmask & CLONE_DEEP_FLAG,
          isFlat = bitmask & CLONE_FLAT_FLAG,
          isFull = bitmask & CLONE_SYMBOLS_FLAG;

      if (customizer) {
        result = object ? customizer(value, key, object, stack) : customizer(value);
      }
      if (result !== undefined) {
        return result;
      }
      if (!isObject(value)) {
        return value;
      }
      var isArr = isArray(value);
      if (isArr) {
        result = initCloneArray(value);
        if (!isDeep) {
          return copyArray(value, result);
        }
      } else {
        var tag = getTag(value),
            isFunc = tag == funcTag || tag == genTag;

        if (isBuffer(value)) {
          return cloneBuffer(value, isDeep);
        }
        if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
          result = (isFlat || isFunc) ? {} : initCloneObject(value);
          if (!isDeep) {
            return isFlat
              ? copySymbolsIn(value, baseAssignIn(result, value))
              : copySymbols(value, baseAssign(result, value));
          }
        } else {
          if (!cloneableTags[tag]) {
            return object ? value : {};
          }
          result = initCloneByTag(value, tag, isDeep);
        }
      }
      // Check for circular references and return its corresponding clone.
      stack || (stack = new Stack);
      var stacked = stack.get(value);
      if (stacked) {
        return stacked;
      }
      stack.set(value, result);

      if (isSet(value)) {
        value.forEach(function(subValue) {
          result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
        });
      } else if (isMap(value)) {
        value.forEach(function(subValue, key) {
          result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
        });
      }

      var keysFunc = isFull
        ? (isFlat ? getAllKeysIn : getAllKeys)
        : (isFlat ? keysIn : keys);

      var props = isArr ? undefined : keysFunc(value);
      arrayEach(props || value, function(subValue, key) {
        if (props) {
          key = subValue;
          subValue = value[key];
        }
        // Recursively populate clone (susceptible to call stack limits).
        assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
      });
      return result;
    }

    /**
     * The base implementation of `_.conforms` which doesn't clone `source`.
     *
     * @private
     * @param {Object} source The object of property predicates to conform to.
     * @returns {Function} Returns the new spec function.
     */
    function baseConforms(source) {
      var props = keys(source);
      return function(object) {
        return baseConformsTo(object, source, props);
      };
    }

    /**
     * The base implementation of `_.conformsTo` which accepts `props` to check.
     *
     * @private
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property predicates to conform to.
     * @returns {boolean} Returns `true` if `object` conforms, else `false`.
     */
    function baseConformsTo(object, source, props) {
      var length = props.length;
      if (object == null) {
        return !length;
      }
      object = Object(object);
      while (length--) {
        var key = props[length],
            predicate = source[key],
            value = object[key];

        if ((value === undefined && !(key in object)) || !predicate(value)) {
          return false;
        }
      }
      return true;
    }

    /**
     * The base implementation of `_.delay` and `_.defer` which accepts `args`
     * to provide to `func`.
     *
     * @private
     * @param {Function} func The function to delay.
     * @param {number} wait The number of milliseconds to delay invocation.
     * @param {Array} args The arguments to provide to `func`.
     * @returns {number|Object} Returns the timer id or timeout object.
     */
    function baseDelay(func, wait, args) {
      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      return setTimeout(function() { func.apply(undefined, args); }, wait);
    }

    /**
     * The base implementation of methods like `_.difference` without support
     * for excluding multiple arrays or iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {Array} values The values to exclude.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     */
    function baseDifference(array, values, iteratee, comparator) {
      var index = -1,
          includes = arrayIncludes,
          isCommon = true,
          length = array.length,
          result = [],
          valuesLength = values.length;

      if (!length) {
        return result;
      }
      if (iteratee) {
        values = arrayMap(values, baseUnary(iteratee));
      }
      if (comparator) {
        includes = arrayIncludesWith;
        isCommon = false;
      }
      else if (values.length >= LARGE_ARRAY_SIZE) {
        includes = cacheHas;
        isCommon = false;
        values = new SetCache(values);
      }
      outer:
      while (++index < length) {
        var value = array[index],
            computed = iteratee == null ? value : iteratee(value);

        value = (comparator || value !== 0) ? value : 0;
        if (isCommon && computed === computed) {
          var valuesIndex = valuesLength;
          while (valuesIndex--) {
            if (values[valuesIndex] === computed) {
              continue outer;
            }
          }
          result.push(value);
        }
        else if (!includes(values, computed, comparator)) {
          result.push(value);
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.forEach` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     */
    var baseEach = createBaseEach(baseForOwn);

    /**
     * The base implementation of `_.forEachRight` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     */
    var baseEachRight = createBaseEach(baseForOwnRight, true);

    /**
     * The base implementation of `_.every` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} predicate The function invoked per iteration.
     * @returns {boolean} Returns `true` if all elements pass the predicate check,
     *  else `false`
     */
    function baseEvery(collection, predicate) {
      var result = true;
      baseEach(collection, function(value, index, collection) {
        result = !!predicate(value, index, collection);
        return result;
      });
      return result;
    }

    /**
     * The base implementation of methods like `_.max` and `_.min` which accepts a
     * `comparator` to determine the extremum value.
     *
     * @private
     * @param {Array} array The array to iterate over.
     * @param {Function} iteratee The iteratee invoked per iteration.
     * @param {Function} comparator The comparator used to compare values.
     * @returns {*} Returns the extremum value.
     */
    function baseExtremum(array, iteratee, comparator) {
      var index = -1,
          length = array.length;

      while (++index < length) {
        var value = array[index],
            current = iteratee(value);

        if (current != null && (computed === undefined
              ? (current === current && !isSymbol(current))
              : comparator(current, computed)
            )) {
          var computed = current,
              result = value;
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.fill` without an iteratee call guard.
     *
     * @private
     * @param {Array} array The array to fill.
     * @param {*} value The value to fill `array` with.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns `array`.
     */
    function baseFill(array, value, start, end) {
      var length = array.length;

      start = toInteger(start);
      if (start < 0) {
        start = -start > length ? 0 : (length + start);
      }
      end = (end === undefined || end > length) ? length : toInteger(end);
      if (end < 0) {
        end += length;
      }
      end = start > end ? 0 : toLength(end);
      while (start < end) {
        array[start++] = value;
      }
      return array;
    }

    /**
     * The base implementation of `_.filter` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} predicate The function invoked per iteration.
     * @returns {Array} Returns the new filtered array.
     */
    function baseFilter(collection, predicate) {
      var result = [];
      baseEach(collection, function(value, index, collection) {
        if (predicate(value, index, collection)) {
          result.push(value);
        }
      });
      return result;
    }

    /**
     * The base implementation of `_.flatten` with support for restricting flattening.
     *
     * @private
     * @param {Array} array The array to flatten.
     * @param {number} depth The maximum recursion depth.
     * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
     * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
     * @param {Array} [result=[]] The initial result value.
     * @returns {Array} Returns the new flattened array.
     */
    function baseFlatten(array, depth, predicate, isStrict, result) {
      var index = -1,
          length = array.length;

      predicate || (predicate = isFlattenable);
      result || (result = []);

      while (++index < length) {
        var value = array[index];
        if (depth > 0 && predicate(value)) {
          if (depth > 1) {
            // Recursively flatten arrays (susceptible to call stack limits).
            baseFlatten(value, depth - 1, predicate, isStrict, result);
          } else {
            arrayPush(result, value);
          }
        } else if (!isStrict) {
          result[result.length] = value;
        }
      }
      return result;
    }

    /**
     * The base implementation of `baseForOwn` which iterates over `object`
     * properties returned by `keysFunc` and invokes `iteratee` for each property.
     * Iteratee functions may exit iteration early by explicitly returning `false`.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @param {Function} keysFunc The function to get the keys of `object`.
     * @returns {Object} Returns `object`.
     */
    var baseFor = createBaseFor();

    /**
     * This function is like `baseFor` except that it iterates over properties
     * in the opposite order.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @param {Function} keysFunc The function to get the keys of `object`.
     * @returns {Object} Returns `object`.
     */
    var baseForRight = createBaseFor(true);

    /**
     * The base implementation of `_.forOwn` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Object} Returns `object`.
     */
    function baseForOwn(object, iteratee) {
      return object && baseFor(object, iteratee, keys);
    }

    /**
     * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Object} Returns `object`.
     */
    function baseForOwnRight(object, iteratee) {
      return object && baseForRight(object, iteratee, keys);
    }

    /**
     * The base implementation of `_.functions` which creates an array of
     * `object` function property names filtered from `props`.
     *
     * @private
     * @param {Object} object The object to inspect.
     * @param {Array} props The property names to filter.
     * @returns {Array} Returns the function names.
     */
    function baseFunctions(object, props) {
      return arrayFilter(props, function(key) {
        return isFunction(object[key]);
      });
    }

    /**
     * The base implementation of `_.get` without support for default values.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the property to get.
     * @returns {*} Returns the resolved value.
     */
    function baseGet(object, path) {
      path = castPath(path, object);

      var index = 0,
          length = path.length;

      while (object != null && index < length) {
        object = object[toKey(path[index++])];
      }
      return (index && index == length) ? object : undefined;
    }

    /**
     * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
     * `keysFunc` and `symbolsFunc` to get the enumerable property names and
     * symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Function} keysFunc The function to get the keys of `object`.
     * @param {Function} symbolsFunc The function to get the symbols of `object`.
     * @returns {Array} Returns the array of property names and symbols.
     */
    function baseGetAllKeys(object, keysFunc, symbolsFunc) {
      var result = keysFunc(object);
      return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
    }

    /**
     * The base implementation of `getTag` without fallbacks for buggy environments.
     *
     * @private
     * @param {*} value The value to query.
     * @returns {string} Returns the `toStringTag`.
     */
    function baseGetTag(value) {
      if (value == null) {
        return value === undefined ? undefinedTag : nullTag;
      }
      return (symToStringTag && symToStringTag in Object(value))
        ? getRawTag(value)
        : objectToString(value);
    }

    /**
     * The base implementation of `_.gt` which doesn't coerce arguments.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is greater than `other`,
     *  else `false`.
     */
    function baseGt(value, other) {
      return value > other;
    }

    /**
     * The base implementation of `_.has` without support for deep paths.
     *
     * @private
     * @param {Object} [object] The object to query.
     * @param {Array|string} key The key to check.
     * @returns {boolean} Returns `true` if `key` exists, else `false`.
     */
    function baseHas(object, key) {
      return object != null && hasOwnProperty.call(object, key);
    }

    /**
     * The base implementation of `_.hasIn` without support for deep paths.
     *
     * @private
     * @param {Object} [object] The object to query.
     * @param {Array|string} key The key to check.
     * @returns {boolean} Returns `true` if `key` exists, else `false`.
     */
    function baseHasIn(object, key) {
      return object != null && key in Object(object);
    }

    /**
     * The base implementation of `_.inRange` which doesn't coerce arguments.
     *
     * @private
     * @param {number} number The number to check.
     * @param {number} start The start of the range.
     * @param {number} end The end of the range.
     * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
     */
    function baseInRange(number, start, end) {
      return number >= nativeMin(start, end) && number < nativeMax(start, end);
    }

    /**
     * The base implementation of methods like `_.intersection`, without support
     * for iteratee shorthands, that accepts an array of arrays to inspect.
     *
     * @private
     * @param {Array} arrays The arrays to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of shared values.
     */
    function baseIntersection(arrays, iteratee, comparator) {
      var includes = comparator ? arrayIncludesWith : arrayIncludes,
          length = arrays[0].length,
          othLength = arrays.length,
          othIndex = othLength,
          caches = Array(othLength),
          maxLength = Infinity,
          result = [];

      while (othIndex--) {
        var array = arrays[othIndex];
        if (othIndex && iteratee) {
          array = arrayMap(array, baseUnary(iteratee));
        }
        maxLength = nativeMin(array.length, maxLength);
        caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
          ? new SetCache(othIndex && array)
          : undefined;
      }
      array = arrays[0];

      var index = -1,
          seen = caches[0];

      outer:
      while (++index < length && result.length < maxLength) {
        var value = array[index],
            computed = iteratee ? iteratee(value) : value;

        value = (comparator || value !== 0) ? value : 0;
        if (!(seen
              ? cacheHas(seen, computed)
              : includes(result, computed, comparator)
            )) {
          othIndex = othLength;
          while (--othIndex) {
            var cache = caches[othIndex];
            if (!(cache
                  ? cacheHas(cache, computed)
                  : includes(arrays[othIndex], computed, comparator))
                ) {
              continue outer;
            }
          }
          if (seen) {
            seen.push(computed);
          }
          result.push(value);
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.invert` and `_.invertBy` which inverts
     * `object` with values transformed by `iteratee` and set by `setter`.
     *
     * @private
     * @param {Object} object The object to iterate over.
     * @param {Function} setter The function to set `accumulator` values.
     * @param {Function} iteratee The iteratee to transform values.
     * @param {Object} accumulator The initial inverted object.
     * @returns {Function} Returns `accumulator`.
     */
    function baseInverter(object, setter, iteratee, accumulator) {
      baseForOwn(object, function(value, key, object) {
        setter(accumulator, iteratee(value), key, object);
      });
      return accumulator;
    }

    /**
     * The base implementation of `_.invoke` without support for individual
     * method arguments.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the method to invoke.
     * @param {Array} args The arguments to invoke the method with.
     * @returns {*} Returns the result of the invoked method.
     */
    function baseInvoke(object, path, args) {
      path = castPath(path, object);
      object = parent(object, path);
      var func = object == null ? object : object[toKey(last(path))];
      return func == null ? undefined : apply(func, object, args);
    }

    /**
     * The base implementation of `_.isArguments`.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an `arguments` object,
     */
    function baseIsArguments(value) {
      return isObjectLike(value) && baseGetTag(value) == argsTag;
    }

    /**
     * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
     */
    function baseIsArrayBuffer(value) {
      return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
    }

    /**
     * The base implementation of `_.isDate` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
     */
    function baseIsDate(value) {
      return isObjectLike(value) && baseGetTag(value) == dateTag;
    }

    /**
     * The base implementation of `_.isEqual` which supports partial comparisons
     * and tracks traversed objects.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @param {boolean} bitmask The bitmask flags.
     *  1 - Unordered comparison
     *  2 - Partial comparison
     * @param {Function} [customizer] The function to customize comparisons.
     * @param {Object} [stack] Tracks traversed `value` and `other` objects.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     */
    function baseIsEqual(value, other, bitmask, customizer, stack) {
      if (value === other) {
        return true;
      }
      if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
        return value !== value && other !== other;
      }
      return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
    }

    /**
     * A specialized version of `baseIsEqual` for arrays and objects which performs
     * deep comparisons and tracks traversed objects enabling objects with circular
     * references to be compared.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} [stack] Tracks traversed `object` and `other` objects.
     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
     */
    function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
      var objIsArr = isArray(object),
          othIsArr = isArray(other),
          objTag = objIsArr ? arrayTag : getTag(object),
          othTag = othIsArr ? arrayTag : getTag(other);

      objTag = objTag == argsTag ? objectTag : objTag;
      othTag = othTag == argsTag ? objectTag : othTag;

      var objIsObj = objTag == objectTag,
          othIsObj = othTag == objectTag,
          isSameTag = objTag == othTag;

      if (isSameTag && isBuffer(object)) {
        if (!isBuffer(other)) {
          return false;
        }
        objIsArr = true;
        objIsObj = false;
      }
      if (isSameTag && !objIsObj) {
        stack || (stack = new Stack);
        return (objIsArr || isTypedArray(object))
          ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
          : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
      }
      if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
        var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
            othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');

        if (objIsWrapped || othIsWrapped) {
          var objUnwrapped = objIsWrapped ? object.value() : object,
              othUnwrapped = othIsWrapped ? other.value() : other;

          stack || (stack = new Stack);
          return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
        }
      }
      if (!isSameTag) {
        return false;
      }
      stack || (stack = new Stack);
      return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
    }

    /**
     * The base implementation of `_.isMap` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a map, else `false`.
     */
    function baseIsMap(value) {
      return isObjectLike(value) && getTag(value) == mapTag;
    }

    /**
     * The base implementation of `_.isMatch` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property values to match.
     * @param {Array} matchData The property names, values, and compare flags to match.
     * @param {Function} [customizer] The function to customize comparisons.
     * @returns {boolean} Returns `true` if `object` is a match, else `false`.
     */
    function baseIsMatch(object, source, matchData, customizer) {
      var index = matchData.length,
          length = index,
          noCustomizer = !customizer;

      if (object == null) {
        return !length;
      }
      object = Object(object);
      while (index--) {
        var data = matchData[index];
        if ((noCustomizer && data[2])
              ? data[1] !== object[data[0]]
              : !(data[0] in object)
            ) {
          return false;
        }
      }
      while (++index < length) {
        data = matchData[index];
        var key = data[0],
            objValue = object[key],
            srcValue = data[1];

        if (noCustomizer && data[2]) {
          if (objValue === undefined && !(key in object)) {
            return false;
          }
        } else {
          var stack = new Stack;
          if (customizer) {
            var result = customizer(objValue, srcValue, key, object, source, stack);
          }
          if (!(result === undefined
                ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
                : result
              )) {
            return false;
          }
        }
      }
      return true;
    }

    /**
     * The base implementation of `_.isNative` without bad shim checks.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a native function,
     *  else `false`.
     */
    function baseIsNative(value) {
      if (!isObject(value) || isMasked(value)) {
        return false;
      }
      var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
      return pattern.test(toSource(value));
    }

    /**
     * The base implementation of `_.isRegExp` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
     */
    function baseIsRegExp(value) {
      return isObjectLike(value) && baseGetTag(value) == regexpTag;
    }

    /**
     * The base implementation of `_.isSet` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a set, else `false`.
     */
    function baseIsSet(value) {
      return isObjectLike(value) && getTag(value) == setTag;
    }

    /**
     * The base implementation of `_.isTypedArray` without Node.js optimizations.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
     */
    function baseIsTypedArray(value) {
      return isObjectLike(value) &&
        isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
    }

    /**
     * The base implementation of `_.iteratee`.
     *
     * @private
     * @param {*} [value=_.identity] The value to convert to an iteratee.
     * @returns {Function} Returns the iteratee.
     */
    function baseIteratee(value) {
      // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
      // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
      if (typeof value == 'function') {
        return value;
      }
      if (value == null) {
        return identity;
      }
      if (typeof value == 'object') {
        return isArray(value)
          ? baseMatchesProperty(value[0], value[1])
          : baseMatches(value);
      }
      return property(value);
    }

    /**
     * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     */
    function baseKeys(object) {
      if (!isPrototype(object)) {
        return nativeKeys(object);
      }
      var result = [];
      for (var key in Object(object)) {
        if (hasOwnProperty.call(object, key) && key != 'constructor') {
          result.push(key);
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     */
    function baseKeysIn(object) {
      if (!isObject(object)) {
        return nativeKeysIn(object);
      }
      var isProto = isPrototype(object),
          result = [];

      for (var key in object) {
        if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
          result.push(key);
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.lt` which doesn't coerce arguments.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is less than `other`,
     *  else `false`.
     */
    function baseLt(value, other) {
      return value < other;
    }

    /**
     * The base implementation of `_.map` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} iteratee The function invoked per iteration.
     * @returns {Array} Returns the new mapped array.
     */
    function baseMap(collection, iteratee) {
      var index = -1,
          result = isArrayLike(collection) ? Array(collection.length) : [];

      baseEach(collection, function(value, key, collection) {
        result[++index] = iteratee(value, key, collection);
      });
      return result;
    }

    /**
     * The base implementation of `_.matches` which doesn't clone `source`.
     *
     * @private
     * @param {Object} source The object of property values to match.
     * @returns {Function} Returns the new spec function.
     */
    function baseMatches(source) {
      var matchData = getMatchData(source);
      if (matchData.length == 1 && matchData[0][2]) {
        return matchesStrictComparable(matchData[0][0], matchData[0][1]);
      }
      return function(object) {
        return object === source || baseIsMatch(object, source, matchData);
      };
    }

    /**
     * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
     *
     * @private
     * @param {string} path The path of the property to get.
     * @param {*} srcValue The value to match.
     * @returns {Function} Returns the new spec function.
     */
    function baseMatchesProperty(path, srcValue) {
      if (isKey(path) && isStrictComparable(srcValue)) {
        return matchesStrictComparable(toKey(path), srcValue);
      }
      return function(object) {
        var objValue = get(object, path);
        return (objValue === undefined && objValue === srcValue)
          ? hasIn(object, path)
          : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
      };
    }

    /**
     * The base implementation of `_.merge` without support for multiple sources.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @param {number} srcIndex The index of `source`.
     * @param {Function} [customizer] The function to customize merged values.
     * @param {Object} [stack] Tracks traversed source values and their merged
     *  counterparts.
     */
    function baseMerge(object, source, srcIndex, customizer, stack) {
      if (object === source) {
        return;
      }
      baseFor(source, function(srcValue, key) {
        stack || (stack = new Stack);
        if (isObject(srcValue)) {
          baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
        }
        else {
          var newValue = customizer
            ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
            : undefined;

          if (newValue === undefined) {
            newValue = srcValue;
          }
          assignMergeValue(object, key, newValue);
        }
      }, keysIn);
    }

    /**
     * A specialized version of `baseMerge` for arrays and objects which performs
     * deep merges and tracks traversed objects enabling objects with circular
     * references to be merged.
     *
     * @private
     * @param {Object} object The destination object.
     * @param {Object} source The source object.
     * @param {string} key The key of the value to merge.
     * @param {number} srcIndex The index of `source`.
     * @param {Function} mergeFunc The function to merge values.
     * @param {Function} [customizer] The function to customize assigned values.
     * @param {Object} [stack] Tracks traversed source values and their merged
     *  counterparts.
     */
    function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
      var objValue = safeGet(object, key),
          srcValue = safeGet(source, key),
          stacked = stack.get(srcValue);

      if (stacked) {
        assignMergeValue(object, key, stacked);
        return;
      }
      var newValue = customizer
        ? customizer(objValue, srcValue, (key + ''), object, source, stack)
        : undefined;

      var isCommon = newValue === undefined;

      if (isCommon) {
        var isArr = isArray(srcValue),
            isBuff = !isArr && isBuffer(srcValue),
            isTyped = !isArr && !isBuff && isTypedArray(srcValue);

        newValue = srcValue;
        if (isArr || isBuff || isTyped) {
          if (isArray(objValue)) {
            newValue = objValue;
          }
          else if (isArrayLikeObject(objValue)) {
            newValue = copyArray(objValue);
          }
          else if (isBuff) {
            isCommon = false;
            newValue = cloneBuffer(srcValue, true);
          }
          else if (isTyped) {
            isCommon = false;
            newValue = cloneTypedArray(srcValue, true);
          }
          else {
            newValue = [];
          }
        }
        else if (isPlainObject(srcValue) || isArguments(srcValue)) {
          newValue = objValue;
          if (isArguments(objValue)) {
            newValue = toPlainObject(objValue);
          }
          else if (!isObject(objValue) || isFunction(objValue)) {
            newValue = initCloneObject(srcValue);
          }
        }
        else {
          isCommon = false;
        }
      }
      if (isCommon) {
        // Recursively merge objects and arrays (susceptible to call stack limits).
        stack.set(srcValue, newValue);
        mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
        stack['delete'](srcValue);
      }
      assignMergeValue(object, key, newValue);
    }

    /**
     * The base implementation of `_.nth` which doesn't coerce arguments.
     *
     * @private
     * @param {Array} array The array to query.
     * @param {number} n The index of the element to return.
     * @returns {*} Returns the nth element of `array`.
     */
    function baseNth(array, n) {
      var length = array.length;
      if (!length) {
        return;
      }
      n += n < 0 ? length : 0;
      return isIndex(n, length) ? array[n] : undefined;
    }

    /**
     * The base implementation of `_.orderBy` without param guards.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
     * @param {string[]} orders The sort orders of `iteratees`.
     * @returns {Array} Returns the new sorted array.
     */
    function baseOrderBy(collection, iteratees, orders) {
      if (iteratees.length) {
        iteratees = arrayMap(iteratees, function(iteratee) {
          if (isArray(iteratee)) {
            return function(value) {
              return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
            }
          }
          return iteratee;
        });
      } else {
        iteratees = [identity];
      }

      var index = -1;
      iteratees = arrayMap(iteratees, baseUnary(getIteratee()));

      var result = baseMap(collection, function(value, key, collection) {
        var criteria = arrayMap(iteratees, function(iteratee) {
          return iteratee(value);
        });
        return { 'criteria': criteria, 'index': ++index, 'value': value };
      });

      return baseSortBy(result, function(object, other) {
        return compareMultiple(object, other, orders);
      });
    }

    /**
     * The base implementation of `_.pick` without support for individual
     * property identifiers.
     *
     * @private
     * @param {Object} object The source object.
     * @param {string[]} paths The property paths to pick.
     * @returns {Object} Returns the new object.
     */
    function basePick(object, paths) {
      return basePickBy(object, paths, function(value, path) {
        return hasIn(object, path);
      });
    }

    /**
     * The base implementation of  `_.pickBy` without support for iteratee shorthands.
     *
     * @private
     * @param {Object} object The source object.
     * @param {string[]} paths The property paths to pick.
     * @param {Function} predicate The function invoked per property.
     * @returns {Object} Returns the new object.
     */
    function basePickBy(object, paths, predicate) {
      var index = -1,
          length = paths.length,
          result = {};

      while (++index < length) {
        var path = paths[index],
            value = baseGet(object, path);

        if (predicate(value, path)) {
          baseSet(result, castPath(path, object), value);
        }
      }
      return result;
    }

    /**
     * A specialized version of `baseProperty` which supports deep paths.
     *
     * @private
     * @param {Array|string} path The path of the property to get.
     * @returns {Function} Returns the new accessor function.
     */
    function basePropertyDeep(path) {
      return function(object) {
        return baseGet(object, path);
      };
    }

    /**
     * The base implementation of `_.pullAllBy` without support for iteratee
     * shorthands.
     *
     * @private
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns `array`.
     */
    function basePullAll(array, values, iteratee, comparator) {
      var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
          index = -1,
          length = values.length,
          seen = array;

      if (array === values) {
        values = copyArray(values);
      }
      if (iteratee) {
        seen = arrayMap(array, baseUnary(iteratee));
      }
      while (++index < length) {
        var fromIndex = 0,
            value = values[index],
            computed = iteratee ? iteratee(value) : value;

        while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
          if (seen !== array) {
            splice.call(seen, fromIndex, 1);
          }
          splice.call(array, fromIndex, 1);
        }
      }
      return array;
    }

    /**
     * The base implementation of `_.pullAt` without support for individual
     * indexes or capturing the removed elements.
     *
     * @private
     * @param {Array} array The array to modify.
     * @param {number[]} indexes The indexes of elements to remove.
     * @returns {Array} Returns `array`.
     */
    function basePullAt(array, indexes) {
      var length = array ? indexes.length : 0,
          lastIndex = length - 1;

      while (length--) {
        var index = indexes[length];
        if (length == lastIndex || index !== previous) {
          var previous = index;
          if (isIndex(index)) {
            splice.call(array, index, 1);
          } else {
            baseUnset(array, index);
          }
        }
      }
      return array;
    }

    /**
     * The base implementation of `_.random` without support for returning
     * floating-point numbers.
     *
     * @private
     * @param {number} lower The lower bound.
     * @param {number} upper The upper bound.
     * @returns {number} Returns the random number.
     */
    function baseRandom(lower, upper) {
      return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
    }

    /**
     * The base implementation of `_.range` and `_.rangeRight` which doesn't
     * coerce arguments.
     *
     * @private
     * @param {number} start The start of the range.
     * @param {number} end The end of the range.
     * @param {number} step The value to increment or decrement by.
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Array} Returns the range of numbers.
     */
    function baseRange(start, end, step, fromRight) {
      var index = -1,
          length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
          result = Array(length);

      while (length--) {
        result[fromRight ? length : ++index] = start;
        start += step;
      }
      return result;
    }

    /**
     * The base implementation of `_.repeat` which doesn't coerce arguments.
     *
     * @private
     * @param {string} string The string to repeat.
     * @param {number} n The number of times to repeat the string.
     * @returns {string} Returns the repeated string.
     */
    function baseRepeat(string, n) {
      var result = '';
      if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
        return result;
      }
      // Leverage the exponentiation by squaring algorithm for a faster repeat.
      // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
      do {
        if (n % 2) {
          result += string;
        }
        n = nativeFloor(n / 2);
        if (n) {
          string += string;
        }
      } while (n);

      return result;
    }

    /**
     * The base implementation of `_.rest` which doesn't validate or coerce arguments.
     *
     * @private
     * @param {Function} func The function to apply a rest parameter to.
     * @param {number} [start=func.length-1] The start position of the rest parameter.
     * @returns {Function} Returns the new function.
     */
    function baseRest(func, start) {
      return setToString(overRest(func, start, identity), func + '');
    }

    /**
     * The base implementation of `_.sample`.
     *
     * @private
     * @param {Array|Object} collection The collection to sample.
     * @returns {*} Returns the random element.
     */
    function baseSample(collection) {
      return arraySample(values(collection));
    }

    /**
     * The base implementation of `_.sampleSize` without param guards.
     *
     * @private
     * @param {Array|Object} collection The collection to sample.
     * @param {number} n The number of elements to sample.
     * @returns {Array} Returns the random elements.
     */
    function baseSampleSize(collection, n) {
      var array = values(collection);
      return shuffleSelf(array, baseClamp(n, 0, array.length));
    }

    /**
     * The base implementation of `_.set`.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {*} value The value to set.
     * @param {Function} [customizer] The function to customize path creation.
     * @returns {Object} Returns `object`.
     */
    function baseSet(object, path, value, customizer) {
      if (!isObject(object)) {
        return object;
      }
      path = castPath(path, object);

      var index = -1,
          length = path.length,
          lastIndex = length - 1,
          nested = object;

      while (nested != null && ++index < length) {
        var key = toKey(path[index]),
            newValue = value;

        if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
          return object;
        }

        if (index != lastIndex) {
          var objValue = nested[key];
          newValue = customizer ? customizer(objValue, key, nested) : undefined;
          if (newValue === undefined) {
            newValue = isObject(objValue)
              ? objValue
              : (isIndex(path[index + 1]) ? [] : {});
          }
        }
        assignValue(nested, key, newValue);
        nested = nested[key];
      }
      return object;
    }

    /**
     * The base implementation of `setData` without support for hot loop shorting.
     *
     * @private
     * @param {Function} func The function to associate metadata with.
     * @param {*} data The metadata.
     * @returns {Function} Returns `func`.
     */
    var baseSetData = !metaMap ? identity : function(func, data) {
      metaMap.set(func, data);
      return func;
    };

    /**
     * The base implementation of `setToString` without support for hot loop shorting.
     *
     * @private
     * @param {Function} func The function to modify.
     * @param {Function} string The `toString` result.
     * @returns {Function} Returns `func`.
     */
    var baseSetToString = !defineProperty ? identity : function(func, string) {
      return defineProperty(func, 'toString', {
        'configurable': true,
        'enumerable': false,
        'value': constant(string),
        'writable': true
      });
    };

    /**
     * The base implementation of `_.shuffle`.
     *
     * @private
     * @param {Array|Object} collection The collection to shuffle.
     * @returns {Array} Returns the new shuffled array.
     */
    function baseShuffle(collection) {
      return shuffleSelf(values(collection));
    }

    /**
     * The base implementation of `_.slice` without an iteratee call guard.
     *
     * @private
     * @param {Array} array The array to slice.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns the slice of `array`.
     */
    function baseSlice(array, start, end) {
      var index = -1,
          length = array.length;

      if (start < 0) {
        start = -start > length ? 0 : (length + start);
      }
      end = end > length ? length : end;
      if (end < 0) {
        end += length;
      }
      length = start > end ? 0 : ((end - start) >>> 0);
      start >>>= 0;

      var result = Array(length);
      while (++index < length) {
        result[index] = array[index + start];
      }
      return result;
    }

    /**
     * The base implementation of `_.some` without support for iteratee shorthands.
     *
     * @private
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} predicate The function invoked per iteration.
     * @returns {boolean} Returns `true` if any element passes the predicate check,
     *  else `false`.
     */
    function baseSome(collection, predicate) {
      var result;

      baseEach(collection, function(value, index, collection) {
        result = predicate(value, index, collection);
        return !result;
      });
      return !!result;
    }

    /**
     * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
     * performs a binary search of `array` to determine the index at which `value`
     * should be inserted into `array` in order to maintain its sort order.
     *
     * @private
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {boolean} [retHighest] Specify returning the highest qualified index.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     */
    function baseSortedIndex(array, value, retHighest) {
      var low = 0,
          high = array == null ? low : array.length;

      if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
        while (low < high) {
          var mid = (low + high) >>> 1,
              computed = array[mid];

          if (computed !== null && !isSymbol(computed) &&
              (retHighest ? (computed <= value) : (computed < value))) {
            low = mid + 1;
          } else {
            high = mid;
          }
        }
        return high;
      }
      return baseSortedIndexBy(array, value, identity, retHighest);
    }

    /**
     * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
     * which invokes `iteratee` for `value` and each element of `array` to compute
     * their sort ranking. The iteratee is invoked with one argument; (value).
     *
     * @private
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {Function} iteratee The iteratee invoked per element.
     * @param {boolean} [retHighest] Specify returning the highest qualified index.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     */
    function baseSortedIndexBy(array, value, iteratee, retHighest) {
      var low = 0,
          high = array == null ? 0 : array.length;
      if (high === 0) {
        return 0;
      }

      value = iteratee(value);
      var valIsNaN = value !== value,
          valIsNull = value === null,
          valIsSymbol = isSymbol(value),
          valIsUndefined = value === undefined;

      while (low < high) {
        var mid = nativeFloor((low + high) / 2),
            computed = iteratee(array[mid]),
            othIsDefined = computed !== undefined,
            othIsNull = computed === null,
            othIsReflexive = computed === computed,
            othIsSymbol = isSymbol(computed);

        if (valIsNaN) {
          var setLow = retHighest || othIsReflexive;
        } else if (valIsUndefined) {
          setLow = othIsReflexive && (retHighest || othIsDefined);
        } else if (valIsNull) {
          setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
        } else if (valIsSymbol) {
          setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
        } else if (othIsNull || othIsSymbol) {
          setLow = false;
        } else {
          setLow = retHighest ? (computed <= value) : (computed < value);
        }
        if (setLow) {
          low = mid + 1;
        } else {
          high = mid;
        }
      }
      return nativeMin(high, MAX_ARRAY_INDEX);
    }

    /**
     * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
     * support for iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     */
    function baseSortedUniq(array, iteratee) {
      var index = -1,
          length = array.length,
          resIndex = 0,
          result = [];

      while (++index < length) {
        var value = array[index],
            computed = iteratee ? iteratee(value) : value;

        if (!index || !eq(computed, seen)) {
          var seen = computed;
          result[resIndex++] = value === 0 ? 0 : value;
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.toNumber` which doesn't ensure correct
     * conversions of binary, hexadecimal, or octal string values.
     *
     * @private
     * @param {*} value The value to process.
     * @returns {number} Returns the number.
     */
    function baseToNumber(value) {
      if (typeof value == 'number') {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      return +value;
    }

    /**
     * The base implementation of `_.toString` which doesn't convert nullish
     * values to empty strings.
     *
     * @private
     * @param {*} value The value to process.
     * @returns {string} Returns the string.
     */
    function baseToString(value) {
      // Exit early for strings to avoid a performance hit in some environments.
      if (typeof value == 'string') {
        return value;
      }
      if (isArray(value)) {
        // Recursively convert values (susceptible to call stack limits).
        return arrayMap(value, baseToString) + '';
      }
      if (isSymbol(value)) {
        return symbolToString ? symbolToString.call(value) : '';
      }
      var result = (value + '');
      return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
    }

    /**
     * The base implementation of `_.uniqBy` without support for iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     */
    function baseUniq(array, iteratee, comparator) {
      var index = -1,
          includes = arrayIncludes,
          length = array.length,
          isCommon = true,
          result = [],
          seen = result;

      if (comparator) {
        isCommon = false;
        includes = arrayIncludesWith;
      }
      else if (length >= LARGE_ARRAY_SIZE) {
        var set = iteratee ? null : createSet(array);
        if (set) {
          return setToArray(set);
        }
        isCommon = false;
        includes = cacheHas;
        seen = new SetCache;
      }
      else {
        seen = iteratee ? [] : result;
      }
      outer:
      while (++index < length) {
        var value = array[index],
            computed = iteratee ? iteratee(value) : value;

        value = (comparator || value !== 0) ? value : 0;
        if (isCommon && computed === computed) {
          var seenIndex = seen.length;
          while (seenIndex--) {
            if (seen[seenIndex] === computed) {
              continue outer;
            }
          }
          if (iteratee) {
            seen.push(computed);
          }
          result.push(value);
        }
        else if (!includes(seen, computed, comparator)) {
          if (seen !== result) {
            seen.push(computed);
          }
          result.push(value);
        }
      }
      return result;
    }

    /**
     * The base implementation of `_.unset`.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {Array|string} path The property path to unset.
     * @returns {boolean} Returns `true` if the property is deleted, else `false`.
     */
    function baseUnset(object, path) {
      path = castPath(path, object);
      object = parent(object, path);
      return object == null || delete object[toKey(last(path))];
    }

    /**
     * The base implementation of `_.update`.
     *
     * @private
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to update.
     * @param {Function} updater The function to produce the updated value.
     * @param {Function} [customizer] The function to customize path creation.
     * @returns {Object} Returns `object`.
     */
    function baseUpdate(object, path, updater, customizer) {
      return baseSet(object, path, updater(baseGet(object, path)), customizer);
    }

    /**
     * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
     * without support for iteratee shorthands.
     *
     * @private
     * @param {Array} array The array to query.
     * @param {Function} predicate The function invoked per iteration.
     * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Array} Returns the slice of `array`.
     */
    function baseWhile(array, predicate, isDrop, fromRight) {
      var length = array.length,
          index = fromRight ? length : -1;

      while ((fromRight ? index-- : ++index < length) &&
        predicate(array[index], index, array)) {}

      return isDrop
        ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
        : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
    }

    /**
     * The base implementation of `wrapperValue` which returns the result of
     * performing a sequence of actions on the unwrapped `value`, where each
     * successive action is supplied the return value of the previous.
     *
     * @private
     * @param {*} value The unwrapped value.
     * @param {Array} actions Actions to perform to resolve the unwrapped value.
     * @returns {*} Returns the resolved value.
     */
    function baseWrapperValue(value, actions) {
      var result = value;
      if (result instanceof LazyWrapper) {
        result = result.value();
      }
      return arrayReduce(actions, function(result, action) {
        return action.func.apply(action.thisArg, arrayPush([result], action.args));
      }, result);
    }

    /**
     * The base implementation of methods like `_.xor`, without support for
     * iteratee shorthands, that accepts an array of arrays to inspect.
     *
     * @private
     * @param {Array} arrays The arrays to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of values.
     */
    function baseXor(arrays, iteratee, comparator) {
      var length = arrays.length;
      if (length < 2) {
        return length ? baseUniq(arrays[0]) : [];
      }
      var index = -1,
          result = Array(length);

      while (++index < length) {
        var array = arrays[index],
            othIndex = -1;

        while (++othIndex < length) {
          if (othIndex != index) {
            result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
          }
        }
      }
      return baseUniq(baseFlatten(result, 1), iteratee, comparator);
    }

    /**
     * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
     *
     * @private
     * @param {Array} props The property identifiers.
     * @param {Array} values The property values.
     * @param {Function} assignFunc The function to assign values.
     * @returns {Object} Returns the new object.
     */
    function baseZipObject(props, values, assignFunc) {
      var index = -1,
          length = props.length,
          valsLength = values.length,
          result = {};

      while (++index < length) {
        var value = index < valsLength ? values[index] : undefined;
        assignFunc(result, props[index], value);
      }
      return result;
    }

    /**
     * Casts `value` to an empty array if it's not an array like object.
     *
     * @private
     * @param {*} value The value to inspect.
     * @returns {Array|Object} Returns the cast array-like object.
     */
    function castArrayLikeObject(value) {
      return isArrayLikeObject(value) ? value : [];
    }

    /**
     * Casts `value` to `identity` if it's not a function.
     *
     * @private
     * @param {*} value The value to inspect.
     * @returns {Function} Returns cast function.
     */
    function castFunction(value) {
      return typeof value == 'function' ? value : identity;
    }

    /**
     * Casts `value` to a path array if it's not one.
     *
     * @private
     * @param {*} value The value to inspect.
     * @param {Object} [object] The object to query keys on.
     * @returns {Array} Returns the cast property path array.
     */
    function castPath(value, object) {
      if (isArray(value)) {
        return value;
      }
      return isKey(value, object) ? [value] : stringToPath(toString(value));
    }

    /**
     * A `baseRest` alias which can be replaced with `identity` by module
     * replacement plugins.
     *
     * @private
     * @type {Function}
     * @param {Function} func The function to apply a rest parameter to.
     * @returns {Function} Returns the new function.
     */
    var castRest = baseRest;

    /**
     * Casts `array` to a slice if it's needed.
     *
     * @private
     * @param {Array} array The array to inspect.
     * @param {number} start The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns the cast slice.
     */
    function castSlice(array, start, end) {
      var length = array.length;
      end = end === undefined ? length : end;
      return (!start && end >= length) ? array : baseSlice(array, start, end);
    }

    /**
     * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
     *
     * @private
     * @param {number|Object} id The timer id or timeout object of the timer to clear.
     */
    var clearTimeout = ctxClearTimeout || function(id) {
      return root.clearTimeout(id);
    };

    /**
     * Creates a clone of  `buffer`.
     *
     * @private
     * @param {Buffer} buffer The buffer to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Buffer} Returns the cloned buffer.
     */
    function cloneBuffer(buffer, isDeep) {
      if (isDeep) {
        return buffer.slice();
      }
      var length = buffer.length,
          result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);

      buffer.copy(result);
      return result;
    }

    /**
     * Creates a clone of `arrayBuffer`.
     *
     * @private
     * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
     * @returns {ArrayBuffer} Returns the cloned array buffer.
     */
    function cloneArrayBuffer(arrayBuffer) {
      var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
      new Uint8Array(result).set(new Uint8Array(arrayBuffer));
      return result;
    }

    /**
     * Creates a clone of `dataView`.
     *
     * @private
     * @param {Object} dataView The data view to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Object} Returns the cloned data view.
     */
    function cloneDataView(dataView, isDeep) {
      var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
      return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
    }

    /**
     * Creates a clone of `regexp`.
     *
     * @private
     * @param {Object} regexp The regexp to clone.
     * @returns {Object} Returns the cloned regexp.
     */
    function cloneRegExp(regexp) {
      var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
      result.lastIndex = regexp.lastIndex;
      return result;
    }

    /**
     * Creates a clone of the `symbol` object.
     *
     * @private
     * @param {Object} symbol The symbol object to clone.
     * @returns {Object} Returns the cloned symbol object.
     */
    function cloneSymbol(symbol) {
      return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
    }

    /**
     * Creates a clone of `typedArray`.
     *
     * @private
     * @param {Object} typedArray The typed array to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Object} Returns the cloned typed array.
     */
    function cloneTypedArray(typedArray, isDeep) {
      var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
      return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
    }

    /**
     * Compares values to sort them in ascending order.
     *
     * @private
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {number} Returns the sort order indicator for `value`.
     */
    function compareAscending(value, other) {
      if (value !== other) {
        var valIsDefined = value !== undefined,
            valIsNull = value === null,
            valIsReflexive = value === value,
            valIsSymbol = isSymbol(value);

        var othIsDefined = other !== undefined,
            othIsNull = other === null,
            othIsReflexive = other === other,
            othIsSymbol = isSymbol(other);

        if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
            (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
            (valIsNull && othIsDefined && othIsReflexive) ||
            (!valIsDefined && othIsReflexive) ||
            !valIsReflexive) {
          return 1;
        }
        if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
            (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
            (othIsNull && valIsDefined && valIsReflexive) ||
            (!othIsDefined && valIsReflexive) ||
            !othIsReflexive) {
          return -1;
        }
      }
      return 0;
    }

    /**
     * Used by `_.orderBy` to compare multiple properties of a value to another
     * and stable sort them.
     *
     * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
     * specify an order of "desc" for descending or "asc" for ascending sort order
     * of corresponding values.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {boolean[]|string[]} orders The order to sort by for each property.
     * @returns {number} Returns the sort order indicator for `object`.
     */
    function compareMultiple(object, other, orders) {
      var index = -1,
          objCriteria = object.criteria,
          othCriteria = other.criteria,
          length = objCriteria.length,
          ordersLength = orders.length;

      while (++index < length) {
        var result = compareAscending(objCriteria[index], othCriteria[index]);
        if (result) {
          if (index >= ordersLength) {
            return result;
          }
          var order = orders[index];
          return result * (order == 'desc' ? -1 : 1);
        }
      }
      // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
      // that causes it, under certain circumstances, to provide the same value for
      // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
      // for more details.
      //
      // This also ensures a stable sort in V8 and other engines.
      // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
      return object.index - other.index;
    }

    /**
     * Creates an array that is the composition of partially applied arguments,
     * placeholders, and provided arguments into a single array of arguments.
     *
     * @private
     * @param {Array} args The provided arguments.
     * @param {Array} partials The arguments to prepend to those provided.
     * @param {Array} holders The `partials` placeholder indexes.
     * @params {boolean} [isCurried] Specify composing for a curried function.
     * @returns {Array} Returns the new array of composed arguments.
     */
    function composeArgs(args, partials, holders, isCurried) {
      var argsIndex = -1,
          argsLength = args.length,
          holdersLength = holders.length,
          leftIndex = -1,
          leftLength = partials.length,
          rangeLength = nativeMax(argsLength - holdersLength, 0),
          result = Array(leftLength + rangeLength),
          isUncurried = !isCurried;

      while (++leftIndex < leftLength) {
        result[leftIndex] = partials[leftIndex];
      }
      while (++argsIndex < holdersLength) {
        if (isUncurried || argsIndex < argsLength) {
          result[holders[argsIndex]] = args[argsIndex];
        }
      }
      while (rangeLength--) {
        result[leftIndex++] = args[argsIndex++];
      }
      return result;
    }

    /**
     * This function is like `composeArgs` except that the arguments composition
     * is tailored for `_.partialRight`.
     *
     * @private
     * @param {Array} args The provided arguments.
     * @param {Array} partials The arguments to append to those provided.
     * @param {Array} holders The `partials` placeholder indexes.
     * @params {boolean} [isCurried] Specify composing for a curried function.
     * @returns {Array} Returns the new array of composed arguments.
     */
    function composeArgsRight(args, partials, holders, isCurried) {
      var argsIndex = -1,
          argsLength = args.length,
          holdersIndex = -1,
          holdersLength = holders.length,
          rightIndex = -1,
          rightLength = partials.length,
          rangeLength = nativeMax(argsLength - holdersLength, 0),
          result = Array(rangeLength + rightLength),
          isUncurried = !isCurried;

      while (++argsIndex < rangeLength) {
        result[argsIndex] = args[argsIndex];
      }
      var offset = argsIndex;
      while (++rightIndex < rightLength) {
        result[offset + rightIndex] = partials[rightIndex];
      }
      while (++holdersIndex < holdersLength) {
        if (isUncurried || argsIndex < argsLength) {
          result[offset + holders[holdersIndex]] = args[argsIndex++];
        }
      }
      return result;
    }

    /**
     * Copies the values of `source` to `array`.
     *
     * @private
     * @param {Array} source The array to copy values from.
     * @param {Array} [array=[]] The array to copy values to.
     * @returns {Array} Returns `array`.
     */
    function copyArray(source, array) {
      var index = -1,
          length = source.length;

      array || (array = Array(length));
      while (++index < length) {
        array[index] = source[index];
      }
      return array;
    }

    /**
     * Copies properties of `source` to `object`.
     *
     * @private
     * @param {Object} source The object to copy properties from.
     * @param {Array} props The property identifiers to copy.
     * @param {Object} [object={}] The object to copy properties to.
     * @param {Function} [customizer] The function to customize copied values.
     * @returns {Object} Returns `object`.
     */
    function copyObject(source, props, object, customizer) {
      var isNew = !object;
      object || (object = {});

      var index = -1,
          length = props.length;

      while (++index < length) {
        var key = props[index];

        var newValue = customizer
          ? customizer(object[key], source[key], key, object, source)
          : undefined;

        if (newValue === undefined) {
          newValue = source[key];
        }
        if (isNew) {
          baseAssignValue(object, key, newValue);
        } else {
          assignValue(object, key, newValue);
        }
      }
      return object;
    }

    /**
     * Copies own symbols of `source` to `object`.
     *
     * @private
     * @param {Object} source The object to copy symbols from.
     * @param {Object} [object={}] The object to copy symbols to.
     * @returns {Object} Returns `object`.
     */
    function copySymbols(source, object) {
      return copyObject(source, getSymbols(source), object);
    }

    /**
     * Copies own and inherited symbols of `source` to `object`.
     *
     * @private
     * @param {Object} source The object to copy symbols from.
     * @param {Object} [object={}] The object to copy symbols to.
     * @returns {Object} Returns `object`.
     */
    function copySymbolsIn(source, object) {
      return copyObject(source, getSymbolsIn(source), object);
    }

    /**
     * Creates a function like `_.groupBy`.
     *
     * @private
     * @param {Function} setter The function to set accumulator values.
     * @param {Function} [initializer] The accumulator object initializer.
     * @returns {Function} Returns the new aggregator function.
     */
    function createAggregator(setter, initializer) {
      return function(collection, iteratee) {
        var func = isArray(collection) ? arrayAggregator : baseAggregator,
            accumulator = initializer ? initializer() : {};

        return func(collection, setter, getIteratee(iteratee, 2), accumulator);
      };
    }

    /**
     * Creates a function like `_.assign`.
     *
     * @private
     * @param {Function} assigner The function to assign values.
     * @returns {Function} Returns the new assigner function.
     */
    function createAssigner(assigner) {
      return baseRest(function(object, sources) {
        var index = -1,
            length = sources.length,
            customizer = length > 1 ? sources[length - 1] : undefined,
            guard = length > 2 ? sources[2] : undefined;

        customizer = (assigner.length > 3 && typeof customizer == 'function')
          ? (length--, customizer)
          : undefined;

        if (guard && isIterateeCall(sources[0], sources[1], guard)) {
          customizer = length < 3 ? undefined : customizer;
          length = 1;
        }
        object = Object(object);
        while (++index < length) {
          var source = sources[index];
          if (source) {
            assigner(object, source, index, customizer);
          }
        }
        return object;
      });
    }

    /**
     * Creates a `baseEach` or `baseEachRight` function.
     *
     * @private
     * @param {Function} eachFunc The function to iterate over a collection.
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new base function.
     */
    function createBaseEach(eachFunc, fromRight) {
      return function(collection, iteratee) {
        if (collection == null) {
          return collection;
        }
        if (!isArrayLike(collection)) {
          return eachFunc(collection, iteratee);
        }
        var length = collection.length,
            index = fromRight ? length : -1,
            iterable = Object(collection);

        while ((fromRight ? index-- : ++index < length)) {
          if (iteratee(iterable[index], index, iterable) === false) {
            break;
          }
        }
        return collection;
      };
    }

    /**
     * Creates a base function for methods like `_.forIn` and `_.forOwn`.
     *
     * @private
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new base function.
     */
    function createBaseFor(fromRight) {
      return function(object, iteratee, keysFunc) {
        var index = -1,
            iterable = Object(object),
            props = keysFunc(object),
            length = props.length;

        while (length--) {
          var key = props[fromRight ? length : ++index];
          if (iteratee(iterable[key], key, iterable) === false) {
            break;
          }
        }
        return object;
      };
    }

    /**
     * Creates a function that wraps `func` to invoke it with the optional `this`
     * binding of `thisArg`.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @returns {Function} Returns the new wrapped function.
     */
    function createBind(func, bitmask, thisArg) {
      var isBind = bitmask & WRAP_BIND_FLAG,
          Ctor = createCtor(func);

      function wrapper() {
        var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
        return fn.apply(isBind ? thisArg : this, arguments);
      }
      return wrapper;
    }

    /**
     * Creates a function like `_.lowerFirst`.
     *
     * @private
     * @param {string} methodName The name of the `String` case method to use.
     * @returns {Function} Returns the new case function.
     */
    function createCaseFirst(methodName) {
      return function(string) {
        string = toString(string);

        var strSymbols = hasUnicode(string)
          ? stringToArray(string)
          : undefined;

        var chr = strSymbols
          ? strSymbols[0]
          : string.charAt(0);

        var trailing = strSymbols
          ? castSlice(strSymbols, 1).join('')
          : string.slice(1);

        return chr[methodName]() + trailing;
      };
    }

    /**
     * Creates a function like `_.camelCase`.
     *
     * @private
     * @param {Function} callback The function to combine each word.
     * @returns {Function} Returns the new compounder function.
     */
    function createCompounder(callback) {
      return function(string) {
        return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
      };
    }

    /**
     * Creates a function that produces an instance of `Ctor` regardless of
     * whether it was invoked as part of a `new` expression or by `call` or `apply`.
     *
     * @private
     * @param {Function} Ctor The constructor to wrap.
     * @returns {Function} Returns the new wrapped function.
     */
    function createCtor(Ctor) {
      return function() {
        // Use a `switch` statement to work with class constructors. See
        // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
        // for more details.
        var args = arguments;
        switch (args.length) {
          case 0: return new Ctor;
          case 1: return new Ctor(args[0]);
          case 2: return new Ctor(args[0], args[1]);
          case 3: return new Ctor(args[0], args[1], args[2]);
          case 4: return new Ctor(args[0], args[1], args[2], args[3]);
          case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
          case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
          case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
        }
        var thisBinding = baseCreate(Ctor.prototype),
            result = Ctor.apply(thisBinding, args);

        // Mimic the constructor's `return` behavior.
        // See https://es5.github.io/#x13.2.2 for more details.
        return isObject(result) ? result : thisBinding;
      };
    }

    /**
     * Creates a function that wraps `func` to enable currying.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {number} arity The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */
    function createCurry(func, bitmask, arity) {
      var Ctor = createCtor(func);

      function wrapper() {
        var length = arguments.length,
            args = Array(length),
            index = length,
            placeholder = getHolder(wrapper);

        while (index--) {
          args[index] = arguments[index];
        }
        var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
          ? []
          : replaceHolders(args, placeholder);

        length -= holders.length;
        if (length < arity) {
          return createRecurry(
            func, bitmask, createHybrid, wrapper.placeholder, undefined,
            args, holders, undefined, undefined, arity - length);
        }
        var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
        return apply(fn, this, args);
      }
      return wrapper;
    }

    /**
     * Creates a `_.find` or `_.findLast` function.
     *
     * @private
     * @param {Function} findIndexFunc The function to find the collection index.
     * @returns {Function} Returns the new find function.
     */
    function createFind(findIndexFunc) {
      return function(collection, predicate, fromIndex) {
        var iterable = Object(collection);
        if (!isArrayLike(collection)) {
          var iteratee = getIteratee(predicate, 3);
          collection = keys(collection);
          predicate = function(key) { return iteratee(iterable[key], key, iterable); };
        }
        var index = findIndexFunc(collection, predicate, fromIndex);
        return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
      };
    }

    /**
     * Creates a `_.flow` or `_.flowRight` function.
     *
     * @private
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new flow function.
     */
    function createFlow(fromRight) {
      return flatRest(function(funcs) {
        var length = funcs.length,
            index = length,
            prereq = LodashWrapper.prototype.thru;

        if (fromRight) {
          funcs.reverse();
        }
        while (index--) {
          var func = funcs[index];
          if (typeof func != 'function') {
            throw new TypeError(FUNC_ERROR_TEXT);
          }
          if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
            var wrapper = new LodashWrapper([], true);
          }
        }
        index = wrapper ? index : length;
        while (++index < length) {
          func = funcs[index];

          var funcName = getFuncName(func),
              data = funcName == 'wrapper' ? getData(func) : undefined;

          if (data && isLaziable(data[0]) &&
                data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
                !data[4].length && data[9] == 1
              ) {
            wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
          } else {
            wrapper = (func.length == 1 && isLaziable(func))
              ? wrapper[funcName]()
              : wrapper.thru(func);
          }
        }
        return function() {
          var args = arguments,
              value = args[0];

          if (wrapper && args.length == 1 && isArray(value)) {
            return wrapper.plant(value).value();
          }
          var index = 0,
              result = length ? funcs[index].apply(this, args) : value;

          while (++index < length) {
            result = funcs[index].call(this, result);
          }
          return result;
        };
      });
    }

    /**
     * Creates a function that wraps `func` to invoke it with optional `this`
     * binding of `thisArg`, partial application, and currying.
     *
     * @private
     * @param {Function|string} func The function or method name to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {Array} [partials] The arguments to prepend to those provided to
     *  the new function.
     * @param {Array} [holders] The `partials` placeholder indexes.
     * @param {Array} [partialsRight] The arguments to append to those provided
     *  to the new function.
     * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
     * @param {Array} [argPos] The argument positions of the new function.
     * @param {number} [ary] The arity cap of `func`.
     * @param {number} [arity] The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */
    function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
      var isAry = bitmask & WRAP_ARY_FLAG,
          isBind = bitmask & WRAP_BIND_FLAG,
          isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
          isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
          isFlip = bitmask & WRAP_FLIP_FLAG,
          Ctor = isBindKey ? undefined : createCtor(func);

      function wrapper() {
        var length = arguments.length,
            args = Array(length),
            index = length;

        while (index--) {
          args[index] = arguments[index];
        }
        if (isCurried) {
          var placeholder = getHolder(wrapper),
              holdersCount = countHolders(args, placeholder);
        }
        if (partials) {
          args = composeArgs(args, partials, holders, isCurried);
        }
        if (partialsRight) {
          args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
        }
        length -= holdersCount;
        if (isCurried && length < arity) {
          var newHolders = replaceHolders(args, placeholder);
          return createRecurry(
            func, bitmask, createHybrid, wrapper.placeholder, thisArg,
            args, newHolders, argPos, ary, arity - length
          );
        }
        var thisBinding = isBind ? thisArg : this,
            fn = isBindKey ? thisBinding[func] : func;

        length = args.length;
        if (argPos) {
          args = reorder(args, argPos);
        } else if (isFlip && length > 1) {
          args.reverse();
        }
        if (isAry && ary < length) {
          args.length = ary;
        }
        if (this && this !== root && this instanceof wrapper) {
          fn = Ctor || createCtor(fn);
        }
        return fn.apply(thisBinding, args);
      }
      return wrapper;
    }

    /**
     * Creates a function like `_.invertBy`.
     *
     * @private
     * @param {Function} setter The function to set accumulator values.
     * @param {Function} toIteratee The function to resolve iteratees.
     * @returns {Function} Returns the new inverter function.
     */
    function createInverter(setter, toIteratee) {
      return function(object, iteratee) {
        return baseInverter(object, setter, toIteratee(iteratee), {});
      };
    }

    /**
     * Creates a function that performs a mathematical operation on two values.
     *
     * @private
     * @param {Function} operator The function to perform the operation.
     * @param {number} [defaultValue] The value used for `undefined` arguments.
     * @returns {Function} Returns the new mathematical operation function.
     */
    function createMathOperation(operator, defaultValue) {
      return function(value, other) {
        var result;
        if (value === undefined && other === undefined) {
          return defaultValue;
        }
        if (value !== undefined) {
          result = value;
        }
        if (other !== undefined) {
          if (result === undefined) {
            return other;
          }
          if (typeof value == 'string' || typeof other == 'string') {
            value = baseToString(value);
            other = baseToString(other);
          } else {
            value = baseToNumber(value);
            other = baseToNumber(other);
          }
          result = operator(value, other);
        }
        return result;
      };
    }

    /**
     * Creates a function like `_.over`.
     *
     * @private
     * @param {Function} arrayFunc The function to iterate over iteratees.
     * @returns {Function} Returns the new over function.
     */
    function createOver(arrayFunc) {
      return flatRest(function(iteratees) {
        iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
        return baseRest(function(args) {
          var thisArg = this;
          return arrayFunc(iteratees, function(iteratee) {
            return apply(iteratee, thisArg, args);
          });
        });
      });
    }

    /**
     * Creates the padding for `string` based on `length`. The `chars` string
     * is truncated if the number of characters exceeds `length`.
     *
     * @private
     * @param {number} length The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padding for `string`.
     */
    function createPadding(length, chars) {
      chars = chars === undefined ? ' ' : baseToString(chars);

      var charsLength = chars.length;
      if (charsLength < 2) {
        return charsLength ? baseRepeat(chars, length) : chars;
      }
      var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
      return hasUnicode(chars)
        ? castSlice(stringToArray(result), 0, length).join('')
        : result.slice(0, length);
    }

    /**
     * Creates a function that wraps `func` to invoke it with the `this` binding
     * of `thisArg` and `partials` prepended to the arguments it receives.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {*} thisArg The `this` binding of `func`.
     * @param {Array} partials The arguments to prepend to those provided to
     *  the new function.
     * @returns {Function} Returns the new wrapped function.
     */
    function createPartial(func, bitmask, thisArg, partials) {
      var isBind = bitmask & WRAP_BIND_FLAG,
          Ctor = createCtor(func);

      function wrapper() {
        var argsIndex = -1,
            argsLength = arguments.length,
            leftIndex = -1,
            leftLength = partials.length,
            args = Array(leftLength + argsLength),
            fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;

        while (++leftIndex < leftLength) {
          args[leftIndex] = partials[leftIndex];
        }
        while (argsLength--) {
          args[leftIndex++] = arguments[++argsIndex];
        }
        return apply(fn, isBind ? thisArg : this, args);
      }
      return wrapper;
    }

    /**
     * Creates a `_.range` or `_.rangeRight` function.
     *
     * @private
     * @param {boolean} [fromRight] Specify iterating from right to left.
     * @returns {Function} Returns the new range function.
     */
    function createRange(fromRight) {
      return function(start, end, step) {
        if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
          end = step = undefined;
        }
        // Ensure the sign of `-0` is preserved.
        start = toFinite(start);
        if (end === undefined) {
          end = start;
          start = 0;
        } else {
          end = toFinite(end);
        }
        step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
        return baseRange(start, end, step, fromRight);
      };
    }

    /**
     * Creates a function that performs a relational operation on two values.
     *
     * @private
     * @param {Function} operator The function to perform the operation.
     * @returns {Function} Returns the new relational operation function.
     */
    function createRelationalOperation(operator) {
      return function(value, other) {
        if (!(typeof value == 'string' && typeof other == 'string')) {
          value = toNumber(value);
          other = toNumber(other);
        }
        return operator(value, other);
      };
    }

    /**
     * Creates a function that wraps `func` to continue currying.
     *
     * @private
     * @param {Function} func The function to wrap.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @param {Function} wrapFunc The function to create the `func` wrapper.
     * @param {*} placeholder The placeholder value.
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {Array} [partials] The arguments to prepend to those provided to
     *  the new function.
     * @param {Array} [holders] The `partials` placeholder indexes.
     * @param {Array} [argPos] The argument positions of the new function.
     * @param {number} [ary] The arity cap of `func`.
     * @param {number} [arity] The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */
    function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
      var isCurry = bitmask & WRAP_CURRY_FLAG,
          newHolders = isCurry ? holders : undefined,
          newHoldersRight = isCurry ? undefined : holders,
          newPartials = isCurry ? partials : undefined,
          newPartialsRight = isCurry ? undefined : partials;

      bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
      bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);

      if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
        bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
      }
      var newData = [
        func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
        newHoldersRight, argPos, ary, arity
      ];

      var result = wrapFunc.apply(undefined, newData);
      if (isLaziable(func)) {
        setData(result, newData);
      }
      result.placeholder = placeholder;
      return setWrapToString(result, func, bitmask);
    }

    /**
     * Creates a function like `_.round`.
     *
     * @private
     * @param {string} methodName The name of the `Math` method to use when rounding.
     * @returns {Function} Returns the new round function.
     */
    function createRound(methodName) {
      var func = Math[methodName];
      return function(number, precision) {
        number = toNumber(number);
        precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
        if (precision && nativeIsFinite(number)) {
          // Shift with exponential notation to avoid floating-point issues.
          // See [MDN](https://mdn.io/round#Examples) for more details.
          var pair = (toString(number) + 'e').split('e'),
              value = func(pair[0] + 'e' + (+pair[1] + precision));

          pair = (toString(value) + 'e').split('e');
          return +(pair[0] + 'e' + (+pair[1] - precision));
        }
        return func(number);
      };
    }

    /**
     * Creates a set object of `values`.
     *
     * @private
     * @param {Array} values The values to add to the set.
     * @returns {Object} Returns the new set.
     */
    var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
      return new Set(values);
    };

    /**
     * Creates a `_.toPairs` or `_.toPairsIn` function.
     *
     * @private
     * @param {Function} keysFunc The function to get the keys of a given object.
     * @returns {Function} Returns the new pairs function.
     */
    function createToPairs(keysFunc) {
      return function(object) {
        var tag = getTag(object);
        if (tag == mapTag) {
          return mapToArray(object);
        }
        if (tag == setTag) {
          return setToPairs(object);
        }
        return baseToPairs(object, keysFunc(object));
      };
    }

    /**
     * Creates a function that either curries or invokes `func` with optional
     * `this` binding and partially applied arguments.
     *
     * @private
     * @param {Function|string} func The function or method name to wrap.
     * @param {number} bitmask The bitmask flags.
     *    1 - `_.bind`
     *    2 - `_.bindKey`
     *    4 - `_.curry` or `_.curryRight` of a bound function
     *    8 - `_.curry`
     *   16 - `_.curryRight`
     *   32 - `_.partial`
     *   64 - `_.partialRight`
     *  128 - `_.rearg`
     *  256 - `_.ary`
     *  512 - `_.flip`
     * @param {*} [thisArg] The `this` binding of `func`.
     * @param {Array} [partials] The arguments to be partially applied.
     * @param {Array} [holders] The `partials` placeholder indexes.
     * @param {Array} [argPos] The argument positions of the new function.
     * @param {number} [ary] The arity cap of `func`.
     * @param {number} [arity] The arity of `func`.
     * @returns {Function} Returns the new wrapped function.
     */
    function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
      var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
      if (!isBindKey && typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      var length = partials ? partials.length : 0;
      if (!length) {
        bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
        partials = holders = undefined;
      }
      ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
      arity = arity === undefined ? arity : toInteger(arity);
      length -= holders ? holders.length : 0;

      if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
        var partialsRight = partials,
            holdersRight = holders;

        partials = holders = undefined;
      }
      var data = isBindKey ? undefined : getData(func);

      var newData = [
        func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
        argPos, ary, arity
      ];

      if (data) {
        mergeData(newData, data);
      }
      func = newData[0];
      bitmask = newData[1];
      thisArg = newData[2];
      partials = newData[3];
      holders = newData[4];
      arity = newData[9] = newData[9] === undefined
        ? (isBindKey ? 0 : func.length)
        : nativeMax(newData[9] - length, 0);

      if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
        bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
      }
      if (!bitmask || bitmask == WRAP_BIND_FLAG) {
        var result = createBind(func, bitmask, thisArg);
      } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
        result = createCurry(func, bitmask, arity);
      } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
        result = createPartial(func, bitmask, thisArg, partials);
      } else {
        result = createHybrid.apply(undefined, newData);
      }
      var setter = data ? baseSetData : setData;
      return setWrapToString(setter(result, newData), func, bitmask);
    }

    /**
     * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
     * of source objects to the destination object for all destination properties
     * that resolve to `undefined`.
     *
     * @private
     * @param {*} objValue The destination value.
     * @param {*} srcValue The source value.
     * @param {string} key The key of the property to assign.
     * @param {Object} object The parent object of `objValue`.
     * @returns {*} Returns the value to assign.
     */
    function customDefaultsAssignIn(objValue, srcValue, key, object) {
      if (objValue === undefined ||
          (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
        return srcValue;
      }
      return objValue;
    }

    /**
     * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
     * objects into destination objects that are passed thru.
     *
     * @private
     * @param {*} objValue The destination value.
     * @param {*} srcValue The source value.
     * @param {string} key The key of the property to merge.
     * @param {Object} object The parent object of `objValue`.
     * @param {Object} source The parent object of `srcValue`.
     * @param {Object} [stack] Tracks traversed source values and their merged
     *  counterparts.
     * @returns {*} Returns the value to assign.
     */
    function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
      if (isObject(objValue) && isObject(srcValue)) {
        // Recursively merge objects and arrays (susceptible to call stack limits).
        stack.set(srcValue, objValue);
        baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
        stack['delete'](srcValue);
      }
      return objValue;
    }

    /**
     * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
     * objects.
     *
     * @private
     * @param {*} value The value to inspect.
     * @param {string} key The key of the property to inspect.
     * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
     */
    function customOmitClone(value) {
      return isPlainObject(value) ? undefined : value;
    }

    /**
     * A specialized version of `baseIsEqualDeep` for arrays with support for
     * partial deep comparisons.
     *
     * @private
     * @param {Array} array The array to compare.
     * @param {Array} other The other array to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} stack Tracks traversed `array` and `other` objects.
     * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
     */
    function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
          arrLength = array.length,
          othLength = other.length;

      if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
        return false;
      }
      // Check that cyclic values are equal.
      var arrStacked = stack.get(array);
      var othStacked = stack.get(other);
      if (arrStacked && othStacked) {
        return arrStacked == other && othStacked == array;
      }
      var index = -1,
          result = true,
          seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;

      stack.set(array, other);
      stack.set(other, array);

      // Ignore non-index properties.
      while (++index < arrLength) {
        var arrValue = array[index],
            othValue = other[index];

        if (customizer) {
          var compared = isPartial
            ? customizer(othValue, arrValue, index, other, array, stack)
            : customizer(arrValue, othValue, index, array, other, stack);
        }
        if (compared !== undefined) {
          if (compared) {
            continue;
          }
          result = false;
          break;
        }
        // Recursively compare arrays (susceptible to call stack limits).
        if (seen) {
          if (!arraySome(other, function(othValue, othIndex) {
                if (!cacheHas(seen, othIndex) &&
                    (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
                  return seen.push(othIndex);
                }
              })) {
            result = false;
            break;
          }
        } else if (!(
              arrValue === othValue ||
                equalFunc(arrValue, othValue, bitmask, customizer, stack)
            )) {
          result = false;
          break;
        }
      }
      stack['delete'](array);
      stack['delete'](other);
      return result;
    }

    /**
     * A specialized version of `baseIsEqualDeep` for comparing objects of
     * the same `toStringTag`.
     *
     * **Note:** This function only supports comparing values with tags of
     * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {string} tag The `toStringTag` of the objects to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} stack Tracks traversed `object` and `other` objects.
     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
     */
    function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
      switch (tag) {
        case dataViewTag:
          if ((object.byteLength != other.byteLength) ||
              (object.byteOffset != other.byteOffset)) {
            return false;
          }
          object = object.buffer;
          other = other.buffer;

        case arrayBufferTag:
          if ((object.byteLength != other.byteLength) ||
              !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
            return false;
          }
          return true;

        case boolTag:
        case dateTag:
        case numberTag:
          // Coerce booleans to `1` or `0` and dates to milliseconds.
          // Invalid dates are coerced to `NaN`.
          return eq(+object, +other);

        case errorTag:
          return object.name == other.name && object.message == other.message;

        case regexpTag:
        case stringTag:
          // Coerce regexes to strings and treat strings, primitives and objects,
          // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
          // for more details.
          return object == (other + '');

        case mapTag:
          var convert = mapToArray;

        case setTag:
          var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
          convert || (convert = setToArray);

          if (object.size != other.size && !isPartial) {
            return false;
          }
          // Assume cyclic values are equal.
          var stacked = stack.get(object);
          if (stacked) {
            return stacked == other;
          }
          bitmask |= COMPARE_UNORDERED_FLAG;

          // Recursively compare objects (susceptible to call stack limits).
          stack.set(object, other);
          var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
          stack['delete'](object);
          return result;

        case symbolTag:
          if (symbolValueOf) {
            return symbolValueOf.call(object) == symbolValueOf.call(other);
          }
      }
      return false;
    }

    /**
     * A specialized version of `baseIsEqualDeep` for objects with support for
     * partial deep comparisons.
     *
     * @private
     * @param {Object} object The object to compare.
     * @param {Object} other The other object to compare.
     * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
     * @param {Function} customizer The function to customize comparisons.
     * @param {Function} equalFunc The function to determine equivalents of values.
     * @param {Object} stack Tracks traversed `object` and `other` objects.
     * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
     */
    function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
          objProps = getAllKeys(object),
          objLength = objProps.length,
          othProps = getAllKeys(other),
          othLength = othProps.length;

      if (objLength != othLength && !isPartial) {
        return false;
      }
      var index = objLength;
      while (index--) {
        var key = objProps[index];
        if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
          return false;
        }
      }
      // Check that cyclic values are equal.
      var objStacked = stack.get(object);
      var othStacked = stack.get(other);
      if (objStacked && othStacked) {
        return objStacked == other && othStacked == object;
      }
      var result = true;
      stack.set(object, other);
      stack.set(other, object);

      var skipCtor = isPartial;
      while (++index < objLength) {
        key = objProps[index];
        var objValue = object[key],
            othValue = other[key];

        if (customizer) {
          var compared = isPartial
            ? customizer(othValue, objValue, key, other, object, stack)
            : customizer(objValue, othValue, key, object, other, stack);
        }
        // Recursively compare objects (susceptible to call stack limits).
        if (!(compared === undefined
              ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
              : compared
            )) {
          result = false;
          break;
        }
        skipCtor || (skipCtor = key == 'constructor');
      }
      if (result && !skipCtor) {
        var objCtor = object.constructor,
            othCtor = other.constructor;

        // Non `Object` object instances with different constructors are not equal.
        if (objCtor != othCtor &&
            ('constructor' in object && 'constructor' in other) &&
            !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
              typeof othCtor == 'function' && othCtor instanceof othCtor)) {
          result = false;
        }
      }
      stack['delete'](object);
      stack['delete'](other);
      return result;
    }

    /**
     * A specialized version of `baseRest` which flattens the rest array.
     *
     * @private
     * @param {Function} func The function to apply a rest parameter to.
     * @returns {Function} Returns the new function.
     */
    function flatRest(func) {
      return setToString(overRest(func, undefined, flatten), func + '');
    }

    /**
     * Creates an array of own enumerable property names and symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names and symbols.
     */
    function getAllKeys(object) {
      return baseGetAllKeys(object, keys, getSymbols);
    }

    /**
     * Creates an array of own and inherited enumerable property names and
     * symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names and symbols.
     */
    function getAllKeysIn(object) {
      return baseGetAllKeys(object, keysIn, getSymbolsIn);
    }

    /**
     * Gets metadata for `func`.
     *
     * @private
     * @param {Function} func The function to query.
     * @returns {*} Returns the metadata for `func`.
     */
    var getData = !metaMap ? noop : function(func) {
      return metaMap.get(func);
    };

    /**
     * Gets the name of `func`.
     *
     * @private
     * @param {Function} func The function to query.
     * @returns {string} Returns the function name.
     */
    function getFuncName(func) {
      var result = (func.name + ''),
          array = realNames[result],
          length = hasOwnProperty.call(realNames, result) ? array.length : 0;

      while (length--) {
        var data = array[length],
            otherFunc = data.func;
        if (otherFunc == null || otherFunc == func) {
          return data.name;
        }
      }
      return result;
    }

    /**
     * Gets the argument placeholder value for `func`.
     *
     * @private
     * @param {Function} func The function to inspect.
     * @returns {*} Returns the placeholder value.
     */
    function getHolder(func) {
      var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
      return object.placeholder;
    }

    /**
     * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
     * this function returns the custom method, otherwise it returns `baseIteratee`.
     * If arguments are provided, the chosen function is invoked with them and
     * its result is returned.
     *
     * @private
     * @param {*} [value] The value to convert to an iteratee.
     * @param {number} [arity] The arity of the created iteratee.
     * @returns {Function} Returns the chosen function or its result.
     */
    function getIteratee() {
      var result = lodash.iteratee || iteratee;
      result = result === iteratee ? baseIteratee : result;
      return arguments.length ? result(arguments[0], arguments[1]) : result;
    }

    /**
     * Gets the data for `map`.
     *
     * @private
     * @param {Object} map The map to query.
     * @param {string} key The reference key.
     * @returns {*} Returns the map data.
     */
    function getMapData(map, key) {
      var data = map.__data__;
      return isKeyable(key)
        ? data[typeof key == 'string' ? 'string' : 'hash']
        : data.map;
    }

    /**
     * Gets the property names, values, and compare flags of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the match data of `object`.
     */
    function getMatchData(object) {
      var result = keys(object),
          length = result.length;

      while (length--) {
        var key = result[length],
            value = object[key];

        result[length] = [key, value, isStrictComparable(value)];
      }
      return result;
    }

    /**
     * Gets the native function at `key` of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {string} key The key of the method to get.
     * @returns {*} Returns the function if it's native, else `undefined`.
     */
    function getNative(object, key) {
      var value = getValue(object, key);
      return baseIsNative(value) ? value : undefined;
    }

    /**
     * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
     *
     * @private
     * @param {*} value The value to query.
     * @returns {string} Returns the raw `toStringTag`.
     */
    function getRawTag(value) {
      var isOwn = hasOwnProperty.call(value, symToStringTag),
          tag = value[symToStringTag];

      try {
        value[symToStringTag] = undefined;
        var unmasked = true;
      } catch (e) {}

      var result = nativeObjectToString.call(value);
      if (unmasked) {
        if (isOwn) {
          value[symToStringTag] = tag;
        } else {
          delete value[symToStringTag];
        }
      }
      return result;
    }

    /**
     * Creates an array of the own enumerable symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of symbols.
     */
    var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
      if (object == null) {
        return [];
      }
      object = Object(object);
      return arrayFilter(nativeGetSymbols(object), function(symbol) {
        return propertyIsEnumerable.call(object, symbol);
      });
    };

    /**
     * Creates an array of the own and inherited enumerable symbols of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of symbols.
     */
    var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
      var result = [];
      while (object) {
        arrayPush(result, getSymbols(object));
        object = getPrototype(object);
      }
      return result;
    };

    /**
     * Gets the `toStringTag` of `value`.
     *
     * @private
     * @param {*} value The value to query.
     * @returns {string} Returns the `toStringTag`.
     */
    var getTag = baseGetTag;

    // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
    if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
        (Map && getTag(new Map) != mapTag) ||
        (Promise && getTag(Promise.resolve()) != promiseTag) ||
        (Set && getTag(new Set) != setTag) ||
        (WeakMap && getTag(new WeakMap) != weakMapTag)) {
      getTag = function(value) {
        var result = baseGetTag(value),
            Ctor = result == objectTag ? value.constructor : undefined,
            ctorString = Ctor ? toSource(Ctor) : '';

        if (ctorString) {
          switch (ctorString) {
            case dataViewCtorString: return dataViewTag;
            case mapCtorString: return mapTag;
            case promiseCtorString: return promiseTag;
            case setCtorString: return setTag;
            case weakMapCtorString: return weakMapTag;
          }
        }
        return result;
      };
    }

    /**
     * Gets the view, applying any `transforms` to the `start` and `end` positions.
     *
     * @private
     * @param {number} start The start of the view.
     * @param {number} end The end of the view.
     * @param {Array} transforms The transformations to apply to the view.
     * @returns {Object} Returns an object containing the `start` and `end`
     *  positions of the view.
     */
    function getView(start, end, transforms) {
      var index = -1,
          length = transforms.length;

      while (++index < length) {
        var data = transforms[index],
            size = data.size;

        switch (data.type) {
          case 'drop':      start += size; break;
          case 'dropRight': end -= size; break;
          case 'take':      end = nativeMin(end, start + size); break;
          case 'takeRight': start = nativeMax(start, end - size); break;
        }
      }
      return { 'start': start, 'end': end };
    }

    /**
     * Extracts wrapper details from the `source` body comment.
     *
     * @private
     * @param {string} source The source to inspect.
     * @returns {Array} Returns the wrapper details.
     */
    function getWrapDetails(source) {
      var match = source.match(reWrapDetails);
      return match ? match[1].split(reSplitDetails) : [];
    }

    /**
     * Checks if `path` exists on `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array|string} path The path to check.
     * @param {Function} hasFunc The function to check properties.
     * @returns {boolean} Returns `true` if `path` exists, else `false`.
     */
    function hasPath(object, path, hasFunc) {
      path = castPath(path, object);

      var index = -1,
          length = path.length,
          result = false;

      while (++index < length) {
        var key = toKey(path[index]);
        if (!(result = object != null && hasFunc(object, key))) {
          break;
        }
        object = object[key];
      }
      if (result || ++index != length) {
        return result;
      }
      length = object == null ? 0 : object.length;
      return !!length && isLength(length) && isIndex(key, length) &&
        (isArray(object) || isArguments(object));
    }

    /**
     * Initializes an array clone.
     *
     * @private
     * @param {Array} array The array to clone.
     * @returns {Array} Returns the initialized clone.
     */
    function initCloneArray(array) {
      var length = array.length,
          result = new array.constructor(length);

      // Add properties assigned by `RegExp#exec`.
      if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
        result.index = array.index;
        result.input = array.input;
      }
      return result;
    }

    /**
     * Initializes an object clone.
     *
     * @private
     * @param {Object} object The object to clone.
     * @returns {Object} Returns the initialized clone.
     */
    function initCloneObject(object) {
      return (typeof object.constructor == 'function' && !isPrototype(object))
        ? baseCreate(getPrototype(object))
        : {};
    }

    /**
     * Initializes an object clone based on its `toStringTag`.
     *
     * **Note:** This function only supports cloning values with tags of
     * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
     *
     * @private
     * @param {Object} object The object to clone.
     * @param {string} tag The `toStringTag` of the object to clone.
     * @param {boolean} [isDeep] Specify a deep clone.
     * @returns {Object} Returns the initialized clone.
     */
    function initCloneByTag(object, tag, isDeep) {
      var Ctor = object.constructor;
      switch (tag) {
        case arrayBufferTag:
          return cloneArrayBuffer(object);

        case boolTag:
        case dateTag:
          return new Ctor(+object);

        case dataViewTag:
          return cloneDataView(object, isDeep);

        case float32Tag: case float64Tag:
        case int8Tag: case int16Tag: case int32Tag:
        case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
          return cloneTypedArray(object, isDeep);

        case mapTag:
          return new Ctor;

        case numberTag:
        case stringTag:
          return new Ctor(object);

        case regexpTag:
          return cloneRegExp(object);

        case setTag:
          return new Ctor;

        case symbolTag:
          return cloneSymbol(object);
      }
    }

    /**
     * Inserts wrapper `details` in a comment at the top of the `source` body.
     *
     * @private
     * @param {string} source The source to modify.
     * @returns {Array} details The details to insert.
     * @returns {string} Returns the modified source.
     */
    function insertWrapDetails(source, details) {
      var length = details.length;
      if (!length) {
        return source;
      }
      var lastIndex = length - 1;
      details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
      details = details.join(length > 2 ? ', ' : ' ');
      return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
    }

    /**
     * Checks if `value` is a flattenable `arguments` object or array.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
     */
    function isFlattenable(value) {
      return isArray(value) || isArguments(value) ||
        !!(spreadableSymbol && value && value[spreadableSymbol]);
    }

    /**
     * Checks if `value` is a valid array-like index.
     *
     * @private
     * @param {*} value The value to check.
     * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
     * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
     */
    function isIndex(value, length) {
      var type = typeof value;
      length = length == null ? MAX_SAFE_INTEGER : length;

      return !!length &&
        (type == 'number' ||
          (type != 'symbol' && reIsUint.test(value))) &&
            (value > -1 && value % 1 == 0 && value < length);
    }

    /**
     * Checks if the given arguments are from an iteratee call.
     *
     * @private
     * @param {*} value The potential iteratee value argument.
     * @param {*} index The potential iteratee index or key argument.
     * @param {*} object The potential iteratee object argument.
     * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
     *  else `false`.
     */
    function isIterateeCall(value, index, object) {
      if (!isObject(object)) {
        return false;
      }
      var type = typeof index;
      if (type == 'number'
            ? (isArrayLike(object) && isIndex(index, object.length))
            : (type == 'string' && index in object)
          ) {
        return eq(object[index], value);
      }
      return false;
    }

    /**
     * Checks if `value` is a property name and not a property path.
     *
     * @private
     * @param {*} value The value to check.
     * @param {Object} [object] The object to query keys on.
     * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
     */
    function isKey(value, object) {
      if (isArray(value)) {
        return false;
      }
      var type = typeof value;
      if (type == 'number' || type == 'symbol' || type == 'boolean' ||
          value == null || isSymbol(value)) {
        return true;
      }
      return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
        (object != null && value in Object(object));
    }

    /**
     * Checks if `value` is suitable for use as unique object key.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
     */
    function isKeyable(value) {
      var type = typeof value;
      return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
        ? (value !== '__proto__')
        : (value === null);
    }

    /**
     * Checks if `func` has a lazy counterpart.
     *
     * @private
     * @param {Function} func The function to check.
     * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
     *  else `false`.
     */
    function isLaziable(func) {
      var funcName = getFuncName(func),
          other = lodash[funcName];

      if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
        return false;
      }
      if (func === other) {
        return true;
      }
      var data = getData(other);
      return !!data && func === data[0];
    }

    /**
     * Checks if `func` has its source masked.
     *
     * @private
     * @param {Function} func The function to check.
     * @returns {boolean} Returns `true` if `func` is masked, else `false`.
     */
    function isMasked(func) {
      return !!maskSrcKey && (maskSrcKey in func);
    }

    /**
     * Checks if `func` is capable of being masked.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
     */
    var isMaskable = coreJsData ? isFunction : stubFalse;

    /**
     * Checks if `value` is likely a prototype object.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
     */
    function isPrototype(value) {
      var Ctor = value && value.constructor,
          proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;

      return value === proto;
    }

    /**
     * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
     *
     * @private
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` if suitable for strict
     *  equality comparisons, else `false`.
     */
    function isStrictComparable(value) {
      return value === value && !isObject(value);
    }

    /**
     * A specialized version of `matchesProperty` for source values suitable
     * for strict equality comparisons, i.e. `===`.
     *
     * @private
     * @param {string} key The key of the property to get.
     * @param {*} srcValue The value to match.
     * @returns {Function} Returns the new spec function.
     */
    function matchesStrictComparable(key, srcValue) {
      return function(object) {
        if (object == null) {
          return false;
        }
        return object[key] === srcValue &&
          (srcValue !== undefined || (key in Object(object)));
      };
    }

    /**
     * A specialized version of `_.memoize` which clears the memoized function's
     * cache when it exceeds `MAX_MEMOIZE_SIZE`.
     *
     * @private
     * @param {Function} func The function to have its output memoized.
     * @returns {Function} Returns the new memoized function.
     */
    function memoizeCapped(func) {
      var result = memoize(func, function(key) {
        if (cache.size === MAX_MEMOIZE_SIZE) {
          cache.clear();
        }
        return key;
      });

      var cache = result.cache;
      return result;
    }

    /**
     * Merges the function metadata of `source` into `data`.
     *
     * Merging metadata reduces the number of wrappers used to invoke a function.
     * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
     * may be applied regardless of execution order. Methods like `_.ary` and
     * `_.rearg` modify function arguments, making the order in which they are
     * executed important, preventing the merging of metadata. However, we make
     * an exception for a safe combined case where curried functions have `_.ary`
     * and or `_.rearg` applied.
     *
     * @private
     * @param {Array} data The destination metadata.
     * @param {Array} source The source metadata.
     * @returns {Array} Returns `data`.
     */
    function mergeData(data, source) {
      var bitmask = data[1],
          srcBitmask = source[1],
          newBitmask = bitmask | srcBitmask,
          isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);

      var isCombo =
        ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
        ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
        ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));

      // Exit early if metadata can't be merged.
      if (!(isCommon || isCombo)) {
        return data;
      }
      // Use source `thisArg` if available.
      if (srcBitmask & WRAP_BIND_FLAG) {
        data[2] = source[2];
        // Set when currying a bound function.
        newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
      }
      // Compose partial arguments.
      var value = source[3];
      if (value) {
        var partials = data[3];
        data[3] = partials ? composeArgs(partials, value, source[4]) : value;
        data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
      }
      // Compose partial right arguments.
      value = source[5];
      if (value) {
        partials = data[5];
        data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
        data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
      }
      // Use source `argPos` if available.
      value = source[7];
      if (value) {
        data[7] = value;
      }
      // Use source `ary` if it's smaller.
      if (srcBitmask & WRAP_ARY_FLAG) {
        data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
      }
      // Use source `arity` if one is not provided.
      if (data[9] == null) {
        data[9] = source[9];
      }
      // Use source `func` and merge bitmasks.
      data[0] = source[0];
      data[1] = newBitmask;

      return data;
    }

    /**
     * This function is like
     * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
     * except that it includes inherited enumerable properties.
     *
     * @private
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     */
    function nativeKeysIn(object) {
      var result = [];
      if (object != null) {
        for (var key in Object(object)) {
          result.push(key);
        }
      }
      return result;
    }

    /**
     * Converts `value` to a string using `Object.prototype.toString`.
     *
     * @private
     * @param {*} value The value to convert.
     * @returns {string} Returns the converted string.
     */
    function objectToString(value) {
      return nativeObjectToString.call(value);
    }

    /**
     * A specialized version of `baseRest` which transforms the rest array.
     *
     * @private
     * @param {Function} func The function to apply a rest parameter to.
     * @param {number} [start=func.length-1] The start position of the rest parameter.
     * @param {Function} transform The rest array transform.
     * @returns {Function} Returns the new function.
     */
    function overRest(func, start, transform) {
      start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
      return function() {
        var args = arguments,
            index = -1,
            length = nativeMax(args.length - start, 0),
            array = Array(length);

        while (++index < length) {
          array[index] = args[start + index];
        }
        index = -1;
        var otherArgs = Array(start + 1);
        while (++index < start) {
          otherArgs[index] = args[index];
        }
        otherArgs[start] = transform(array);
        return apply(func, this, otherArgs);
      };
    }

    /**
     * Gets the parent value at `path` of `object`.
     *
     * @private
     * @param {Object} object The object to query.
     * @param {Array} path The path to get the parent value of.
     * @returns {*} Returns the parent value.
     */
    function parent(object, path) {
      return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
    }

    /**
     * Reorder `array` according to the specified indexes where the element at
     * the first index is assigned as the first element, the element at
     * the second index is assigned as the second element, and so on.
     *
     * @private
     * @param {Array} array The array to reorder.
     * @param {Array} indexes The arranged array indexes.
     * @returns {Array} Returns `array`.
     */
    function reorder(array, indexes) {
      var arrLength = array.length,
          length = nativeMin(indexes.length, arrLength),
          oldArray = copyArray(array);

      while (length--) {
        var index = indexes[length];
        array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
      }
      return array;
    }

    /**
     * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
     *
     * @private
     * @param {Object} object The object to query.
     * @param {string} key The key of the property to get.
     * @returns {*} Returns the property value.
     */
    function safeGet(object, key) {
      if (key === 'constructor' && typeof object[key] === 'function') {
        return;
      }

      if (key == '__proto__') {
        return;
      }

      return object[key];
    }

    /**
     * Sets metadata for `func`.
     *
     * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
     * period of time, it will trip its breaker and transition to an identity
     * function to avoid garbage collection pauses in V8. See
     * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
     * for more details.
     *
     * @private
     * @param {Function} func The function to associate metadata with.
     * @param {*} data The metadata.
     * @returns {Function} Returns `func`.
     */
    var setData = shortOut(baseSetData);

    /**
     * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
     *
     * @private
     * @param {Function} func The function to delay.
     * @param {number} wait The number of milliseconds to delay invocation.
     * @returns {number|Object} Returns the timer id or timeout object.
     */
    var setTimeout = ctxSetTimeout || function(func, wait) {
      return root.setTimeout(func, wait);
    };

    /**
     * Sets the `toString` method of `func` to return `string`.
     *
     * @private
     * @param {Function} func The function to modify.
     * @param {Function} string The `toString` result.
     * @returns {Function} Returns `func`.
     */
    var setToString = shortOut(baseSetToString);

    /**
     * Sets the `toString` method of `wrapper` to mimic the source of `reference`
     * with wrapper details in a comment at the top of the source body.
     *
     * @private
     * @param {Function} wrapper The function to modify.
     * @param {Function} reference The reference function.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @returns {Function} Returns `wrapper`.
     */
    function setWrapToString(wrapper, reference, bitmask) {
      var source = (reference + '');
      return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
    }

    /**
     * Creates a function that'll short out and invoke `identity` instead
     * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
     * milliseconds.
     *
     * @private
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new shortable function.
     */
    function shortOut(func) {
      var count = 0,
          lastCalled = 0;

      return function() {
        var stamp = nativeNow(),
            remaining = HOT_SPAN - (stamp - lastCalled);

        lastCalled = stamp;
        if (remaining > 0) {
          if (++count >= HOT_COUNT) {
            return arguments[0];
          }
        } else {
          count = 0;
        }
        return func.apply(undefined, arguments);
      };
    }

    /**
     * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
     *
     * @private
     * @param {Array} array The array to shuffle.
     * @param {number} [size=array.length] The size of `array`.
     * @returns {Array} Returns `array`.
     */
    function shuffleSelf(array, size) {
      var index = -1,
          length = array.length,
          lastIndex = length - 1;

      size = size === undefined ? length : size;
      while (++index < size) {
        var rand = baseRandom(index, lastIndex),
            value = array[rand];

        array[rand] = array[index];
        array[index] = value;
      }
      array.length = size;
      return array;
    }

    /**
     * Converts `string` to a property path array.
     *
     * @private
     * @param {string} string The string to convert.
     * @returns {Array} Returns the property path array.
     */
    var stringToPath = memoizeCapped(function(string) {
      var result = [];
      if (string.charCodeAt(0) === 46 /* . */) {
        result.push('');
      }
      string.replace(rePropName, function(match, number, quote, subString) {
        result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
      });
      return result;
    });

    /**
     * Converts `value` to a string key if it's not a string or symbol.
     *
     * @private
     * @param {*} value The value to inspect.
     * @returns {string|symbol} Returns the key.
     */
    function toKey(value) {
      if (typeof value == 'string' || isSymbol(value)) {
        return value;
      }
      var result = (value + '');
      return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
    }

    /**
     * Converts `func` to its source code.
     *
     * @private
     * @param {Function} func The function to convert.
     * @returns {string} Returns the source code.
     */
    function toSource(func) {
      if (func != null) {
        try {
          return funcToString.call(func);
        } catch (e) {}
        try {
          return (func + '');
        } catch (e) {}
      }
      return '';
    }

    /**
     * Updates wrapper `details` based on `bitmask` flags.
     *
     * @private
     * @returns {Array} details The details to modify.
     * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
     * @returns {Array} Returns `details`.
     */
    function updateWrapDetails(details, bitmask) {
      arrayEach(wrapFlags, function(pair) {
        var value = '_.' + pair[0];
        if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
          details.push(value);
        }
      });
      return details.sort();
    }

    /**
     * Creates a clone of `wrapper`.
     *
     * @private
     * @param {Object} wrapper The wrapper to clone.
     * @returns {Object} Returns the cloned wrapper.
     */
    function wrapperClone(wrapper) {
      if (wrapper instanceof LazyWrapper) {
        return wrapper.clone();
      }
      var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
      result.__actions__ = copyArray(wrapper.__actions__);
      result.__index__  = wrapper.__index__;
      result.__values__ = wrapper.__values__;
      return result;
    }

    /*------------------------------------------------------------------------*/

    /**
     * Creates an array of elements split into groups the length of `size`.
     * If `array` can't be split evenly, the final chunk will be the remaining
     * elements.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to process.
     * @param {number} [size=1] The length of each chunk
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the new array of chunks.
     * @example
     *
     * _.chunk(['a', 'b', 'c', 'd'], 2);
     * // => [['a', 'b'], ['c', 'd']]
     *
     * _.chunk(['a', 'b', 'c', 'd'], 3);
     * // => [['a', 'b', 'c'], ['d']]
     */
    function chunk(array, size, guard) {
      if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
        size = 1;
      } else {
        size = nativeMax(toInteger(size), 0);
      }
      var length = array == null ? 0 : array.length;
      if (!length || size < 1) {
        return [];
      }
      var index = 0,
          resIndex = 0,
          result = Array(nativeCeil(length / size));

      while (index < length) {
        result[resIndex++] = baseSlice(array, index, (index += size));
      }
      return result;
    }

    /**
     * Creates an array with all falsey values removed. The values `false`, `null`,
     * `0`, `""`, `undefined`, and `NaN` are falsey.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to compact.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * _.compact([0, 1, false, 2, '', 3]);
     * // => [1, 2, 3]
     */
    function compact(array) {
      var index = -1,
          length = array == null ? 0 : array.length,
          resIndex = 0,
          result = [];

      while (++index < length) {
        var value = array[index];
        if (value) {
          result[resIndex++] = value;
        }
      }
      return result;
    }

    /**
     * Creates a new array concatenating `array` with any additional arrays
     * and/or values.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to concatenate.
     * @param {...*} [values] The values to concatenate.
     * @returns {Array} Returns the new concatenated array.
     * @example
     *
     * var array = [1];
     * var other = _.concat(array, 2, [3], [[4]]);
     *
     * console.log(other);
     * // => [1, 2, 3, [4]]
     *
     * console.log(array);
     * // => [1]
     */
    function concat() {
      var length = arguments.length;
      if (!length) {
        return [];
      }
      var args = Array(length - 1),
          array = arguments[0],
          index = length;

      while (index--) {
        args[index - 1] = arguments[index];
      }
      return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
    }

    /**
     * Creates an array of `array` values not included in the other given arrays
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons. The order and references of result values are
     * determined by the first array.
     *
     * **Note:** Unlike `_.pullAll`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...Array} [values] The values to exclude.
     * @returns {Array} Returns the new array of filtered values.
     * @see _.without, _.xor
     * @example
     *
     * _.difference([2, 1], [2, 3]);
     * // => [1]
     */
    var difference = baseRest(function(array, values) {
      return isArrayLikeObject(array)
        ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
        : [];
    });

    /**
     * This method is like `_.difference` except that it accepts `iteratee` which
     * is invoked for each element of `array` and `values` to generate the criterion
     * by which they're compared. The order and references of result values are
     * determined by the first array. The iteratee is invoked with one argument:
     * (value).
     *
     * **Note:** Unlike `_.pullAllBy`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...Array} [values] The values to exclude.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
     * // => [1.2]
     *
     * // The `_.property` iteratee shorthand.
     * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
     * // => [{ 'x': 2 }]
     */
    var differenceBy = baseRest(function(array, values) {
      var iteratee = last(values);
      if (isArrayLikeObject(iteratee)) {
        iteratee = undefined;
      }
      return isArrayLikeObject(array)
        ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
        : [];
    });

    /**
     * This method is like `_.difference` except that it accepts `comparator`
     * which is invoked to compare elements of `array` to `values`. The order and
     * references of result values are determined by the first array. The comparator
     * is invoked with two arguments: (arrVal, othVal).
     *
     * **Note:** Unlike `_.pullAllWith`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...Array} [values] The values to exclude.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     *
     * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
     * // => [{ 'x': 2, 'y': 1 }]
     */
    var differenceWith = baseRest(function(array, values) {
      var comparator = last(values);
      if (isArrayLikeObject(comparator)) {
        comparator = undefined;
      }
      return isArrayLikeObject(array)
        ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
        : [];
    });

    /**
     * Creates a slice of `array` with `n` elements dropped from the beginning.
     *
     * @static
     * @memberOf _
     * @since 0.5.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to drop.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.drop([1, 2, 3]);
     * // => [2, 3]
     *
     * _.drop([1, 2, 3], 2);
     * // => [3]
     *
     * _.drop([1, 2, 3], 5);
     * // => []
     *
     * _.drop([1, 2, 3], 0);
     * // => [1, 2, 3]
     */
    function drop(array, n, guard) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return [];
      }
      n = (guard || n === undefined) ? 1 : toInteger(n);
      return baseSlice(array, n < 0 ? 0 : n, length);
    }

    /**
     * Creates a slice of `array` with `n` elements dropped from the end.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to drop.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.dropRight([1, 2, 3]);
     * // => [1, 2]
     *
     * _.dropRight([1, 2, 3], 2);
     * // => [1]
     *
     * _.dropRight([1, 2, 3], 5);
     * // => []
     *
     * _.dropRight([1, 2, 3], 0);
     * // => [1, 2, 3]
     */
    function dropRight(array, n, guard) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return [];
      }
      n = (guard || n === undefined) ? 1 : toInteger(n);
      n = length - n;
      return baseSlice(array, 0, n < 0 ? 0 : n);
    }

    /**
     * Creates a slice of `array` excluding elements dropped from the end.
     * Elements are dropped until `predicate` returns falsey. The predicate is
     * invoked with three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': true },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': false }
     * ];
     *
     * _.dropRightWhile(users, function(o) { return !o.active; });
     * // => objects for ['barney']
     *
     * // The `_.matches` iteratee shorthand.
     * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
     * // => objects for ['barney', 'fred']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.dropRightWhile(users, ['active', false]);
     * // => objects for ['barney']
     *
     * // The `_.property` iteratee shorthand.
     * _.dropRightWhile(users, 'active');
     * // => objects for ['barney', 'fred', 'pebbles']
     */
    function dropRightWhile(array, predicate) {
      return (array && array.length)
        ? baseWhile(array, getIteratee(predicate, 3), true, true)
        : [];
    }

    /**
     * Creates a slice of `array` excluding elements dropped from the beginning.
     * Elements are dropped until `predicate` returns falsey. The predicate is
     * invoked with three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': false },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': true }
     * ];
     *
     * _.dropWhile(users, function(o) { return !o.active; });
     * // => objects for ['pebbles']
     *
     * // The `_.matches` iteratee shorthand.
     * _.dropWhile(users, { 'user': 'barney', 'active': false });
     * // => objects for ['fred', 'pebbles']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.dropWhile(users, ['active', false]);
     * // => objects for ['pebbles']
     *
     * // The `_.property` iteratee shorthand.
     * _.dropWhile(users, 'active');
     * // => objects for ['barney', 'fred', 'pebbles']
     */
    function dropWhile(array, predicate) {
      return (array && array.length)
        ? baseWhile(array, getIteratee(predicate, 3), true)
        : [];
    }

    /**
     * Fills elements of `array` with `value` from `start` up to, but not
     * including, `end`.
     *
     * **Note:** This method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 3.2.0
     * @category Array
     * @param {Array} array The array to fill.
     * @param {*} value The value to fill `array` with.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [1, 2, 3];
     *
     * _.fill(array, 'a');
     * console.log(array);
     * // => ['a', 'a', 'a']
     *
     * _.fill(Array(3), 2);
     * // => [2, 2, 2]
     *
     * _.fill([4, 6, 8, 10], '*', 1, 3);
     * // => [4, '*', '*', 10]
     */
    function fill(array, value, start, end) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return [];
      }
      if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
        start = 0;
        end = length;
      }
      return baseFill(array, value, start, end);
    }

    /**
     * This method is like `_.find` except that it returns the index of the first
     * element `predicate` returns truthy for instead of the element itself.
     *
     * @static
     * @memberOf _
     * @since 1.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=0] The index to search from.
     * @returns {number} Returns the index of the found element, else `-1`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': false },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': true }
     * ];
     *
     * _.findIndex(users, function(o) { return o.user == 'barney'; });
     * // => 0
     *
     * // The `_.matches` iteratee shorthand.
     * _.findIndex(users, { 'user': 'fred', 'active': false });
     * // => 1
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findIndex(users, ['active', false]);
     * // => 0
     *
     * // The `_.property` iteratee shorthand.
     * _.findIndex(users, 'active');
     * // => 2
     */
    function findIndex(array, predicate, fromIndex) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return -1;
      }
      var index = fromIndex == null ? 0 : toInteger(fromIndex);
      if (index < 0) {
        index = nativeMax(length + index, 0);
      }
      return baseFindIndex(array, getIteratee(predicate, 3), index);
    }

    /**
     * This method is like `_.findIndex` except that it iterates over elements
     * of `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=array.length-1] The index to search from.
     * @returns {number} Returns the index of the found element, else `-1`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': true },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': false }
     * ];
     *
     * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
     * // => 2
     *
     * // The `_.matches` iteratee shorthand.
     * _.findLastIndex(users, { 'user': 'barney', 'active': true });
     * // => 0
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findLastIndex(users, ['active', false]);
     * // => 2
     *
     * // The `_.property` iteratee shorthand.
     * _.findLastIndex(users, 'active');
     * // => 0
     */
    function findLastIndex(array, predicate, fromIndex) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return -1;
      }
      var index = length - 1;
      if (fromIndex !== undefined) {
        index = toInteger(fromIndex);
        index = fromIndex < 0
          ? nativeMax(length + index, 0)
          : nativeMin(index, length - 1);
      }
      return baseFindIndex(array, getIteratee(predicate, 3), index, true);
    }

    /**
     * Flattens `array` a single level deep.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to flatten.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * _.flatten([1, [2, [3, [4]], 5]]);
     * // => [1, 2, [3, [4]], 5]
     */
    function flatten(array) {
      var length = array == null ? 0 : array.length;
      return length ? baseFlatten(array, 1) : [];
    }

    /**
     * Recursively flattens `array`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to flatten.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * _.flattenDeep([1, [2, [3, [4]], 5]]);
     * // => [1, 2, 3, 4, 5]
     */
    function flattenDeep(array) {
      var length = array == null ? 0 : array.length;
      return length ? baseFlatten(array, INFINITY) : [];
    }

    /**
     * Recursively flatten `array` up to `depth` times.
     *
     * @static
     * @memberOf _
     * @since 4.4.0
     * @category Array
     * @param {Array} array The array to flatten.
     * @param {number} [depth=1] The maximum recursion depth.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * var array = [1, [2, [3, [4]], 5]];
     *
     * _.flattenDepth(array, 1);
     * // => [1, 2, [3, [4]], 5]
     *
     * _.flattenDepth(array, 2);
     * // => [1, 2, 3, [4], 5]
     */
    function flattenDepth(array, depth) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return [];
      }
      depth = depth === undefined ? 1 : toInteger(depth);
      return baseFlatten(array, depth);
    }

    /**
     * The inverse of `_.toPairs`; this method returns an object composed
     * from key-value `pairs`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} pairs The key-value pairs.
     * @returns {Object} Returns the new object.
     * @example
     *
     * _.fromPairs([['a', 1], ['b', 2]]);
     * // => { 'a': 1, 'b': 2 }
     */
    function fromPairs(pairs) {
      var index = -1,
          length = pairs == null ? 0 : pairs.length,
          result = {};

      while (++index < length) {
        var pair = pairs[index];
        result[pair[0]] = pair[1];
      }
      return result;
    }

    /**
     * Gets the first element of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @alias first
     * @category Array
     * @param {Array} array The array to query.
     * @returns {*} Returns the first element of `array`.
     * @example
     *
     * _.head([1, 2, 3]);
     * // => 1
     *
     * _.head([]);
     * // => undefined
     */
    function head(array) {
      return (array && array.length) ? array[0] : undefined;
    }

    /**
     * Gets the index at which the first occurrence of `value` is found in `array`
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons. If `fromIndex` is negative, it's used as the
     * offset from the end of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @param {number} [fromIndex=0] The index to search from.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.indexOf([1, 2, 1, 2], 2);
     * // => 1
     *
     * // Search from the `fromIndex`.
     * _.indexOf([1, 2, 1, 2], 2, 2);
     * // => 3
     */
    function indexOf(array, value, fromIndex) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return -1;
      }
      var index = fromIndex == null ? 0 : toInteger(fromIndex);
      if (index < 0) {
        index = nativeMax(length + index, 0);
      }
      return baseIndexOf(array, value, index);
    }

    /**
     * Gets all but the last element of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to query.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.initial([1, 2, 3]);
     * // => [1, 2]
     */
    function initial(array) {
      var length = array == null ? 0 : array.length;
      return length ? baseSlice(array, 0, -1) : [];
    }

    /**
     * Creates an array of unique values that are included in all given arrays
     * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons. The order and references of result values are
     * determined by the first array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @returns {Array} Returns the new array of intersecting values.
     * @example
     *
     * _.intersection([2, 1], [2, 3]);
     * // => [2]
     */
    var intersection = baseRest(function(arrays) {
      var mapped = arrayMap(arrays, castArrayLikeObject);
      return (mapped.length && mapped[0] === arrays[0])
        ? baseIntersection(mapped)
        : [];
    });

    /**
     * This method is like `_.intersection` except that it accepts `iteratee`
     * which is invoked for each element of each `arrays` to generate the criterion
     * by which they're compared. The order and references of result values are
     * determined by the first array. The iteratee is invoked with one argument:
     * (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of intersecting values.
     * @example
     *
     * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
     * // => [2.1]
     *
     * // The `_.property` iteratee shorthand.
     * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 1 }]
     */
    var intersectionBy = baseRest(function(arrays) {
      var iteratee = last(arrays),
          mapped = arrayMap(arrays, castArrayLikeObject);

      if (iteratee === last(mapped)) {
        iteratee = undefined;
      } else {
        mapped.pop();
      }
      return (mapped.length && mapped[0] === arrays[0])
        ? baseIntersection(mapped, getIteratee(iteratee, 2))
        : [];
    });

    /**
     * This method is like `_.intersection` except that it accepts `comparator`
     * which is invoked to compare elements of `arrays`. The order and references
     * of result values are determined by the first array. The comparator is
     * invoked with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of intersecting values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.intersectionWith(objects, others, _.isEqual);
     * // => [{ 'x': 1, 'y': 2 }]
     */
    var intersectionWith = baseRest(function(arrays) {
      var comparator = last(arrays),
          mapped = arrayMap(arrays, castArrayLikeObject);

      comparator = typeof comparator == 'function' ? comparator : undefined;
      if (comparator) {
        mapped.pop();
      }
      return (mapped.length && mapped[0] === arrays[0])
        ? baseIntersection(mapped, undefined, comparator)
        : [];
    });

    /**
     * Converts all elements in `array` into a string separated by `separator`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to convert.
     * @param {string} [separator=','] The element separator.
     * @returns {string} Returns the joined string.
     * @example
     *
     * _.join(['a', 'b', 'c'], '~');
     * // => 'a~b~c'
     */
    function join(array, separator) {
      return array == null ? '' : nativeJoin.call(array, separator);
    }

    /**
     * Gets the last element of `array`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to query.
     * @returns {*} Returns the last element of `array`.
     * @example
     *
     * _.last([1, 2, 3]);
     * // => 3
     */
    function last(array) {
      var length = array == null ? 0 : array.length;
      return length ? array[length - 1] : undefined;
    }

    /**
     * This method is like `_.indexOf` except that it iterates over elements of
     * `array` from right to left.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @param {number} [fromIndex=array.length-1] The index to search from.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.lastIndexOf([1, 2, 1, 2], 2);
     * // => 3
     *
     * // Search from the `fromIndex`.
     * _.lastIndexOf([1, 2, 1, 2], 2, 2);
     * // => 1
     */
    function lastIndexOf(array, value, fromIndex) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return -1;
      }
      var index = length;
      if (fromIndex !== undefined) {
        index = toInteger(fromIndex);
        index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
      }
      return value === value
        ? strictLastIndexOf(array, value, index)
        : baseFindIndex(array, baseIsNaN, index, true);
    }

    /**
     * Gets the element at index `n` of `array`. If `n` is negative, the nth
     * element from the end is returned.
     *
     * @static
     * @memberOf _
     * @since 4.11.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=0] The index of the element to return.
     * @returns {*} Returns the nth element of `array`.
     * @example
     *
     * var array = ['a', 'b', 'c', 'd'];
     *
     * _.nth(array, 1);
     * // => 'b'
     *
     * _.nth(array, -2);
     * // => 'c';
     */
    function nth(array, n) {
      return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
    }

    /**
     * Removes all given values from `array` using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
     * to remove elements from an array by predicate.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {...*} [values] The values to remove.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
     *
     * _.pull(array, 'a', 'c');
     * console.log(array);
     * // => ['b', 'b']
     */
    var pull = baseRest(pullAll);

    /**
     * This method is like `_.pull` except that it accepts an array of values to remove.
     *
     * **Note:** Unlike `_.difference`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
     *
     * _.pullAll(array, ['a', 'c']);
     * console.log(array);
     * // => ['b', 'b']
     */
    function pullAll(array, values) {
      return (array && array.length && values && values.length)
        ? basePullAll(array, values)
        : array;
    }

    /**
     * This method is like `_.pullAll` except that it accepts `iteratee` which is
     * invoked for each element of `array` and `values` to generate the criterion
     * by which they're compared. The iteratee is invoked with one argument: (value).
     *
     * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
     *
     * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
     * console.log(array);
     * // => [{ 'x': 2 }]
     */
    function pullAllBy(array, values, iteratee) {
      return (array && array.length && values && values.length)
        ? basePullAll(array, values, getIteratee(iteratee, 2))
        : array;
    }

    /**
     * This method is like `_.pullAll` except that it accepts `comparator` which
     * is invoked to compare elements of `array` to `values`. The comparator is
     * invoked with two arguments: (arrVal, othVal).
     *
     * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 4.6.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Array} values The values to remove.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
     *
     * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
     * console.log(array);
     * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
     */
    function pullAllWith(array, values, comparator) {
      return (array && array.length && values && values.length)
        ? basePullAll(array, values, undefined, comparator)
        : array;
    }

    /**
     * Removes elements from `array` corresponding to `indexes` and returns an
     * array of removed elements.
     *
     * **Note:** Unlike `_.at`, this method mutates `array`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {...(number|number[])} [indexes] The indexes of elements to remove.
     * @returns {Array} Returns the new array of removed elements.
     * @example
     *
     * var array = ['a', 'b', 'c', 'd'];
     * var pulled = _.pullAt(array, [1, 3]);
     *
     * console.log(array);
     * // => ['a', 'c']
     *
     * console.log(pulled);
     * // => ['b', 'd']
     */
    var pullAt = flatRest(function(array, indexes) {
      var length = array == null ? 0 : array.length,
          result = baseAt(array, indexes);

      basePullAt(array, arrayMap(indexes, function(index) {
        return isIndex(index, length) ? +index : index;
      }).sort(compareAscending));

      return result;
    });

    /**
     * Removes all elements from `array` that `predicate` returns truthy for
     * and returns an array of the removed elements. The predicate is invoked
     * with three arguments: (value, index, array).
     *
     * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
     * to pull elements from an array by value.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new array of removed elements.
     * @example
     *
     * var array = [1, 2, 3, 4];
     * var evens = _.remove(array, function(n) {
     *   return n % 2 == 0;
     * });
     *
     * console.log(array);
     * // => [1, 3]
     *
     * console.log(evens);
     * // => [2, 4]
     */
    function remove(array, predicate) {
      var result = [];
      if (!(array && array.length)) {
        return result;
      }
      var index = -1,
          indexes = [],
          length = array.length;

      predicate = getIteratee(predicate, 3);
      while (++index < length) {
        var value = array[index];
        if (predicate(value, index, array)) {
          result.push(value);
          indexes.push(index);
        }
      }
      basePullAt(array, indexes);
      return result;
    }

    /**
     * Reverses `array` so that the first element becomes the last, the second
     * element becomes the second to last, and so on.
     *
     * **Note:** This method mutates `array` and is based on
     * [`Array#reverse`](https://mdn.io/Array/reverse).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to modify.
     * @returns {Array} Returns `array`.
     * @example
     *
     * var array = [1, 2, 3];
     *
     * _.reverse(array);
     * // => [3, 2, 1]
     *
     * console.log(array);
     * // => [3, 2, 1]
     */
    function reverse(array) {
      return array == null ? array : nativeReverse.call(array);
    }

    /**
     * Creates a slice of `array` from `start` up to, but not including, `end`.
     *
     * **Note:** This method is used instead of
     * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
     * returned.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to slice.
     * @param {number} [start=0] The start position.
     * @param {number} [end=array.length] The end position.
     * @returns {Array} Returns the slice of `array`.
     */
    function slice(array, start, end) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return [];
      }
      if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
        start = 0;
        end = length;
      }
      else {
        start = start == null ? 0 : toInteger(start);
        end = end === undefined ? length : toInteger(end);
      }
      return baseSlice(array, start, end);
    }

    /**
     * Uses a binary search to determine the lowest index at which `value`
     * should be inserted into `array` in order to maintain its sort order.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * _.sortedIndex([30, 50], 40);
     * // => 1
     */
    function sortedIndex(array, value) {
      return baseSortedIndex(array, value);
    }

    /**
     * This method is like `_.sortedIndex` except that it accepts `iteratee`
     * which is invoked for `value` and each element of `array` to compute their
     * sort ranking. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * var objects = [{ 'x': 4 }, { 'x': 5 }];
     *
     * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
     * // => 0
     *
     * // The `_.property` iteratee shorthand.
     * _.sortedIndexBy(objects, { 'x': 4 }, 'x');
     * // => 0
     */
    function sortedIndexBy(array, value, iteratee) {
      return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
    }

    /**
     * This method is like `_.indexOf` except that it performs a binary
     * search on a sorted `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.sortedIndexOf([4, 5, 5, 5, 6], 5);
     * // => 1
     */
    function sortedIndexOf(array, value) {
      var length = array == null ? 0 : array.length;
      if (length) {
        var index = baseSortedIndex(array, value);
        if (index < length && eq(array[index], value)) {
          return index;
        }
      }
      return -1;
    }

    /**
     * This method is like `_.sortedIndex` except that it returns the highest
     * index at which `value` should be inserted into `array` in order to
     * maintain its sort order.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * _.sortedLastIndex([4, 5, 5, 5, 6], 5);
     * // => 4
     */
    function sortedLastIndex(array, value) {
      return baseSortedIndex(array, value, true);
    }

    /**
     * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
     * which is invoked for `value` and each element of `array` to compute their
     * sort ranking. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The sorted array to inspect.
     * @param {*} value The value to evaluate.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the index at which `value` should be inserted
     *  into `array`.
     * @example
     *
     * var objects = [{ 'x': 4 }, { 'x': 5 }];
     *
     * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
     * // => 1
     *
     * // The `_.property` iteratee shorthand.
     * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
     * // => 1
     */
    function sortedLastIndexBy(array, value, iteratee) {
      return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
    }

    /**
     * This method is like `_.lastIndexOf` except that it performs a binary
     * search on a sorted `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {*} value The value to search for.
     * @returns {number} Returns the index of the matched value, else `-1`.
     * @example
     *
     * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
     * // => 3
     */
    function sortedLastIndexOf(array, value) {
      var length = array == null ? 0 : array.length;
      if (length) {
        var index = baseSortedIndex(array, value, true) - 1;
        if (eq(array[index], value)) {
          return index;
        }
      }
      return -1;
    }

    /**
     * This method is like `_.uniq` except that it's designed and optimized
     * for sorted arrays.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.sortedUniq([1, 1, 2]);
     * // => [1, 2]
     */
    function sortedUniq(array) {
      return (array && array.length)
        ? baseSortedUniq(array)
        : [];
    }

    /**
     * This method is like `_.uniqBy` except that it's designed and optimized
     * for sorted arrays.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee] The iteratee invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
     * // => [1.1, 2.3]
     */
    function sortedUniqBy(array, iteratee) {
      return (array && array.length)
        ? baseSortedUniq(array, getIteratee(iteratee, 2))
        : [];
    }

    /**
     * Gets all but the first element of `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.tail([1, 2, 3]);
     * // => [2, 3]
     */
    function tail(array) {
      var length = array == null ? 0 : array.length;
      return length ? baseSlice(array, 1, length) : [];
    }

    /**
     * Creates a slice of `array` with `n` elements taken from the beginning.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to take.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.take([1, 2, 3]);
     * // => [1]
     *
     * _.take([1, 2, 3], 2);
     * // => [1, 2]
     *
     * _.take([1, 2, 3], 5);
     * // => [1, 2, 3]
     *
     * _.take([1, 2, 3], 0);
     * // => []
     */
    function take(array, n, guard) {
      if (!(array && array.length)) {
        return [];
      }
      n = (guard || n === undefined) ? 1 : toInteger(n);
      return baseSlice(array, 0, n < 0 ? 0 : n);
    }

    /**
     * Creates a slice of `array` with `n` elements taken from the end.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {number} [n=1] The number of elements to take.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * _.takeRight([1, 2, 3]);
     * // => [3]
     *
     * _.takeRight([1, 2, 3], 2);
     * // => [2, 3]
     *
     * _.takeRight([1, 2, 3], 5);
     * // => [1, 2, 3]
     *
     * _.takeRight([1, 2, 3], 0);
     * // => []
     */
    function takeRight(array, n, guard) {
      var length = array == null ? 0 : array.length;
      if (!length) {
        return [];
      }
      n = (guard || n === undefined) ? 1 : toInteger(n);
      n = length - n;
      return baseSlice(array, n < 0 ? 0 : n, length);
    }

    /**
     * Creates a slice of `array` with elements taken from the end. Elements are
     * taken until `predicate` returns falsey. The predicate is invoked with
     * three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': true },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': false }
     * ];
     *
     * _.takeRightWhile(users, function(o) { return !o.active; });
     * // => objects for ['fred', 'pebbles']
     *
     * // The `_.matches` iteratee shorthand.
     * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
     * // => objects for ['pebbles']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.takeRightWhile(users, ['active', false]);
     * // => objects for ['fred', 'pebbles']
     *
     * // The `_.property` iteratee shorthand.
     * _.takeRightWhile(users, 'active');
     * // => []
     */
    function takeRightWhile(array, predicate) {
      return (array && array.length)
        ? baseWhile(array, getIteratee(predicate, 3), false, true)
        : [];
    }

    /**
     * Creates a slice of `array` with elements taken from the beginning. Elements
     * are taken until `predicate` returns falsey. The predicate is invoked with
     * three arguments: (value, index, array).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Array
     * @param {Array} array The array to query.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the slice of `array`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'active': false },
     *   { 'user': 'fred',    'active': false },
     *   { 'user': 'pebbles', 'active': true }
     * ];
     *
     * _.takeWhile(users, function(o) { return !o.active; });
     * // => objects for ['barney', 'fred']
     *
     * // The `_.matches` iteratee shorthand.
     * _.takeWhile(users, { 'user': 'barney', 'active': false });
     * // => objects for ['barney']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.takeWhile(users, ['active', false]);
     * // => objects for ['barney', 'fred']
     *
     * // The `_.property` iteratee shorthand.
     * _.takeWhile(users, 'active');
     * // => []
     */
    function takeWhile(array, predicate) {
      return (array && array.length)
        ? baseWhile(array, getIteratee(predicate, 3))
        : [];
    }

    /**
     * Creates an array of unique values, in order, from all given arrays using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @returns {Array} Returns the new array of combined values.
     * @example
     *
     * _.union([2], [1, 2]);
     * // => [2, 1]
     */
    var union = baseRest(function(arrays) {
      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
    });

    /**
     * This method is like `_.union` except that it accepts `iteratee` which is
     * invoked for each element of each `arrays` to generate the criterion by
     * which uniqueness is computed. Result values are chosen from the first
     * array in which the value occurs. The iteratee is invoked with one argument:
     * (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of combined values.
     * @example
     *
     * _.unionBy([2.1], [1.2, 2.3], Math.floor);
     * // => [2.1, 1.2]
     *
     * // The `_.property` iteratee shorthand.
     * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 1 }, { 'x': 2 }]
     */
    var unionBy = baseRest(function(arrays) {
      var iteratee = last(arrays);
      if (isArrayLikeObject(iteratee)) {
        iteratee = undefined;
      }
      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
    });

    /**
     * This method is like `_.union` except that it accepts `comparator` which
     * is invoked to compare elements of `arrays`. Result values are chosen from
     * the first array in which the value occurs. The comparator is invoked
     * with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of combined values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.unionWith(objects, others, _.isEqual);
     * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
     */
    var unionWith = baseRest(function(arrays) {
      var comparator = last(arrays);
      comparator = typeof comparator == 'function' ? comparator : undefined;
      return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
    });

    /**
     * Creates a duplicate-free version of an array, using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons, in which only the first occurrence of each element
     * is kept. The order of result values is determined by the order they occur
     * in the array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.uniq([2, 1, 2]);
     * // => [2, 1]
     */
    function uniq(array) {
      return (array && array.length) ? baseUniq(array) : [];
    }

    /**
     * This method is like `_.uniq` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the criterion by which
     * uniqueness is computed. The order of result values is determined by the
     * order they occur in the array. The iteratee is invoked with one argument:
     * (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
     * // => [2.1, 1.2]
     *
     * // The `_.property` iteratee shorthand.
     * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 1 }, { 'x': 2 }]
     */
    function uniqBy(array, iteratee) {
      return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
    }

    /**
     * This method is like `_.uniq` except that it accepts `comparator` which
     * is invoked to compare elements of `array`. The order of result values is
     * determined by the order they occur in the array.The comparator is invoked
     * with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new duplicate free array.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.uniqWith(objects, _.isEqual);
     * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
     */
    function uniqWith(array, comparator) {
      comparator = typeof comparator == 'function' ? comparator : undefined;
      return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
    }

    /**
     * This method is like `_.zip` except that it accepts an array of grouped
     * elements and creates an array regrouping the elements to their pre-zip
     * configuration.
     *
     * @static
     * @memberOf _
     * @since 1.2.0
     * @category Array
     * @param {Array} array The array of grouped elements to process.
     * @returns {Array} Returns the new array of regrouped elements.
     * @example
     *
     * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
     * // => [['a', 1, true], ['b', 2, false]]
     *
     * _.unzip(zipped);
     * // => [['a', 'b'], [1, 2], [true, false]]
     */
    function unzip(array) {
      if (!(array && array.length)) {
        return [];
      }
      var length = 0;
      array = arrayFilter(array, function(group) {
        if (isArrayLikeObject(group)) {
          length = nativeMax(group.length, length);
          return true;
        }
      });
      return baseTimes(length, function(index) {
        return arrayMap(array, baseProperty(index));
      });
    }

    /**
     * This method is like `_.unzip` except that it accepts `iteratee` to specify
     * how regrouped values should be combined. The iteratee is invoked with the
     * elements of each group: (...group).
     *
     * @static
     * @memberOf _
     * @since 3.8.0
     * @category Array
     * @param {Array} array The array of grouped elements to process.
     * @param {Function} [iteratee=_.identity] The function to combine
     *  regrouped values.
     * @returns {Array} Returns the new array of regrouped elements.
     * @example
     *
     * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
     * // => [[1, 10, 100], [2, 20, 200]]
     *
     * _.unzipWith(zipped, _.add);
     * // => [3, 30, 300]
     */
    function unzipWith(array, iteratee) {
      if (!(array && array.length)) {
        return [];
      }
      var result = unzip(array);
      if (iteratee == null) {
        return result;
      }
      return arrayMap(result, function(group) {
        return apply(iteratee, undefined, group);
      });
    }

    /**
     * Creates an array excluding all given values using
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * for equality comparisons.
     *
     * **Note:** Unlike `_.pull`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {Array} array The array to inspect.
     * @param {...*} [values] The values to exclude.
     * @returns {Array} Returns the new array of filtered values.
     * @see _.difference, _.xor
     * @example
     *
     * _.without([2, 1, 2, 3], 1, 2);
     * // => [3]
     */
    var without = baseRest(function(array, values) {
      return isArrayLikeObject(array)
        ? baseDifference(array, values)
        : [];
    });

    /**
     * Creates an array of unique values that is the
     * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
     * of the given arrays. The order of result values is determined by the order
     * they occur in the arrays.
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @returns {Array} Returns the new array of filtered values.
     * @see _.difference, _.without
     * @example
     *
     * _.xor([2, 1], [2, 3]);
     * // => [1, 3]
     */
    var xor = baseRest(function(arrays) {
      return baseXor(arrayFilter(arrays, isArrayLikeObject));
    });

    /**
     * This method is like `_.xor` except that it accepts `iteratee` which is
     * invoked for each element of each `arrays` to generate the criterion by
     * which by which they're compared. The order of result values is determined
     * by the order they occur in the arrays. The iteratee is invoked with one
     * argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
     * // => [1.2, 3.4]
     *
     * // The `_.property` iteratee shorthand.
     * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
     * // => [{ 'x': 2 }]
     */
    var xorBy = baseRest(function(arrays) {
      var iteratee = last(arrays);
      if (isArrayLikeObject(iteratee)) {
        iteratee = undefined;
      }
      return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
    });

    /**
     * This method is like `_.xor` except that it accepts `comparator` which is
     * invoked to compare elements of `arrays`. The order of result values is
     * determined by the order they occur in the arrays. The comparator is invoked
     * with two arguments: (arrVal, othVal).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Array
     * @param {...Array} [arrays] The arrays to inspect.
     * @param {Function} [comparator] The comparator invoked per element.
     * @returns {Array} Returns the new array of filtered values.
     * @example
     *
     * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
     * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
     *
     * _.xorWith(objects, others, _.isEqual);
     * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
     */
    var xorWith = baseRest(function(arrays) {
      var comparator = last(arrays);
      comparator = typeof comparator == 'function' ? comparator : undefined;
      return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
    });

    /**
     * Creates an array of grouped elements, the first of which contains the
     * first elements of the given arrays, the second of which contains the
     * second elements of the given arrays, and so on.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Array
     * @param {...Array} [arrays] The arrays to process.
     * @returns {Array} Returns the new array of grouped elements.
     * @example
     *
     * _.zip(['a', 'b'], [1, 2], [true, false]);
     * // => [['a', 1, true], ['b', 2, false]]
     */
    var zip = baseRest(unzip);

    /**
     * This method is like `_.fromPairs` except that it accepts two arrays,
     * one of property identifiers and one of corresponding values.
     *
     * @static
     * @memberOf _
     * @since 0.4.0
     * @category Array
     * @param {Array} [props=[]] The property identifiers.
     * @param {Array} [values=[]] The property values.
     * @returns {Object} Returns the new object.
     * @example
     *
     * _.zipObject(['a', 'b'], [1, 2]);
     * // => { 'a': 1, 'b': 2 }
     */
    function zipObject(props, values) {
      return baseZipObject(props || [], values || [], assignValue);
    }

    /**
     * This method is like `_.zipObject` except that it supports property paths.
     *
     * @static
     * @memberOf _
     * @since 4.1.0
     * @category Array
     * @param {Array} [props=[]] The property identifiers.
     * @param {Array} [values=[]] The property values.
     * @returns {Object} Returns the new object.
     * @example
     *
     * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
     * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
     */
    function zipObjectDeep(props, values) {
      return baseZipObject(props || [], values || [], baseSet);
    }

    /**
     * This method is like `_.zip` except that it accepts `iteratee` to specify
     * how grouped values should be combined. The iteratee is invoked with the
     * elements of each group: (...group).
     *
     * @static
     * @memberOf _
     * @since 3.8.0
     * @category Array
     * @param {...Array} [arrays] The arrays to process.
     * @param {Function} [iteratee=_.identity] The function to combine
     *  grouped values.
     * @returns {Array} Returns the new array of grouped elements.
     * @example
     *
     * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
     *   return a + b + c;
     * });
     * // => [111, 222]
     */
    var zipWith = baseRest(function(arrays) {
      var length = arrays.length,
          iteratee = length > 1 ? arrays[length - 1] : undefined;

      iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
      return unzipWith(arrays, iteratee);
    });

    /*------------------------------------------------------------------------*/

    /**
     * Creates a `lodash` wrapper instance that wraps `value` with explicit method
     * chain sequences enabled. The result of such sequences must be unwrapped
     * with `_#value`.
     *
     * @static
     * @memberOf _
     * @since 1.3.0
     * @category Seq
     * @param {*} value The value to wrap.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'age': 36 },
     *   { 'user': 'fred',    'age': 40 },
     *   { 'user': 'pebbles', 'age': 1 }
     * ];
     *
     * var youngest = _
     *   .chain(users)
     *   .sortBy('age')
     *   .map(function(o) {
     *     return o.user + ' is ' + o.age;
     *   })
     *   .head()
     *   .value();
     * // => 'pebbles is 1'
     */
    function chain(value) {
      var result = lodash(value);
      result.__chain__ = true;
      return result;
    }

    /**
     * This method invokes `interceptor` and returns `value`. The interceptor
     * is invoked with one argument; (value). The purpose of this method is to
     * "tap into" a method chain sequence in order to modify intermediate results.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Seq
     * @param {*} value The value to provide to `interceptor`.
     * @param {Function} interceptor The function to invoke.
     * @returns {*} Returns `value`.
     * @example
     *
     * _([1, 2, 3])
     *  .tap(function(array) {
     *    // Mutate input array.
     *    array.pop();
     *  })
     *  .reverse()
     *  .value();
     * // => [2, 1]
     */
    function tap(value, interceptor) {
      interceptor(value);
      return value;
    }

    /**
     * This method is like `_.tap` except that it returns the result of `interceptor`.
     * The purpose of this method is to "pass thru" values replacing intermediate
     * results in a method chain sequence.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Seq
     * @param {*} value The value to provide to `interceptor`.
     * @param {Function} interceptor The function to invoke.
     * @returns {*} Returns the result of `interceptor`.
     * @example
     *
     * _('  abc  ')
     *  .chain()
     *  .trim()
     *  .thru(function(value) {
     *    return [value];
     *  })
     *  .value();
     * // => ['abc']
     */
    function thru(value, interceptor) {
      return interceptor(value);
    }

    /**
     * This method is the wrapper version of `_.at`.
     *
     * @name at
     * @memberOf _
     * @since 1.0.0
     * @category Seq
     * @param {...(string|string[])} [paths] The property paths to pick.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
     *
     * _(object).at(['a[0].b.c', 'a[1]']).value();
     * // => [3, 4]
     */
    var wrapperAt = flatRest(function(paths) {
      var length = paths.length,
          start = length ? paths[0] : 0,
          value = this.__wrapped__,
          interceptor = function(object) { return baseAt(object, paths); };

      if (length > 1 || this.__actions__.length ||
          !(value instanceof LazyWrapper) || !isIndex(start)) {
        return this.thru(interceptor);
      }
      value = value.slice(start, +start + (length ? 1 : 0));
      value.__actions__.push({
        'func': thru,
        'args': [interceptor],
        'thisArg': undefined
      });
      return new LodashWrapper(value, this.__chain__).thru(function(array) {
        if (length && !array.length) {
          array.push(undefined);
        }
        return array;
      });
    });

    /**
     * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
     *
     * @name chain
     * @memberOf _
     * @since 0.1.0
     * @category Seq
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36 },
     *   { 'user': 'fred',   'age': 40 }
     * ];
     *
     * // A sequence without explicit chaining.
     * _(users).head();
     * // => { 'user': 'barney', 'age': 36 }
     *
     * // A sequence with explicit chaining.
     * _(users)
     *   .chain()
     *   .head()
     *   .pick('user')
     *   .value();
     * // => { 'user': 'barney' }
     */
    function wrapperChain() {
      return chain(this);
    }

    /**
     * Executes the chain sequence and returns the wrapped result.
     *
     * @name commit
     * @memberOf _
     * @since 3.2.0
     * @category Seq
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var array = [1, 2];
     * var wrapped = _(array).push(3);
     *
     * console.log(array);
     * // => [1, 2]
     *
     * wrapped = wrapped.commit();
     * console.log(array);
     * // => [1, 2, 3]
     *
     * wrapped.last();
     * // => 3
     *
     * console.log(array);
     * // => [1, 2, 3]
     */
    function wrapperCommit() {
      return new LodashWrapper(this.value(), this.__chain__);
    }

    /**
     * Gets the next value on a wrapped object following the
     * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
     *
     * @name next
     * @memberOf _
     * @since 4.0.0
     * @category Seq
     * @returns {Object} Returns the next iterator value.
     * @example
     *
     * var wrapped = _([1, 2]);
     *
     * wrapped.next();
     * // => { 'done': false, 'value': 1 }
     *
     * wrapped.next();
     * // => { 'done': false, 'value': 2 }
     *
     * wrapped.next();
     * // => { 'done': true, 'value': undefined }
     */
    function wrapperNext() {
      if (this.__values__ === undefined) {
        this.__values__ = toArray(this.value());
      }
      var done = this.__index__ >= this.__values__.length,
          value = done ? undefined : this.__values__[this.__index__++];

      return { 'done': done, 'value': value };
    }

    /**
     * Enables the wrapper to be iterable.
     *
     * @name Symbol.iterator
     * @memberOf _
     * @since 4.0.0
     * @category Seq
     * @returns {Object} Returns the wrapper object.
     * @example
     *
     * var wrapped = _([1, 2]);
     *
     * wrapped[Symbol.iterator]() === wrapped;
     * // => true
     *
     * Array.from(wrapped);
     * // => [1, 2]
     */
    function wrapperToIterator() {
      return this;
    }

    /**
     * Creates a clone of the chain sequence planting `value` as the wrapped value.
     *
     * @name plant
     * @memberOf _
     * @since 3.2.0
     * @category Seq
     * @param {*} value The value to plant.
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var wrapped = _([1, 2]).map(square);
     * var other = wrapped.plant([3, 4]);
     *
     * other.value();
     * // => [9, 16]
     *
     * wrapped.value();
     * // => [1, 4]
     */
    function wrapperPlant(value) {
      var result,
          parent = this;

      while (parent instanceof baseLodash) {
        var clone = wrapperClone(parent);
        clone.__index__ = 0;
        clone.__values__ = undefined;
        if (result) {
          previous.__wrapped__ = clone;
        } else {
          result = clone;
        }
        var previous = clone;
        parent = parent.__wrapped__;
      }
      previous.__wrapped__ = value;
      return result;
    }

    /**
     * This method is the wrapper version of `_.reverse`.
     *
     * **Note:** This method mutates the wrapped array.
     *
     * @name reverse
     * @memberOf _
     * @since 0.1.0
     * @category Seq
     * @returns {Object} Returns the new `lodash` wrapper instance.
     * @example
     *
     * var array = [1, 2, 3];
     *
     * _(array).reverse().value()
     * // => [3, 2, 1]
     *
     * console.log(array);
     * // => [3, 2, 1]
     */
    function wrapperReverse() {
      var value = this.__wrapped__;
      if (value instanceof LazyWrapper) {
        var wrapped = value;
        if (this.__actions__.length) {
          wrapped = new LazyWrapper(this);
        }
        wrapped = wrapped.reverse();
        wrapped.__actions__.push({
          'func': thru,
          'args': [reverse],
          'thisArg': undefined
        });
        return new LodashWrapper(wrapped, this.__chain__);
      }
      return this.thru(reverse);
    }

    /**
     * Executes the chain sequence to resolve the unwrapped value.
     *
     * @name value
     * @memberOf _
     * @since 0.1.0
     * @alias toJSON, valueOf
     * @category Seq
     * @returns {*} Returns the resolved unwrapped value.
     * @example
     *
     * _([1, 2, 3]).value();
     * // => [1, 2, 3]
     */
    function wrapperValue() {
      return baseWrapperValue(this.__wrapped__, this.__actions__);
    }

    /*------------------------------------------------------------------------*/

    /**
     * Creates an object composed of keys generated from the results of running
     * each element of `collection` thru `iteratee`. The corresponding value of
     * each key is the number of times the key was returned by `iteratee`. The
     * iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 0.5.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * _.countBy([6.1, 4.2, 6.3], Math.floor);
     * // => { '4': 1, '6': 2 }
     *
     * // The `_.property` iteratee shorthand.
     * _.countBy(['one', 'two', 'three'], 'length');
     * // => { '3': 2, '5': 1 }
     */
    var countBy = createAggregator(function(result, value, key) {
      if (hasOwnProperty.call(result, key)) {
        ++result[key];
      } else {
        baseAssignValue(result, key, 1);
      }
    });

    /**
     * Checks if `predicate` returns truthy for **all** elements of `collection`.
     * Iteration is stopped once `predicate` returns falsey. The predicate is
     * invoked with three arguments: (value, index|key, collection).
     *
     * **Note:** This method returns `true` for
     * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
     * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
     * elements of empty collections.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {boolean} Returns `true` if all elements pass the predicate check,
     *  else `false`.
     * @example
     *
     * _.every([true, 1, null, 'yes'], Boolean);
     * // => false
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': false },
     *   { 'user': 'fred',   'age': 40, 'active': false }
     * ];
     *
     * // The `_.matches` iteratee shorthand.
     * _.every(users, { 'user': 'barney', 'active': false });
     * // => false
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.every(users, ['active', false]);
     * // => true
     *
     * // The `_.property` iteratee shorthand.
     * _.every(users, 'active');
     * // => false
     */
    function every(collection, predicate, guard) {
      var func = isArray(collection) ? arrayEvery : baseEvery;
      if (guard && isIterateeCall(collection, predicate, guard)) {
        predicate = undefined;
      }
      return func(collection, getIteratee(predicate, 3));
    }

    /**
     * Iterates over elements of `collection`, returning an array of all elements
     * `predicate` returns truthy for. The predicate is invoked with three
     * arguments: (value, index|key, collection).
     *
     * **Note:** Unlike `_.remove`, this method returns a new array.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new filtered array.
     * @see _.reject
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': true },
     *   { 'user': 'fred',   'age': 40, 'active': false }
     * ];
     *
     * _.filter(users, function(o) { return !o.active; });
     * // => objects for ['fred']
     *
     * // The `_.matches` iteratee shorthand.
     * _.filter(users, { 'age': 36, 'active': true });
     * // => objects for ['barney']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.filter(users, ['active', false]);
     * // => objects for ['fred']
     *
     * // The `_.property` iteratee shorthand.
     * _.filter(users, 'active');
     * // => objects for ['barney']
     *
     * // Combining several predicates using `_.overEvery` or `_.overSome`.
     * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
     * // => objects for ['fred', 'barney']
     */
    function filter(collection, predicate) {
      var func = isArray(collection) ? arrayFilter : baseFilter;
      return func(collection, getIteratee(predicate, 3));
    }

    /**
     * Iterates over elements of `collection`, returning the first element
     * `predicate` returns truthy for. The predicate is invoked with three
     * arguments: (value, index|key, collection).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=0] The index to search from.
     * @returns {*} Returns the matched element, else `undefined`.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'age': 36, 'active': true },
     *   { 'user': 'fred',    'age': 40, 'active': false },
     *   { 'user': 'pebbles', 'age': 1,  'active': true }
     * ];
     *
     * _.find(users, function(o) { return o.age < 40; });
     * // => object for 'barney'
     *
     * // The `_.matches` iteratee shorthand.
     * _.find(users, { 'age': 1, 'active': true });
     * // => object for 'pebbles'
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.find(users, ['active', false]);
     * // => object for 'fred'
     *
     * // The `_.property` iteratee shorthand.
     * _.find(users, 'active');
     * // => object for 'barney'
     */
    var find = createFind(findIndex);

    /**
     * This method is like `_.find` except that it iterates over elements of
     * `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param {number} [fromIndex=collection.length-1] The index to search from.
     * @returns {*} Returns the matched element, else `undefined`.
     * @example
     *
     * _.findLast([1, 2, 3, 4], function(n) {
     *   return n % 2 == 1;
     * });
     * // => 3
     */
    var findLast = createFind(findLastIndex);

    /**
     * Creates a flattened array of values by running each element in `collection`
     * thru `iteratee` and flattening the mapped results. The iteratee is invoked
     * with three arguments: (value, index|key, collection).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * function duplicate(n) {
     *   return [n, n];
     * }
     *
     * _.flatMap([1, 2], duplicate);
     * // => [1, 1, 2, 2]
     */
    function flatMap(collection, iteratee) {
      return baseFlatten(map(collection, iteratee), 1);
    }

    /**
     * This method is like `_.flatMap` except that it recursively flattens the
     * mapped results.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * function duplicate(n) {
     *   return [[[n, n]]];
     * }
     *
     * _.flatMapDeep([1, 2], duplicate);
     * // => [1, 1, 2, 2]
     */
    function flatMapDeep(collection, iteratee) {
      return baseFlatten(map(collection, iteratee), INFINITY);
    }

    /**
     * This method is like `_.flatMap` except that it recursively flattens the
     * mapped results up to `depth` times.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {number} [depth=1] The maximum recursion depth.
     * @returns {Array} Returns the new flattened array.
     * @example
     *
     * function duplicate(n) {
     *   return [[[n, n]]];
     * }
     *
     * _.flatMapDepth([1, 2], duplicate, 2);
     * // => [[1, 1], [2, 2]]
     */
    function flatMapDepth(collection, iteratee, depth) {
      depth = depth === undefined ? 1 : toInteger(depth);
      return baseFlatten(map(collection, iteratee), depth);
    }

    /**
     * Iterates over elements of `collection` and invokes `iteratee` for each element.
     * The iteratee is invoked with three arguments: (value, index|key, collection).
     * Iteratee functions may exit iteration early by explicitly returning `false`.
     *
     * **Note:** As with other "Collections" methods, objects with a "length"
     * property are iterated like arrays. To avoid this behavior use `_.forIn`
     * or `_.forOwn` for object iteration.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @alias each
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     * @see _.forEachRight
     * @example
     *
     * _.forEach([1, 2], function(value) {
     *   console.log(value);
     * });
     * // => Logs `1` then `2`.
     *
     * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'a' then 'b' (iteration order is not guaranteed).
     */
    function forEach(collection, iteratee) {
      var func = isArray(collection) ? arrayEach : baseEach;
      return func(collection, getIteratee(iteratee, 3));
    }

    /**
     * This method is like `_.forEach` except that it iterates over elements of
     * `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @alias eachRight
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array|Object} Returns `collection`.
     * @see _.forEach
     * @example
     *
     * _.forEachRight([1, 2], function(value) {
     *   console.log(value);
     * });
     * // => Logs `2` then `1`.
     */
    function forEachRight(collection, iteratee) {
      var func = isArray(collection) ? arrayEachRight : baseEachRight;
      return func(collection, getIteratee(iteratee, 3));
    }

    /**
     * Creates an object composed of keys generated from the results of running
     * each element of `collection` thru `iteratee`. The order of grouped values
     * is determined by the order they occur in `collection`. The corresponding
     * value of each key is an array of elements responsible for generating the
     * key. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * _.groupBy([6.1, 4.2, 6.3], Math.floor);
     * // => { '4': [4.2], '6': [6.1, 6.3] }
     *
     * // The `_.property` iteratee shorthand.
     * _.groupBy(['one', 'two', 'three'], 'length');
     * // => { '3': ['one', 'two'], '5': ['three'] }
     */
    var groupBy = createAggregator(function(result, value, key) {
      if (hasOwnProperty.call(result, key)) {
        result[key].push(value);
      } else {
        baseAssignValue(result, key, [value]);
      }
    });

    /**
     * Checks if `value` is in `collection`. If `collection` is a string, it's
     * checked for a substring of `value`, otherwise
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * is used for equality comparisons. If `fromIndex` is negative, it's used as
     * the offset from the end of `collection`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object|string} collection The collection to inspect.
     * @param {*} value The value to search for.
     * @param {number} [fromIndex=0] The index to search from.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
     * @returns {boolean} Returns `true` if `value` is found, else `false`.
     * @example
     *
     * _.includes([1, 2, 3], 1);
     * // => true
     *
     * _.includes([1, 2, 3], 1, 2);
     * // => false
     *
     * _.includes({ 'a': 1, 'b': 2 }, 1);
     * // => true
     *
     * _.includes('abcd', 'bc');
     * // => true
     */
    function includes(collection, value, fromIndex, guard) {
      collection = isArrayLike(collection) ? collection : values(collection);
      fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;

      var length = collection.length;
      if (fromIndex < 0) {
        fromIndex = nativeMax(length + fromIndex, 0);
      }
      return isString(collection)
        ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
        : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
    }

    /**
     * Invokes the method at `path` of each element in `collection`, returning
     * an array of the results of each invoked method. Any additional arguments
     * are provided to each invoked method. If `path` is a function, it's invoked
     * for, and `this` bound to, each element in `collection`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Array|Function|string} path The path of the method to invoke or
     *  the function invoked per iteration.
     * @param {...*} [args] The arguments to invoke each method with.
     * @returns {Array} Returns the array of results.
     * @example
     *
     * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
     * // => [[1, 5, 7], [1, 2, 3]]
     *
     * _.invokeMap([123, 456], String.prototype.split, '');
     * // => [['1', '2', '3'], ['4', '5', '6']]
     */
    var invokeMap = baseRest(function(collection, path, args) {
      var index = -1,
          isFunc = typeof path == 'function',
          result = isArrayLike(collection) ? Array(collection.length) : [];

      baseEach(collection, function(value) {
        result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
      });
      return result;
    });

    /**
     * Creates an object composed of keys generated from the results of running
     * each element of `collection` thru `iteratee`. The corresponding value of
     * each key is the last element responsible for generating the key. The
     * iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
     * @returns {Object} Returns the composed aggregate object.
     * @example
     *
     * var array = [
     *   { 'dir': 'left', 'code': 97 },
     *   { 'dir': 'right', 'code': 100 }
     * ];
     *
     * _.keyBy(array, function(o) {
     *   return String.fromCharCode(o.code);
     * });
     * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
     *
     * _.keyBy(array, 'dir');
     * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
     */
    var keyBy = createAggregator(function(result, value, key) {
      baseAssignValue(result, key, value);
    });

    /**
     * Creates an array of values by running each element in `collection` thru
     * `iteratee`. The iteratee is invoked with three arguments:
     * (value, index|key, collection).
     *
     * Many lodash methods are guarded to work as iteratees for methods like
     * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
     *
     * The guarded methods are:
     * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
     * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
     * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
     * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new mapped array.
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * _.map([4, 8], square);
     * // => [16, 64]
     *
     * _.map({ 'a': 4, 'b': 8 }, square);
     * // => [16, 64] (iteration order is not guaranteed)
     *
     * var users = [
     *   { 'user': 'barney' },
     *   { 'user': 'fred' }
     * ];
     *
     * // The `_.property` iteratee shorthand.
     * _.map(users, 'user');
     * // => ['barney', 'fred']
     */
    function map(collection, iteratee) {
      var func = isArray(collection) ? arrayMap : baseMap;
      return func(collection, getIteratee(iteratee, 3));
    }

    /**
     * This method is like `_.sortBy` except that it allows specifying the sort
     * orders of the iteratees to sort by. If `orders` is unspecified, all values
     * are sorted in ascending order. Otherwise, specify an order of "desc" for
     * descending or "asc" for ascending sort order of corresponding values.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
     *  The iteratees to sort by.
     * @param {string[]} [orders] The sort orders of `iteratees`.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
     * @returns {Array} Returns the new sorted array.
     * @example
     *
     * var users = [
     *   { 'user': 'fred',   'age': 48 },
     *   { 'user': 'barney', 'age': 34 },
     *   { 'user': 'fred',   'age': 40 },
     *   { 'user': 'barney', 'age': 36 }
     * ];
     *
     * // Sort by `user` in ascending order and by `age` in descending order.
     * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
     * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
     */
    function orderBy(collection, iteratees, orders, guard) {
      if (collection == null) {
        return [];
      }
      if (!isArray(iteratees)) {
        iteratees = iteratees == null ? [] : [iteratees];
      }
      orders = guard ? undefined : orders;
      if (!isArray(orders)) {
        orders = orders == null ? [] : [orders];
      }
      return baseOrderBy(collection, iteratees, orders);
    }

    /**
     * Creates an array of elements split into two groups, the first of which
     * contains elements `predicate` returns truthy for, the second of which
     * contains elements `predicate` returns falsey for. The predicate is
     * invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the array of grouped elements.
     * @example
     *
     * var users = [
     *   { 'user': 'barney',  'age': 36, 'active': false },
     *   { 'user': 'fred',    'age': 40, 'active': true },
     *   { 'user': 'pebbles', 'age': 1,  'active': false }
     * ];
     *
     * _.partition(users, function(o) { return o.active; });
     * // => objects for [['fred'], ['barney', 'pebbles']]
     *
     * // The `_.matches` iteratee shorthand.
     * _.partition(users, { 'age': 1, 'active': false });
     * // => objects for [['pebbles'], ['barney', 'fred']]
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.partition(users, ['active', false]);
     * // => objects for [['barney', 'pebbles'], ['fred']]
     *
     * // The `_.property` iteratee shorthand.
     * _.partition(users, 'active');
     * // => objects for [['fred'], ['barney', 'pebbles']]
     */
    var partition = createAggregator(function(result, value, key) {
      result[key ? 0 : 1].push(value);
    }, function() { return [[], []]; });

    /**
     * Reduces `collection` to a value which is the accumulated result of running
     * each element in `collection` thru `iteratee`, where each successive
     * invocation is supplied the return value of the previous. If `accumulator`
     * is not given, the first element of `collection` is used as the initial
     * value. The iteratee is invoked with four arguments:
     * (accumulator, value, index|key, collection).
     *
     * Many lodash methods are guarded to work as iteratees for methods like
     * `_.reduce`, `_.reduceRight`, and `_.transform`.
     *
     * The guarded methods are:
     * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
     * and `sortBy`
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {*} [accumulator] The initial value.
     * @returns {*} Returns the accumulated value.
     * @see _.reduceRight
     * @example
     *
     * _.reduce([1, 2], function(sum, n) {
     *   return sum + n;
     * }, 0);
     * // => 3
     *
     * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
     *   (result[value] || (result[value] = [])).push(key);
     *   return result;
     * }, {});
     * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
     */
    function reduce(collection, iteratee, accumulator) {
      var func = isArray(collection) ? arrayReduce : baseReduce,
          initAccum = arguments.length < 3;

      return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
    }

    /**
     * This method is like `_.reduce` except that it iterates over elements of
     * `collection` from right to left.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {*} [accumulator] The initial value.
     * @returns {*} Returns the accumulated value.
     * @see _.reduce
     * @example
     *
     * var array = [[0, 1], [2, 3], [4, 5]];
     *
     * _.reduceRight(array, function(flattened, other) {
     *   return flattened.concat(other);
     * }, []);
     * // => [4, 5, 2, 3, 0, 1]
     */
    function reduceRight(collection, iteratee, accumulator) {
      var func = isArray(collection) ? arrayReduceRight : baseReduce,
          initAccum = arguments.length < 3;

      return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
    }

    /**
     * The opposite of `_.filter`; this method returns the elements of `collection`
     * that `predicate` does **not** return truthy for.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the new filtered array.
     * @see _.filter
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': false },
     *   { 'user': 'fred',   'age': 40, 'active': true }
     * ];
     *
     * _.reject(users, function(o) { return !o.active; });
     * // => objects for ['fred']
     *
     * // The `_.matches` iteratee shorthand.
     * _.reject(users, { 'age': 40, 'active': true });
     * // => objects for ['barney']
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.reject(users, ['active', false]);
     * // => objects for ['fred']
     *
     * // The `_.property` iteratee shorthand.
     * _.reject(users, 'active');
     * // => objects for ['barney']
     */
    function reject(collection, predicate) {
      var func = isArray(collection) ? arrayFilter : baseFilter;
      return func(collection, negate(getIteratee(predicate, 3)));
    }

    /**
     * Gets a random element from `collection`.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to sample.
     * @returns {*} Returns the random element.
     * @example
     *
     * _.sample([1, 2, 3, 4]);
     * // => 2
     */
    function sample(collection) {
      var func = isArray(collection) ? arraySample : baseSample;
      return func(collection);
    }

    /**
     * Gets `n` random elements at unique keys from `collection` up to the
     * size of `collection`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Collection
     * @param {Array|Object} collection The collection to sample.
     * @param {number} [n=1] The number of elements to sample.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the random elements.
     * @example
     *
     * _.sampleSize([1, 2, 3], 2);
     * // => [3, 1]
     *
     * _.sampleSize([1, 2, 3], 4);
     * // => [2, 3, 1]
     */
    function sampleSize(collection, n, guard) {
      if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
        n = 1;
      } else {
        n = toInteger(n);
      }
      var func = isArray(collection) ? arraySampleSize : baseSampleSize;
      return func(collection, n);
    }

    /**
     * Creates an array of shuffled values, using a version of the
     * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to shuffle.
     * @returns {Array} Returns the new shuffled array.
     * @example
     *
     * _.shuffle([1, 2, 3, 4]);
     * // => [4, 1, 3, 2]
     */
    function shuffle(collection) {
      var func = isArray(collection) ? arrayShuffle : baseShuffle;
      return func(collection);
    }

    /**
     * Gets the size of `collection` by returning its length for array-like
     * values or the number of own enumerable string keyed properties for objects.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object|string} collection The collection to inspect.
     * @returns {number} Returns the collection size.
     * @example
     *
     * _.size([1, 2, 3]);
     * // => 3
     *
     * _.size({ 'a': 1, 'b': 2 });
     * // => 2
     *
     * _.size('pebbles');
     * // => 7
     */
    function size(collection) {
      if (collection == null) {
        return 0;
      }
      if (isArrayLike(collection)) {
        return isString(collection) ? stringSize(collection) : collection.length;
      }
      var tag = getTag(collection);
      if (tag == mapTag || tag == setTag) {
        return collection.size;
      }
      return baseKeys(collection).length;
    }

    /**
     * Checks if `predicate` returns truthy for **any** element of `collection`.
     * Iteration is stopped once `predicate` returns truthy. The predicate is
     * invoked with three arguments: (value, index|key, collection).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {boolean} Returns `true` if any element passes the predicate check,
     *  else `false`.
     * @example
     *
     * _.some([null, 0, 'yes', false], Boolean);
     * // => true
     *
     * var users = [
     *   { 'user': 'barney', 'active': true },
     *   { 'user': 'fred',   'active': false }
     * ];
     *
     * // The `_.matches` iteratee shorthand.
     * _.some(users, { 'user': 'barney', 'active': false });
     * // => false
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.some(users, ['active', false]);
     * // => true
     *
     * // The `_.property` iteratee shorthand.
     * _.some(users, 'active');
     * // => true
     */
    function some(collection, predicate, guard) {
      var func = isArray(collection) ? arraySome : baseSome;
      if (guard && isIterateeCall(collection, predicate, guard)) {
        predicate = undefined;
      }
      return func(collection, getIteratee(predicate, 3));
    }

    /**
     * Creates an array of elements, sorted in ascending order by the results of
     * running each element in a collection thru each iteratee. This method
     * performs a stable sort, that is, it preserves the original sort order of
     * equal elements. The iteratees are invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Collection
     * @param {Array|Object} collection The collection to iterate over.
     * @param {...(Function|Function[])} [iteratees=[_.identity]]
     *  The iteratees to sort by.
     * @returns {Array} Returns the new sorted array.
     * @example
     *
     * var users = [
     *   { 'user': 'fred',   'age': 48 },
     *   { 'user': 'barney', 'age': 36 },
     *   { 'user': 'fred',   'age': 30 },
     *   { 'user': 'barney', 'age': 34 }
     * ];
     *
     * _.sortBy(users, [function(o) { return o.user; }]);
     * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
     *
     * _.sortBy(users, ['user', 'age']);
     * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
     */
    var sortBy = baseRest(function(collection, iteratees) {
      if (collection == null) {
        return [];
      }
      var length = iteratees.length;
      if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
        iteratees = [];
      } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
        iteratees = [iteratees[0]];
      }
      return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
    });

    /*------------------------------------------------------------------------*/

    /**
     * Gets the timestamp of the number of milliseconds that have elapsed since
     * the Unix epoch (1 January 1970 00:00:00 UTC).
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Date
     * @returns {number} Returns the timestamp.
     * @example
     *
     * _.defer(function(stamp) {
     *   console.log(_.now() - stamp);
     * }, _.now());
     * // => Logs the number of milliseconds it took for the deferred invocation.
     */
    var now = ctxNow || function() {
      return root.Date.now();
    };

    /*------------------------------------------------------------------------*/

    /**
     * The opposite of `_.before`; this method creates a function that invokes
     * `func` once it's called `n` or more times.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {number} n The number of calls before `func` is invoked.
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * var saves = ['profile', 'settings'];
     *
     * var done = _.after(saves.length, function() {
     *   console.log('done saving!');
     * });
     *
     * _.forEach(saves, function(type) {
     *   asyncSave({ 'type': type, 'complete': done });
     * });
     * // => Logs 'done saving!' after the two async saves have completed.
     */
    function after(n, func) {
      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      n = toInteger(n);
      return function() {
        if (--n < 1) {
          return func.apply(this, arguments);
        }
      };
    }

    /**
     * Creates a function that invokes `func`, with up to `n` arguments,
     * ignoring any additional arguments.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} func The function to cap arguments for.
     * @param {number} [n=func.length] The arity cap.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the new capped function.
     * @example
     *
     * _.map(['6', '8', '10'], _.ary(parseInt, 1));
     * // => [6, 8, 10]
     */
    function ary(func, n, guard) {
      n = guard ? undefined : n;
      n = (func && n == null) ? func.length : n;
      return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
    }

    /**
     * Creates a function that invokes `func`, with the `this` binding and arguments
     * of the created function, while it's called less than `n` times. Subsequent
     * calls to the created function return the result of the last `func` invocation.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {number} n The number of calls at which `func` is no longer invoked.
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * jQuery(element).on('click', _.before(5, addContactToList));
     * // => Allows adding up to 4 contacts to the list.
     */
    function before(n, func) {
      var result;
      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      n = toInteger(n);
      return function() {
        if (--n > 0) {
          result = func.apply(this, arguments);
        }
        if (n <= 1) {
          func = undefined;
        }
        return result;
      };
    }

    /**
     * Creates a function that invokes `func` with the `this` binding of `thisArg`
     * and `partials` prepended to the arguments it receives.
     *
     * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
     * may be used as a placeholder for partially applied arguments.
     *
     * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
     * property of bound functions.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to bind.
     * @param {*} thisArg The `this` binding of `func`.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new bound function.
     * @example
     *
     * function greet(greeting, punctuation) {
     *   return greeting + ' ' + this.user + punctuation;
     * }
     *
     * var object = { 'user': 'fred' };
     *
     * var bound = _.bind(greet, object, 'hi');
     * bound('!');
     * // => 'hi fred!'
     *
     * // Bound with placeholders.
     * var bound = _.bind(greet, object, _, '!');
     * bound('hi');
     * // => 'hi fred!'
     */
    var bind = baseRest(function(func, thisArg, partials) {
      var bitmask = WRAP_BIND_FLAG;
      if (partials.length) {
        var holders = replaceHolders(partials, getHolder(bind));
        bitmask |= WRAP_PARTIAL_FLAG;
      }
      return createWrap(func, bitmask, thisArg, partials, holders);
    });

    /**
     * Creates a function that invokes the method at `object[key]` with `partials`
     * prepended to the arguments it receives.
     *
     * This method differs from `_.bind` by allowing bound functions to reference
     * methods that may be redefined or don't yet exist. See
     * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
     * for more details.
     *
     * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for partially applied arguments.
     *
     * @static
     * @memberOf _
     * @since 0.10.0
     * @category Function
     * @param {Object} object The object to invoke the method on.
     * @param {string} key The key of the method.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new bound function.
     * @example
     *
     * var object = {
     *   'user': 'fred',
     *   'greet': function(greeting, punctuation) {
     *     return greeting + ' ' + this.user + punctuation;
     *   }
     * };
     *
     * var bound = _.bindKey(object, 'greet', 'hi');
     * bound('!');
     * // => 'hi fred!'
     *
     * object.greet = function(greeting, punctuation) {
     *   return greeting + 'ya ' + this.user + punctuation;
     * };
     *
     * bound('!');
     * // => 'hiya fred!'
     *
     * // Bound with placeholders.
     * var bound = _.bindKey(object, 'greet', _, '!');
     * bound('hi');
     * // => 'hiya fred!'
     */
    var bindKey = baseRest(function(object, key, partials) {
      var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
      if (partials.length) {
        var holders = replaceHolders(partials, getHolder(bindKey));
        bitmask |= WRAP_PARTIAL_FLAG;
      }
      return createWrap(key, bitmask, object, partials, holders);
    });

    /**
     * Creates a function that accepts arguments of `func` and either invokes
     * `func` returning its result, if at least `arity` number of arguments have
     * been provided, or returns a function that accepts the remaining `func`
     * arguments, and so on. The arity of `func` may be specified if `func.length`
     * is not sufficient.
     *
     * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
     * may be used as a placeholder for provided arguments.
     *
     * **Note:** This method doesn't set the "length" property of curried functions.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Function
     * @param {Function} func The function to curry.
     * @param {number} [arity=func.length] The arity of `func`.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the new curried function.
     * @example
     *
     * var abc = function(a, b, c) {
     *   return [a, b, c];
     * };
     *
     * var curried = _.curry(abc);
     *
     * curried(1)(2)(3);
     * // => [1, 2, 3]
     *
     * curried(1, 2)(3);
     * // => [1, 2, 3]
     *
     * curried(1, 2, 3);
     * // => [1, 2, 3]
     *
     * // Curried with placeholders.
     * curried(1)(_, 3)(2);
     * // => [1, 2, 3]
     */
    function curry(func, arity, guard) {
      arity = guard ? undefined : arity;
      var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
      result.placeholder = curry.placeholder;
      return result;
    }

    /**
     * This method is like `_.curry` except that arguments are applied to `func`
     * in the manner of `_.partialRight` instead of `_.partial`.
     *
     * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for provided arguments.
     *
     * **Note:** This method doesn't set the "length" property of curried functions.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} func The function to curry.
     * @param {number} [arity=func.length] The arity of `func`.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the new curried function.
     * @example
     *
     * var abc = function(a, b, c) {
     *   return [a, b, c];
     * };
     *
     * var curried = _.curryRight(abc);
     *
     * curried(3)(2)(1);
     * // => [1, 2, 3]
     *
     * curried(2, 3)(1);
     * // => [1, 2, 3]
     *
     * curried(1, 2, 3);
     * // => [1, 2, 3]
     *
     * // Curried with placeholders.
     * curried(3)(1, _)(2);
     * // => [1, 2, 3]
     */
    function curryRight(func, arity, guard) {
      arity = guard ? undefined : arity;
      var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
      result.placeholder = curryRight.placeholder;
      return result;
    }

    /**
     * Creates a debounced function that delays invoking `func` until after `wait`
     * milliseconds have elapsed since the last time the debounced function was
     * invoked. The debounced function comes with a `cancel` method to cancel
     * delayed `func` invocations and a `flush` method to immediately invoke them.
     * Provide `options` to indicate whether `func` should be invoked on the
     * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
     * with the last arguments provided to the debounced function. Subsequent
     * calls to the debounced function return the result of the last `func`
     * invocation.
     *
     * **Note:** If `leading` and `trailing` options are `true`, `func` is
     * invoked on the trailing edge of the timeout only if the debounced function
     * is invoked more than once during the `wait` timeout.
     *
     * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
     * until to the next tick, similar to `setTimeout` with a timeout of `0`.
     *
     * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
     * for details over the differences between `_.debounce` and `_.throttle`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to debounce.
     * @param {number} [wait=0] The number of milliseconds to delay.
     * @param {Object} [options={}] The options object.
     * @param {boolean} [options.leading=false]
     *  Specify invoking on the leading edge of the timeout.
     * @param {number} [options.maxWait]
     *  The maximum time `func` is allowed to be delayed before it's invoked.
     * @param {boolean} [options.trailing=true]
     *  Specify invoking on the trailing edge of the timeout.
     * @returns {Function} Returns the new debounced function.
     * @example
     *
     * // Avoid costly calculations while the window size is in flux.
     * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
     *
     * // Invoke `sendMail` when clicked, debouncing subsequent calls.
     * jQuery(element).on('click', _.debounce(sendMail, 300, {
     *   'leading': true,
     *   'trailing': false
     * }));
     *
     * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
     * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
     * var source = new EventSource('/stream');
     * jQuery(source).on('message', debounced);
     *
     * // Cancel the trailing debounced invocation.
     * jQuery(window).on('popstate', debounced.cancel);
     */
    function debounce(func, wait, options) {
      var lastArgs,
          lastThis,
          maxWait,
          result,
          timerId,
          lastCallTime,
          lastInvokeTime = 0,
          leading = false,
          maxing = false,
          trailing = true;

      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject(options)) {
        leading = !!options.leading;
        maxing = 'maxWait' in options;
        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
        trailing = 'trailing' in options ? !!options.trailing : trailing;
      }

      function invokeFunc(time) {
        var args = lastArgs,
            thisArg = lastThis;

        lastArgs = lastThis = undefined;
        lastInvokeTime = time;
        result = func.apply(thisArg, args);
        return result;
      }

      function leadingEdge(time) {
        // Reset any `maxWait` timer.
        lastInvokeTime = time;
        // Start the timer for the trailing edge.
        timerId = setTimeout(timerExpired, wait);
        // Invoke the leading edge.
        return leading ? invokeFunc(time) : result;
      }

      function remainingWait(time) {
        var timeSinceLastCall = time - lastCallTime,
            timeSinceLastInvoke = time - lastInvokeTime,
            timeWaiting = wait - timeSinceLastCall;

        return maxing
          ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
          : timeWaiting;
      }

      function shouldInvoke(time) {
        var timeSinceLastCall = time - lastCallTime,
            timeSinceLastInvoke = time - lastInvokeTime;

        // Either this is the first call, activity has stopped and we're at the
        // trailing edge, the system time has gone backwards and we're treating
        // it as the trailing edge, or we've hit the `maxWait` limit.
        return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
          (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
      }

      function timerExpired() {
        var time = now();
        if (shouldInvoke(time)) {
          return trailingEdge(time);
        }
        // Restart the timer.
        timerId = setTimeout(timerExpired, remainingWait(time));
      }

      function trailingEdge(time) {
        timerId = undefined;

        // Only invoke if we have `lastArgs` which means `func` has been
        // debounced at least once.
        if (trailing && lastArgs) {
          return invokeFunc(time);
        }
        lastArgs = lastThis = undefined;
        return result;
      }

      function cancel() {
        if (timerId !== undefined) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = undefined;
      }

      function flush() {
        return timerId === undefined ? result : trailingEdge(now());
      }

      function debounced() {
        var time = now(),
            isInvoking = shouldInvoke(time);

        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time;

        if (isInvoking) {
          if (timerId === undefined) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            // Handle invocations in a tight loop.
            clearTimeout(timerId);
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === undefined) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }

    /**
     * Defers invoking the `func` until the current call stack has cleared. Any
     * additional arguments are provided to `func` when it's invoked.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to defer.
     * @param {...*} [args] The arguments to invoke `func` with.
     * @returns {number} Returns the timer id.
     * @example
     *
     * _.defer(function(text) {
     *   console.log(text);
     * }, 'deferred');
     * // => Logs 'deferred' after one millisecond.
     */
    var defer = baseRest(function(func, args) {
      return baseDelay(func, 1, args);
    });

    /**
     * Invokes `func` after `wait` milliseconds. Any additional arguments are
     * provided to `func` when it's invoked.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to delay.
     * @param {number} wait The number of milliseconds to delay invocation.
     * @param {...*} [args] The arguments to invoke `func` with.
     * @returns {number} Returns the timer id.
     * @example
     *
     * _.delay(function(text) {
     *   console.log(text);
     * }, 1000, 'later');
     * // => Logs 'later' after one second.
     */
    var delay = baseRest(function(func, wait, args) {
      return baseDelay(func, toNumber(wait) || 0, args);
    });

    /**
     * Creates a function that invokes `func` with arguments reversed.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Function
     * @param {Function} func The function to flip arguments for.
     * @returns {Function} Returns the new flipped function.
     * @example
     *
     * var flipped = _.flip(function() {
     *   return _.toArray(arguments);
     * });
     *
     * flipped('a', 'b', 'c', 'd');
     * // => ['d', 'c', 'b', 'a']
     */
    function flip(func) {
      return createWrap(func, WRAP_FLIP_FLAG);
    }

    /**
     * Creates a function that memoizes the result of `func`. If `resolver` is
     * provided, it determines the cache key for storing the result based on the
     * arguments provided to the memoized function. By default, the first argument
     * provided to the memoized function is used as the map cache key. The `func`
     * is invoked with the `this` binding of the memoized function.
     *
     * **Note:** The cache is exposed as the `cache` property on the memoized
     * function. Its creation may be customized by replacing the `_.memoize.Cache`
     * constructor with one whose instances implement the
     * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
     * method interface of `clear`, `delete`, `get`, `has`, and `set`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to have its output memoized.
     * @param {Function} [resolver] The function to resolve the cache key.
     * @returns {Function} Returns the new memoized function.
     * @example
     *
     * var object = { 'a': 1, 'b': 2 };
     * var other = { 'c': 3, 'd': 4 };
     *
     * var values = _.memoize(_.values);
     * values(object);
     * // => [1, 2]
     *
     * values(other);
     * // => [3, 4]
     *
     * object.a = 2;
     * values(object);
     * // => [1, 2]
     *
     * // Modify the result cache.
     * values.cache.set(object, ['a', 'b']);
     * values(object);
     * // => ['a', 'b']
     *
     * // Replace `_.memoize.Cache`.
     * _.memoize.Cache = WeakMap;
     */
    function memoize(func, resolver) {
      if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      var memoized = function() {
        var args = arguments,
            key = resolver ? resolver.apply(this, args) : args[0],
            cache = memoized.cache;

        if (cache.has(key)) {
          return cache.get(key);
        }
        var result = func.apply(this, args);
        memoized.cache = cache.set(key, result) || cache;
        return result;
      };
      memoized.cache = new (memoize.Cache || MapCache);
      return memoized;
    }

    // Expose `MapCache`.
    memoize.Cache = MapCache;

    /**
     * Creates a function that negates the result of the predicate `func`. The
     * `func` predicate is invoked with the `this` binding and arguments of the
     * created function.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} predicate The predicate to negate.
     * @returns {Function} Returns the new negated function.
     * @example
     *
     * function isEven(n) {
     *   return n % 2 == 0;
     * }
     *
     * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
     * // => [1, 3, 5]
     */
    function negate(predicate) {
      if (typeof predicate != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      return function() {
        var args = arguments;
        switch (args.length) {
          case 0: return !predicate.call(this);
          case 1: return !predicate.call(this, args[0]);
          case 2: return !predicate.call(this, args[0], args[1]);
          case 3: return !predicate.call(this, args[0], args[1], args[2]);
        }
        return !predicate.apply(this, args);
      };
    }

    /**
     * Creates a function that is restricted to invoking `func` once. Repeat calls
     * to the function return the value of the first invocation. The `func` is
     * invoked with the `this` binding and arguments of the created function.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to restrict.
     * @returns {Function} Returns the new restricted function.
     * @example
     *
     * var initialize = _.once(createApplication);
     * initialize();
     * initialize();
     * // => `createApplication` is invoked once
     */
    function once(func) {
      return before(2, func);
    }

    /**
     * Creates a function that invokes `func` with its arguments transformed.
     *
     * @static
     * @since 4.0.0
     * @memberOf _
     * @category Function
     * @param {Function} func The function to wrap.
     * @param {...(Function|Function[])} [transforms=[_.identity]]
     *  The argument transforms.
     * @returns {Function} Returns the new function.
     * @example
     *
     * function doubled(n) {
     *   return n * 2;
     * }
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var func = _.overArgs(function(x, y) {
     *   return [x, y];
     * }, [square, doubled]);
     *
     * func(9, 3);
     * // => [81, 6]
     *
     * func(10, 5);
     * // => [100, 10]
     */
    var overArgs = castRest(function(func, transforms) {
      transforms = (transforms.length == 1 && isArray(transforms[0]))
        ? arrayMap(transforms[0], baseUnary(getIteratee()))
        : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));

      var funcsLength = transforms.length;
      return baseRest(function(args) {
        var index = -1,
            length = nativeMin(args.length, funcsLength);

        while (++index < length) {
          args[index] = transforms[index].call(this, args[index]);
        }
        return apply(func, this, args);
      });
    });

    /**
     * Creates a function that invokes `func` with `partials` prepended to the
     * arguments it receives. This method is like `_.bind` except it does **not**
     * alter the `this` binding.
     *
     * The `_.partial.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for partially applied arguments.
     *
     * **Note:** This method doesn't set the "length" property of partially
     * applied functions.
     *
     * @static
     * @memberOf _
     * @since 0.2.0
     * @category Function
     * @param {Function} func The function to partially apply arguments to.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new partially applied function.
     * @example
     *
     * function greet(greeting, name) {
     *   return greeting + ' ' + name;
     * }
     *
     * var sayHelloTo = _.partial(greet, 'hello');
     * sayHelloTo('fred');
     * // => 'hello fred'
     *
     * // Partially applied with placeholders.
     * var greetFred = _.partial(greet, _, 'fred');
     * greetFred('hi');
     * // => 'hi fred'
     */
    var partial = baseRest(function(func, partials) {
      var holders = replaceHolders(partials, getHolder(partial));
      return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
    });

    /**
     * This method is like `_.partial` except that partially applied arguments
     * are appended to the arguments it receives.
     *
     * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
     * builds, may be used as a placeholder for partially applied arguments.
     *
     * **Note:** This method doesn't set the "length" property of partially
     * applied functions.
     *
     * @static
     * @memberOf _
     * @since 1.0.0
     * @category Function
     * @param {Function} func The function to partially apply arguments to.
     * @param {...*} [partials] The arguments to be partially applied.
     * @returns {Function} Returns the new partially applied function.
     * @example
     *
     * function greet(greeting, name) {
     *   return greeting + ' ' + name;
     * }
     *
     * var greetFred = _.partialRight(greet, 'fred');
     * greetFred('hi');
     * // => 'hi fred'
     *
     * // Partially applied with placeholders.
     * var sayHelloTo = _.partialRight(greet, 'hello', _);
     * sayHelloTo('fred');
     * // => 'hello fred'
     */
    var partialRight = baseRest(function(func, partials) {
      var holders = replaceHolders(partials, getHolder(partialRight));
      return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
    });

    /**
     * Creates a function that invokes `func` with arguments arranged according
     * to the specified `indexes` where the argument value at the first index is
     * provided as the first argument, the argument value at the second index is
     * provided as the second argument, and so on.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Function
     * @param {Function} func The function to rearrange arguments for.
     * @param {...(number|number[])} indexes The arranged argument indexes.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var rearged = _.rearg(function(a, b, c) {
     *   return [a, b, c];
     * }, [2, 0, 1]);
     *
     * rearged('b', 'c', 'a')
     * // => ['a', 'b', 'c']
     */
    var rearg = flatRest(function(func, indexes) {
      return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
    });

    /**
     * Creates a function that invokes `func` with the `this` binding of the
     * created function and arguments from `start` and beyond provided as
     * an array.
     *
     * **Note:** This method is based on the
     * [rest parameter](https://mdn.io/rest_parameters).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Function
     * @param {Function} func The function to apply a rest parameter to.
     * @param {number} [start=func.length-1] The start position of the rest parameter.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var say = _.rest(function(what, names) {
     *   return what + ' ' + _.initial(names).join(', ') +
     *     (_.size(names) > 1 ? ', & ' : '') + _.last(names);
     * });
     *
     * say('hello', 'fred', 'barney', 'pebbles');
     * // => 'hello fred, barney, & pebbles'
     */
    function rest(func, start) {
      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      start = start === undefined ? start : toInteger(start);
      return baseRest(func, start);
    }

    /**
     * Creates a function that invokes `func` with the `this` binding of the
     * create function and an array of arguments much like
     * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
     *
     * **Note:** This method is based on the
     * [spread operator](https://mdn.io/spread_operator).
     *
     * @static
     * @memberOf _
     * @since 3.2.0
     * @category Function
     * @param {Function} func The function to spread arguments over.
     * @param {number} [start=0] The start position of the spread.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var say = _.spread(function(who, what) {
     *   return who + ' says ' + what;
     * });
     *
     * say(['fred', 'hello']);
     * // => 'fred says hello'
     *
     * var numbers = Promise.all([
     *   Promise.resolve(40),
     *   Promise.resolve(36)
     * ]);
     *
     * numbers.then(_.spread(function(x, y) {
     *   return x + y;
     * }));
     * // => a Promise of 76
     */
    function spread(func, start) {
      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      start = start == null ? 0 : nativeMax(toInteger(start), 0);
      return baseRest(function(args) {
        var array = args[start],
            otherArgs = castSlice(args, 0, start);

        if (array) {
          arrayPush(otherArgs, array);
        }
        return apply(func, this, otherArgs);
      });
    }

    /**
     * Creates a throttled function that only invokes `func` at most once per
     * every `wait` milliseconds. The throttled function comes with a `cancel`
     * method to cancel delayed `func` invocations and a `flush` method to
     * immediately invoke them. Provide `options` to indicate whether `func`
     * should be invoked on the leading and/or trailing edge of the `wait`
     * timeout. The `func` is invoked with the last arguments provided to the
     * throttled function. Subsequent calls to the throttled function return the
     * result of the last `func` invocation.
     *
     * **Note:** If `leading` and `trailing` options are `true`, `func` is
     * invoked on the trailing edge of the timeout only if the throttled function
     * is invoked more than once during the `wait` timeout.
     *
     * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
     * until to the next tick, similar to `setTimeout` with a timeout of `0`.
     *
     * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
     * for details over the differences between `_.throttle` and `_.debounce`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {Function} func The function to throttle.
     * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
     * @param {Object} [options={}] The options object.
     * @param {boolean} [options.leading=true]
     *  Specify invoking on the leading edge of the timeout.
     * @param {boolean} [options.trailing=true]
     *  Specify invoking on the trailing edge of the timeout.
     * @returns {Function} Returns the new throttled function.
     * @example
     *
     * // Avoid excessively updating the position while scrolling.
     * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
     *
     * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
     * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
     * jQuery(element).on('click', throttled);
     *
     * // Cancel the trailing throttled invocation.
     * jQuery(window).on('popstate', throttled.cancel);
     */
    function throttle(func, wait, options) {
      var leading = true,
          trailing = true;

      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject(options)) {
        leading = 'leading' in options ? !!options.leading : leading;
        trailing = 'trailing' in options ? !!options.trailing : trailing;
      }
      return debounce(func, wait, {
        'leading': leading,
        'maxWait': wait,
        'trailing': trailing
      });
    }

    /**
     * Creates a function that accepts up to one argument, ignoring any
     * additional arguments.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Function
     * @param {Function} func The function to cap arguments for.
     * @returns {Function} Returns the new capped function.
     * @example
     *
     * _.map(['6', '8', '10'], _.unary(parseInt));
     * // => [6, 8, 10]
     */
    function unary(func) {
      return ary(func, 1);
    }

    /**
     * Creates a function that provides `value` to `wrapper` as its first
     * argument. Any additional arguments provided to the function are appended
     * to those provided to the `wrapper`. The wrapper is invoked with the `this`
     * binding of the created function.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Function
     * @param {*} value The value to wrap.
     * @param {Function} [wrapper=identity] The wrapper function.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var p = _.wrap(_.escape, function(func, text) {
     *   return '<p>' + func(text) + '</p>';
     * });
     *
     * p('fred, barney, & pebbles');
     * // => '<p>fred, barney, &amp; pebbles</p>'
     */
    function wrap(value, wrapper) {
      return partial(castFunction(wrapper), value);
    }

    /*------------------------------------------------------------------------*/

    /**
     * Casts `value` as an array if it's not one.
     *
     * @static
     * @memberOf _
     * @since 4.4.0
     * @category Lang
     * @param {*} value The value to inspect.
     * @returns {Array} Returns the cast array.
     * @example
     *
     * _.castArray(1);
     * // => [1]
     *
     * _.castArray({ 'a': 1 });
     * // => [{ 'a': 1 }]
     *
     * _.castArray('abc');
     * // => ['abc']
     *
     * _.castArray(null);
     * // => [null]
     *
     * _.castArray(undefined);
     * // => [undefined]
     *
     * _.castArray();
     * // => []
     *
     * var array = [1, 2, 3];
     * console.log(_.castArray(array) === array);
     * // => true
     */
    function castArray() {
      if (!arguments.length) {
        return [];
      }
      var value = arguments[0];
      return isArray(value) ? value : [value];
    }

    /**
     * Creates a shallow clone of `value`.
     *
     * **Note:** This method is loosely based on the
     * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
     * and supports cloning arrays, array buffers, booleans, date objects, maps,
     * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
     * arrays. The own enumerable properties of `arguments` objects are cloned
     * as plain objects. An empty object is returned for uncloneable values such
     * as error objects, functions, DOM nodes, and WeakMaps.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to clone.
     * @returns {*} Returns the cloned value.
     * @see _.cloneDeep
     * @example
     *
     * var objects = [{ 'a': 1 }, { 'b': 2 }];
     *
     * var shallow = _.clone(objects);
     * console.log(shallow[0] === objects[0]);
     * // => true
     */
    function clone(value) {
      return baseClone(value, CLONE_SYMBOLS_FLAG);
    }

    /**
     * This method is like `_.clone` except that it accepts `customizer` which
     * is invoked to produce the cloned value. If `customizer` returns `undefined`,
     * cloning is handled by the method instead. The `customizer` is invoked with
     * up to four arguments; (value [, index|key, object, stack]).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to clone.
     * @param {Function} [customizer] The function to customize cloning.
     * @returns {*} Returns the cloned value.
     * @see _.cloneDeepWith
     * @example
     *
     * function customizer(value) {
     *   if (_.isElement(value)) {
     *     return value.cloneNode(false);
     *   }
     * }
     *
     * var el = _.cloneWith(document.body, customizer);
     *
     * console.log(el === document.body);
     * // => false
     * console.log(el.nodeName);
     * // => 'BODY'
     * console.log(el.childNodes.length);
     * // => 0
     */
    function cloneWith(value, customizer) {
      customizer = typeof customizer == 'function' ? customizer : undefined;
      return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
    }

    /**
     * This method is like `_.clone` except that it recursively clones `value`.
     *
     * @static
     * @memberOf _
     * @since 1.0.0
     * @category Lang
     * @param {*} value The value to recursively clone.
     * @returns {*} Returns the deep cloned value.
     * @see _.clone
     * @example
     *
     * var objects = [{ 'a': 1 }, { 'b': 2 }];
     *
     * var deep = _.cloneDeep(objects);
     * console.log(deep[0] === objects[0]);
     * // => false
     */
    function cloneDeep(value) {
      return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
    }

    /**
     * This method is like `_.cloneWith` except that it recursively clones `value`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to recursively clone.
     * @param {Function} [customizer] The function to customize cloning.
     * @returns {*} Returns the deep cloned value.
     * @see _.cloneWith
     * @example
     *
     * function customizer(value) {
     *   if (_.isElement(value)) {
     *     return value.cloneNode(true);
     *   }
     * }
     *
     * var el = _.cloneDeepWith(document.body, customizer);
     *
     * console.log(el === document.body);
     * // => false
     * console.log(el.nodeName);
     * // => 'BODY'
     * console.log(el.childNodes.length);
     * // => 20
     */
    function cloneDeepWith(value, customizer) {
      customizer = typeof customizer == 'function' ? customizer : undefined;
      return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
    }

    /**
     * Checks if `object` conforms to `source` by invoking the predicate
     * properties of `source` with the corresponding property values of `object`.
     *
     * **Note:** This method is equivalent to `_.conforms` when `source` is
     * partially applied.
     *
     * @static
     * @memberOf _
     * @since 4.14.0
     * @category Lang
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property predicates to conform to.
     * @returns {boolean} Returns `true` if `object` conforms, else `false`.
     * @example
     *
     * var object = { 'a': 1, 'b': 2 };
     *
     * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
     * // => true
     *
     * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
     * // => false
     */
    function conformsTo(object, source) {
      return source == null || baseConformsTo(object, source, keys(source));
    }

    /**
     * Performs a
     * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
     * comparison between two values to determine if they are equivalent.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     * @example
     *
     * var object = { 'a': 1 };
     * var other = { 'a': 1 };
     *
     * _.eq(object, object);
     * // => true
     *
     * _.eq(object, other);
     * // => false
     *
     * _.eq('a', 'a');
     * // => true
     *
     * _.eq('a', Object('a'));
     * // => false
     *
     * _.eq(NaN, NaN);
     * // => true
     */
    function eq(value, other) {
      return value === other || (value !== value && other !== other);
    }

    /**
     * Checks if `value` is greater than `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is greater than `other`,
     *  else `false`.
     * @see _.lt
     * @example
     *
     * _.gt(3, 1);
     * // => true
     *
     * _.gt(3, 3);
     * // => false
     *
     * _.gt(1, 3);
     * // => false
     */
    var gt = createRelationalOperation(baseGt);

    /**
     * Checks if `value` is greater than or equal to `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is greater than or equal to
     *  `other`, else `false`.
     * @see _.lte
     * @example
     *
     * _.gte(3, 1);
     * // => true
     *
     * _.gte(3, 3);
     * // => true
     *
     * _.gte(1, 3);
     * // => false
     */
    var gte = createRelationalOperation(function(value, other) {
      return value >= other;
    });

    /**
     * Checks if `value` is likely an `arguments` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an `arguments` object,
     *  else `false`.
     * @example
     *
     * _.isArguments(function() { return arguments; }());
     * // => true
     *
     * _.isArguments([1, 2, 3]);
     * // => false
     */
    var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
      return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
        !propertyIsEnumerable.call(value, 'callee');
    };

    /**
     * Checks if `value` is classified as an `Array` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array, else `false`.
     * @example
     *
     * _.isArray([1, 2, 3]);
     * // => true
     *
     * _.isArray(document.body.children);
     * // => false
     *
     * _.isArray('abc');
     * // => false
     *
     * _.isArray(_.noop);
     * // => false
     */
    var isArray = Array.isArray;

    /**
     * Checks if `value` is classified as an `ArrayBuffer` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
     * @example
     *
     * _.isArrayBuffer(new ArrayBuffer(2));
     * // => true
     *
     * _.isArrayBuffer(new Array(2));
     * // => false
     */
    var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;

    /**
     * Checks if `value` is array-like. A value is considered array-like if it's
     * not a function and has a `value.length` that's an integer greater than or
     * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
     * @example
     *
     * _.isArrayLike([1, 2, 3]);
     * // => true
     *
     * _.isArrayLike(document.body.children);
     * // => true
     *
     * _.isArrayLike('abc');
     * // => true
     *
     * _.isArrayLike(_.noop);
     * // => false
     */
    function isArrayLike(value) {
      return value != null && isLength(value.length) && !isFunction(value);
    }

    /**
     * This method is like `_.isArrayLike` except that it also checks if `value`
     * is an object.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an array-like object,
     *  else `false`.
     * @example
     *
     * _.isArrayLikeObject([1, 2, 3]);
     * // => true
     *
     * _.isArrayLikeObject(document.body.children);
     * // => true
     *
     * _.isArrayLikeObject('abc');
     * // => false
     *
     * _.isArrayLikeObject(_.noop);
     * // => false
     */
    function isArrayLikeObject(value) {
      return isObjectLike(value) && isArrayLike(value);
    }

    /**
     * Checks if `value` is classified as a boolean primitive or object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
     * @example
     *
     * _.isBoolean(false);
     * // => true
     *
     * _.isBoolean(null);
     * // => false
     */
    function isBoolean(value) {
      return value === true || value === false ||
        (isObjectLike(value) && baseGetTag(value) == boolTag);
    }

    /**
     * Checks if `value` is a buffer.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
     * @example
     *
     * _.isBuffer(new Buffer(2));
     * // => true
     *
     * _.isBuffer(new Uint8Array(2));
     * // => false
     */
    var isBuffer = nativeIsBuffer || stubFalse;

    /**
     * Checks if `value` is classified as a `Date` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
     * @example
     *
     * _.isDate(new Date);
     * // => true
     *
     * _.isDate('Mon April 23 2012');
     * // => false
     */
    var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;

    /**
     * Checks if `value` is likely a DOM element.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
     * @example
     *
     * _.isElement(document.body);
     * // => true
     *
     * _.isElement('<body>');
     * // => false
     */
    function isElement(value) {
      return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
    }

    /**
     * Checks if `value` is an empty object, collection, map, or set.
     *
     * Objects are considered empty if they have no own enumerable string keyed
     * properties.
     *
     * Array-like values such as `arguments` objects, arrays, buffers, strings, or
     * jQuery-like collections are considered empty if they have a `length` of `0`.
     * Similarly, maps and sets are considered empty if they have a `size` of `0`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is empty, else `false`.
     * @example
     *
     * _.isEmpty(null);
     * // => true
     *
     * _.isEmpty(true);
     * // => true
     *
     * _.isEmpty(1);
     * // => true
     *
     * _.isEmpty([1, 2, 3]);
     * // => false
     *
     * _.isEmpty({ 'a': 1 });
     * // => false
     */
    function isEmpty(value) {
      if (value == null) {
        return true;
      }
      if (isArrayLike(value) &&
          (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
            isBuffer(value) || isTypedArray(value) || isArguments(value))) {
        return !value.length;
      }
      var tag = getTag(value);
      if (tag == mapTag || tag == setTag) {
        return !value.size;
      }
      if (isPrototype(value)) {
        return !baseKeys(value).length;
      }
      for (var key in value) {
        if (hasOwnProperty.call(value, key)) {
          return false;
        }
      }
      return true;
    }

    /**
     * Performs a deep comparison between two values to determine if they are
     * equivalent.
     *
     * **Note:** This method supports comparing arrays, array buffers, booleans,
     * date objects, error objects, maps, numbers, `Object` objects, regexes,
     * sets, strings, symbols, and typed arrays. `Object` objects are compared
     * by their own, not inherited, enumerable properties. Functions and DOM
     * nodes are compared by strict equality, i.e. `===`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     * @example
     *
     * var object = { 'a': 1 };
     * var other = { 'a': 1 };
     *
     * _.isEqual(object, other);
     * // => true
     *
     * object === other;
     * // => false
     */
    function isEqual(value, other) {
      return baseIsEqual(value, other);
    }

    /**
     * This method is like `_.isEqual` except that it accepts `customizer` which
     * is invoked to compare values. If `customizer` returns `undefined`, comparisons
     * are handled by the method instead. The `customizer` is invoked with up to
     * six arguments: (objValue, othValue [, index|key, object, other, stack]).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @param {Function} [customizer] The function to customize comparisons.
     * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
     * @example
     *
     * function isGreeting(value) {
     *   return /^h(?:i|ello)$/.test(value);
     * }
     *
     * function customizer(objValue, othValue) {
     *   if (isGreeting(objValue) && isGreeting(othValue)) {
     *     return true;
     *   }
     * }
     *
     * var array = ['hello', 'goodbye'];
     * var other = ['hi', 'goodbye'];
     *
     * _.isEqualWith(array, other, customizer);
     * // => true
     */
    function isEqualWith(value, other, customizer) {
      customizer = typeof customizer == 'function' ? customizer : undefined;
      var result = customizer ? customizer(value, other) : undefined;
      return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
    }

    /**
     * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
     * `SyntaxError`, `TypeError`, or `URIError` object.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
     * @example
     *
     * _.isError(new Error);
     * // => true
     *
     * _.isError(Error);
     * // => false
     */
    function isError(value) {
      if (!isObjectLike(value)) {
        return false;
      }
      var tag = baseGetTag(value);
      return tag == errorTag || tag == domExcTag ||
        (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
    }

    /**
     * Checks if `value` is a finite primitive number.
     *
     * **Note:** This method is based on
     * [`Number.isFinite`](https://mdn.io/Number/isFinite).
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
     * @example
     *
     * _.isFinite(3);
     * // => true
     *
     * _.isFinite(Number.MIN_VALUE);
     * // => true
     *
     * _.isFinite(Infinity);
     * // => false
     *
     * _.isFinite('3');
     * // => false
     */
    function isFinite(value) {
      return typeof value == 'number' && nativeIsFinite(value);
    }

    /**
     * Checks if `value` is classified as a `Function` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a function, else `false`.
     * @example
     *
     * _.isFunction(_);
     * // => true
     *
     * _.isFunction(/abc/);
     * // => false
     */
    function isFunction(value) {
      if (!isObject(value)) {
        return false;
      }
      // The use of `Object#toString` avoids issues with the `typeof` operator
      // in Safari 9 which returns 'object' for typed arrays and other constructors.
      var tag = baseGetTag(value);
      return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
    }

    /**
     * Checks if `value` is an integer.
     *
     * **Note:** This method is based on
     * [`Number.isInteger`](https://mdn.io/Number/isInteger).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
     * @example
     *
     * _.isInteger(3);
     * // => true
     *
     * _.isInteger(Number.MIN_VALUE);
     * // => false
     *
     * _.isInteger(Infinity);
     * // => false
     *
     * _.isInteger('3');
     * // => false
     */
    function isInteger(value) {
      return typeof value == 'number' && value == toInteger(value);
    }

    /**
     * Checks if `value` is a valid array-like length.
     *
     * **Note:** This method is loosely based on
     * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
     * @example
     *
     * _.isLength(3);
     * // => true
     *
     * _.isLength(Number.MIN_VALUE);
     * // => false
     *
     * _.isLength(Infinity);
     * // => false
     *
     * _.isLength('3');
     * // => false
     */
    function isLength(value) {
      return typeof value == 'number' &&
        value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
    }

    /**
     * Checks if `value` is the
     * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
     * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is an object, else `false`.
     * @example
     *
     * _.isObject({});
     * // => true
     *
     * _.isObject([1, 2, 3]);
     * // => true
     *
     * _.isObject(_.noop);
     * // => true
     *
     * _.isObject(null);
     * // => false
     */
    function isObject(value) {
      var type = typeof value;
      return value != null && (type == 'object' || type == 'function');
    }

    /**
     * Checks if `value` is object-like. A value is object-like if it's not `null`
     * and has a `typeof` result of "object".
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
     * @example
     *
     * _.isObjectLike({});
     * // => true
     *
     * _.isObjectLike([1, 2, 3]);
     * // => true
     *
     * _.isObjectLike(_.noop);
     * // => false
     *
     * _.isObjectLike(null);
     * // => false
     */
    function isObjectLike(value) {
      return value != null && typeof value == 'object';
    }

    /**
     * Checks if `value` is classified as a `Map` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a map, else `false`.
     * @example
     *
     * _.isMap(new Map);
     * // => true
     *
     * _.isMap(new WeakMap);
     * // => false
     */
    var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;

    /**
     * Performs a partial deep comparison between `object` and `source` to
     * determine if `object` contains equivalent property values.
     *
     * **Note:** This method is equivalent to `_.matches` when `source` is
     * partially applied.
     *
     * Partial comparisons will match empty array and empty object `source`
     * values against any array or object value, respectively. See `_.isEqual`
     * for a list of supported value comparisons.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property values to match.
     * @returns {boolean} Returns `true` if `object` is a match, else `false`.
     * @example
     *
     * var object = { 'a': 1, 'b': 2 };
     *
     * _.isMatch(object, { 'b': 2 });
     * // => true
     *
     * _.isMatch(object, { 'b': 1 });
     * // => false
     */
    function isMatch(object, source) {
      return object === source || baseIsMatch(object, source, getMatchData(source));
    }

    /**
     * This method is like `_.isMatch` except that it accepts `customizer` which
     * is invoked to compare values. If `customizer` returns `undefined`, comparisons
     * are handled by the method instead. The `customizer` is invoked with five
     * arguments: (objValue, srcValue, index|key, object, source).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {Object} object The object to inspect.
     * @param {Object} source The object of property values to match.
     * @param {Function} [customizer] The function to customize comparisons.
     * @returns {boolean} Returns `true` if `object` is a match, else `false`.
     * @example
     *
     * function isGreeting(value) {
     *   return /^h(?:i|ello)$/.test(value);
     * }
     *
     * function customizer(objValue, srcValue) {
     *   if (isGreeting(objValue) && isGreeting(srcValue)) {
     *     return true;
     *   }
     * }
     *
     * var object = { 'greeting': 'hello' };
     * var source = { 'greeting': 'hi' };
     *
     * _.isMatchWith(object, source, customizer);
     * // => true
     */
    function isMatchWith(object, source, customizer) {
      customizer = typeof customizer == 'function' ? customizer : undefined;
      return baseIsMatch(object, source, getMatchData(source), customizer);
    }

    /**
     * Checks if `value` is `NaN`.
     *
     * **Note:** This method is based on
     * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
     * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
     * `undefined` and other non-number values.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
     * @example
     *
     * _.isNaN(NaN);
     * // => true
     *
     * _.isNaN(new Number(NaN));
     * // => true
     *
     * isNaN(undefined);
     * // => true
     *
     * _.isNaN(undefined);
     * // => false
     */
    function isNaN(value) {
      // An `NaN` primitive is the only value that is not equal to itself.
      // Perform the `toStringTag` check first to avoid errors with some
      // ActiveX objects in IE.
      return isNumber(value) && value != +value;
    }

    /**
     * Checks if `value` is a pristine native function.
     *
     * **Note:** This method can't reliably detect native functions in the presence
     * of the core-js package because core-js circumvents this kind of detection.
     * Despite multiple requests, the core-js maintainer has made it clear: any
     * attempt to fix the detection will be obstructed. As a result, we're left
     * with little choice but to throw an error. Unfortunately, this also affects
     * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
     * which rely on core-js.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a native function,
     *  else `false`.
     * @example
     *
     * _.isNative(Array.prototype.push);
     * // => true
     *
     * _.isNative(_);
     * // => false
     */
    function isNative(value) {
      if (isMaskable(value)) {
        throw new Error(CORE_ERROR_TEXT);
      }
      return baseIsNative(value);
    }

    /**
     * Checks if `value` is `null`.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
     * @example
     *
     * _.isNull(null);
     * // => true
     *
     * _.isNull(void 0);
     * // => false
     */
    function isNull(value) {
      return value === null;
    }

    /**
     * Checks if `value` is `null` or `undefined`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
     * @example
     *
     * _.isNil(null);
     * // => true
     *
     * _.isNil(void 0);
     * // => true
     *
     * _.isNil(NaN);
     * // => false
     */
    function isNil(value) {
      return value == null;
    }

    /**
     * Checks if `value` is classified as a `Number` primitive or object.
     *
     * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
     * classified as numbers, use the `_.isFinite` method.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a number, else `false`.
     * @example
     *
     * _.isNumber(3);
     * // => true
     *
     * _.isNumber(Number.MIN_VALUE);
     * // => true
     *
     * _.isNumber(Infinity);
     * // => true
     *
     * _.isNumber('3');
     * // => false
     */
    function isNumber(value) {
      return typeof value == 'number' ||
        (isObjectLike(value) && baseGetTag(value) == numberTag);
    }

    /**
     * Checks if `value` is a plain object, that is, an object created by the
     * `Object` constructor or one with a `[[Prototype]]` of `null`.
     *
     * @static
     * @memberOf _
     * @since 0.8.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     * }
     *
     * _.isPlainObject(new Foo);
     * // => false
     *
     * _.isPlainObject([1, 2, 3]);
     * // => false
     *
     * _.isPlainObject({ 'x': 0, 'y': 0 });
     * // => true
     *
     * _.isPlainObject(Object.create(null));
     * // => true
     */
    function isPlainObject(value) {
      if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
        return false;
      }
      var proto = getPrototype(value);
      if (proto === null) {
        return true;
      }
      var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
      return typeof Ctor == 'function' && Ctor instanceof Ctor &&
        funcToString.call(Ctor) == objectCtorString;
    }

    /**
     * Checks if `value` is classified as a `RegExp` object.
     *
     * @static
     * @memberOf _
     * @since 0.1.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
     * @example
     *
     * _.isRegExp(/abc/);
     * // => true
     *
     * _.isRegExp('/abc/');
     * // => false
     */
    var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;

    /**
     * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
     * double precision number which isn't the result of a rounded unsafe integer.
     *
     * **Note:** This method is based on
     * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
     * @example
     *
     * _.isSafeInteger(3);
     * // => true
     *
     * _.isSafeInteger(Number.MIN_VALUE);
     * // => false
     *
     * _.isSafeInteger(Infinity);
     * // => false
     *
     * _.isSafeInteger('3');
     * // => false
     */
    function isSafeInteger(value) {
      return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
    }

    /**
     * Checks if `value` is classified as a `Set` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a set, else `false`.
     * @example
     *
     * _.isSet(new Set);
     * // => true
     *
     * _.isSet(new WeakSet);
     * // => false
     */
    var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;

    /**
     * Checks if `value` is classified as a `String` primitive or object.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a string, else `false`.
     * @example
     *
     * _.isString('abc');
     * // => true
     *
     * _.isString(1);
     * // => false
     */
    function isString(value) {
      return typeof value == 'string' ||
        (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
    }

    /**
     * Checks if `value` is classified as a `Symbol` primitive or object.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
     * @example
     *
     * _.isSymbol(Symbol.iterator);
     * // => true
     *
     * _.isSymbol('abc');
     * // => false
     */
    function isSymbol(value) {
      return typeof value == 'symbol' ||
        (isObjectLike(value) && baseGetTag(value) == symbolTag);
    }

    /**
     * Checks if `value` is classified as a typed array.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
     * @example
     *
     * _.isTypedArray(new Uint8Array);
     * // => true
     *
     * _.isTypedArray([]);
     * // => false
     */
    var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;

    /**
     * Checks if `value` is `undefined`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
     * @example
     *
     * _.isUndefined(void 0);
     * // => true
     *
     * _.isUndefined(null);
     * // => false
     */
    function isUndefined(value) {
      return value === undefined;
    }

    /**
     * Checks if `value` is classified as a `WeakMap` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
     * @example
     *
     * _.isWeakMap(new WeakMap);
     * // => true
     *
     * _.isWeakMap(new Map);
     * // => false
     */
    function isWeakMap(value) {
      return isObjectLike(value) && getTag(value) == weakMapTag;
    }

    /**
     * Checks if `value` is classified as a `WeakSet` object.
     *
     * @static
     * @memberOf _
     * @since 4.3.0
     * @category Lang
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
     * @example
     *
     * _.isWeakSet(new WeakSet);
     * // => true
     *
     * _.isWeakSet(new Set);
     * // => false
     */
    function isWeakSet(value) {
      return isObjectLike(value) && baseGetTag(value) == weakSetTag;
    }

    /**
     * Checks if `value` is less than `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is less than `other`,
     *  else `false`.
     * @see _.gt
     * @example
     *
     * _.lt(1, 3);
     * // => true
     *
     * _.lt(3, 3);
     * // => false
     *
     * _.lt(3, 1);
     * // => false
     */
    var lt = createRelationalOperation(baseLt);

    /**
     * Checks if `value` is less than or equal to `other`.
     *
     * @static
     * @memberOf _
     * @since 3.9.0
     * @category Lang
     * @param {*} value The value to compare.
     * @param {*} other The other value to compare.
     * @returns {boolean} Returns `true` if `value` is less than or equal to
     *  `other`, else `false`.
     * @see _.gte
     * @example
     *
     * _.lte(1, 3);
     * // => true
     *
     * _.lte(3, 3);
     * // => true
     *
     * _.lte(3, 1);
     * // => false
     */
    var lte = createRelationalOperation(function(value, other) {
      return value <= other;
    });

    /**
     * Converts `value` to an array.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {Array} Returns the converted array.
     * @example
     *
     * _.toArray({ 'a': 1, 'b': 2 });
     * // => [1, 2]
     *
     * _.toArray('abc');
     * // => ['a', 'b', 'c']
     *
     * _.toArray(1);
     * // => []
     *
     * _.toArray(null);
     * // => []
     */
    function toArray(value) {
      if (!value) {
        return [];
      }
      if (isArrayLike(value)) {
        return isString(value) ? stringToArray(value) : copyArray(value);
      }
      if (symIterator && value[symIterator]) {
        return iteratorToArray(value[symIterator]());
      }
      var tag = getTag(value),
          func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);

      return func(value);
    }

    /**
     * Converts `value` to a finite number.
     *
     * @static
     * @memberOf _
     * @since 4.12.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted number.
     * @example
     *
     * _.toFinite(3.2);
     * // => 3.2
     *
     * _.toFinite(Number.MIN_VALUE);
     * // => 5e-324
     *
     * _.toFinite(Infinity);
     * // => 1.7976931348623157e+308
     *
     * _.toFinite('3.2');
     * // => 3.2
     */
    function toFinite(value) {
      if (!value) {
        return value === 0 ? value : 0;
      }
      value = toNumber(value);
      if (value === INFINITY || value === -INFINITY) {
        var sign = (value < 0 ? -1 : 1);
        return sign * MAX_INTEGER;
      }
      return value === value ? value : 0;
    }

    /**
     * Converts `value` to an integer.
     *
     * **Note:** This method is loosely based on
     * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.toInteger(3.2);
     * // => 3
     *
     * _.toInteger(Number.MIN_VALUE);
     * // => 0
     *
     * _.toInteger(Infinity);
     * // => 1.7976931348623157e+308
     *
     * _.toInteger('3.2');
     * // => 3
     */
    function toInteger(value) {
      var result = toFinite(value),
          remainder = result % 1;

      return result === result ? (remainder ? result - remainder : result) : 0;
    }

    /**
     * Converts `value` to an integer suitable for use as the length of an
     * array-like object.
     *
     * **Note:** This method is based on
     * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.toLength(3.2);
     * // => 3
     *
     * _.toLength(Number.MIN_VALUE);
     * // => 0
     *
     * _.toLength(Infinity);
     * // => 4294967295
     *
     * _.toLength('3.2');
     * // => 3
     */
    function toLength(value) {
      return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
    }

    /**
     * Converts `value` to a number.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to process.
     * @returns {number} Returns the number.
     * @example
     *
     * _.toNumber(3.2);
     * // => 3.2
     *
     * _.toNumber(Number.MIN_VALUE);
     * // => 5e-324
     *
     * _.toNumber(Infinity);
     * // => Infinity
     *
     * _.toNumber('3.2');
     * // => 3.2
     */
    function toNumber(value) {
      if (typeof value == 'number') {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject(value)) {
        var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
        value = isObject(other) ? (other + '') : other;
      }
      if (typeof value != 'string') {
        return value === 0 ? value : +value;
      }
      value = baseTrim(value);
      var isBinary = reIsBinary.test(value);
      return (isBinary || reIsOctal.test(value))
        ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
        : (reIsBadHex.test(value) ? NAN : +value);
    }

    /**
     * Converts `value` to a plain object flattening inherited enumerable string
     * keyed properties of `value` to own properties of the plain object.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {Object} Returns the converted plain object.
     * @example
     *
     * function Foo() {
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.assign({ 'a': 1 }, new Foo);
     * // => { 'a': 1, 'b': 2 }
     *
     * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
     * // => { 'a': 1, 'b': 2, 'c': 3 }
     */
    function toPlainObject(value) {
      return copyObject(value, keysIn(value));
    }

    /**
     * Converts `value` to a safe integer. A safe integer can be compared and
     * represented correctly.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.toSafeInteger(3.2);
     * // => 3
     *
     * _.toSafeInteger(Number.MIN_VALUE);
     * // => 0
     *
     * _.toSafeInteger(Infinity);
     * // => 9007199254740991
     *
     * _.toSafeInteger('3.2');
     * // => 3
     */
    function toSafeInteger(value) {
      return value
        ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
        : (value === 0 ? value : 0);
    }

    /**
     * Converts `value` to a string. An empty string is returned for `null`
     * and `undefined` values. The sign of `-0` is preserved.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Lang
     * @param {*} value The value to convert.
     * @returns {string} Returns the converted string.
     * @example
     *
     * _.toString(null);
     * // => ''
     *
     * _.toString(-0);
     * // => '-0'
     *
     * _.toString([1, 2, 3]);
     * // => '1,2,3'
     */
    function toString(value) {
      return value == null ? '' : baseToString(value);
    }

    /*------------------------------------------------------------------------*/

    /**
     * Assigns own enumerable string keyed properties of source objects to the
     * destination object. Source objects are applied from left to right.
     * Subsequent sources overwrite property assignments of previous sources.
     *
     * **Note:** This method mutates `object` and is loosely based on
     * [`Object.assign`](https://mdn.io/Object/assign).
     *
     * @static
     * @memberOf _
     * @since 0.10.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.assignIn
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     * }
     *
     * function Bar() {
     *   this.c = 3;
     * }
     *
     * Foo.prototype.b = 2;
     * Bar.prototype.d = 4;
     *
     * _.assign({ 'a': 0 }, new Foo, new Bar);
     * // => { 'a': 1, 'c': 3 }
     */
    var assign = createAssigner(function(object, source) {
      if (isPrototype(source) || isArrayLike(source)) {
        copyObject(source, keys(source), object);
        return;
      }
      for (var key in source) {
        if (hasOwnProperty.call(source, key)) {
          assignValue(object, key, source[key]);
        }
      }
    });

    /**
     * This method is like `_.assign` except that it iterates over own and
     * inherited source properties.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias extend
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.assign
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     * }
     *
     * function Bar() {
     *   this.c = 3;
     * }
     *
     * Foo.prototype.b = 2;
     * Bar.prototype.d = 4;
     *
     * _.assignIn({ 'a': 0 }, new Foo, new Bar);
     * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
     */
    var assignIn = createAssigner(function(object, source) {
      copyObject(source, keysIn(source), object);
    });

    /**
     * This method is like `_.assignIn` except that it accepts `customizer`
     * which is invoked to produce the assigned values. If `customizer` returns
     * `undefined`, assignment is handled by the method instead. The `customizer`
     * is invoked with five arguments: (objValue, srcValue, key, object, source).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias extendWith
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} sources The source objects.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @see _.assignWith
     * @example
     *
     * function customizer(objValue, srcValue) {
     *   return _.isUndefined(objValue) ? srcValue : objValue;
     * }
     *
     * var defaults = _.partialRight(_.assignInWith, customizer);
     *
     * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
     * // => { 'a': 1, 'b': 2 }
     */
    var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
      copyObject(source, keysIn(source), object, customizer);
    });

    /**
     * This method is like `_.assign` except that it accepts `customizer`
     * which is invoked to produce the assigned values. If `customizer` returns
     * `undefined`, assignment is handled by the method instead. The `customizer`
     * is invoked with five arguments: (objValue, srcValue, key, object, source).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} sources The source objects.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @see _.assignInWith
     * @example
     *
     * function customizer(objValue, srcValue) {
     *   return _.isUndefined(objValue) ? srcValue : objValue;
     * }
     *
     * var defaults = _.partialRight(_.assignWith, customizer);
     *
     * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
     * // => { 'a': 1, 'b': 2 }
     */
    var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
      copyObject(source, keys(source), object, customizer);
    });

    /**
     * Creates an array of values corresponding to `paths` of `object`.
     *
     * @static
     * @memberOf _
     * @since 1.0.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {...(string|string[])} [paths] The property paths to pick.
     * @returns {Array} Returns the picked values.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
     *
     * _.at(object, ['a[0].b.c', 'a[1]']);
     * // => [3, 4]
     */
    var at = flatRest(baseAt);

    /**
     * Creates an object that inherits from the `prototype` object. If a
     * `properties` object is given, its own enumerable string keyed properties
     * are assigned to the created object.
     *
     * @static
     * @memberOf _
     * @since 2.3.0
     * @category Object
     * @param {Object} prototype The object to inherit from.
     * @param {Object} [properties] The properties to assign to the object.
     * @returns {Object} Returns the new object.
     * @example
     *
     * function Shape() {
     *   this.x = 0;
     *   this.y = 0;
     * }
     *
     * function Circle() {
     *   Shape.call(this);
     * }
     *
     * Circle.prototype = _.create(Shape.prototype, {
     *   'constructor': Circle
     * });
     *
     * var circle = new Circle;
     * circle instanceof Circle;
     * // => true
     *
     * circle instanceof Shape;
     * // => true
     */
    function create(prototype, properties) {
      var result = baseCreate(prototype);
      return properties == null ? result : baseAssign(result, properties);
    }

    /**
     * Assigns own and inherited enumerable string keyed properties of source
     * objects to the destination object for all destination properties that
     * resolve to `undefined`. Source objects are applied from left to right.
     * Once a property is set, additional values of the same property are ignored.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.defaultsDeep
     * @example
     *
     * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
     * // => { 'a': 1, 'b': 2 }
     */
    var defaults = baseRest(function(object, sources) {
      object = Object(object);

      var index = -1;
      var length = sources.length;
      var guard = length > 2 ? sources[2] : undefined;

      if (guard && isIterateeCall(sources[0], sources[1], guard)) {
        length = 1;
      }

      while (++index < length) {
        var source = sources[index];
        var props = keysIn(source);
        var propsIndex = -1;
        var propsLength = props.length;

        while (++propsIndex < propsLength) {
          var key = props[propsIndex];
          var value = object[key];

          if (value === undefined ||
              (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
            object[key] = source[key];
          }
        }
      }

      return object;
    });

    /**
     * This method is like `_.defaults` except that it recursively assigns
     * default properties.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @see _.defaults
     * @example
     *
     * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
     * // => { 'a': { 'b': 2, 'c': 3 } }
     */
    var defaultsDeep = baseRest(function(args) {
      args.push(undefined, customDefaultsMerge);
      return apply(mergeWith, undefined, args);
    });

    /**
     * This method is like `_.find` except that it returns the key of the first
     * element `predicate` returns truthy for instead of the element itself.
     *
     * @static
     * @memberOf _
     * @since 1.1.0
     * @category Object
     * @param {Object} object The object to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {string|undefined} Returns the key of the matched element,
     *  else `undefined`.
     * @example
     *
     * var users = {
     *   'barney':  { 'age': 36, 'active': true },
     *   'fred':    { 'age': 40, 'active': false },
     *   'pebbles': { 'age': 1,  'active': true }
     * };
     *
     * _.findKey(users, function(o) { return o.age < 40; });
     * // => 'barney' (iteration order is not guaranteed)
     *
     * // The `_.matches` iteratee shorthand.
     * _.findKey(users, { 'age': 1, 'active': true });
     * // => 'pebbles'
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findKey(users, ['active', false]);
     * // => 'fred'
     *
     * // The `_.property` iteratee shorthand.
     * _.findKey(users, 'active');
     * // => 'barney'
     */
    function findKey(object, predicate) {
      return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
    }

    /**
     * This method is like `_.findKey` except that it iterates over elements of
     * a collection in the opposite order.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Object
     * @param {Object} object The object to inspect.
     * @param {Function} [predicate=_.identity] The function invoked per iteration.
     * @returns {string|undefined} Returns the key of the matched element,
     *  else `undefined`.
     * @example
     *
     * var users = {
     *   'barney':  { 'age': 36, 'active': true },
     *   'fred':    { 'age': 40, 'active': false },
     *   'pebbles': { 'age': 1,  'active': true }
     * };
     *
     * _.findLastKey(users, function(o) { return o.age < 40; });
     * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
     *
     * // The `_.matches` iteratee shorthand.
     * _.findLastKey(users, { 'age': 36, 'active': true });
     * // => 'barney'
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.findLastKey(users, ['active', false]);
     * // => 'fred'
     *
     * // The `_.property` iteratee shorthand.
     * _.findLastKey(users, 'active');
     * // => 'pebbles'
     */
    function findLastKey(object, predicate) {
      return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
    }

    /**
     * Iterates over own and inherited enumerable string keyed properties of an
     * object and invokes `iteratee` for each property. The iteratee is invoked
     * with three arguments: (value, key, object). Iteratee functions may exit
     * iteration early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @since 0.3.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forInRight
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forIn(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
     */
    function forIn(object, iteratee) {
      return object == null
        ? object
        : baseFor(object, getIteratee(iteratee, 3), keysIn);
    }

    /**
     * This method is like `_.forIn` except that it iterates over properties of
     * `object` in the opposite order.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forIn
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forInRight(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
     */
    function forInRight(object, iteratee) {
      return object == null
        ? object
        : baseForRight(object, getIteratee(iteratee, 3), keysIn);
    }

    /**
     * Iterates over own enumerable string keyed properties of an object and
     * invokes `iteratee` for each property. The iteratee is invoked with three
     * arguments: (value, key, object). Iteratee functions may exit iteration
     * early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @since 0.3.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forOwnRight
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forOwn(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'a' then 'b' (iteration order is not guaranteed).
     */
    function forOwn(object, iteratee) {
      return object && baseForOwn(object, getIteratee(iteratee, 3));
    }

    /**
     * This method is like `_.forOwn` except that it iterates over properties of
     * `object` in the opposite order.
     *
     * @static
     * @memberOf _
     * @since 2.0.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns `object`.
     * @see _.forOwn
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.forOwnRight(new Foo, function(value, key) {
     *   console.log(key);
     * });
     * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
     */
    function forOwnRight(object, iteratee) {
      return object && baseForOwnRight(object, getIteratee(iteratee, 3));
    }

    /**
     * Creates an array of function property names from own enumerable properties
     * of `object`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns the function names.
     * @see _.functionsIn
     * @example
     *
     * function Foo() {
     *   this.a = _.constant('a');
     *   this.b = _.constant('b');
     * }
     *
     * Foo.prototype.c = _.constant('c');
     *
     * _.functions(new Foo);
     * // => ['a', 'b']
     */
    function functions(object) {
      return object == null ? [] : baseFunctions(object, keys(object));
    }

    /**
     * Creates an array of function property names from own and inherited
     * enumerable properties of `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to inspect.
     * @returns {Array} Returns the function names.
     * @see _.functions
     * @example
     *
     * function Foo() {
     *   this.a = _.constant('a');
     *   this.b = _.constant('b');
     * }
     *
     * Foo.prototype.c = _.constant('c');
     *
     * _.functionsIn(new Foo);
     * // => ['a', 'b', 'c']
     */
    function functionsIn(object) {
      return object == null ? [] : baseFunctions(object, keysIn(object));
    }

    /**
     * Gets the value at `path` of `object`. If the resolved value is
     * `undefined`, the `defaultValue` is returned in its place.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the property to get.
     * @param {*} [defaultValue] The value returned for `undefined` resolved values.
     * @returns {*} Returns the resolved value.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }] };
     *
     * _.get(object, 'a[0].b.c');
     * // => 3
     *
     * _.get(object, ['a', '0', 'b', 'c']);
     * // => 3
     *
     * _.get(object, 'a.b.c', 'default');
     * // => 'default'
     */
    function get(object, path, defaultValue) {
      var result = object == null ? undefined : baseGet(object, path);
      return result === undefined ? defaultValue : result;
    }

    /**
     * Checks if `path` is a direct property of `object`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path to check.
     * @returns {boolean} Returns `true` if `path` exists, else `false`.
     * @example
     *
     * var object = { 'a': { 'b': 2 } };
     * var other = _.create({ 'a': _.create({ 'b': 2 }) });
     *
     * _.has(object, 'a');
     * // => true
     *
     * _.has(object, 'a.b');
     * // => true
     *
     * _.has(object, ['a', 'b']);
     * // => true
     *
     * _.has(other, 'a');
     * // => false
     */
    function has(object, path) {
      return object != null && hasPath(object, path, baseHas);
    }

    /**
     * Checks if `path` is a direct or inherited property of `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path to check.
     * @returns {boolean} Returns `true` if `path` exists, else `false`.
     * @example
     *
     * var object = _.create({ 'a': _.create({ 'b': 2 }) });
     *
     * _.hasIn(object, 'a');
     * // => true
     *
     * _.hasIn(object, 'a.b');
     * // => true
     *
     * _.hasIn(object, ['a', 'b']);
     * // => true
     *
     * _.hasIn(object, 'b');
     * // => false
     */
    function hasIn(object, path) {
      return object != null && hasPath(object, path, baseHasIn);
    }

    /**
     * Creates an object composed of the inverted keys and values of `object`.
     * If `object` contains duplicate values, subsequent values overwrite
     * property assignments of previous values.
     *
     * @static
     * @memberOf _
     * @since 0.7.0
     * @category Object
     * @param {Object} object The object to invert.
     * @returns {Object} Returns the new inverted object.
     * @example
     *
     * var object = { 'a': 1, 'b': 2, 'c': 1 };
     *
     * _.invert(object);
     * // => { '1': 'c', '2': 'b' }
     */
    var invert = createInverter(function(result, value, key) {
      if (value != null &&
          typeof value.toString != 'function') {
        value = nativeObjectToString.call(value);
      }

      result[value] = key;
    }, constant(identity));

    /**
     * This method is like `_.invert` except that the inverted object is generated
     * from the results of running each element of `object` thru `iteratee`. The
     * corresponding inverted value of each inverted key is an array of keys
     * responsible for generating the inverted value. The iteratee is invoked
     * with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.1.0
     * @category Object
     * @param {Object} object The object to invert.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {Object} Returns the new inverted object.
     * @example
     *
     * var object = { 'a': 1, 'b': 2, 'c': 1 };
     *
     * _.invertBy(object);
     * // => { '1': ['a', 'c'], '2': ['b'] }
     *
     * _.invertBy(object, function(value) {
     *   return 'group' + value;
     * });
     * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
     */
    var invertBy = createInverter(function(result, value, key) {
      if (value != null &&
          typeof value.toString != 'function') {
        value = nativeObjectToString.call(value);
      }

      if (hasOwnProperty.call(result, value)) {
        result[value].push(key);
      } else {
        result[value] = [key];
      }
    }, getIteratee);

    /**
     * Invokes the method at `path` of `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the method to invoke.
     * @param {...*} [args] The arguments to invoke the method with.
     * @returns {*} Returns the result of the invoked method.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
     *
     * _.invoke(object, 'a[0].b.c.slice', 1, 3);
     * // => [2, 3]
     */
    var invoke = baseRest(baseInvoke);

    /**
     * Creates an array of the own enumerable property names of `object`.
     *
     * **Note:** Non-object values are coerced to objects. See the
     * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
     * for more details.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.keys(new Foo);
     * // => ['a', 'b'] (iteration order is not guaranteed)
     *
     * _.keys('hi');
     * // => ['0', '1']
     */
    function keys(object) {
      return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
    }

    /**
     * Creates an array of the own and inherited enumerable property names of `object`.
     *
     * **Note:** Non-object values are coerced to objects.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property names.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.keysIn(new Foo);
     * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
     */
    function keysIn(object) {
      return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
    }

    /**
     * The opposite of `_.mapValues`; this method creates an object with the
     * same values as `object` and keys generated by running each own enumerable
     * string keyed property of `object` thru `iteratee`. The iteratee is invoked
     * with three arguments: (value, key, object).
     *
     * @static
     * @memberOf _
     * @since 3.8.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns the new mapped object.
     * @see _.mapValues
     * @example
     *
     * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
     *   return key + value;
     * });
     * // => { 'a1': 1, 'b2': 2 }
     */
    function mapKeys(object, iteratee) {
      var result = {};
      iteratee = getIteratee(iteratee, 3);

      baseForOwn(object, function(value, key, object) {
        baseAssignValue(result, iteratee(value, key, object), value);
      });
      return result;
    }

    /**
     * Creates an object with the same keys as `object` and values generated
     * by running each own enumerable string keyed property of `object` thru
     * `iteratee`. The iteratee is invoked with three arguments:
     * (value, key, object).
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Object} Returns the new mapped object.
     * @see _.mapKeys
     * @example
     *
     * var users = {
     *   'fred':    { 'user': 'fred',    'age': 40 },
     *   'pebbles': { 'user': 'pebbles', 'age': 1 }
     * };
     *
     * _.mapValues(users, function(o) { return o.age; });
     * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
     *
     * // The `_.property` iteratee shorthand.
     * _.mapValues(users, 'age');
     * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
     */
    function mapValues(object, iteratee) {
      var result = {};
      iteratee = getIteratee(iteratee, 3);

      baseForOwn(object, function(value, key, object) {
        baseAssignValue(result, key, iteratee(value, key, object));
      });
      return result;
    }

    /**
     * This method is like `_.assign` except that it recursively merges own and
     * inherited enumerable string keyed properties of source objects into the
     * destination object. Source properties that resolve to `undefined` are
     * skipped if a destination value exists. Array and plain object properties
     * are merged recursively. Other objects and value types are overridden by
     * assignment. Source objects are applied from left to right. Subsequent
     * sources overwrite property assignments of previous sources.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 0.5.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} [sources] The source objects.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = {
     *   'a': [{ 'b': 2 }, { 'd': 4 }]
     * };
     *
     * var other = {
     *   'a': [{ 'c': 3 }, { 'e': 5 }]
     * };
     *
     * _.merge(object, other);
     * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
     */
    var merge = createAssigner(function(object, source, srcIndex) {
      baseMerge(object, source, srcIndex);
    });

    /**
     * This method is like `_.merge` except that it accepts `customizer` which
     * is invoked to produce the merged values of the destination and source
     * properties. If `customizer` returns `undefined`, merging is handled by the
     * method instead. The `customizer` is invoked with six arguments:
     * (objValue, srcValue, key, object, source, stack).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The destination object.
     * @param {...Object} sources The source objects.
     * @param {Function} customizer The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @example
     *
     * function customizer(objValue, srcValue) {
     *   if (_.isArray(objValue)) {
     *     return objValue.concat(srcValue);
     *   }
     * }
     *
     * var object = { 'a': [1], 'b': [2] };
     * var other = { 'a': [3], 'b': [4] };
     *
     * _.mergeWith(object, other, customizer);
     * // => { 'a': [1, 3], 'b': [2, 4] }
     */
    var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
      baseMerge(object, source, srcIndex, customizer);
    });

    /**
     * The opposite of `_.pick`; this method creates an object composed of the
     * own and inherited enumerable property paths of `object` that are not omitted.
     *
     * **Note:** This method is considerably slower than `_.pick`.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The source object.
     * @param {...(string|string[])} [paths] The property paths to omit.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.omit(object, ['a', 'c']);
     * // => { 'b': '2' }
     */
    var omit = flatRest(function(object, paths) {
      var result = {};
      if (object == null) {
        return result;
      }
      var isDeep = false;
      paths = arrayMap(paths, function(path) {
        path = castPath(path, object);
        isDeep || (isDeep = path.length > 1);
        return path;
      });
      copyObject(object, getAllKeysIn(object), result);
      if (isDeep) {
        result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
      }
      var length = paths.length;
      while (length--) {
        baseUnset(result, paths[length]);
      }
      return result;
    });

    /**
     * The opposite of `_.pickBy`; this method creates an object composed of
     * the own and inherited enumerable string keyed properties of `object` that
     * `predicate` doesn't return truthy for. The predicate is invoked with two
     * arguments: (value, key).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The source object.
     * @param {Function} [predicate=_.identity] The function invoked per property.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.omitBy(object, _.isNumber);
     * // => { 'b': '2' }
     */
    function omitBy(object, predicate) {
      return pickBy(object, negate(getIteratee(predicate)));
    }

    /**
     * Creates an object composed of the picked `object` properties.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The source object.
     * @param {...(string|string[])} [paths] The property paths to pick.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.pick(object, ['a', 'c']);
     * // => { 'a': 1, 'c': 3 }
     */
    var pick = flatRest(function(object, paths) {
      return object == null ? {} : basePick(object, paths);
    });

    /**
     * Creates an object composed of the `object` properties `predicate` returns
     * truthy for. The predicate is invoked with two arguments: (value, key).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The source object.
     * @param {Function} [predicate=_.identity] The function invoked per property.
     * @returns {Object} Returns the new object.
     * @example
     *
     * var object = { 'a': 1, 'b': '2', 'c': 3 };
     *
     * _.pickBy(object, _.isNumber);
     * // => { 'a': 1, 'c': 3 }
     */
    function pickBy(object, predicate) {
      if (object == null) {
        return {};
      }
      var props = arrayMap(getAllKeysIn(object), function(prop) {
        return [prop];
      });
      predicate = getIteratee(predicate);
      return basePickBy(object, props, function(value, path) {
        return predicate(value, path[0]);
      });
    }

    /**
     * This method is like `_.get` except that if the resolved value is a
     * function it's invoked with the `this` binding of its parent object and
     * its result is returned.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @param {Array|string} path The path of the property to resolve.
     * @param {*} [defaultValue] The value returned for `undefined` resolved values.
     * @returns {*} Returns the resolved value.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
     *
     * _.result(object, 'a[0].b.c1');
     * // => 3
     *
     * _.result(object, 'a[0].b.c2');
     * // => 4
     *
     * _.result(object, 'a[0].b.c3', 'default');
     * // => 'default'
     *
     * _.result(object, 'a[0].b.c3', _.constant('default'));
     * // => 'default'
     */
    function result(object, path, defaultValue) {
      path = castPath(path, object);

      var index = -1,
          length = path.length;

      // Ensure the loop is entered when path is empty.
      if (!length) {
        length = 1;
        object = undefined;
      }
      while (++index < length) {
        var value = object == null ? undefined : object[toKey(path[index])];
        if (value === undefined) {
          index = length;
          value = defaultValue;
        }
        object = isFunction(value) ? value.call(object) : value;
      }
      return object;
    }

    /**
     * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
     * it's created. Arrays are created for missing index properties while objects
     * are created for all other missing properties. Use `_.setWith` to customize
     * `path` creation.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {*} value The value to set.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }] };
     *
     * _.set(object, 'a[0].b.c', 4);
     * console.log(object.a[0].b.c);
     * // => 4
     *
     * _.set(object, ['x', '0', 'y', 'z'], 5);
     * console.log(object.x[0].y.z);
     * // => 5
     */
    function set(object, path, value) {
      return object == null ? object : baseSet(object, path, value);
    }

    /**
     * This method is like `_.set` except that it accepts `customizer` which is
     * invoked to produce the objects of `path`.  If `customizer` returns `undefined`
     * path creation is handled by the method instead. The `customizer` is invoked
     * with three arguments: (nsValue, key, nsObject).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {*} value The value to set.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = {};
     *
     * _.setWith(object, '[0][1]', 'a', Object);
     * // => { '0': { '1': 'a' } }
     */
    function setWith(object, path, value, customizer) {
      customizer = typeof customizer == 'function' ? customizer : undefined;
      return object == null ? object : baseSet(object, path, value, customizer);
    }

    /**
     * Creates an array of own enumerable string keyed-value pairs for `object`
     * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
     * entries are returned.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias entries
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the key-value pairs.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.toPairs(new Foo);
     * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
     */
    var toPairs = createToPairs(keys);

    /**
     * Creates an array of own and inherited enumerable string keyed-value pairs
     * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
     * or set, its entries are returned.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @alias entriesIn
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the key-value pairs.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.toPairsIn(new Foo);
     * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
     */
    var toPairsIn = createToPairs(keysIn);

    /**
     * An alternative to `_.reduce`; this method transforms `object` to a new
     * `accumulator` object which is the result of running each of its own
     * enumerable string keyed properties thru `iteratee`, with each invocation
     * potentially mutating the `accumulator` object. If `accumulator` is not
     * provided, a new object with the same `[[Prototype]]` will be used. The
     * iteratee is invoked with four arguments: (accumulator, value, key, object).
     * Iteratee functions may exit iteration early by explicitly returning `false`.
     *
     * @static
     * @memberOf _
     * @since 1.3.0
     * @category Object
     * @param {Object} object The object to iterate over.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @param {*} [accumulator] The custom accumulator value.
     * @returns {*} Returns the accumulated value.
     * @example
     *
     * _.transform([2, 3, 4], function(result, n) {
     *   result.push(n *= n);
     *   return n % 2 == 0;
     * }, []);
     * // => [4, 9]
     *
     * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
     *   (result[value] || (result[value] = [])).push(key);
     * }, {});
     * // => { '1': ['a', 'c'], '2': ['b'] }
     */
    function transform(object, iteratee, accumulator) {
      var isArr = isArray(object),
          isArrLike = isArr || isBuffer(object) || isTypedArray(object);

      iteratee = getIteratee(iteratee, 4);
      if (accumulator == null) {
        var Ctor = object && object.constructor;
        if (isArrLike) {
          accumulator = isArr ? new Ctor : [];
        }
        else if (isObject(object)) {
          accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
        }
        else {
          accumulator = {};
        }
      }
      (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
        return iteratee(accumulator, value, index, object);
      });
      return accumulator;
    }

    /**
     * Removes the property at `path` of `object`.
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to unset.
     * @returns {boolean} Returns `true` if the property is deleted, else `false`.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 7 } }] };
     * _.unset(object, 'a[0].b.c');
     * // => true
     *
     * console.log(object);
     * // => { 'a': [{ 'b': {} }] };
     *
     * _.unset(object, ['a', '0', 'b', 'c']);
     * // => true
     *
     * console.log(object);
     * // => { 'a': [{ 'b': {} }] };
     */
    function unset(object, path) {
      return object == null ? true : baseUnset(object, path);
    }

    /**
     * This method is like `_.set` except that accepts `updater` to produce the
     * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
     * is invoked with one argument: (value).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.6.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {Function} updater The function to produce the updated value.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = { 'a': [{ 'b': { 'c': 3 } }] };
     *
     * _.update(object, 'a[0].b.c', function(n) { return n * n; });
     * console.log(object.a[0].b.c);
     * // => 9
     *
     * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
     * console.log(object.x[0].y.z);
     * // => 0
     */
    function update(object, path, updater) {
      return object == null ? object : baseUpdate(object, path, castFunction(updater));
    }

    /**
     * This method is like `_.update` except that it accepts `customizer` which is
     * invoked to produce the objects of `path`.  If `customizer` returns `undefined`
     * path creation is handled by the method instead. The `customizer` is invoked
     * with three arguments: (nsValue, key, nsObject).
     *
     * **Note:** This method mutates `object`.
     *
     * @static
     * @memberOf _
     * @since 4.6.0
     * @category Object
     * @param {Object} object The object to modify.
     * @param {Array|string} path The path of the property to set.
     * @param {Function} updater The function to produce the updated value.
     * @param {Function} [customizer] The function to customize assigned values.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var object = {};
     *
     * _.updateWith(object, '[0][1]', _.constant('a'), Object);
     * // => { '0': { '1': 'a' } }
     */
    function updateWith(object, path, updater, customizer) {
      customizer = typeof customizer == 'function' ? customizer : undefined;
      return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
    }

    /**
     * Creates an array of the own enumerable string keyed property values of `object`.
     *
     * **Note:** Non-object values are coerced to objects.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property values.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.values(new Foo);
     * // => [1, 2] (iteration order is not guaranteed)
     *
     * _.values('hi');
     * // => ['h', 'i']
     */
    function values(object) {
      return object == null ? [] : baseValues(object, keys(object));
    }

    /**
     * Creates an array of the own and inherited enumerable string keyed property
     * values of `object`.
     *
     * **Note:** Non-object values are coerced to objects.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Object
     * @param {Object} object The object to query.
     * @returns {Array} Returns the array of property values.
     * @example
     *
     * function Foo() {
     *   this.a = 1;
     *   this.b = 2;
     * }
     *
     * Foo.prototype.c = 3;
     *
     * _.valuesIn(new Foo);
     * // => [1, 2, 3] (iteration order is not guaranteed)
     */
    function valuesIn(object) {
      return object == null ? [] : baseValues(object, keysIn(object));
    }

    /*------------------------------------------------------------------------*/

    /**
     * Clamps `number` within the inclusive `lower` and `upper` bounds.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Number
     * @param {number} number The number to clamp.
     * @param {number} [lower] The lower bound.
     * @param {number} upper The upper bound.
     * @returns {number} Returns the clamped number.
     * @example
     *
     * _.clamp(-10, -5, 5);
     * // => -5
     *
     * _.clamp(10, -5, 5);
     * // => 5
     */
    function clamp(number, lower, upper) {
      if (upper === undefined) {
        upper = lower;
        lower = undefined;
      }
      if (upper !== undefined) {
        upper = toNumber(upper);
        upper = upper === upper ? upper : 0;
      }
      if (lower !== undefined) {
        lower = toNumber(lower);
        lower = lower === lower ? lower : 0;
      }
      return baseClamp(toNumber(number), lower, upper);
    }

    /**
     * Checks if `n` is between `start` and up to, but not including, `end`. If
     * `end` is not specified, it's set to `start` with `start` then set to `0`.
     * If `start` is greater than `end` the params are swapped to support
     * negative ranges.
     *
     * @static
     * @memberOf _
     * @since 3.3.0
     * @category Number
     * @param {number} number The number to check.
     * @param {number} [start=0] The start of the range.
     * @param {number} end The end of the range.
     * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
     * @see _.range, _.rangeRight
     * @example
     *
     * _.inRange(3, 2, 4);
     * // => true
     *
     * _.inRange(4, 8);
     * // => true
     *
     * _.inRange(4, 2);
     * // => false
     *
     * _.inRange(2, 2);
     * // => false
     *
     * _.inRange(1.2, 2);
     * // => true
     *
     * _.inRange(5.2, 4);
     * // => false
     *
     * _.inRange(-3, -2, -6);
     * // => true
     */
    function inRange(number, start, end) {
      start = toFinite(start);
      if (end === undefined) {
        end = start;
        start = 0;
      } else {
        end = toFinite(end);
      }
      number = toNumber(number);
      return baseInRange(number, start, end);
    }

    /**
     * Produces a random number between the inclusive `lower` and `upper` bounds.
     * If only one argument is provided a number between `0` and the given number
     * is returned. If `floating` is `true`, or either `lower` or `upper` are
     * floats, a floating-point number is returned instead of an integer.
     *
     * **Note:** JavaScript follows the IEEE-754 standard for resolving
     * floating-point values which can produce unexpected results.
     *
     * @static
     * @memberOf _
     * @since 0.7.0
     * @category Number
     * @param {number} [lower=0] The lower bound.
     * @param {number} [upper=1] The upper bound.
     * @param {boolean} [floating] Specify returning a floating-point number.
     * @returns {number} Returns the random number.
     * @example
     *
     * _.random(0, 5);
     * // => an integer between 0 and 5
     *
     * _.random(5);
     * // => also an integer between 0 and 5
     *
     * _.random(5, true);
     * // => a floating-point number between 0 and 5
     *
     * _.random(1.2, 5.2);
     * // => a floating-point number between 1.2 and 5.2
     */
    function random(lower, upper, floating) {
      if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
        upper = floating = undefined;
      }
      if (floating === undefined) {
        if (typeof upper == 'boolean') {
          floating = upper;
          upper = undefined;
        }
        else if (typeof lower == 'boolean') {
          floating = lower;
          lower = undefined;
        }
      }
      if (lower === undefined && upper === undefined) {
        lower = 0;
        upper = 1;
      }
      else {
        lower = toFinite(lower);
        if (upper === undefined) {
          upper = lower;
          lower = 0;
        } else {
          upper = toFinite(upper);
        }
      }
      if (lower > upper) {
        var temp = lower;
        lower = upper;
        upper = temp;
      }
      if (floating || lower % 1 || upper % 1) {
        var rand = nativeRandom();
        return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
      }
      return baseRandom(lower, upper);
    }

    /*------------------------------------------------------------------------*/

    /**
     * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the camel cased string.
     * @example
     *
     * _.camelCase('Foo Bar');
     * // => 'fooBar'
     *
     * _.camelCase('--foo-bar--');
     * // => 'fooBar'
     *
     * _.camelCase('__FOO_BAR__');
     * // => 'fooBar'
     */
    var camelCase = createCompounder(function(result, word, index) {
      word = word.toLowerCase();
      return result + (index ? capitalize(word) : word);
    });

    /**
     * Converts the first character of `string` to upper case and the remaining
     * to lower case.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to capitalize.
     * @returns {string} Returns the capitalized string.
     * @example
     *
     * _.capitalize('FRED');
     * // => 'Fred'
     */
    function capitalize(string) {
      return upperFirst(toString(string).toLowerCase());
    }

    /**
     * Deburrs `string` by converting
     * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
     * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
     * letters to basic Latin letters and removing
     * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to deburr.
     * @returns {string} Returns the deburred string.
     * @example
     *
     * _.deburr('déjà vu');
     * // => 'deja vu'
     */
    function deburr(string) {
      string = toString(string);
      return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
    }

    /**
     * Checks if `string` ends with the given target string.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to inspect.
     * @param {string} [target] The string to search for.
     * @param {number} [position=string.length] The position to search up to.
     * @returns {boolean} Returns `true` if `string` ends with `target`,
     *  else `false`.
     * @example
     *
     * _.endsWith('abc', 'c');
     * // => true
     *
     * _.endsWith('abc', 'b');
     * // => false
     *
     * _.endsWith('abc', 'b', 2);
     * // => true
     */
    function endsWith(string, target, position) {
      string = toString(string);
      target = baseToString(target);

      var length = string.length;
      position = position === undefined
        ? length
        : baseClamp(toInteger(position), 0, length);

      var end = position;
      position -= target.length;
      return position >= 0 && string.slice(position, end) == target;
    }

    /**
     * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
     * corresponding HTML entities.
     *
     * **Note:** No other characters are escaped. To escape additional
     * characters use a third-party library like [_he_](https://mths.be/he).
     *
     * Though the ">" character is escaped for symmetry, characters like
     * ">" and "/" don't need escaping in HTML and have no special meaning
     * unless they're part of a tag or unquoted attribute value. See
     * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
     * (under "semi-related fun fact") for more details.
     *
     * When working with HTML you should always
     * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
     * XSS vectors.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category String
     * @param {string} [string=''] The string to escape.
     * @returns {string} Returns the escaped string.
     * @example
     *
     * _.escape('fred, barney, & pebbles');
     * // => 'fred, barney, &amp; pebbles'
     */
    function escape(string) {
      string = toString(string);
      return (string && reHasUnescapedHtml.test(string))
        ? string.replace(reUnescapedHtml, escapeHtmlChar)
        : string;
    }

    /**
     * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
     * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to escape.
     * @returns {string} Returns the escaped string.
     * @example
     *
     * _.escapeRegExp('[lodash](https://lodash.com/)');
     * // => '\[lodash\]\(https://lodash\.com/\)'
     */
    function escapeRegExp(string) {
      string = toString(string);
      return (string && reHasRegExpChar.test(string))
        ? string.replace(reRegExpChar, '\\$&')
        : string;
    }

    /**
     * Converts `string` to
     * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the kebab cased string.
     * @example
     *
     * _.kebabCase('Foo Bar');
     * // => 'foo-bar'
     *
     * _.kebabCase('fooBar');
     * // => 'foo-bar'
     *
     * _.kebabCase('__FOO_BAR__');
     * // => 'foo-bar'
     */
    var kebabCase = createCompounder(function(result, word, index) {
      return result + (index ? '-' : '') + word.toLowerCase();
    });

    /**
     * Converts `string`, as space separated words, to lower case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the lower cased string.
     * @example
     *
     * _.lowerCase('--Foo-Bar--');
     * // => 'foo bar'
     *
     * _.lowerCase('fooBar');
     * // => 'foo bar'
     *
     * _.lowerCase('__FOO_BAR__');
     * // => 'foo bar'
     */
    var lowerCase = createCompounder(function(result, word, index) {
      return result + (index ? ' ' : '') + word.toLowerCase();
    });

    /**
     * Converts the first character of `string` to lower case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the converted string.
     * @example
     *
     * _.lowerFirst('Fred');
     * // => 'fred'
     *
     * _.lowerFirst('FRED');
     * // => 'fRED'
     */
    var lowerFirst = createCaseFirst('toLowerCase');

    /**
     * Pads `string` on the left and right sides if it's shorter than `length`.
     * Padding characters are truncated if they can't be evenly divided by `length`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to pad.
     * @param {number} [length=0] The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padded string.
     * @example
     *
     * _.pad('abc', 8);
     * // => '  abc   '
     *
     * _.pad('abc', 8, '_-');
     * // => '_-abc_-_'
     *
     * _.pad('abc', 3);
     * // => 'abc'
     */
    function pad(string, length, chars) {
      string = toString(string);
      length = toInteger(length);

      var strLength = length ? stringSize(string) : 0;
      if (!length || strLength >= length) {
        return string;
      }
      var mid = (length - strLength) / 2;
      return (
        createPadding(nativeFloor(mid), chars) +
        string +
        createPadding(nativeCeil(mid), chars)
      );
    }

    /**
     * Pads `string` on the right side if it's shorter than `length`. Padding
     * characters are truncated if they exceed `length`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to pad.
     * @param {number} [length=0] The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padded string.
     * @example
     *
     * _.padEnd('abc', 6);
     * // => 'abc   '
     *
     * _.padEnd('abc', 6, '_-');
     * // => 'abc_-_'
     *
     * _.padEnd('abc', 3);
     * // => 'abc'
     */
    function padEnd(string, length, chars) {
      string = toString(string);
      length = toInteger(length);

      var strLength = length ? stringSize(string) : 0;
      return (length && strLength < length)
        ? (string + createPadding(length - strLength, chars))
        : string;
    }

    /**
     * Pads `string` on the left side if it's shorter than `length`. Padding
     * characters are truncated if they exceed `length`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to pad.
     * @param {number} [length=0] The padding length.
     * @param {string} [chars=' '] The string used as padding.
     * @returns {string} Returns the padded string.
     * @example
     *
     * _.padStart('abc', 6);
     * // => '   abc'
     *
     * _.padStart('abc', 6, '_-');
     * // => '_-_abc'
     *
     * _.padStart('abc', 3);
     * // => 'abc'
     */
    function padStart(string, length, chars) {
      string = toString(string);
      length = toInteger(length);

      var strLength = length ? stringSize(string) : 0;
      return (length && strLength < length)
        ? (createPadding(length - strLength, chars) + string)
        : string;
    }

    /**
     * Converts `string` to an integer of the specified radix. If `radix` is
     * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
     * hexadecimal, in which case a `radix` of `16` is used.
     *
     * **Note:** This method aligns with the
     * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
     *
     * @static
     * @memberOf _
     * @since 1.1.0
     * @category String
     * @param {string} string The string to convert.
     * @param {number} [radix=10] The radix to interpret `value` by.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {number} Returns the converted integer.
     * @example
     *
     * _.parseInt('08');
     * // => 8
     *
     * _.map(['6', '08', '10'], _.parseInt);
     * // => [6, 8, 10]
     */
    function parseInt(string, radix, guard) {
      if (guard || radix == null) {
        radix = 0;
      } else if (radix) {
        radix = +radix;
      }
      return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
    }

    /**
     * Repeats the given string `n` times.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to repeat.
     * @param {number} [n=1] The number of times to repeat the string.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the repeated string.
     * @example
     *
     * _.repeat('*', 3);
     * // => '***'
     *
     * _.repeat('abc', 2);
     * // => 'abcabc'
     *
     * _.repeat('abc', 0);
     * // => ''
     */
    function repeat(string, n, guard) {
      if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
        n = 1;
      } else {
        n = toInteger(n);
      }
      return baseRepeat(toString(string), n);
    }

    /**
     * Replaces matches for `pattern` in `string` with `replacement`.
     *
     * **Note:** This method is based on
     * [`String#replace`](https://mdn.io/String/replace).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to modify.
     * @param {RegExp|string} pattern The pattern to replace.
     * @param {Function|string} replacement The match replacement.
     * @returns {string} Returns the modified string.
     * @example
     *
     * _.replace('Hi Fred', 'Fred', 'Barney');
     * // => 'Hi Barney'
     */
    function replace() {
      var args = arguments,
          string = toString(args[0]);

      return args.length < 3 ? string : string.replace(args[1], args[2]);
    }

    /**
     * Converts `string` to
     * [snake case](https://en.wikipedia.org/wiki/Snake_case).
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the snake cased string.
     * @example
     *
     * _.snakeCase('Foo Bar');
     * // => 'foo_bar'
     *
     * _.snakeCase('fooBar');
     * // => 'foo_bar'
     *
     * _.snakeCase('--FOO-BAR--');
     * // => 'foo_bar'
     */
    var snakeCase = createCompounder(function(result, word, index) {
      return result + (index ? '_' : '') + word.toLowerCase();
    });

    /**
     * Splits `string` by `separator`.
     *
     * **Note:** This method is based on
     * [`String#split`](https://mdn.io/String/split).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to split.
     * @param {RegExp|string} separator The separator pattern to split by.
     * @param {number} [limit] The length to truncate results to.
     * @returns {Array} Returns the string segments.
     * @example
     *
     * _.split('a-b-c', '-', 2);
     * // => ['a', 'b']
     */
    function split(string, separator, limit) {
      if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
        separator = limit = undefined;
      }
      limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
      if (!limit) {
        return [];
      }
      string = toString(string);
      if (string && (
            typeof separator == 'string' ||
            (separator != null && !isRegExp(separator))
          )) {
        separator = baseToString(separator);
        if (!separator && hasUnicode(string)) {
          return castSlice(stringToArray(string), 0, limit);
        }
      }
      return string.split(separator, limit);
    }

    /**
     * Converts `string` to
     * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
     *
     * @static
     * @memberOf _
     * @since 3.1.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the start cased string.
     * @example
     *
     * _.startCase('--foo-bar--');
     * // => 'Foo Bar'
     *
     * _.startCase('fooBar');
     * // => 'Foo Bar'
     *
     * _.startCase('__FOO_BAR__');
     * // => 'FOO BAR'
     */
    var startCase = createCompounder(function(result, word, index) {
      return result + (index ? ' ' : '') + upperFirst(word);
    });

    /**
     * Checks if `string` starts with the given target string.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to inspect.
     * @param {string} [target] The string to search for.
     * @param {number} [position=0] The position to search from.
     * @returns {boolean} Returns `true` if `string` starts with `target`,
     *  else `false`.
     * @example
     *
     * _.startsWith('abc', 'a');
     * // => true
     *
     * _.startsWith('abc', 'b');
     * // => false
     *
     * _.startsWith('abc', 'b', 1);
     * // => true
     */
    function startsWith(string, target, position) {
      string = toString(string);
      position = position == null
        ? 0
        : baseClamp(toInteger(position), 0, string.length);

      target = baseToString(target);
      return string.slice(position, position + target.length) == target;
    }

    /**
     * Creates a compiled template function that can interpolate data properties
     * in "interpolate" delimiters, HTML-escape interpolated data properties in
     * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
     * properties may be accessed as free variables in the template. If a setting
     * object is given, it takes precedence over `_.templateSettings` values.
     *
     * **Note:** In the development build `_.template` utilizes
     * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
     * for easier debugging.
     *
     * For more information on precompiling templates see
     * [lodash's custom builds documentation](https://lodash.com/custom-builds).
     *
     * For more information on Chrome extension sandboxes see
     * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category String
     * @param {string} [string=''] The template string.
     * @param {Object} [options={}] The options object.
     * @param {RegExp} [options.escape=_.templateSettings.escape]
     *  The HTML "escape" delimiter.
     * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
     *  The "evaluate" delimiter.
     * @param {Object} [options.imports=_.templateSettings.imports]
     *  An object to import into the template as free variables.
     * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
     *  The "interpolate" delimiter.
     * @param {string} [options.sourceURL='lodash.templateSources[n]']
     *  The sourceURL of the compiled template.
     * @param {string} [options.variable='obj']
     *  The data object variable name.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Function} Returns the compiled template function.
     * @example
     *
     * // Use the "interpolate" delimiter to create a compiled template.
     * var compiled = _.template('hello <%= user %>!');
     * compiled({ 'user': 'fred' });
     * // => 'hello fred!'
     *
     * // Use the HTML "escape" delimiter to escape data property values.
     * var compiled = _.template('<b><%- value %></b>');
     * compiled({ 'value': '<script>' });
     * // => '<b>&lt;script&gt;</b>'
     *
     * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
     * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
     * compiled({ 'users': ['fred', 'barney'] });
     * // => '<li>fred</li><li>barney</li>'
     *
     * // Use the internal `print` function in "evaluate" delimiters.
     * var compiled = _.template('<% print("hello " + user); %>!');
     * compiled({ 'user': 'barney' });
     * // => 'hello barney!'
     *
     * // Use the ES template literal delimiter as an "interpolate" delimiter.
     * // Disable support by replacing the "interpolate" delimiter.
     * var compiled = _.template('hello ${ user }!');
     * compiled({ 'user': 'pebbles' });
     * // => 'hello pebbles!'
     *
     * // Use backslashes to treat delimiters as plain text.
     * var compiled = _.template('<%= "\\<%- value %\\>" %>');
     * compiled({ 'value': 'ignored' });
     * // => '<%- value %>'
     *
     * // Use the `imports` option to import `jQuery` as `jq`.
     * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
     * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
     * compiled({ 'users': ['fred', 'barney'] });
     * // => '<li>fred</li><li>barney</li>'
     *
     * // Use the `sourceURL` option to specify a custom sourceURL for the template.
     * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
     * compiled(data);
     * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
     *
     * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
     * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
     * compiled.source;
     * // => function(data) {
     * //   var __t, __p = '';
     * //   __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
     * //   return __p;
     * // }
     *
     * // Use custom template delimiters.
     * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
     * var compiled = _.template('hello {{ user }}!');
     * compiled({ 'user': 'mustache' });
     * // => 'hello mustache!'
     *
     * // Use the `source` property to inline compiled templates for meaningful
     * // line numbers in error messages and stack traces.
     * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
     *   var JST = {\
     *     "main": ' + _.template(mainText).source + '\
     *   };\
     * ');
     */
    function template(string, options, guard) {
      // Based on John Resig's `tmpl` implementation
      // (http://ejohn.org/blog/javascript-micro-templating/)
      // and Laura Doktorova's doT.js (https://github.com/olado/doT).
      var settings = lodash.templateSettings;

      if (guard && isIterateeCall(string, options, guard)) {
        options = undefined;
      }
      string = toString(string);
      options = assignInWith({}, options, settings, customDefaultsAssignIn);

      var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
          importsKeys = keys(imports),
          importsValues = baseValues(imports, importsKeys);

      var isEscaping,
          isEvaluating,
          index = 0,
          interpolate = options.interpolate || reNoMatch,
          source = "__p += '";

      // Compile the regexp to match each delimiter.
      var reDelimiters = RegExp(
        (options.escape || reNoMatch).source + '|' +
        interpolate.source + '|' +
        (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
        (options.evaluate || reNoMatch).source + '|$'
      , 'g');

      // Use a sourceURL for easier debugging.
      // The sourceURL gets injected into the source that's eval-ed, so be careful
      // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
      // and escape the comment, thus injecting code that gets evaled.
      var sourceURL = '//# sourceURL=' +
        (hasOwnProperty.call(options, 'sourceURL')
          ? (options.sourceURL + '').replace(/\s/g, ' ')
          : ('lodash.templateSources[' + (++templateCounter) + ']')
        ) + '\n';

      string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
        interpolateValue || (interpolateValue = esTemplateValue);

        // Escape characters that can't be included in string literals.
        source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);

        // Replace delimiters with snippets.
        if (escapeValue) {
          isEscaping = true;
          source += "' +\n__e(" + escapeValue + ") +\n'";
        }
        if (evaluateValue) {
          isEvaluating = true;
          source += "';\n" + evaluateValue + ";\n__p += '";
        }
        if (interpolateValue) {
          source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
        }
        index = offset + match.length;

        // The JS engine embedded in Adobe products needs `match` returned in
        // order to produce the correct `offset` value.
        return match;
      });

      source += "';\n";

      // If `variable` is not specified wrap a with-statement around the generated
      // code to add the data object to the top of the scope chain.
      var variable = hasOwnProperty.call(options, 'variable') && options.variable;
      if (!variable) {
        source = 'with (obj) {\n' + source + '\n}\n';
      }
      // Throw an error if a forbidden character was found in `variable`, to prevent
      // potential command injection attacks.
      else if (reForbiddenIdentifierChars.test(variable)) {
        throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
      }

      // Cleanup code by stripping empty strings.
      source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
        .replace(reEmptyStringMiddle, '$1')
        .replace(reEmptyStringTrailing, '$1;');

      // Frame code as the function body.
      source = 'function(' + (variable || 'obj') + ') {\n' +
        (variable
          ? ''
          : 'obj || (obj = {});\n'
        ) +
        "var __t, __p = ''" +
        (isEscaping
           ? ', __e = _.escape'
           : ''
        ) +
        (isEvaluating
          ? ', __j = Array.prototype.join;\n' +
            "function print() { __p += __j.call(arguments, '') }\n"
          : ';\n'
        ) +
        source +
        'return __p\n}';

      var result = attempt(function() {
        return Function(importsKeys, sourceURL + 'return ' + source)
          .apply(undefined, importsValues);
      });

      // Provide the compiled function's source by its `toString` method or
      // the `source` property as a convenience for inlining compiled templates.
      result.source = source;
      if (isError(result)) {
        throw result;
      }
      return result;
    }

    /**
     * Converts `string`, as a whole, to lower case just like
     * [String#toLowerCase](https://mdn.io/toLowerCase).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the lower cased string.
     * @example
     *
     * _.toLower('--Foo-Bar--');
     * // => '--foo-bar--'
     *
     * _.toLower('fooBar');
     * // => 'foobar'
     *
     * _.toLower('__FOO_BAR__');
     * // => '__foo_bar__'
     */
    function toLower(value) {
      return toString(value).toLowerCase();
    }

    /**
     * Converts `string`, as a whole, to upper case just like
     * [String#toUpperCase](https://mdn.io/toUpperCase).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the upper cased string.
     * @example
     *
     * _.toUpper('--foo-bar--');
     * // => '--FOO-BAR--'
     *
     * _.toUpper('fooBar');
     * // => 'FOOBAR'
     *
     * _.toUpper('__foo_bar__');
     * // => '__FOO_BAR__'
     */
    function toUpper(value) {
      return toString(value).toUpperCase();
    }

    /**
     * Removes leading and trailing whitespace or specified characters from `string`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to trim.
     * @param {string} [chars=whitespace] The characters to trim.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the trimmed string.
     * @example
     *
     * _.trim('  abc  ');
     * // => 'abc'
     *
     * _.trim('-_-abc-_-', '_-');
     * // => 'abc'
     *
     * _.map(['  foo  ', '  bar  '], _.trim);
     * // => ['foo', 'bar']
     */
    function trim(string, chars, guard) {
      string = toString(string);
      if (string && (guard || chars === undefined)) {
        return baseTrim(string);
      }
      if (!string || !(chars = baseToString(chars))) {
        return string;
      }
      var strSymbols = stringToArray(string),
          chrSymbols = stringToArray(chars),
          start = charsStartIndex(strSymbols, chrSymbols),
          end = charsEndIndex(strSymbols, chrSymbols) + 1;

      return castSlice(strSymbols, start, end).join('');
    }

    /**
     * Removes trailing whitespace or specified characters from `string`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to trim.
     * @param {string} [chars=whitespace] The characters to trim.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the trimmed string.
     * @example
     *
     * _.trimEnd('  abc  ');
     * // => '  abc'
     *
     * _.trimEnd('-_-abc-_-', '_-');
     * // => '-_-abc'
     */
    function trimEnd(string, chars, guard) {
      string = toString(string);
      if (string && (guard || chars === undefined)) {
        return string.slice(0, trimmedEndIndex(string) + 1);
      }
      if (!string || !(chars = baseToString(chars))) {
        return string;
      }
      var strSymbols = stringToArray(string),
          end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;

      return castSlice(strSymbols, 0, end).join('');
    }

    /**
     * Removes leading whitespace or specified characters from `string`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to trim.
     * @param {string} [chars=whitespace] The characters to trim.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {string} Returns the trimmed string.
     * @example
     *
     * _.trimStart('  abc  ');
     * // => 'abc  '
     *
     * _.trimStart('-_-abc-_-', '_-');
     * // => 'abc-_-'
     */
    function trimStart(string, chars, guard) {
      string = toString(string);
      if (string && (guard || chars === undefined)) {
        return string.replace(reTrimStart, '');
      }
      if (!string || !(chars = baseToString(chars))) {
        return string;
      }
      var strSymbols = stringToArray(string),
          start = charsStartIndex(strSymbols, stringToArray(chars));

      return castSlice(strSymbols, start).join('');
    }

    /**
     * Truncates `string` if it's longer than the given maximum string length.
     * The last characters of the truncated string are replaced with the omission
     * string which defaults to "...".
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to truncate.
     * @param {Object} [options={}] The options object.
     * @param {number} [options.length=30] The maximum string length.
     * @param {string} [options.omission='...'] The string to indicate text is omitted.
     * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
     * @returns {string} Returns the truncated string.
     * @example
     *
     * _.truncate('hi-diddly-ho there, neighborino');
     * // => 'hi-diddly-ho there, neighbo...'
     *
     * _.truncate('hi-diddly-ho there, neighborino', {
     *   'length': 24,
     *   'separator': ' '
     * });
     * // => 'hi-diddly-ho there,...'
     *
     * _.truncate('hi-diddly-ho there, neighborino', {
     *   'length': 24,
     *   'separator': /,? +/
     * });
     * // => 'hi-diddly-ho there...'
     *
     * _.truncate('hi-diddly-ho there, neighborino', {
     *   'omission': ' [...]'
     * });
     * // => 'hi-diddly-ho there, neig [...]'
     */
    function truncate(string, options) {
      var length = DEFAULT_TRUNC_LENGTH,
          omission = DEFAULT_TRUNC_OMISSION;

      if (isObject(options)) {
        var separator = 'separator' in options ? options.separator : separator;
        length = 'length' in options ? toInteger(options.length) : length;
        omission = 'omission' in options ? baseToString(options.omission) : omission;
      }
      string = toString(string);

      var strLength = string.length;
      if (hasUnicode(string)) {
        var strSymbols = stringToArray(string);
        strLength = strSymbols.length;
      }
      if (length >= strLength) {
        return string;
      }
      var end = length - stringSize(omission);
      if (end < 1) {
        return omission;
      }
      var result = strSymbols
        ? castSlice(strSymbols, 0, end).join('')
        : string.slice(0, end);

      if (separator === undefined) {
        return result + omission;
      }
      if (strSymbols) {
        end += (result.length - end);
      }
      if (isRegExp(separator)) {
        if (string.slice(end).search(separator)) {
          var match,
              substring = result;

          if (!separator.global) {
            separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
          }
          separator.lastIndex = 0;
          while ((match = separator.exec(substring))) {
            var newEnd = match.index;
          }
          result = result.slice(0, newEnd === undefined ? end : newEnd);
        }
      } else if (string.indexOf(baseToString(separator), end) != end) {
        var index = result.lastIndexOf(separator);
        if (index > -1) {
          result = result.slice(0, index);
        }
      }
      return result + omission;
    }

    /**
     * The inverse of `_.escape`; this method converts the HTML entities
     * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
     * their corresponding characters.
     *
     * **Note:** No other HTML entities are unescaped. To unescape additional
     * HTML entities use a third-party library like [_he_](https://mths.be/he).
     *
     * @static
     * @memberOf _
     * @since 0.6.0
     * @category String
     * @param {string} [string=''] The string to unescape.
     * @returns {string} Returns the unescaped string.
     * @example
     *
     * _.unescape('fred, barney, &amp; pebbles');
     * // => 'fred, barney, & pebbles'
     */
    function unescape(string) {
      string = toString(string);
      return (string && reHasEscapedHtml.test(string))
        ? string.replace(reEscapedHtml, unescapeHtmlChar)
        : string;
    }

    /**
     * Converts `string`, as space separated words, to upper case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the upper cased string.
     * @example
     *
     * _.upperCase('--foo-bar');
     * // => 'FOO BAR'
     *
     * _.upperCase('fooBar');
     * // => 'FOO BAR'
     *
     * _.upperCase('__foo_bar__');
     * // => 'FOO BAR'
     */
    var upperCase = createCompounder(function(result, word, index) {
      return result + (index ? ' ' : '') + word.toUpperCase();
    });

    /**
     * Converts the first character of `string` to upper case.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category String
     * @param {string} [string=''] The string to convert.
     * @returns {string} Returns the converted string.
     * @example
     *
     * _.upperFirst('fred');
     * // => 'Fred'
     *
     * _.upperFirst('FRED');
     * // => 'FRED'
     */
    var upperFirst = createCaseFirst('toUpperCase');

    /**
     * Splits `string` into an array of its words.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category String
     * @param {string} [string=''] The string to inspect.
     * @param {RegExp|string} [pattern] The pattern to match words.
     * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
     * @returns {Array} Returns the words of `string`.
     * @example
     *
     * _.words('fred, barney, & pebbles');
     * // => ['fred', 'barney', 'pebbles']
     *
     * _.words('fred, barney, & pebbles', /[^, ]+/g);
     * // => ['fred', 'barney', '&', 'pebbles']
     */
    function words(string, pattern, guard) {
      string = toString(string);
      pattern = guard ? undefined : pattern;

      if (pattern === undefined) {
        return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
      }
      return string.match(pattern) || [];
    }

    /*------------------------------------------------------------------------*/

    /**
     * Attempts to invoke `func`, returning either the result or the caught error
     * object. Any additional arguments are provided to `func` when it's invoked.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {Function} func The function to attempt.
     * @param {...*} [args] The arguments to invoke `func` with.
     * @returns {*} Returns the `func` result or error object.
     * @example
     *
     * // Avoid throwing errors for invalid selectors.
     * var elements = _.attempt(function(selector) {
     *   return document.querySelectorAll(selector);
     * }, '>_>');
     *
     * if (_.isError(elements)) {
     *   elements = [];
     * }
     */
    var attempt = baseRest(function(func, args) {
      try {
        return apply(func, undefined, args);
      } catch (e) {
        return isError(e) ? e : new Error(e);
      }
    });

    /**
     * Binds methods of an object to the object itself, overwriting the existing
     * method.
     *
     * **Note:** This method doesn't set the "length" property of bound functions.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {Object} object The object to bind and assign the bound methods to.
     * @param {...(string|string[])} methodNames The object method names to bind.
     * @returns {Object} Returns `object`.
     * @example
     *
     * var view = {
     *   'label': 'docs',
     *   'click': function() {
     *     console.log('clicked ' + this.label);
     *   }
     * };
     *
     * _.bindAll(view, ['click']);
     * jQuery(element).on('click', view.click);
     * // => Logs 'clicked docs' when clicked.
     */
    var bindAll = flatRest(function(object, methodNames) {
      arrayEach(methodNames, function(key) {
        key = toKey(key);
        baseAssignValue(object, key, bind(object[key], object));
      });
      return object;
    });

    /**
     * Creates a function that iterates over `pairs` and invokes the corresponding
     * function of the first predicate to return truthy. The predicate-function
     * pairs are invoked with the `this` binding and arguments of the created
     * function.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {Array} pairs The predicate-function pairs.
     * @returns {Function} Returns the new composite function.
     * @example
     *
     * var func = _.cond([
     *   [_.matches({ 'a': 1 }),           _.constant('matches A')],
     *   [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
     *   [_.stubTrue,                      _.constant('no match')]
     * ]);
     *
     * func({ 'a': 1, 'b': 2 });
     * // => 'matches A'
     *
     * func({ 'a': 0, 'b': 1 });
     * // => 'matches B'
     *
     * func({ 'a': '1', 'b': '2' });
     * // => 'no match'
     */
    function cond(pairs) {
      var length = pairs == null ? 0 : pairs.length,
          toIteratee = getIteratee();

      pairs = !length ? [] : arrayMap(pairs, function(pair) {
        if (typeof pair[1] != 'function') {
          throw new TypeError(FUNC_ERROR_TEXT);
        }
        return [toIteratee(pair[0]), pair[1]];
      });

      return baseRest(function(args) {
        var index = -1;
        while (++index < length) {
          var pair = pairs[index];
          if (apply(pair[0], this, args)) {
            return apply(pair[1], this, args);
          }
        }
      });
    }

    /**
     * Creates a function that invokes the predicate properties of `source` with
     * the corresponding property values of a given object, returning `true` if
     * all predicates return truthy, else `false`.
     *
     * **Note:** The created function is equivalent to `_.conformsTo` with
     * `source` partially applied.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {Object} source The object of property predicates to conform to.
     * @returns {Function} Returns the new spec function.
     * @example
     *
     * var objects = [
     *   { 'a': 2, 'b': 1 },
     *   { 'a': 1, 'b': 2 }
     * ];
     *
     * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
     * // => [{ 'a': 1, 'b': 2 }]
     */
    function conforms(source) {
      return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
    }

    /**
     * Creates a function that returns `value`.
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Util
     * @param {*} value The value to return from the new function.
     * @returns {Function} Returns the new constant function.
     * @example
     *
     * var objects = _.times(2, _.constant({ 'a': 1 }));
     *
     * console.log(objects);
     * // => [{ 'a': 1 }, { 'a': 1 }]
     *
     * console.log(objects[0] === objects[1]);
     * // => true
     */
    function constant(value) {
      return function() {
        return value;
      };
    }

    /**
     * Checks `value` to determine whether a default value should be returned in
     * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
     * or `undefined`.
     *
     * @static
     * @memberOf _
     * @since 4.14.0
     * @category Util
     * @param {*} value The value to check.
     * @param {*} defaultValue The default value.
     * @returns {*} Returns the resolved value.
     * @example
     *
     * _.defaultTo(1, 10);
     * // => 1
     *
     * _.defaultTo(undefined, 10);
     * // => 10
     */
    function defaultTo(value, defaultValue) {
      return (value == null || value !== value) ? defaultValue : value;
    }

    /**
     * Creates a function that returns the result of invoking the given functions
     * with the `this` binding of the created function, where each successive
     * invocation is supplied the return value of the previous.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {...(Function|Function[])} [funcs] The functions to invoke.
     * @returns {Function} Returns the new composite function.
     * @see _.flowRight
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var addSquare = _.flow([_.add, square]);
     * addSquare(1, 2);
     * // => 9
     */
    var flow = createFlow();

    /**
     * This method is like `_.flow` except that it creates a function that
     * invokes the given functions from right to left.
     *
     * @static
     * @since 3.0.0
     * @memberOf _
     * @category Util
     * @param {...(Function|Function[])} [funcs] The functions to invoke.
     * @returns {Function} Returns the new composite function.
     * @see _.flow
     * @example
     *
     * function square(n) {
     *   return n * n;
     * }
     *
     * var addSquare = _.flowRight([square, _.add]);
     * addSquare(1, 2);
     * // => 9
     */
    var flowRight = createFlow(true);

    /**
     * This method returns the first argument it receives.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {*} value Any value.
     * @returns {*} Returns `value`.
     * @example
     *
     * var object = { 'a': 1 };
     *
     * console.log(_.identity(object) === object);
     * // => true
     */
    function identity(value) {
      return value;
    }

    /**
     * Creates a function that invokes `func` with the arguments of the created
     * function. If `func` is a property name, the created function returns the
     * property value for a given element. If `func` is an array or object, the
     * created function returns `true` for elements that contain the equivalent
     * source properties, otherwise it returns `false`.
     *
     * @static
     * @since 4.0.0
     * @memberOf _
     * @category Util
     * @param {*} [func=_.identity] The value to convert to a callback.
     * @returns {Function} Returns the callback.
     * @example
     *
     * var users = [
     *   { 'user': 'barney', 'age': 36, 'active': true },
     *   { 'user': 'fred',   'age': 40, 'active': false }
     * ];
     *
     * // The `_.matches` iteratee shorthand.
     * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
     * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
     *
     * // The `_.matchesProperty` iteratee shorthand.
     * _.filter(users, _.iteratee(['user', 'fred']));
     * // => [{ 'user': 'fred', 'age': 40 }]
     *
     * // The `_.property` iteratee shorthand.
     * _.map(users, _.iteratee('user'));
     * // => ['barney', 'fred']
     *
     * // Create custom iteratee shorthands.
     * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
     *   return !_.isRegExp(func) ? iteratee(func) : function(string) {
     *     return func.test(string);
     *   };
     * });
     *
     * _.filter(['abc', 'def'], /ef/);
     * // => ['def']
     */
    function iteratee(func) {
      return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
    }

    /**
     * Creates a function that performs a partial deep comparison between a given
     * object and `source`, returning `true` if the given object has equivalent
     * property values, else `false`.
     *
     * **Note:** The created function is equivalent to `_.isMatch` with `source`
     * partially applied.
     *
     * Partial comparisons will match empty array and empty object `source`
     * values against any array or object value, respectively. See `_.isEqual`
     * for a list of supported value comparisons.
     *
     * **Note:** Multiple values can be checked by combining several matchers
     * using `_.overSome`
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {Object} source The object of property values to match.
     * @returns {Function} Returns the new spec function.
     * @example
     *
     * var objects = [
     *   { 'a': 1, 'b': 2, 'c': 3 },
     *   { 'a': 4, 'b': 5, 'c': 6 }
     * ];
     *
     * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
     * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
     *
     * // Checking for several possible values
     * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
     * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
     */
    function matches(source) {
      return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
    }

    /**
     * Creates a function that performs a partial deep comparison between the
     * value at `path` of a given object to `srcValue`, returning `true` if the
     * object value is equivalent, else `false`.
     *
     * **Note:** Partial comparisons will match empty array and empty object
     * `srcValue` values against any array or object value, respectively. See
     * `_.isEqual` for a list of supported value comparisons.
     *
     * **Note:** Multiple values can be checked by combining several matchers
     * using `_.overSome`
     *
     * @static
     * @memberOf _
     * @since 3.2.0
     * @category Util
     * @param {Array|string} path The path of the property to get.
     * @param {*} srcValue The value to match.
     * @returns {Function} Returns the new spec function.
     * @example
     *
     * var objects = [
     *   { 'a': 1, 'b': 2, 'c': 3 },
     *   { 'a': 4, 'b': 5, 'c': 6 }
     * ];
     *
     * _.find(objects, _.matchesProperty('a', 4));
     * // => { 'a': 4, 'b': 5, 'c': 6 }
     *
     * // Checking for several possible values
     * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
     * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
     */
    function matchesProperty(path, srcValue) {
      return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
    }

    /**
     * Creates a function that invokes the method at `path` of a given object.
     * Any additional arguments are provided to the invoked method.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Util
     * @param {Array|string} path The path of the method to invoke.
     * @param {...*} [args] The arguments to invoke the method with.
     * @returns {Function} Returns the new invoker function.
     * @example
     *
     * var objects = [
     *   { 'a': { 'b': _.constant(2) } },
     *   { 'a': { 'b': _.constant(1) } }
     * ];
     *
     * _.map(objects, _.method('a.b'));
     * // => [2, 1]
     *
     * _.map(objects, _.method(['a', 'b']));
     * // => [2, 1]
     */
    var method = baseRest(function(path, args) {
      return function(object) {
        return baseInvoke(object, path, args);
      };
    });

    /**
     * The opposite of `_.method`; this method creates a function that invokes
     * the method at a given path of `object`. Any additional arguments are
     * provided to the invoked method.
     *
     * @static
     * @memberOf _
     * @since 3.7.0
     * @category Util
     * @param {Object} object The object to query.
     * @param {...*} [args] The arguments to invoke the method with.
     * @returns {Function} Returns the new invoker function.
     * @example
     *
     * var array = _.times(3, _.constant),
     *     object = { 'a': array, 'b': array, 'c': array };
     *
     * _.map(['a[2]', 'c[0]'], _.methodOf(object));
     * // => [2, 0]
     *
     * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
     * // => [2, 0]
     */
    var methodOf = baseRest(function(object, args) {
      return function(path) {
        return baseInvoke(object, path, args);
      };
    });

    /**
     * Adds all own enumerable string keyed function properties of a source
     * object to the destination object. If `object` is a function, then methods
     * are added to its prototype as well.
     *
     * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
     * avoid conflicts caused by modifying the original.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {Function|Object} [object=lodash] The destination object.
     * @param {Object} source The object of functions to add.
     * @param {Object} [options={}] The options object.
     * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
     * @returns {Function|Object} Returns `object`.
     * @example
     *
     * function vowels(string) {
     *   return _.filter(string, function(v) {
     *     return /[aeiou]/i.test(v);
     *   });
     * }
     *
     * _.mixin({ 'vowels': vowels });
     * _.vowels('fred');
     * // => ['e']
     *
     * _('fred').vowels().value();
     * // => ['e']
     *
     * _.mixin({ 'vowels': vowels }, { 'chain': false });
     * _('fred').vowels();
     * // => ['e']
     */
    function mixin(object, source, options) {
      var props = keys(source),
          methodNames = baseFunctions(source, props);

      if (options == null &&
          !(isObject(source) && (methodNames.length || !props.length))) {
        options = source;
        source = object;
        object = this;
        methodNames = baseFunctions(source, keys(source));
      }
      var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
          isFunc = isFunction(object);

      arrayEach(methodNames, function(methodName) {
        var func = source[methodName];
        object[methodName] = func;
        if (isFunc) {
          object.prototype[methodName] = function() {
            var chainAll = this.__chain__;
            if (chain || chainAll) {
              var result = object(this.__wrapped__),
                  actions = result.__actions__ = copyArray(this.__actions__);

              actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
              result.__chain__ = chainAll;
              return result;
            }
            return func.apply(object, arrayPush([this.value()], arguments));
          };
        }
      });

      return object;
    }

    /**
     * Reverts the `_` variable to its previous value and returns a reference to
     * the `lodash` function.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @returns {Function} Returns the `lodash` function.
     * @example
     *
     * var lodash = _.noConflict();
     */
    function noConflict() {
      if (root._ === this) {
        root._ = oldDash;
      }
      return this;
    }

    /**
     * This method returns `undefined`.
     *
     * @static
     * @memberOf _
     * @since 2.3.0
     * @category Util
     * @example
     *
     * _.times(2, _.noop);
     * // => [undefined, undefined]
     */
    function noop() {
      // No operation performed.
    }

    /**
     * Creates a function that gets the argument at index `n`. If `n` is negative,
     * the nth argument from the end is returned.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {number} [n=0] The index of the argument to return.
     * @returns {Function} Returns the new pass-thru function.
     * @example
     *
     * var func = _.nthArg(1);
     * func('a', 'b', 'c', 'd');
     * // => 'b'
     *
     * var func = _.nthArg(-2);
     * func('a', 'b', 'c', 'd');
     * // => 'c'
     */
    function nthArg(n) {
      n = toInteger(n);
      return baseRest(function(args) {
        return baseNth(args, n);
      });
    }

    /**
     * Creates a function that invokes `iteratees` with the arguments it receives
     * and returns their results.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {...(Function|Function[])} [iteratees=[_.identity]]
     *  The iteratees to invoke.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var func = _.over([Math.max, Math.min]);
     *
     * func(1, 2, 3, 4);
     * // => [4, 1]
     */
    var over = createOver(arrayMap);

    /**
     * Creates a function that checks if **all** of the `predicates` return
     * truthy when invoked with the arguments it receives.
     *
     * Following shorthands are possible for providing predicates.
     * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
     * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {...(Function|Function[])} [predicates=[_.identity]]
     *  The predicates to check.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var func = _.overEvery([Boolean, isFinite]);
     *
     * func('1');
     * // => true
     *
     * func(null);
     * // => false
     *
     * func(NaN);
     * // => false
     */
    var overEvery = createOver(arrayEvery);

    /**
     * Creates a function that checks if **any** of the `predicates` return
     * truthy when invoked with the arguments it receives.
     *
     * Following shorthands are possible for providing predicates.
     * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
     * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {...(Function|Function[])} [predicates=[_.identity]]
     *  The predicates to check.
     * @returns {Function} Returns the new function.
     * @example
     *
     * var func = _.overSome([Boolean, isFinite]);
     *
     * func('1');
     * // => true
     *
     * func(null);
     * // => true
     *
     * func(NaN);
     * // => false
     *
     * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
     * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
     */
    var overSome = createOver(arraySome);

    /**
     * Creates a function that returns the value at `path` of a given object.
     *
     * @static
     * @memberOf _
     * @since 2.4.0
     * @category Util
     * @param {Array|string} path The path of the property to get.
     * @returns {Function} Returns the new accessor function.
     * @example
     *
     * var objects = [
     *   { 'a': { 'b': 2 } },
     *   { 'a': { 'b': 1 } }
     * ];
     *
     * _.map(objects, _.property('a.b'));
     * // => [2, 1]
     *
     * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
     * // => [1, 2]
     */
    function property(path) {
      return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
    }

    /**
     * The opposite of `_.property`; this method creates a function that returns
     * the value at a given path of `object`.
     *
     * @static
     * @memberOf _
     * @since 3.0.0
     * @category Util
     * @param {Object} object The object to query.
     * @returns {Function} Returns the new accessor function.
     * @example
     *
     * var array = [0, 1, 2],
     *     object = { 'a': array, 'b': array, 'c': array };
     *
     * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
     * // => [2, 0]
     *
     * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
     * // => [2, 0]
     */
    function propertyOf(object) {
      return function(path) {
        return object == null ? undefined : baseGet(object, path);
      };
    }

    /**
     * Creates an array of numbers (positive and/or negative) progressing from
     * `start` up to, but not including, `end`. A step of `-1` is used if a negative
     * `start` is specified without an `end` or `step`. If `end` is not specified,
     * it's set to `start` with `start` then set to `0`.
     *
     * **Note:** JavaScript follows the IEEE-754 standard for resolving
     * floating-point values which can produce unexpected results.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {number} [start=0] The start of the range.
     * @param {number} end The end of the range.
     * @param {number} [step=1] The value to increment or decrement by.
     * @returns {Array} Returns the range of numbers.
     * @see _.inRange, _.rangeRight
     * @example
     *
     * _.range(4);
     * // => [0, 1, 2, 3]
     *
     * _.range(-4);
     * // => [0, -1, -2, -3]
     *
     * _.range(1, 5);
     * // => [1, 2, 3, 4]
     *
     * _.range(0, 20, 5);
     * // => [0, 5, 10, 15]
     *
     * _.range(0, -4, -1);
     * // => [0, -1, -2, -3]
     *
     * _.range(1, 4, 0);
     * // => [1, 1, 1]
     *
     * _.range(0);
     * // => []
     */
    var range = createRange();

    /**
     * This method is like `_.range` except that it populates values in
     * descending order.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {number} [start=0] The start of the range.
     * @param {number} end The end of the range.
     * @param {number} [step=1] The value to increment or decrement by.
     * @returns {Array} Returns the range of numbers.
     * @see _.inRange, _.range
     * @example
     *
     * _.rangeRight(4);
     * // => [3, 2, 1, 0]
     *
     * _.rangeRight(-4);
     * // => [-3, -2, -1, 0]
     *
     * _.rangeRight(1, 5);
     * // => [4, 3, 2, 1]
     *
     * _.rangeRight(0, 20, 5);
     * // => [15, 10, 5, 0]
     *
     * _.rangeRight(0, -4, -1);
     * // => [-3, -2, -1, 0]
     *
     * _.rangeRight(1, 4, 0);
     * // => [1, 1, 1]
     *
     * _.rangeRight(0);
     * // => []
     */
    var rangeRight = createRange(true);

    /**
     * This method returns a new empty array.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {Array} Returns the new empty array.
     * @example
     *
     * var arrays = _.times(2, _.stubArray);
     *
     * console.log(arrays);
     * // => [[], []]
     *
     * console.log(arrays[0] === arrays[1]);
     * // => false
     */
    function stubArray() {
      return [];
    }

    /**
     * This method returns `false`.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {boolean} Returns `false`.
     * @example
     *
     * _.times(2, _.stubFalse);
     * // => [false, false]
     */
    function stubFalse() {
      return false;
    }

    /**
     * This method returns a new empty object.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {Object} Returns the new empty object.
     * @example
     *
     * var objects = _.times(2, _.stubObject);
     *
     * console.log(objects);
     * // => [{}, {}]
     *
     * console.log(objects[0] === objects[1]);
     * // => false
     */
    function stubObject() {
      return {};
    }

    /**
     * This method returns an empty string.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {string} Returns the empty string.
     * @example
     *
     * _.times(2, _.stubString);
     * // => ['', '']
     */
    function stubString() {
      return '';
    }

    /**
     * This method returns `true`.
     *
     * @static
     * @memberOf _
     * @since 4.13.0
     * @category Util
     * @returns {boolean} Returns `true`.
     * @example
     *
     * _.times(2, _.stubTrue);
     * // => [true, true]
     */
    function stubTrue() {
      return true;
    }

    /**
     * Invokes the iteratee `n` times, returning an array of the results of
     * each invocation. The iteratee is invoked with one argument; (index).
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {number} n The number of times to invoke `iteratee`.
     * @param {Function} [iteratee=_.identity] The function invoked per iteration.
     * @returns {Array} Returns the array of results.
     * @example
     *
     * _.times(3, String);
     * // => ['0', '1', '2']
     *
     *  _.times(4, _.constant(0));
     * // => [0, 0, 0, 0]
     */
    function times(n, iteratee) {
      n = toInteger(n);
      if (n < 1 || n > MAX_SAFE_INTEGER) {
        return [];
      }
      var index = MAX_ARRAY_LENGTH,
          length = nativeMin(n, MAX_ARRAY_LENGTH);

      iteratee = getIteratee(iteratee);
      n -= MAX_ARRAY_LENGTH;

      var result = baseTimes(length, iteratee);
      while (++index < n) {
        iteratee(index);
      }
      return result;
    }

    /**
     * Converts `value` to a property path array.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Util
     * @param {*} value The value to convert.
     * @returns {Array} Returns the new property path array.
     * @example
     *
     * _.toPath('a.b.c');
     * // => ['a', 'b', 'c']
     *
     * _.toPath('a[0].b.c');
     * // => ['a', '0', 'b', 'c']
     */
    function toPath(value) {
      if (isArray(value)) {
        return arrayMap(value, toKey);
      }
      return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
    }

    /**
     * Generates a unique ID. If `prefix` is given, the ID is appended to it.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Util
     * @param {string} [prefix=''] The value to prefix the ID with.
     * @returns {string} Returns the unique ID.
     * @example
     *
     * _.uniqueId('contact_');
     * // => 'contact_104'
     *
     * _.uniqueId();
     * // => '105'
     */
    function uniqueId(prefix) {
      var id = ++idCounter;
      return toString(prefix) + id;
    }

    /*------------------------------------------------------------------------*/

    /**
     * Adds two numbers.
     *
     * @static
     * @memberOf _
     * @since 3.4.0
     * @category Math
     * @param {number} augend The first number in an addition.
     * @param {number} addend The second number in an addition.
     * @returns {number} Returns the total.
     * @example
     *
     * _.add(6, 4);
     * // => 10
     */
    var add = createMathOperation(function(augend, addend) {
      return augend + addend;
    }, 0);

    /**
     * Computes `number` rounded up to `precision`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Math
     * @param {number} number The number to round up.
     * @param {number} [precision=0] The precision to round up to.
     * @returns {number} Returns the rounded up number.
     * @example
     *
     * _.ceil(4.006);
     * // => 5
     *
     * _.ceil(6.004, 2);
     * // => 6.01
     *
     * _.ceil(6040, -2);
     * // => 6100
     */
    var ceil = createRound('ceil');

    /**
     * Divide two numbers.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Math
     * @param {number} dividend The first number in a division.
     * @param {number} divisor The second number in a division.
     * @returns {number} Returns the quotient.
     * @example
     *
     * _.divide(6, 4);
     * // => 1.5
     */
    var divide = createMathOperation(function(dividend, divisor) {
      return dividend / divisor;
    }, 1);

    /**
     * Computes `number` rounded down to `precision`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Math
     * @param {number} number The number to round down.
     * @param {number} [precision=0] The precision to round down to.
     * @returns {number} Returns the rounded down number.
     * @example
     *
     * _.floor(4.006);
     * // => 4
     *
     * _.floor(0.046, 2);
     * // => 0.04
     *
     * _.floor(4060, -2);
     * // => 4000
     */
    var floor = createRound('floor');

    /**
     * Computes the maximum value of `array`. If `array` is empty or falsey,
     * `undefined` is returned.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {*} Returns the maximum value.
     * @example
     *
     * _.max([4, 2, 8, 6]);
     * // => 8
     *
     * _.max([]);
     * // => undefined
     */
    function max(array) {
      return (array && array.length)
        ? baseExtremum(array, identity, baseGt)
        : undefined;
    }

    /**
     * This method is like `_.max` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the criterion by which
     * the value is ranked. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {*} Returns the maximum value.
     * @example
     *
     * var objects = [{ 'n': 1 }, { 'n': 2 }];
     *
     * _.maxBy(objects, function(o) { return o.n; });
     * // => { 'n': 2 }
     *
     * // The `_.property` iteratee shorthand.
     * _.maxBy(objects, 'n');
     * // => { 'n': 2 }
     */
    function maxBy(array, iteratee) {
      return (array && array.length)
        ? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
        : undefined;
    }

    /**
     * Computes the mean of the values in `array`.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {number} Returns the mean.
     * @example
     *
     * _.mean([4, 2, 8, 6]);
     * // => 5
     */
    function mean(array) {
      return baseMean(array, identity);
    }

    /**
     * This method is like `_.mean` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the value to be averaged.
     * The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the mean.
     * @example
     *
     * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
     *
     * _.meanBy(objects, function(o) { return o.n; });
     * // => 5
     *
     * // The `_.property` iteratee shorthand.
     * _.meanBy(objects, 'n');
     * // => 5
     */
    function meanBy(array, iteratee) {
      return baseMean(array, getIteratee(iteratee, 2));
    }

    /**
     * Computes the minimum value of `array`. If `array` is empty or falsey,
     * `undefined` is returned.
     *
     * @static
     * @since 0.1.0
     * @memberOf _
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {*} Returns the minimum value.
     * @example
     *
     * _.min([4, 2, 8, 6]);
     * // => 2
     *
     * _.min([]);
     * // => undefined
     */
    function min(array) {
      return (array && array.length)
        ? baseExtremum(array, identity, baseLt)
        : undefined;
    }

    /**
     * This method is like `_.min` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the criterion by which
     * the value is ranked. The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {*} Returns the minimum value.
     * @example
     *
     * var objects = [{ 'n': 1 }, { 'n': 2 }];
     *
     * _.minBy(objects, function(o) { return o.n; });
     * // => { 'n': 1 }
     *
     * // The `_.property` iteratee shorthand.
     * _.minBy(objects, 'n');
     * // => { 'n': 1 }
     */
    function minBy(array, iteratee) {
      return (array && array.length)
        ? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
        : undefined;
    }

    /**
     * Multiply two numbers.
     *
     * @static
     * @memberOf _
     * @since 4.7.0
     * @category Math
     * @param {number} multiplier The first number in a multiplication.
     * @param {number} multiplicand The second number in a multiplication.
     * @returns {number} Returns the product.
     * @example
     *
     * _.multiply(6, 4);
     * // => 24
     */
    var multiply = createMathOperation(function(multiplier, multiplicand) {
      return multiplier * multiplicand;
    }, 1);

    /**
     * Computes `number` rounded to `precision`.
     *
     * @static
     * @memberOf _
     * @since 3.10.0
     * @category Math
     * @param {number} number The number to round.
     * @param {number} [precision=0] The precision to round to.
     * @returns {number} Returns the rounded number.
     * @example
     *
     * _.round(4.006);
     * // => 4
     *
     * _.round(4.006, 2);
     * // => 4.01
     *
     * _.round(4060, -2);
     * // => 4100
     */
    var round = createRound('round');

    /**
     * Subtract two numbers.
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {number} minuend The first number in a subtraction.
     * @param {number} subtrahend The second number in a subtraction.
     * @returns {number} Returns the difference.
     * @example
     *
     * _.subtract(6, 4);
     * // => 2
     */
    var subtract = createMathOperation(function(minuend, subtrahend) {
      return minuend - subtrahend;
    }, 0);

    /**
     * Computes the sum of the values in `array`.
     *
     * @static
     * @memberOf _
     * @since 3.4.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @returns {number} Returns the sum.
     * @example
     *
     * _.sum([4, 2, 8, 6]);
     * // => 20
     */
    function sum(array) {
      return (array && array.length)
        ? baseSum(array, identity)
        : 0;
    }

    /**
     * This method is like `_.sum` except that it accepts `iteratee` which is
     * invoked for each element in `array` to generate the value to be summed.
     * The iteratee is invoked with one argument: (value).
     *
     * @static
     * @memberOf _
     * @since 4.0.0
     * @category Math
     * @param {Array} array The array to iterate over.
     * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
     * @returns {number} Returns the sum.
     * @example
     *
     * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
     *
     * _.sumBy(objects, function(o) { return o.n; });
     * // => 20
     *
     * // The `_.property` iteratee shorthand.
     * _.sumBy(objects, 'n');
     * // => 20
     */
    function sumBy(array, iteratee) {
      return (array && array.length)
        ? baseSum(array, getIteratee(iteratee, 2))
        : 0;
    }

    /*------------------------------------------------------------------------*/

    // Add methods that return wrapped values in chain sequences.
    lodash.after = after;
    lodash.ary = ary;
    lodash.assign = assign;
    lodash.assignIn = assignIn;
    lodash.assignInWith = assignInWith;
    lodash.assignWith = assignWith;
    lodash.at = at;
    lodash.before = before;
    lodash.bind = bind;
    lodash.bindAll = bindAll;
    lodash.bindKey = bindKey;
    lodash.castArray = castArray;
    lodash.chain = chain;
    lodash.chunk = chunk;
    lodash.compact = compact;
    lodash.concat = concat;
    lodash.cond = cond;
    lodash.conforms = conforms;
    lodash.constant = constant;
    lodash.countBy = countBy;
    lodash.create = create;
    lodash.curry = curry;
    lodash.curryRight = curryRight;
    lodash.debounce = debounce;
    lodash.defaults = defaults;
    lodash.defaultsDeep = defaultsDeep;
    lodash.defer = defer;
    lodash.delay = delay;
    lodash.difference = difference;
    lodash.differenceBy = differenceBy;
    lodash.differenceWith = differenceWith;
    lodash.drop = drop;
    lodash.dropRight = dropRight;
    lodash.dropRightWhile = dropRightWhile;
    lodash.dropWhile = dropWhile;
    lodash.fill = fill;
    lodash.filter = filter;
    lodash.flatMap = flatMap;
    lodash.flatMapDeep = flatMapDeep;
    lodash.flatMapDepth = flatMapDepth;
    lodash.flatten = flatten;
    lodash.flattenDeep = flattenDeep;
    lodash.flattenDepth = flattenDepth;
    lodash.flip = flip;
    lodash.flow = flow;
    lodash.flowRight = flowRight;
    lodash.fromPairs = fromPairs;
    lodash.functions = functions;
    lodash.functionsIn = functionsIn;
    lodash.groupBy = groupBy;
    lodash.initial = initial;
    lodash.intersection = intersection;
    lodash.intersectionBy = intersectionBy;
    lodash.intersectionWith = intersectionWith;
    lodash.invert = invert;
    lodash.invertBy = invertBy;
    lodash.invokeMap = invokeMap;
    lodash.iteratee = iteratee;
    lodash.keyBy = keyBy;
    lodash.keys = keys;
    lodash.keysIn = keysIn;
    lodash.map = map;
    lodash.mapKeys = mapKeys;
    lodash.mapValues = mapValues;
    lodash.matches = matches;
    lodash.matchesProperty = matchesProperty;
    lodash.memoize = memoize;
    lodash.merge = merge;
    lodash.mergeWith = mergeWith;
    lodash.method = method;
    lodash.methodOf = methodOf;
    lodash.mixin = mixin;
    lodash.negate = negate;
    lodash.nthArg = nthArg;
    lodash.omit = omit;
    lodash.omitBy = omitBy;
    lodash.once = once;
    lodash.orderBy = orderBy;
    lodash.over = over;
    lodash.overArgs = overArgs;
    lodash.overEvery = overEvery;
    lodash.overSome = overSome;
    lodash.partial = partial;
    lodash.partialRight = partialRight;
    lodash.partition = partition;
    lodash.pick = pick;
    lodash.pickBy = pickBy;
    lodash.property = property;
    lodash.propertyOf = propertyOf;
    lodash.pull = pull;
    lodash.pullAll = pullAll;
    lodash.pullAllBy = pullAllBy;
    lodash.pullAllWith = pullAllWith;
    lodash.pullAt = pullAt;
    lodash.range = range;
    lodash.rangeRight = rangeRight;
    lodash.rearg = rearg;
    lodash.reject = reject;
    lodash.remove = remove;
    lodash.rest = rest;
    lodash.reverse = reverse;
    lodash.sampleSize = sampleSize;
    lodash.set = set;
    lodash.setWith = setWith;
    lodash.shuffle = shuffle;
    lodash.slice = slice;
    lodash.sortBy = sortBy;
    lodash.sortedUniq = sortedUniq;
    lodash.sortedUniqBy = sortedUniqBy;
    lodash.split = split;
    lodash.spread = spread;
    lodash.tail = tail;
    lodash.take = take;
    lodash.takeRight = takeRight;
    lodash.takeRightWhile = takeRightWhile;
    lodash.takeWhile = takeWhile;
    lodash.tap = tap;
    lodash.throttle = throttle;
    lodash.thru = thru;
    lodash.toArray = toArray;
    lodash.toPairs = toPairs;
    lodash.toPairsIn = toPairsIn;
    lodash.toPath = toPath;
    lodash.toPlainObject = toPlainObject;
    lodash.transform = transform;
    lodash.unary = unary;
    lodash.union = union;
    lodash.unionBy = unionBy;
    lodash.unionWith = unionWith;
    lodash.uniq = uniq;
    lodash.uniqBy = uniqBy;
    lodash.uniqWith = uniqWith;
    lodash.unset = unset;
    lodash.unzip = unzip;
    lodash.unzipWith = unzipWith;
    lodash.update = update;
    lodash.updateWith = updateWith;
    lodash.values = values;
    lodash.valuesIn = valuesIn;
    lodash.without = without;
    lodash.words = words;
    lodash.wrap = wrap;
    lodash.xor = xor;
    lodash.xorBy = xorBy;
    lodash.xorWith = xorWith;
    lodash.zip = zip;
    lodash.zipObject = zipObject;
    lodash.zipObjectDeep = zipObjectDeep;
    lodash.zipWith = zipWith;

    // Add aliases.
    lodash.entries = toPairs;
    lodash.entriesIn = toPairsIn;
    lodash.extend = assignIn;
    lodash.extendWith = assignInWith;

    // Add methods to `lodash.prototype`.
    mixin(lodash, lodash);

    /*------------------------------------------------------------------------*/

    // Add methods that return unwrapped values in chain sequences.
    lodash.add = add;
    lodash.attempt = attempt;
    lodash.camelCase = camelCase;
    lodash.capitalize = capitalize;
    lodash.ceil = ceil;
    lodash.clamp = clamp;
    lodash.clone = clone;
    lodash.cloneDeep = cloneDeep;
    lodash.cloneDeepWith = cloneDeepWith;
    lodash.cloneWith = cloneWith;
    lodash.conformsTo = conformsTo;
    lodash.deburr = deburr;
    lodash.defaultTo = defaultTo;
    lodash.divide = divide;
    lodash.endsWith = endsWith;
    lodash.eq = eq;
    lodash.escape = escape;
    lodash.escapeRegExp = escapeRegExp;
    lodash.every = every;
    lodash.find = find;
    lodash.findIndex = findIndex;
    lodash.findKey = findKey;
    lodash.findLast = findLast;
    lodash.findLastIndex = findLastIndex;
    lodash.findLastKey = findLastKey;
    lodash.floor = floor;
    lodash.forEach = forEach;
    lodash.forEachRight = forEachRight;
    lodash.forIn = forIn;
    lodash.forInRight = forInRight;
    lodash.forOwn = forOwn;
    lodash.forOwnRight = forOwnRight;
    lodash.get = get;
    lodash.gt = gt;
    lodash.gte = gte;
    lodash.has = has;
    lodash.hasIn = hasIn;
    lodash.head = head;
    lodash.identity = identity;
    lodash.includes = includes;
    lodash.indexOf = indexOf;
    lodash.inRange = inRange;
    lodash.invoke = invoke;
    lodash.isArguments = isArguments;
    lodash.isArray = isArray;
    lodash.isArrayBuffer = isArrayBuffer;
    lodash.isArrayLike = isArrayLike;
    lodash.isArrayLikeObject = isArrayLikeObject;
    lodash.isBoolean = isBoolean;
    lodash.isBuffer = isBuffer;
    lodash.isDate = isDate;
    lodash.isElement = isElement;
    lodash.isEmpty = isEmpty;
    lodash.isEqual = isEqual;
    lodash.isEqualWith = isEqualWith;
    lodash.isError = isError;
    lodash.isFinite = isFinite;
    lodash.isFunction = isFunction;
    lodash.isInteger = isInteger;
    lodash.isLength = isLength;
    lodash.isMap = isMap;
    lodash.isMatch = isMatch;
    lodash.isMatchWith = isMatchWith;
    lodash.isNaN = isNaN;
    lodash.isNative = isNative;
    lodash.isNil = isNil;
    lodash.isNull = isNull;
    lodash.isNumber = isNumber;
    lodash.isObject = isObject;
    lodash.isObjectLike = isObjectLike;
    lodash.isPlainObject = isPlainObject;
    lodash.isRegExp = isRegExp;
    lodash.isSafeInteger = isSafeInteger;
    lodash.isSet = isSet;
    lodash.isString = isString;
    lodash.isSymbol = isSymbol;
    lodash.isTypedArray = isTypedArray;
    lodash.isUndefined = isUndefined;
    lodash.isWeakMap = isWeakMap;
    lodash.isWeakSet = isWeakSet;
    lodash.join = join;
    lodash.kebabCase = kebabCase;
    lodash.last = last;
    lodash.lastIndexOf = lastIndexOf;
    lodash.lowerCase = lowerCase;
    lodash.lowerFirst = lowerFirst;
    lodash.lt = lt;
    lodash.lte = lte;
    lodash.max = max;
    lodash.maxBy = maxBy;
    lodash.mean = mean;
    lodash.meanBy = meanBy;
    lodash.min = min;
    lodash.minBy = minBy;
    lodash.stubArray = stubArray;
    lodash.stubFalse = stubFalse;
    lodash.stubObject = stubObject;
    lodash.stubString = stubString;
    lodash.stubTrue = stubTrue;
    lodash.multiply = multiply;
    lodash.nth = nth;
    lodash.noConflict = noConflict;
    lodash.noop = noop;
    lodash.now = now;
    lodash.pad = pad;
    lodash.padEnd = padEnd;
    lodash.padStart = padStart;
    lodash.parseInt = parseInt;
    lodash.random = random;
    lodash.reduce = reduce;
    lodash.reduceRight = reduceRight;
    lodash.repeat = repeat;
    lodash.replace = replace;
    lodash.result = result;
    lodash.round = round;
    lodash.runInContext = runInContext;
    lodash.sample = sample;
    lodash.size = size;
    lodash.snakeCase = snakeCase;
    lodash.some = some;
    lodash.sortedIndex = sortedIndex;
    lodash.sortedIndexBy = sortedIndexBy;
    lodash.sortedIndexOf = sortedIndexOf;
    lodash.sortedLastIndex = sortedLastIndex;
    lodash.sortedLastIndexBy = sortedLastIndexBy;
    lodash.sortedLastIndexOf = sortedLastIndexOf;
    lodash.startCase = startCase;
    lodash.startsWith = startsWith;
    lodash.subtract = subtract;
    lodash.sum = sum;
    lodash.sumBy = sumBy;
    lodash.template = template;
    lodash.times = times;
    lodash.toFinite = toFinite;
    lodash.toInteger = toInteger;
    lodash.toLength = toLength;
    lodash.toLower = toLower;
    lodash.toNumber = toNumber;
    lodash.toSafeInteger = toSafeInteger;
    lodash.toString = toString;
    lodash.toUpper = toUpper;
    lodash.trim = trim;
    lodash.trimEnd = trimEnd;
    lodash.trimStart = trimStart;
    lodash.truncate = truncate;
    lodash.unescape = unescape;
    lodash.uniqueId = uniqueId;
    lodash.upperCase = upperCase;
    lodash.upperFirst = upperFirst;

    // Add aliases.
    lodash.each = forEach;
    lodash.eachRight = forEachRight;
    lodash.first = head;

    mixin(lodash, (function() {
      var source = {};
      baseForOwn(lodash, function(func, methodName) {
        if (!hasOwnProperty.call(lodash.prototype, methodName)) {
          source[methodName] = func;
        }
      });
      return source;
    }()), { 'chain': false });

    /*------------------------------------------------------------------------*/

    /**
     * The semantic version number.
     *
     * @static
     * @memberOf _
     * @type {string}
     */
    lodash.VERSION = VERSION;

    // Assign default placeholders.
    arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
      lodash[methodName].placeholder = lodash;
    });

    // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
    arrayEach(['drop', 'take'], function(methodName, index) {
      LazyWrapper.prototype[methodName] = function(n) {
        n = n === undefined ? 1 : nativeMax(toInteger(n), 0);

        var result = (this.__filtered__ && !index)
          ? new LazyWrapper(this)
          : this.clone();

        if (result.__filtered__) {
          result.__takeCount__ = nativeMin(n, result.__takeCount__);
        } else {
          result.__views__.push({
            'size': nativeMin(n, MAX_ARRAY_LENGTH),
            'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
          });
        }
        return result;
      };

      LazyWrapper.prototype[methodName + 'Right'] = function(n) {
        return this.reverse()[methodName](n).reverse();
      };
    });

    // Add `LazyWrapper` methods that accept an `iteratee` value.
    arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
      var type = index + 1,
          isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;

      LazyWrapper.prototype[methodName] = function(iteratee) {
        var result = this.clone();
        result.__iteratees__.push({
          'iteratee': getIteratee(iteratee, 3),
          'type': type
        });
        result.__filtered__ = result.__filtered__ || isFilter;
        return result;
      };
    });

    // Add `LazyWrapper` methods for `_.head` and `_.last`.
    arrayEach(['head', 'last'], function(methodName, index) {
      var takeName = 'take' + (index ? 'Right' : '');

      LazyWrapper.prototype[methodName] = function() {
        return this[takeName](1).value()[0];
      };
    });

    // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
    arrayEach(['initial', 'tail'], function(methodName, index) {
      var dropName = 'drop' + (index ? '' : 'Right');

      LazyWrapper.prototype[methodName] = function() {
        return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
      };
    });

    LazyWrapper.prototype.compact = function() {
      return this.filter(identity);
    };

    LazyWrapper.prototype.find = function(predicate) {
      return this.filter(predicate).head();
    };

    LazyWrapper.prototype.findLast = function(predicate) {
      return this.reverse().find(predicate);
    };

    LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
      if (typeof path == 'function') {
        return new LazyWrapper(this);
      }
      return this.map(function(value) {
        return baseInvoke(value, path, args);
      });
    });

    LazyWrapper.prototype.reject = function(predicate) {
      return this.filter(negate(getIteratee(predicate)));
    };

    LazyWrapper.prototype.slice = function(start, end) {
      start = toInteger(start);

      var result = this;
      if (result.__filtered__ && (start > 0 || end < 0)) {
        return new LazyWrapper(result);
      }
      if (start < 0) {
        result = result.takeRight(-start);
      } else if (start) {
        result = result.drop(start);
      }
      if (end !== undefined) {
        end = toInteger(end);
        result = end < 0 ? result.dropRight(-end) : result.take(end - start);
      }
      return result;
    };

    LazyWrapper.prototype.takeRightWhile = function(predicate) {
      return this.reverse().takeWhile(predicate).reverse();
    };

    LazyWrapper.prototype.toArray = function() {
      return this.take(MAX_ARRAY_LENGTH);
    };

    // Add `LazyWrapper` methods to `lodash.prototype`.
    baseForOwn(LazyWrapper.prototype, function(func, methodName) {
      var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
          isTaker = /^(?:head|last)$/.test(methodName),
          lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
          retUnwrapped = isTaker || /^find/.test(methodName);

      if (!lodashFunc) {
        return;
      }
      lodash.prototype[methodName] = function() {
        var value = this.__wrapped__,
            args = isTaker ? [1] : arguments,
            isLazy = value instanceof LazyWrapper,
            iteratee = args[0],
            useLazy = isLazy || isArray(value);

        var interceptor = function(value) {
          var result = lodashFunc.apply(lodash, arrayPush([value], args));
          return (isTaker && chainAll) ? result[0] : result;
        };

        if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
          // Avoid lazy use if the iteratee has a "length" value other than `1`.
          isLazy = useLazy = false;
        }
        var chainAll = this.__chain__,
            isHybrid = !!this.__actions__.length,
            isUnwrapped = retUnwrapped && !chainAll,
            onlyLazy = isLazy && !isHybrid;

        if (!retUnwrapped && useLazy) {
          value = onlyLazy ? value : new LazyWrapper(this);
          var result = func.apply(value, args);
          result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
          return new LodashWrapper(result, chainAll);
        }
        if (isUnwrapped && onlyLazy) {
          return func.apply(this, args);
        }
        result = this.thru(interceptor);
        return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
      };
    });

    // Add `Array` methods to `lodash.prototype`.
    arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
      var func = arrayProto[methodName],
          chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
          retUnwrapped = /^(?:pop|shift)$/.test(methodName);

      lodash.prototype[methodName] = function() {
        var args = arguments;
        if (retUnwrapped && !this.__chain__) {
          var value = this.value();
          return func.apply(isArray(value) ? value : [], args);
        }
        return this[chainName](function(value) {
          return func.apply(isArray(value) ? value : [], args);
        });
      };
    });

    // Map minified method names to their real names.
    baseForOwn(LazyWrapper.prototype, function(func, methodName) {
      var lodashFunc = lodash[methodName];
      if (lodashFunc) {
        var key = lodashFunc.name + '';
        if (!hasOwnProperty.call(realNames, key)) {
          realNames[key] = [];
        }
        realNames[key].push({ 'name': methodName, 'func': lodashFunc });
      }
    });

    realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
      'name': 'wrapper',
      'func': undefined
    }];

    // Add methods to `LazyWrapper`.
    LazyWrapper.prototype.clone = lazyClone;
    LazyWrapper.prototype.reverse = lazyReverse;
    LazyWrapper.prototype.value = lazyValue;

    // Add chain sequence methods to the `lodash` wrapper.
    lodash.prototype.at = wrapperAt;
    lodash.prototype.chain = wrapperChain;
    lodash.prototype.commit = wrapperCommit;
    lodash.prototype.next = wrapperNext;
    lodash.prototype.plant = wrapperPlant;
    lodash.prototype.reverse = wrapperReverse;
    lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;

    // Add lazy aliases.
    lodash.prototype.first = lodash.prototype.head;

    if (symIterator) {
      lodash.prototype[symIterator] = wrapperToIterator;
    }
    return lodash;
  });

  /*--------------------------------------------------------------------------*/

  // Export lodash.
  var _ = runInContext();

  // Some AMD build optimizers, like r.js, check for condition patterns like:
  if (true) {
    // Expose Lodash on the global object to prevent errors when Lodash is
    // loaded by a script tag in the presence of an AMD loader.
    // See http://requirejs.org/docs/errors.html#mismatch for more details.
    // Use `_.noConflict` to remove Lodash from the global object.
    root._ = _;

    // Define as an anonymous module so, through path mapping, it can be
    // referenced as the "underscore" module.
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
      return _;
    }).call(exports, __webpack_require__, exports, module),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  }
  // Check for `exports` after `define` in case a build optimizer adds it.
  else {}
}.call(this));


/***/ }),

/***/ "./node_modules/lodash/mapValues.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/mapValues.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseAssignValue = __webpack_require__(/*! ./_baseAssignValue */ "./node_modules/lodash/_baseAssignValue.js"),
    baseForOwn = __webpack_require__(/*! ./_baseForOwn */ "./node_modules/lodash/_baseForOwn.js"),
    baseIteratee = __webpack_require__(/*! ./_baseIteratee */ "./node_modules/lodash/_baseIteratee.js");

/**
 * Creates an object with the same keys as `object` and values generated
 * by running each own enumerable string keyed property of `object` thru
 * `iteratee`. The iteratee is invoked with three arguments:
 * (value, key, object).
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Object
 * @param {Object} object The object to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Object} Returns the new mapped object.
 * @see _.mapKeys
 * @example
 *
 * var users = {
 *   'fred':    { 'user': 'fred',    'age': 40 },
 *   'pebbles': { 'user': 'pebbles', 'age': 1 }
 * };
 *
 * _.mapValues(users, function(o) { return o.age; });
 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
 *
 * // The `_.property` iteratee shorthand.
 * _.mapValues(users, 'age');
 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
 */
function mapValues(object, iteratee) {
  var result = {};
  iteratee = baseIteratee(iteratee, 3);

  baseForOwn(object, function(value, key, object) {
    baseAssignValue(result, key, iteratee(value, key, object));
  });
  return result;
}

module.exports = mapValues;


/***/ }),

/***/ "./node_modules/lodash/max.js":
/*!************************************!*\
  !*** ./node_modules/lodash/max.js ***!
  \************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseExtremum = __webpack_require__(/*! ./_baseExtremum */ "./node_modules/lodash/_baseExtremum.js"),
    baseGt = __webpack_require__(/*! ./_baseGt */ "./node_modules/lodash/_baseGt.js"),
    identity = __webpack_require__(/*! ./identity */ "./node_modules/lodash/identity.js");

/**
 * Computes the maximum value of `array`. If `array` is empty or falsey,
 * `undefined` is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Math
 * @param {Array} array The array to iterate over.
 * @returns {*} Returns the maximum value.
 * @example
 *
 * _.max([4, 2, 8, 6]);
 * // => 8
 *
 * _.max([]);
 * // => undefined
 */
function max(array) {
  return (array && array.length)
    ? baseExtremum(array, identity, baseGt)
    : undefined;
}

module.exports = max;


/***/ }),

/***/ "./node_modules/lodash/merge.js":
/*!**************************************!*\
  !*** ./node_modules/lodash/merge.js ***!
  \**************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseMerge = __webpack_require__(/*! ./_baseMerge */ "./node_modules/lodash/_baseMerge.js"),
    createAssigner = __webpack_require__(/*! ./_createAssigner */ "./node_modules/lodash/_createAssigner.js");

/**
 * This method is like `_.assign` except that it recursively merges own and
 * inherited enumerable string keyed properties of source objects into the
 * destination object. Source properties that resolve to `undefined` are
 * skipped if a destination value exists. Array and plain object properties
 * are merged recursively. Other objects and value types are overridden by
 * assignment. Source objects are applied from left to right. Subsequent
 * sources overwrite property assignments of previous sources.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @example
 *
 * var object = {
 *   'a': [{ 'b': 2 }, { 'd': 4 }]
 * };
 *
 * var other = {
 *   'a': [{ 'c': 3 }, { 'e': 5 }]
 * };
 *
 * _.merge(object, other);
 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
 */
var merge = createAssigner(function(object, source, srcIndex) {
  baseMerge(object, source, srcIndex);
});

module.exports = merge;


/***/ }),

/***/ "./node_modules/lodash/min.js":
/*!************************************!*\
  !*** ./node_modules/lodash/min.js ***!
  \************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseExtremum = __webpack_require__(/*! ./_baseExtremum */ "./node_modules/lodash/_baseExtremum.js"),
    baseLt = __webpack_require__(/*! ./_baseLt */ "./node_modules/lodash/_baseLt.js"),
    identity = __webpack_require__(/*! ./identity */ "./node_modules/lodash/identity.js");

/**
 * Computes the minimum value of `array`. If `array` is empty or falsey,
 * `undefined` is returned.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Math
 * @param {Array} array The array to iterate over.
 * @returns {*} Returns the minimum value.
 * @example
 *
 * _.min([4, 2, 8, 6]);
 * // => 2
 *
 * _.min([]);
 * // => undefined
 */
function min(array) {
  return (array && array.length)
    ? baseExtremum(array, identity, baseLt)
    : undefined;
}

module.exports = min;


/***/ }),

/***/ "./node_modules/lodash/minBy.js":
/*!**************************************!*\
  !*** ./node_modules/lodash/minBy.js ***!
  \**************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseExtremum = __webpack_require__(/*! ./_baseExtremum */ "./node_modules/lodash/_baseExtremum.js"),
    baseIteratee = __webpack_require__(/*! ./_baseIteratee */ "./node_modules/lodash/_baseIteratee.js"),
    baseLt = __webpack_require__(/*! ./_baseLt */ "./node_modules/lodash/_baseLt.js");

/**
 * This method is like `_.min` except that it accepts `iteratee` which is
 * invoked for each element in `array` to generate the criterion by which
 * the value is ranked. The iteratee is invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Math
 * @param {Array} array The array to iterate over.
 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
 * @returns {*} Returns the minimum value.
 * @example
 *
 * var objects = [{ 'n': 1 }, { 'n': 2 }];
 *
 * _.minBy(objects, function(o) { return o.n; });
 * // => { 'n': 1 }
 *
 * // The `_.property` iteratee shorthand.
 * _.minBy(objects, 'n');
 * // => { 'n': 1 }
 */
function minBy(array, iteratee) {
  return (array && array.length)
    ? baseExtremum(array, baseIteratee(iteratee, 2), baseLt)
    : undefined;
}

module.exports = minBy;


/***/ }),

/***/ "./node_modules/lodash/now.js":
/*!************************************!*\
  !*** ./node_modules/lodash/now.js ***!
  \************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var root = __webpack_require__(/*! ./_root */ "./node_modules/lodash/_root.js");

/**
 * Gets the timestamp of the number of milliseconds that have elapsed since
 * the Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Date
 * @returns {number} Returns the timestamp.
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => Logs the number of milliseconds it took for the deferred invocation.
 */
var now = function() {
  return root.Date.now();
};

module.exports = now;


/***/ }),

/***/ "./node_modules/lodash/pick.js":
/*!*************************************!*\
  !*** ./node_modules/lodash/pick.js ***!
  \*************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var basePick = __webpack_require__(/*! ./_basePick */ "./node_modules/lodash/_basePick.js"),
    flatRest = __webpack_require__(/*! ./_flatRest */ "./node_modules/lodash/_flatRest.js");

/**
 * Creates an object composed of the picked `object` properties.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The source object.
 * @param {...(string|string[])} [paths] The property paths to pick.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.pick(object, ['a', 'c']);
 * // => { 'a': 1, 'c': 3 }
 */
var pick = flatRest(function(object, paths) {
  return object == null ? {} : basePick(object, paths);
});

module.exports = pick;


/***/ }),

/***/ "./node_modules/lodash/range.js":
/*!**************************************!*\
  !*** ./node_modules/lodash/range.js ***!
  \**************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var createRange = __webpack_require__(/*! ./_createRange */ "./node_modules/lodash/_createRange.js");

/**
 * Creates an array of numbers (positive and/or negative) progressing from
 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
 * `start` is specified without an `end` or `step`. If `end` is not specified,
 * it's set to `start` with `start` then set to `0`.
 *
 * **Note:** JavaScript follows the IEEE-754 standard for resolving
 * floating-point values which can produce unexpected results.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {number} [start=0] The start of the range.
 * @param {number} end The end of the range.
 * @param {number} [step=1] The value to increment or decrement by.
 * @returns {Array} Returns the range of numbers.
 * @see _.inRange, _.rangeRight
 * @example
 *
 * _.range(4);
 * // => [0, 1, 2, 3]
 *
 * _.range(-4);
 * // => [0, -1, -2, -3]
 *
 * _.range(1, 5);
 * // => [1, 2, 3, 4]
 *
 * _.range(0, 20, 5);
 * // => [0, 5, 10, 15]
 *
 * _.range(0, -4, -1);
 * // => [0, -1, -2, -3]
 *
 * _.range(1, 4, 0);
 * // => [1, 1, 1]
 *
 * _.range(0);
 * // => []
 */
var range = createRange();

module.exports = range;


/***/ }),

/***/ "./node_modules/lodash/sortBy.js":
/*!***************************************!*\
  !*** ./node_modules/lodash/sortBy.js ***!
  \***************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseFlatten = __webpack_require__(/*! ./_baseFlatten */ "./node_modules/lodash/_baseFlatten.js"),
    baseOrderBy = __webpack_require__(/*! ./_baseOrderBy */ "./node_modules/lodash/_baseOrderBy.js"),
    baseRest = __webpack_require__(/*! ./_baseRest */ "./node_modules/lodash/_baseRest.js"),
    isIterateeCall = __webpack_require__(/*! ./_isIterateeCall */ "./node_modules/lodash/_isIterateeCall.js");

/**
 * Creates an array of elements, sorted in ascending order by the results of
 * running each element in a collection thru each iteratee. This method
 * performs a stable sort, that is, it preserves the original sort order of
 * equal elements. The iteratees are invoked with one argument: (value).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {...(Function|Function[])} [iteratees=[_.identity]]
 *  The iteratees to sort by.
 * @returns {Array} Returns the new sorted array.
 * @example
 *
 * var users = [
 *   { 'user': 'fred',   'age': 48 },
 *   { 'user': 'barney', 'age': 36 },
 *   { 'user': 'fred',   'age': 30 },
 *   { 'user': 'barney', 'age': 34 }
 * ];
 *
 * _.sortBy(users, [function(o) { return o.user; }]);
 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
 *
 * _.sortBy(users, ['user', 'age']);
 * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
 */
var sortBy = baseRest(function(collection, iteratees) {
  if (collection == null) {
    return [];
  }
  var length = iteratees.length;
  if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
    iteratees = [];
  } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
    iteratees = [iteratees[0]];
  }
  return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});

module.exports = sortBy;


/***/ }),

/***/ "./node_modules/lodash/toFinite.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/toFinite.js ***!
  \*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var toNumber = __webpack_require__(/*! ./toNumber */ "./node_modules/lodash/toNumber.js");

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_INTEGER = 1.7976931348623157e+308;

/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = toNumber(value);
  if (value === INFINITY || value === -INFINITY) {
    var sign = (value < 0 ? -1 : 1);
    return sign * MAX_INTEGER;
  }
  return value === value ? value : 0;
}

module.exports = toFinite;


/***/ }),

/***/ "./node_modules/lodash/toInteger.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/toInteger.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var toFinite = __webpack_require__(/*! ./toFinite */ "./node_modules/lodash/toFinite.js");

/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */
function toInteger(value) {
  var result = toFinite(value),
      remainder = result % 1;

  return result === result ? (remainder ? result - remainder : result) : 0;
}

module.exports = toInteger;


/***/ }),

/***/ "./node_modules/lodash/toNumber.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/toNumber.js ***!
  \*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var baseTrim = __webpack_require__(/*! ./_baseTrim */ "./node_modules/lodash/_baseTrim.js"),
    isObject = __webpack_require__(/*! ./isObject */ "./node_modules/lodash/isObject.js"),
    isSymbol = __webpack_require__(/*! ./isSymbol */ "./node_modules/lodash/isSymbol.js");

/** Used as references for various `Number` constants. */
var NAN = 0 / 0;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

module.exports = toNumber;


/***/ }),

/***/ "./node_modules/lodash/toPlainObject.js":
/*!**********************************************!*\
  !*** ./node_modules/lodash/toPlainObject.js ***!
  \**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var copyObject = __webpack_require__(/*! ./_copyObject */ "./node_modules/lodash/_copyObject.js"),
    keysIn = __webpack_require__(/*! ./keysIn */ "./node_modules/lodash/keysIn.js");

/**
 * Converts `value` to a plain object flattening inherited enumerable string
 * keyed properties of `value` to own properties of the plain object.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {Object} Returns the converted plain object.
 * @example
 *
 * function Foo() {
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.assign({ 'a': 1 }, new Foo);
 * // => { 'a': 1, 'b': 2 }
 *
 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
 * // => { 'a': 1, 'b': 2, 'c': 3 }
 */
function toPlainObject(value) {
  return copyObject(value, keysIn(value));
}

module.exports = toPlainObject;


/***/ }),

/***/ "./node_modules/lodash/uniqueId.js":
/*!*****************************************!*\
  !*** ./node_modules/lodash/uniqueId.js ***!
  \*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var toString = __webpack_require__(/*! ./toString */ "./node_modules/lodash/toString.js");

/** Used to generate unique IDs. */
var idCounter = 0;

/**
 * Generates a unique ID. If `prefix` is given, the ID is appended to it.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {string} [prefix=''] The value to prefix the ID with.
 * @returns {string} Returns the unique ID.
 * @example
 *
 * _.uniqueId('contact_');
 * // => 'contact_104'
 *
 * _.uniqueId();
 * // => '105'
 */
function uniqueId(prefix) {
  var id = ++idCounter;
  return toString(prefix) + id;
}

module.exports = uniqueId;


/***/ }),

/***/ "./node_modules/lodash/zipObject.js":
/*!******************************************!*\
  !*** ./node_modules/lodash/zipObject.js ***!
  \******************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var assignValue = __webpack_require__(/*! ./_assignValue */ "./node_modules/lodash/_assignValue.js"),
    baseZipObject = __webpack_require__(/*! ./_baseZipObject */ "./node_modules/lodash/_baseZipObject.js");

/**
 * This method is like `_.fromPairs` except that it accepts two arrays,
 * one of property identifiers and one of corresponding values.
 *
 * @static
 * @memberOf _
 * @since 0.4.0
 * @category Array
 * @param {Array} [props=[]] The property identifiers.
 * @param {Array} [values=[]] The property values.
 * @returns {Object} Returns the new object.
 * @example
 *
 * _.zipObject(['a', 'b'], [1, 2]);
 * // => { 'a': 1, 'b': 2 }
 */
function zipObject(props, values) {
  return baseZipObject(props || [], values || [], assignValue);
}

module.exports = zipObject;


/***/ }),

/***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js":
/*!****************************************************************************!*\
  !*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
  \****************************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


var isOldIE = function isOldIE() {
  var memo;
  return function memorize() {
    if (typeof memo === 'undefined') {
      // Test for IE <= 9 as proposed by Browserhacks
      // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
      // Tests for existence of standard globals is to allow style-loader
      // to operate correctly into non-standard environments
      // @see https://github.com/webpack-contrib/style-loader/issues/177
      memo = Boolean(window && document && document.all && !window.atob);
    }

    return memo;
  };
}();

var getTarget = function getTarget() {
  var memo = {};
  return function memorize(target) {
    if (typeof memo[target] === 'undefined') {
      var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself

      if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
        try {
          // This will throw an exception if access to iframe is blocked
          // due to cross-origin restrictions
          styleTarget = styleTarget.contentDocument.head;
        } catch (e) {
          // istanbul ignore next
          styleTarget = null;
        }
      }

      memo[target] = styleTarget;
    }

    return memo[target];
  };
}();

var stylesInDom = [];

function getIndexByIdentifier(identifier) {
  var result = -1;

  for (var i = 0; i < stylesInDom.length; i++) {
    if (stylesInDom[i].identifier === identifier) {
      result = i;
      break;
    }
  }

  return result;
}

function modulesToDom(list, options) {
  var idCountMap = {};
  var identifiers = [];

  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var id = options.base ? item[0] + options.base : item[0];
    var count = idCountMap[id] || 0;
    var identifier = "".concat(id, " ").concat(count);
    idCountMap[id] = count + 1;
    var index = getIndexByIdentifier(identifier);
    var obj = {
      css: item[1],
      media: item[2],
      sourceMap: item[3]
    };

    if (index !== -1) {
      stylesInDom[index].references++;
      stylesInDom[index].updater(obj);
    } else {
      stylesInDom.push({
        identifier: identifier,
        updater: addStyle(obj, options),
        references: 1
      });
    }

    identifiers.push(identifier);
  }

  return identifiers;
}

function insertStyleElement(options) {
  var style = document.createElement('style');
  var attributes = options.attributes || {};

  if (typeof attributes.nonce === 'undefined') {
    var nonce =  true ? __webpack_require__.nc : 0;

    if (nonce) {
      attributes.nonce = nonce;
    }
  }

  Object.keys(attributes).forEach(function (key) {
    style.setAttribute(key, attributes[key]);
  });

  if (typeof options.insert === 'function') {
    options.insert(style);
  } else {
    var target = getTarget(options.insert || 'head');

    if (!target) {
      throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
    }

    target.appendChild(style);
  }

  return style;
}

function removeStyleElement(style) {
  // istanbul ignore if
  if (style.parentNode === null) {
    return false;
  }

  style.parentNode.removeChild(style);
}
/* istanbul ignore next  */


var replaceText = function replaceText() {
  var textStore = [];
  return function replace(index, replacement) {
    textStore[index] = replacement;
    return textStore.filter(Boolean).join('\n');
  };
}();

function applyToSingletonTag(style, index, remove, obj) {
  var css = remove ? '' : obj.media ? "@media ".concat(obj.media, " {").concat(obj.css, "}") : obj.css; // For old IE

  /* istanbul ignore if  */

  if (style.styleSheet) {
    style.styleSheet.cssText = replaceText(index, css);
  } else {
    var cssNode = document.createTextNode(css);
    var childNodes = style.childNodes;

    if (childNodes[index]) {
      style.removeChild(childNodes[index]);
    }

    if (childNodes.length) {
      style.insertBefore(cssNode, childNodes[index]);
    } else {
      style.appendChild(cssNode);
    }
  }
}

function applyToTag(style, options, obj) {
  var css = obj.css;
  var media = obj.media;
  var sourceMap = obj.sourceMap;

  if (media) {
    style.setAttribute('media', media);
  } else {
    style.removeAttribute('media');
  }

  if (sourceMap && typeof btoa !== 'undefined') {
    css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
  } // For old IE

  /* istanbul ignore if  */


  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    while (style.firstChild) {
      style.removeChild(style.firstChild);
    }

    style.appendChild(document.createTextNode(css));
  }
}

var singleton = null;
var singletonCounter = 0;

function addStyle(obj, options) {
  var style;
  var update;
  var remove;

  if (options.singleton) {
    var styleIndex = singletonCounter++;
    style = singleton || (singleton = insertStyleElement(options));
    update = applyToSingletonTag.bind(null, style, styleIndex, false);
    remove = applyToSingletonTag.bind(null, style, styleIndex, true);
  } else {
    style = insertStyleElement(options);
    update = applyToTag.bind(null, style, options);

    remove = function remove() {
      removeStyleElement(style);
    };
  }

  update(obj);
  return function updateStyle(newObj) {
    if (newObj) {
      if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {
        return;
      }

      update(obj = newObj);
    } else {
      remove();
    }
  };
}

module.exports = function (list, options) {
  options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
  // tags it will allow on a page

  if (!options.singleton && typeof options.singleton !== 'boolean') {
    options.singleton = isOldIE();
  }

  list = list || [];
  var lastIdentifiers = modulesToDom(list, options);
  return function update(newList) {
    newList = newList || [];

    if (Object.prototype.toString.call(newList) !== '[object Array]') {
      return;
    }

    for (var i = 0; i < lastIdentifiers.length; i++) {
      var identifier = lastIdentifiers[i];
      var index = getIndexByIdentifier(identifier);
      stylesInDom[index].references--;
    }

    var newLastIdentifiers = modulesToDom(newList, options);

    for (var _i = 0; _i < lastIdentifiers.length; _i++) {
      var _identifier = lastIdentifiers[_i];

      var _index = getIndexByIdentifier(_identifier);

      if (stylesInDom[_index].references === 0) {
        stylesInDom[_index].updater();

        stylesInDom.splice(_index, 1);
      }
    }

    lastIdentifiers = newLastIdentifiers;
  };
};

/***/ }),

/***/ "./node_modules/underscore/underscore-umd.js":
/*!***************************************************!*\
  !*** ./node_modules/underscore/underscore-umd.js ***!
  \***************************************************/
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

(function (global, factory) {
   true ? module.exports = factory() :
  0;
}(this, (function () {
  //     Underscore.js 1.13.1
  //     https://underscorejs.org
  //     (c) 2009-2021 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
  //     Underscore may be freely distributed under the MIT license.

  // Current version.
  var VERSION = '1.13.1';

  // Establish the root object, `window` (`self`) in the browser, `global`
  // on the server, or `this` in some virtual machines. We use `self`
  // instead of `window` for `WebWorker` support.
  var root = typeof self == 'object' && self.self === self && self ||
            typeof __webpack_require__.g == 'object' && __webpack_require__.g.global === __webpack_require__.g && __webpack_require__.g ||
            Function('return this')() ||
            {};

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype;
  var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;

  // Create quick reference variables for speed access to core prototypes.
  var push = ArrayProto.push,
      slice = ArrayProto.slice,
      toString = ObjProto.toString,
      hasOwnProperty = ObjProto.hasOwnProperty;

  // Modern feature detection.
  var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
      supportsDataView = typeof DataView !== 'undefined';

  // All **ECMAScript 5+** native function implementations that we hope to use
  // are declared here.
  var nativeIsArray = Array.isArray,
      nativeKeys = Object.keys,
      nativeCreate = Object.create,
      nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;

  // Create references to these builtin functions because we override them.
  var _isNaN = isNaN,
      _isFinite = isFinite;

  // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
    'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

  // The largest integer that can be represented exactly.
  var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;

  // Some functions take a variable number of arguments, or a few expected
  // arguments at the beginning and then a variable number of values to operate
  // on. This helper accumulates all remaining arguments past the function’s
  // argument length (or an explicit `startIndex`), into an array that becomes
  // the last argument. Similar to ES6’s "rest parameter".
  function restArguments(func, startIndex) {
    startIndex = startIndex == null ? func.length - 1 : +startIndex;
    return function() {
      var length = Math.max(arguments.length - startIndex, 0),
          rest = Array(length),
          index = 0;
      for (; index < length; index++) {
        rest[index] = arguments[index + startIndex];
      }
      switch (startIndex) {
        case 0: return func.call(this, rest);
        case 1: return func.call(this, arguments[0], rest);
        case 2: return func.call(this, arguments[0], arguments[1], rest);
      }
      var args = Array(startIndex + 1);
      for (index = 0; index < startIndex; index++) {
        args[index] = arguments[index];
      }
      args[startIndex] = rest;
      return func.apply(this, args);
    };
  }

  // Is a given variable an object?
  function isObject(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
  }

  // Is a given value equal to null?
  function isNull(obj) {
    return obj === null;
  }

  // Is a given variable undefined?
  function isUndefined(obj) {
    return obj === void 0;
  }

  // Is a given value a boolean?
  function isBoolean(obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  }

  // Is a given value a DOM element?
  function isElement(obj) {
    return !!(obj && obj.nodeType === 1);
  }

  // Internal function for creating a `toString`-based type tester.
  function tagTester(name) {
    var tag = '[object ' + name + ']';
    return function(obj) {
      return toString.call(obj) === tag;
    };
  }

  var isString = tagTester('String');

  var isNumber = tagTester('Number');

  var isDate = tagTester('Date');

  var isRegExp = tagTester('RegExp');

  var isError = tagTester('Error');

  var isSymbol = tagTester('Symbol');

  var isArrayBuffer = tagTester('ArrayBuffer');

  var isFunction = tagTester('Function');

  // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
  // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
  var nodelist = root.document && root.document.childNodes;
  if ( true && typeof Int8Array != 'object' && typeof nodelist != 'function') {
    isFunction = function(obj) {
      return typeof obj == 'function' || false;
    };
  }

  var isFunction$1 = isFunction;

  var hasObjectTag = tagTester('Object');

  // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
  // In IE 11, the most common among them, this problem also applies to
  // `Map`, `WeakMap` and `Set`.
  var hasStringTagBug = (
        supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8)))
      ),
      isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map));

  var isDataView = tagTester('DataView');

  // In IE 10 - Edge 13, we need a different heuristic
  // to determine whether an object is a `DataView`.
  function ie10IsDataView(obj) {
    return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer);
  }

  var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView);

  // Is a given value an array?
  // Delegates to ECMA5's native `Array.isArray`.
  var isArray = nativeIsArray || tagTester('Array');

  // Internal function to check whether `key` is an own property name of `obj`.
  function has$1(obj, key) {
    return obj != null && hasOwnProperty.call(obj, key);
  }

  var isArguments = tagTester('Arguments');

  // Define a fallback version of the method in browsers (ahem, IE < 9), where
  // there isn't any inspectable "Arguments" type.
  (function() {
    if (!isArguments(arguments)) {
      isArguments = function(obj) {
        return has$1(obj, 'callee');
      };
    }
  }());

  var isArguments$1 = isArguments;

  // Is a given object a finite number?
  function isFinite$1(obj) {
    return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
  }

  // Is the given value `NaN`?
  function isNaN$1(obj) {
    return isNumber(obj) && _isNaN(obj);
  }

  // Predicate-generating function. Often useful outside of Underscore.
  function constant(value) {
    return function() {
      return value;
    };
  }

  // Common internal logic for `isArrayLike` and `isBufferLike`.
  function createSizePropertyCheck(getSizeProperty) {
    return function(collection) {
      var sizeProperty = getSizeProperty(collection);
      return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
    }
  }

  // Internal helper to generate a function to obtain property `key` from `obj`.
  function shallowProperty(key) {
    return function(obj) {
      return obj == null ? void 0 : obj[key];
    };
  }

  // Internal helper to obtain the `byteLength` property of an object.
  var getByteLength = shallowProperty('byteLength');

  // Internal helper to determine whether we should spend extensive checks against
  // `ArrayBuffer` et al.
  var isBufferLike = createSizePropertyCheck(getByteLength);

  // Is a given value a typed array?
  var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
  function isTypedArray(obj) {
    // `ArrayBuffer.isView` is the most future-proof, so use it when available.
    // Otherwise, fall back on the above regular expression.
    return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) :
                  isBufferLike(obj) && typedArrayPattern.test(toString.call(obj));
  }

  var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false);

  // Internal helper to obtain the `length` property of an object.
  var getLength = shallowProperty('length');

  // Internal helper to create a simple lookup structure.
  // `collectNonEnumProps` used to depend on `_.contains`, but this led to
  // circular imports. `emulatedSet` is a one-off solution that only works for
  // arrays of strings.
  function emulatedSet(keys) {
    var hash = {};
    for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
    return {
      contains: function(key) { return hash[key]; },
      push: function(key) {
        hash[key] = true;
        return keys.push(key);
      }
    };
  }

  // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
  // be iterated by `for key in ...` and thus missed. Extends `keys` in place if
  // needed.
  function collectNonEnumProps(obj, keys) {
    keys = emulatedSet(keys);
    var nonEnumIdx = nonEnumerableProps.length;
    var constructor = obj.constructor;
    var proto = isFunction$1(constructor) && constructor.prototype || ObjProto;

    // Constructor is a special case.
    var prop = 'constructor';
    if (has$1(obj, prop) && !keys.contains(prop)) keys.push(prop);

    while (nonEnumIdx--) {
      prop = nonEnumerableProps[nonEnumIdx];
      if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
        keys.push(prop);
      }
    }
  }

  // Retrieve the names of an object's own properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`.
  function keys(obj) {
    if (!isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) if (has$1(obj, key)) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  }

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  function isEmpty(obj) {
    if (obj == null) return true;
    // Skip the more expensive `toString`-based type checks if `obj` has no
    // `.length`.
    var length = getLength(obj);
    if (typeof length == 'number' && (
      isArray(obj) || isString(obj) || isArguments$1(obj)
    )) return length === 0;
    return getLength(keys(obj)) === 0;
  }

  // Returns whether an object has a given set of `key:value` pairs.
  function isMatch(object, attrs) {
    var _keys = keys(attrs), length = _keys.length;
    if (object == null) return !length;
    var obj = Object(object);
    for (var i = 0; i < length; i++) {
      var key = _keys[i];
      if (attrs[key] !== obj[key] || !(key in obj)) return false;
    }
    return true;
  }

  // If Underscore is called as a function, it returns a wrapped object that can
  // be used OO-style. This wrapper holds altered versions of all functions added
  // through `_.mixin`. Wrapped objects may be chained.
  function _$1(obj) {
    if (obj instanceof _$1) return obj;
    if (!(this instanceof _$1)) return new _$1(obj);
    this._wrapped = obj;
  }

  _$1.VERSION = VERSION;

  // Extracts the result from a wrapped and chained object.
  _$1.prototype.value = function() {
    return this._wrapped;
  };

  // Provide unwrapping proxies for some methods used in engine operations
  // such as arithmetic and JSON stringification.
  _$1.prototype.valueOf = _$1.prototype.toJSON = _$1.prototype.value;

  _$1.prototype.toString = function() {
    return String(this._wrapped);
  };

  // Internal function to wrap or shallow-copy an ArrayBuffer,
  // typed array or DataView to a new view, reusing the buffer.
  function toBufferView(bufferSource) {
    return new Uint8Array(
      bufferSource.buffer || bufferSource,
      bufferSource.byteOffset || 0,
      getByteLength(bufferSource)
    );
  }

  // We use this string twice, so give it a name for minification.
  var tagDataView = '[object DataView]';

  // Internal recursive comparison function for `_.isEqual`.
  function eq(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
    if (a === b) return a !== 0 || 1 / a === 1 / b;
    // `null` or `undefined` only equal to itself (strict comparison).
    if (a == null || b == null) return false;
    // `NaN`s are equivalent, but non-reflexive.
    if (a !== a) return b !== b;
    // Exhaust primitive checks
    var type = typeof a;
    if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
    return deepEq(a, b, aStack, bStack);
  }

  // Internal recursive comparison function for `_.isEqual`.
  function deepEq(a, b, aStack, bStack) {
    // Unwrap any wrapped objects.
    if (a instanceof _$1) a = a._wrapped;
    if (b instanceof _$1) b = b._wrapped;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className !== toString.call(b)) return false;
    // Work around a bug in IE 10 - Edge 13.
    if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) {
      if (!isDataView$1(b)) return false;
      className = tagDataView;
    }
    switch (className) {
      // These types are compared by value.
      case '[object RegExp]':
        // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return '' + a === '' + b;
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive.
        // Object(NaN) is equivalent to NaN.
        if (+a !== +a) return +b !== +b;
        // An `egal` comparison is performed for other numeric values.
        return +a === 0 ? 1 / +a === 1 / b : +a === +b;
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a === +b;
      case '[object Symbol]':
        return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
      case '[object ArrayBuffer]':
      case tagDataView:
        // Coerce to typed array so we can fall through.
        return deepEq(toBufferView(a), toBufferView(b), aStack, bStack);
    }

    var areArrays = className === '[object Array]';
    if (!areArrays && isTypedArray$1(a)) {
        var byteLength = getByteLength(a);
        if (byteLength !== getByteLength(b)) return false;
        if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
        areArrays = true;
    }
    if (!areArrays) {
      if (typeof a != 'object' || typeof b != 'object') return false;

      // Objects with different constructors are not equivalent, but `Object`s or `Array`s
      // from different frames are.
      var aCtor = a.constructor, bCtor = b.constructor;
      if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor &&
                               isFunction$1(bCtor) && bCtor instanceof bCtor)
                          && ('constructor' in a && 'constructor' in b)) {
        return false;
      }
    }
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

    // Initializing stack of traversed objects.
    // It's done here since we only need them for objects and arrays comparison.
    aStack = aStack || [];
    bStack = bStack || [];
    var length = aStack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (aStack[length] === a) return bStack[length] === b;
    }

    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);

    // Recursively compare objects and arrays.
    if (areArrays) {
      // Compare array lengths to determine if a deep comparison is necessary.
      length = a.length;
      if (length !== b.length) return false;
      // Deep compare the contents, ignoring non-numeric properties.
      while (length--) {
        if (!eq(a[length], b[length], aStack, bStack)) return false;
      }
    } else {
      // Deep compare objects.
      var _keys = keys(a), key;
      length = _keys.length;
      // Ensure that both objects contain the same number of properties before comparing deep equality.
      if (keys(b).length !== length) return false;
      while (length--) {
        // Deep compare each member
        key = _keys[length];
        if (!(has$1(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return true;
  }

  // Perform a deep comparison to check if two objects are equal.
  function isEqual(a, b) {
    return eq(a, b);
  }

  // Retrieve all the enumerable property names of an object.
  function allKeys(obj) {
    if (!isObject(obj)) return [];
    var keys = [];
    for (var key in obj) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  }

  // Since the regular `Object.prototype.toString` type tests don't work for
  // some types in IE 11, we use a fingerprinting heuristic instead, based
  // on the methods. It's not great, but it's the best we got.
  // The fingerprint method lists are defined below.
  function ie11fingerprint(methods) {
    var length = getLength(methods);
    return function(obj) {
      if (obj == null) return false;
      // `Map`, `WeakMap` and `Set` have no enumerable keys.
      var keys = allKeys(obj);
      if (getLength(keys)) return false;
      for (var i = 0; i < length; i++) {
        if (!isFunction$1(obj[methods[i]])) return false;
      }
      // If we are testing against `WeakMap`, we need to ensure that
      // `obj` doesn't have a `forEach` method in order to distinguish
      // it from a regular `Map`.
      return methods !== weakMapMethods || !isFunction$1(obj[forEachName]);
    };
  }

  // In the interest of compact minification, we write
  // each string in the fingerprints only once.
  var forEachName = 'forEach',
      hasName = 'has',
      commonInit = ['clear', 'delete'],
      mapTail = ['get', hasName, 'set'];

  // `Map`, `WeakMap` and `Set` each have slightly different
  // combinations of the above sublists.
  var mapMethods = commonInit.concat(forEachName, mapTail),
      weakMapMethods = commonInit.concat(mapTail),
      setMethods = ['add'].concat(commonInit, forEachName, hasName);

  var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map');

  var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap');

  var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set');

  var isWeakSet = tagTester('WeakSet');

  // Retrieve the values of an object's properties.
  function values(obj) {
    var _keys = keys(obj);
    var length = _keys.length;
    var values = Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[_keys[i]];
    }
    return values;
  }

  // Convert an object into a list of `[key, value]` pairs.
  // The opposite of `_.object` with one argument.
  function pairs(obj) {
    var _keys = keys(obj);
    var length = _keys.length;
    var pairs = Array(length);
    for (var i = 0; i < length; i++) {
      pairs[i] = [_keys[i], obj[_keys[i]]];
    }
    return pairs;
  }

  // Invert the keys and values of an object. The values must be serializable.
  function invert(obj) {
    var result = {};
    var _keys = keys(obj);
    for (var i = 0, length = _keys.length; i < length; i++) {
      result[obj[_keys[i]]] = _keys[i];
    }
    return result;
  }

  // Return a sorted list of the function names available on the object.
  function functions(obj) {
    var names = [];
    for (var key in obj) {
      if (isFunction$1(obj[key])) names.push(key);
    }
    return names.sort();
  }

  // An internal function for creating assigner functions.
  function createAssigner(keysFunc, defaults) {
    return function(obj) {
      var length = arguments.length;
      if (defaults) obj = Object(obj);
      if (length < 2 || obj == null) return obj;
      for (var index = 1; index < length; index++) {
        var source = arguments[index],
            keys = keysFunc(source),
            l = keys.length;
        for (var i = 0; i < l; i++) {
          var key = keys[i];
          if (!defaults || obj[key] === void 0) obj[key] = source[key];
        }
      }
      return obj;
    };
  }

  // Extend a given object with all the properties in passed-in object(s).
  var extend = createAssigner(allKeys);

  // Assigns a given object with all the own properties in the passed-in
  // object(s).
  // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  var extendOwn = createAssigner(keys);

  // Fill in a given object with default properties.
  var defaults = createAssigner(allKeys, true);

  // Create a naked function reference for surrogate-prototype-swapping.
  function ctor() {
    return function(){};
  }

  // An internal function for creating a new object that inherits from another.
  function baseCreate(prototype) {
    if (!isObject(prototype)) return {};
    if (nativeCreate) return nativeCreate(prototype);
    var Ctor = ctor();
    Ctor.prototype = prototype;
    var result = new Ctor;
    Ctor.prototype = null;
    return result;
  }

  // Creates an object that inherits from the given prototype object.
  // If additional properties are provided then they will be added to the
  // created object.
  function create(prototype, props) {
    var result = baseCreate(prototype);
    if (props) extendOwn(result, props);
    return result;
  }

  // Create a (shallow-cloned) duplicate of an object.
  function clone(obj) {
    if (!isObject(obj)) return obj;
    return isArray(obj) ? obj.slice() : extend({}, obj);
  }

  // Invokes `interceptor` with the `obj` and then returns `obj`.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  function tap(obj, interceptor) {
    interceptor(obj);
    return obj;
  }

  // Normalize a (deep) property `path` to array.
  // Like `_.iteratee`, this function can be customized.
  function toPath$1(path) {
    return isArray(path) ? path : [path];
  }
  _$1.toPath = toPath$1;

  // Internal wrapper for `_.toPath` to enable minification.
  // Similar to `cb` for `_.iteratee`.
  function toPath(path) {
    return _$1.toPath(path);
  }

  // Internal function to obtain a nested property in `obj` along `path`.
  function deepGet(obj, path) {
    var length = path.length;
    for (var i = 0; i < length; i++) {
      if (obj == null) return void 0;
      obj = obj[path[i]];
    }
    return length ? obj : void 0;
  }

  // Get the value of the (deep) property on `path` from `object`.
  // If any property in `path` does not exist or if the value is
  // `undefined`, return `defaultValue` instead.
  // The `path` is normalized through `_.toPath`.
  function get(object, path, defaultValue) {
    var value = deepGet(object, toPath(path));
    return isUndefined(value) ? defaultValue : value;
  }

  // Shortcut function for checking if an object has a given property directly on
  // itself (in other words, not on a prototype). Unlike the internal `has`
  // function, this public version can also traverse nested properties.
  function has(obj, path) {
    path = toPath(path);
    var length = path.length;
    for (var i = 0; i < length; i++) {
      var key = path[i];
      if (!has$1(obj, key)) return false;
      obj = obj[key];
    }
    return !!length;
  }

  // Keep the identity function around for default iteratees.
  function identity(value) {
    return value;
  }

  // Returns a predicate for checking whether an object has a given set of
  // `key:value` pairs.
  function matcher(attrs) {
    attrs = extendOwn({}, attrs);
    return function(obj) {
      return isMatch(obj, attrs);
    };
  }

  // Creates a function that, when passed an object, will traverse that object’s
  // properties down the given `path`, specified as an array of keys or indices.
  function property(path) {
    path = toPath(path);
    return function(obj) {
      return deepGet(obj, path);
    };
  }

  // Internal function that returns an efficient (for current engines) version
  // of the passed-in callback, to be repeatedly applied in other Underscore
  // functions.
  function optimizeCb(func, context, argCount) {
    if (context === void 0) return func;
    switch (argCount == null ? 3 : argCount) {
      case 1: return function(value) {
        return func.call(context, value);
      };
      // The 2-argument case is omitted because we’re not using it.
      case 3: return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
      case 4: return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
    }
    return function() {
      return func.apply(context, arguments);
    };
  }

  // An internal function to generate callbacks that can be applied to each
  // element in a collection, returning the desired result — either `_.identity`,
  // an arbitrary callback, a property matcher, or a property accessor.
  function baseIteratee(value, context, argCount) {
    if (value == null) return identity;
    if (isFunction$1(value)) return optimizeCb(value, context, argCount);
    if (isObject(value) && !isArray(value)) return matcher(value);
    return property(value);
  }

  // External wrapper for our callback generator. Users may customize
  // `_.iteratee` if they want additional predicate/iteratee shorthand styles.
  // This abstraction hides the internal-only `argCount` argument.
  function iteratee(value, context) {
    return baseIteratee(value, context, Infinity);
  }
  _$1.iteratee = iteratee;

  // The function we call internally to generate a callback. It invokes
  // `_.iteratee` if overridden, otherwise `baseIteratee`.
  function cb(value, context, argCount) {
    if (_$1.iteratee !== iteratee) return _$1.iteratee(value, context);
    return baseIteratee(value, context, argCount);
  }

  // Returns the results of applying the `iteratee` to each element of `obj`.
  // In contrast to `_.map` it returns an object.
  function mapObject(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var _keys = keys(obj),
        length = _keys.length,
        results = {};
    for (var index = 0; index < length; index++) {
      var currentKey = _keys[index];
      results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
    }
    return results;
  }

  // Predicate-generating function. Often useful outside of Underscore.
  function noop(){}

  // Generates a function for a given object that returns a given property.
  function propertyOf(obj) {
    if (obj == null) return noop;
    return function(path) {
      return get(obj, path);
    };
  }

  // Run a function **n** times.
  function times(n, iteratee, context) {
    var accum = Array(Math.max(0, n));
    iteratee = optimizeCb(iteratee, context, 1);
    for (var i = 0; i < n; i++) accum[i] = iteratee(i);
    return accum;
  }

  // Return a random integer between `min` and `max` (inclusive).
  function random(min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
  }

  // A (possibly faster) way to get the current timestamp as an integer.
  var now = Date.now || function() {
    return new Date().getTime();
  };

  // Internal helper to generate functions for escaping and unescaping strings
  // to/from HTML interpolation.
  function createEscaper(map) {
    var escaper = function(match) {
      return map[match];
    };
    // Regexes for identifying a key that needs to be escaped.
    var source = '(?:' + keys(map).join('|') + ')';
    var testRegexp = RegExp(source);
    var replaceRegexp = RegExp(source, 'g');
    return function(string) {
      string = string == null ? '' : '' + string;
      return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
    };
  }

  // Internal list of HTML entities for escaping.
  var escapeMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;',
    '`': '&#x60;'
  };

  // Function for escaping strings to HTML interpolation.
  var _escape = createEscaper(escapeMap);

  // Internal list of HTML entities for unescaping.
  var unescapeMap = invert(escapeMap);

  // Function for unescaping strings from HTML interpolation.
  var _unescape = createEscaper(unescapeMap);

  // By default, Underscore uses ERB-style template delimiters. Change the
  // following template settings to use alternative delimiters.
  var templateSettings = _$1.templateSettings = {
    evaluate: /<%([\s\S]+?)%>/g,
    interpolate: /<%=([\s\S]+?)%>/g,
    escape: /<%-([\s\S]+?)%>/g
  };

  // When customizing `_.templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'": "'",
    '\\': '\\',
    '\r': 'r',
    '\n': 'n',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;

  function escapeChar(match) {
    return '\\' + escapes[match];
  }

  // In order to prevent third-party code injection through
  // `_.templateSettings.variable`, we test it against the following regular
  // expression. It is intentionally a bit more liberal than just matching valid
  // identifiers, but still prevents possible loopholes through defaults or
  // destructuring assignment.
  var bareIdentifier = /^\s*(\w|\$)+\s*$/;

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  // NB: `oldSettings` only exists for backwards compatibility.
  function template(text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    settings = defaults({}, settings, _$1.templateSettings);

    // Combine delimiters into one regular expression via alternation.
    var matcher = RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
      index = offset + match.length;

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      } else if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      } else if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }

      // Adobe VMs need the match returned to produce the correct offset.
      return match;
    });
    source += "';\n";

    var argument = settings.variable;
    if (argument) {
      // Insure against third-party code injection. (CVE-2021-23358)
      if (!bareIdentifier.test(argument)) throw new Error(
        'variable is not a bare identifier: ' + argument
      );
    } else {
      // If a variable is not specified, place data values in local scope.
      source = 'with(obj||{}){\n' + source + '}\n';
      argument = 'obj';
    }

    source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + 'return __p;\n';

    var render;
    try {
      render = new Function(argument, '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    var template = function(data) {
      return render.call(this, data, _$1);
    };

    // Provide the compiled source as a convenience for precompilation.
    template.source = 'function(' + argument + '){\n' + source + '}';

    return template;
  }

  // Traverses the children of `obj` along `path`. If a child is a function, it
  // is invoked with its parent as context. Returns the value of the final
  // child, or `fallback` if any child is undefined.
  function result(obj, path, fallback) {
    path = toPath(path);
    var length = path.length;
    if (!length) {
      return isFunction$1(fallback) ? fallback.call(obj) : fallback;
    }
    for (var i = 0; i < length; i++) {
      var prop = obj == null ? void 0 : obj[path[i]];
      if (prop === void 0) {
        prop = fallback;
        i = length; // Ensure we don't continue iterating.
      }
      obj = isFunction$1(prop) ? prop.call(obj) : prop;
    }
    return obj;
  }

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  function uniqueId(prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  }

  // Start chaining a wrapped Underscore object.
  function chain(obj) {
    var instance = _$1(obj);
    instance._chain = true;
    return instance;
  }

  // Internal function to execute `sourceFunc` bound to `context` with optional
  // `args`. Determines whether to execute a function as a constructor or as a
  // normal function.
  function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
    if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
    var self = baseCreate(sourceFunc.prototype);
    var result = sourceFunc.apply(self, args);
    if (isObject(result)) return result;
    return self;
  }

  // Partially apply a function by creating a version that has had some of its
  // arguments pre-filled, without changing its dynamic `this` context. `_` acts
  // as a placeholder by default, allowing any combination of arguments to be
  // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
  var partial = restArguments(function(func, boundArgs) {
    var placeholder = partial.placeholder;
    var bound = function() {
      var position = 0, length = boundArgs.length;
      var args = Array(length);
      for (var i = 0; i < length; i++) {
        args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
      }
      while (position < arguments.length) args.push(arguments[position++]);
      return executeBound(func, bound, this, this, args);
    };
    return bound;
  });

  partial.placeholder = _$1;

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally).
  var bind = restArguments(function(func, context, args) {
    if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function');
    var bound = restArguments(function(callArgs) {
      return executeBound(func, bound, context, this, args.concat(callArgs));
    });
    return bound;
  });

  // Internal helper for collection methods to determine whether a collection
  // should be iterated as an array or as an object.
  // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  var isArrayLike = createSizePropertyCheck(getLength);

  // Internal implementation of a recursive `flatten` function.
  function flatten$1(input, depth, strict, output) {
    output = output || [];
    if (!depth && depth !== 0) {
      depth = Infinity;
    } else if (depth <= 0) {
      return output.concat(input);
    }
    var idx = output.length;
    for (var i = 0, length = getLength(input); i < length; i++) {
      var value = input[i];
      if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) {
        // Flatten current level of array or arguments object.
        if (depth > 1) {
          flatten$1(value, depth - 1, strict, output);
          idx = output.length;
        } else {
          var j = 0, len = value.length;
          while (j < len) output[idx++] = value[j++];
        }
      } else if (!strict) {
        output[idx++] = value;
      }
    }
    return output;
  }

  // Bind a number of an object's methods to that object. Remaining arguments
  // are the method names to be bound. Useful for ensuring that all callbacks
  // defined on an object belong to it.
  var bindAll = restArguments(function(obj, keys) {
    keys = flatten$1(keys, false, false);
    var index = keys.length;
    if (index < 1) throw new Error('bindAll must be passed function names');
    while (index--) {
      var key = keys[index];
      obj[key] = bind(obj[key], obj);
    }
    return obj;
  });

  // Memoize an expensive function by storing its results.
  function memoize(func, hasher) {
    var memoize = function(key) {
      var cache = memoize.cache;
      var address = '' + (hasher ? hasher.apply(this, arguments) : key);
      if (!has$1(cache, address)) cache[address] = func.apply(this, arguments);
      return cache[address];
    };
    memoize.cache = {};
    return memoize;
  }

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  var delay = restArguments(function(func, wait, args) {
    return setTimeout(function() {
      return func.apply(null, args);
    }, wait);
  });

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  var defer = partial(delay, _$1, 1);

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time. Normally, the throttled function will run
  // as much as it can, without ever going more than once per `wait` duration;
  // but if you'd like to disable the execution on the leading edge, pass
  // `{leading: false}`. To disable execution on the trailing edge, ditto.
  function throttle(func, wait, options) {
    var timeout, context, args, result;
    var previous = 0;
    if (!options) options = {};

    var later = function() {
      previous = options.leading === false ? 0 : now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };

    var throttled = function() {
      var _now = now();
      if (!previous && options.leading === false) previous = _now;
      var remaining = wait - (_now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = _now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };

    throttled.cancel = function() {
      clearTimeout(timeout);
      previous = 0;
      timeout = context = args = null;
    };

    return throttled;
  }

  // When a sequence of calls of the returned function ends, the argument
  // function is triggered. The end of a sequence is defined by the `wait`
  // parameter. If `immediate` is passed, the argument function will be
  // triggered at the beginning of the sequence instead of at the end.
  function debounce(func, wait, immediate) {
    var timeout, previous, args, result, context;

    var later = function() {
      var passed = now() - previous;
      if (wait > passed) {
        timeout = setTimeout(later, wait - passed);
      } else {
        timeout = null;
        if (!immediate) result = func.apply(context, args);
        // This check is needed because `func` can recursively invoke `debounced`.
        if (!timeout) args = context = null;
      }
    };

    var debounced = restArguments(function(_args) {
      context = this;
      args = _args;
      previous = now();
      if (!timeout) {
        timeout = setTimeout(later, wait);
        if (immediate) result = func.apply(context, args);
      }
      return result;
    });

    debounced.cancel = function() {
      clearTimeout(timeout);
      timeout = args = context = null;
    };

    return debounced;
  }

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  function wrap(func, wrapper) {
    return partial(wrapper, func);
  }

  // Returns a negated version of the passed-in predicate.
  function negate(predicate) {
    return function() {
      return !predicate.apply(this, arguments);
    };
  }

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  function compose() {
    var args = arguments;
    var start = args.length - 1;
    return function() {
      var i = start;
      var result = args[start].apply(this, arguments);
      while (i--) result = args[i].call(this, result);
      return result;
    };
  }

  // Returns a function that will only be executed on and after the Nth call.
  function after(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  }

  // Returns a function that will only be executed up to (but not including) the
  // Nth call.
  function before(times, func) {
    var memo;
    return function() {
      if (--times > 0) {
        memo = func.apply(this, arguments);
      }
      if (times <= 1) func = null;
      return memo;
    };
  }

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  var once = partial(before, 2);

  // Returns the first key on an object that passes a truth test.
  function findKey(obj, predicate, context) {
    predicate = cb(predicate, context);
    var _keys = keys(obj), key;
    for (var i = 0, length = _keys.length; i < length; i++) {
      key = _keys[i];
      if (predicate(obj[key], key, obj)) return key;
    }
  }

  // Internal function to generate `_.findIndex` and `_.findLastIndex`.
  function createPredicateIndexFinder(dir) {
    return function(array, predicate, context) {
      predicate = cb(predicate, context);
      var length = getLength(array);
      var index = dir > 0 ? 0 : length - 1;
      for (; index >= 0 && index < length; index += dir) {
        if (predicate(array[index], index, array)) return index;
      }
      return -1;
    };
  }

  // Returns the first index on an array-like that passes a truth test.
  var findIndex = createPredicateIndexFinder(1);

  // Returns the last index on an array-like that passes a truth test.
  var findLastIndex = createPredicateIndexFinder(-1);

  // Use a comparator function to figure out the smallest index at which
  // an object should be inserted so as to maintain order. Uses binary search.
  function sortedIndex(array, obj, iteratee, context) {
    iteratee = cb(iteratee, context, 1);
    var value = iteratee(obj);
    var low = 0, high = getLength(array);
    while (low < high) {
      var mid = Math.floor((low + high) / 2);
      if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
    }
    return low;
  }

  // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
  function createIndexFinder(dir, predicateFind, sortedIndex) {
    return function(array, item, idx) {
      var i = 0, length = getLength(array);
      if (typeof idx == 'number') {
        if (dir > 0) {
          i = idx >= 0 ? idx : Math.max(idx + length, i);
        } else {
          length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
        }
      } else if (sortedIndex && idx && length) {
        idx = sortedIndex(array, item);
        return array[idx] === item ? idx : -1;
      }
      if (item !== item) {
        idx = predicateFind(slice.call(array, i, length), isNaN$1);
        return idx >= 0 ? idx + i : -1;
      }
      for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
        if (array[idx] === item) return idx;
      }
      return -1;
    };
  }

  // Return the position of the first occurrence of an item in an array,
  // or -1 if the item is not included in the array.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  var indexOf = createIndexFinder(1, findIndex, sortedIndex);

  // Return the position of the last occurrence of an item in an array,
  // or -1 if the item is not included in the array.
  var lastIndexOf = createIndexFinder(-1, findLastIndex);

  // Return the first value which passes a truth test.
  function find(obj, predicate, context) {
    var keyFinder = isArrayLike(obj) ? findIndex : findKey;
    var key = keyFinder(obj, predicate, context);
    if (key !== void 0 && key !== -1) return obj[key];
  }

  // Convenience version of a common use case of `_.find`: getting the first
  // object containing specific `key:value` pairs.
  function findWhere(obj, attrs) {
    return find(obj, matcher(attrs));
  }

  // The cornerstone for collection functions, an `each`
  // implementation, aka `forEach`.
  // Handles raw objects in addition to array-likes. Treats all
  // sparse array-likes as if they were dense.
  function each(obj, iteratee, context) {
    iteratee = optimizeCb(iteratee, context);
    var i, length;
    if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
        iteratee(obj[i], i, obj);
      }
    } else {
      var _keys = keys(obj);
      for (i = 0, length = _keys.length; i < length; i++) {
        iteratee(obj[_keys[i]], _keys[i], obj);
      }
    }
    return obj;
  }

  // Return the results of applying the iteratee to each element.
  function map(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var _keys = !isArrayLike(obj) && keys(obj),
        length = (_keys || obj).length,
        results = Array(length);
    for (var index = 0; index < length; index++) {
      var currentKey = _keys ? _keys[index] : index;
      results[index] = iteratee(obj[currentKey], currentKey, obj);
    }
    return results;
  }

  // Internal helper to create a reducing function, iterating left or right.
  function createReduce(dir) {
    // Wrap code that reassigns argument variables in a separate function than
    // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
    var reducer = function(obj, iteratee, memo, initial) {
      var _keys = !isArrayLike(obj) && keys(obj),
          length = (_keys || obj).length,
          index = dir > 0 ? 0 : length - 1;
      if (!initial) {
        memo = obj[_keys ? _keys[index] : index];
        index += dir;
      }
      for (; index >= 0 && index < length; index += dir) {
        var currentKey = _keys ? _keys[index] : index;
        memo = iteratee(memo, obj[currentKey], currentKey, obj);
      }
      return memo;
    };

    return function(obj, iteratee, memo, context) {
      var initial = arguments.length >= 3;
      return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
    };
  }

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`.
  var reduce = createReduce(1);

  // The right-associative version of reduce, also known as `foldr`.
  var reduceRight = createReduce(-1);

  // Return all the elements that pass a truth test.
  function filter(obj, predicate, context) {
    var results = [];
    predicate = cb(predicate, context);
    each(obj, function(value, index, list) {
      if (predicate(value, index, list)) results.push(value);
    });
    return results;
  }

  // Return all the elements for which a truth test fails.
  function reject(obj, predicate, context) {
    return filter(obj, negate(cb(predicate)), context);
  }

  // Determine whether all of the elements pass a truth test.
  function every(obj, predicate, context) {
    predicate = cb(predicate, context);
    var _keys = !isArrayLike(obj) && keys(obj),
        length = (_keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = _keys ? _keys[index] : index;
      if (!predicate(obj[currentKey], currentKey, obj)) return false;
    }
    return true;
  }

  // Determine if at least one element in the object passes a truth test.
  function some(obj, predicate, context) {
    predicate = cb(predicate, context);
    var _keys = !isArrayLike(obj) && keys(obj),
        length = (_keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = _keys ? _keys[index] : index;
      if (predicate(obj[currentKey], currentKey, obj)) return true;
    }
    return false;
  }

  // Determine if the array or object contains a given item (using `===`).
  function contains(obj, item, fromIndex, guard) {
    if (!isArrayLike(obj)) obj = values(obj);
    if (typeof fromIndex != 'number' || guard) fromIndex = 0;
    return indexOf(obj, item, fromIndex) >= 0;
  }

  // Invoke a method (with arguments) on every item in a collection.
  var invoke = restArguments(function(obj, path, args) {
    var contextPath, func;
    if (isFunction$1(path)) {
      func = path;
    } else {
      path = toPath(path);
      contextPath = path.slice(0, -1);
      path = path[path.length - 1];
    }
    return map(obj, function(context) {
      var method = func;
      if (!method) {
        if (contextPath && contextPath.length) {
          context = deepGet(context, contextPath);
        }
        if (context == null) return void 0;
        method = context[path];
      }
      return method == null ? method : method.apply(context, args);
    });
  });

  // Convenience version of a common use case of `_.map`: fetching a property.
  function pluck(obj, key) {
    return map(obj, property(key));
  }

  // Convenience version of a common use case of `_.filter`: selecting only
  // objects containing specific `key:value` pairs.
  function where(obj, attrs) {
    return filter(obj, matcher(attrs));
  }

  // Return the maximum element (or element-based computation).
  function max(obj, iteratee, context) {
    var result = -Infinity, lastComputed = -Infinity,
        value, computed;
    if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
      obj = isArrayLike(obj) ? obj : values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value != null && value > result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      each(obj, function(v, index, list) {
        computed = iteratee(v, index, list);
        if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
          result = v;
          lastComputed = computed;
        }
      });
    }
    return result;
  }

  // Return the minimum element (or element-based computation).
  function min(obj, iteratee, context) {
    var result = Infinity, lastComputed = Infinity,
        value, computed;
    if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
      obj = isArrayLike(obj) ? obj : values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value != null && value < result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      each(obj, function(v, index, list) {
        computed = iteratee(v, index, list);
        if (computed < lastComputed || computed === Infinity && result === Infinity) {
          result = v;
          lastComputed = computed;
        }
      });
    }
    return result;
  }

  // Sample **n** random values from a collection using the modern version of the
  // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  // If **n** is not specified, returns a single random element.
  // The internal `guard` argument allows it to work with `_.map`.
  function sample(obj, n, guard) {
    if (n == null || guard) {
      if (!isArrayLike(obj)) obj = values(obj);
      return obj[random(obj.length - 1)];
    }
    var sample = isArrayLike(obj) ? clone(obj) : values(obj);
    var length = getLength(sample);
    n = Math.max(Math.min(n, length), 0);
    var last = length - 1;
    for (var index = 0; index < n; index++) {
      var rand = random(index, last);
      var temp = sample[index];
      sample[index] = sample[rand];
      sample[rand] = temp;
    }
    return sample.slice(0, n);
  }

  // Shuffle a collection.
  function shuffle(obj) {
    return sample(obj, Infinity);
  }

  // Sort the object's values by a criterion produced by an iteratee.
  function sortBy(obj, iteratee, context) {
    var index = 0;
    iteratee = cb(iteratee, context);
    return pluck(map(obj, function(value, key, list) {
      return {
        value: value,
        index: index++,
        criteria: iteratee(value, key, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index - right.index;
    }), 'value');
  }

  // An internal function used for aggregate "group by" operations.
  function group(behavior, partition) {
    return function(obj, iteratee, context) {
      var result = partition ? [[], []] : {};
      iteratee = cb(iteratee, context);
      each(obj, function(value, index) {
        var key = iteratee(value, index, obj);
        behavior(result, value, key);
      });
      return result;
    };
  }

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  var groupBy = group(function(result, value, key) {
    if (has$1(result, key)) result[key].push(value); else result[key] = [value];
  });

  // Indexes the object's values by a criterion, similar to `_.groupBy`, but for
  // when you know that your index values will be unique.
  var indexBy = group(function(result, value, key) {
    result[key] = value;
  });

  // Counts instances of an object that group by a certain criterion. Pass
  // either a string attribute to count by, or a function that returns the
  // criterion.
  var countBy = group(function(result, value, key) {
    if (has$1(result, key)) result[key]++; else result[key] = 1;
  });

  // Split a collection into two arrays: one whose elements all pass the given
  // truth test, and one whose elements all do not pass the truth test.
  var partition = group(function(result, value, pass) {
    result[pass ? 0 : 1].push(value);
  }, true);

  // Safely create a real, live array from anything iterable.
  var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
  function toArray(obj) {
    if (!obj) return [];
    if (isArray(obj)) return slice.call(obj);
    if (isString(obj)) {
      // Keep surrogate pair characters together.
      return obj.match(reStrSymbol);
    }
    if (isArrayLike(obj)) return map(obj, identity);
    return values(obj);
  }

  // Return the number of elements in a collection.
  function size(obj) {
    if (obj == null) return 0;
    return isArrayLike(obj) ? obj.length : keys(obj).length;
  }

  // Internal `_.pick` helper function to determine whether `key` is an enumerable
  // property name of `obj`.
  function keyInObj(value, key, obj) {
    return key in obj;
  }

  // Return a copy of the object only containing the allowed properties.
  var pick = restArguments(function(obj, keys) {
    var result = {}, iteratee = keys[0];
    if (obj == null) return result;
    if (isFunction$1(iteratee)) {
      if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
      keys = allKeys(obj);
    } else {
      iteratee = keyInObj;
      keys = flatten$1(keys, false, false);
      obj = Object(obj);
    }
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      var value = obj[key];
      if (iteratee(value, key, obj)) result[key] = value;
    }
    return result;
  });

  // Return a copy of the object without the disallowed properties.
  var omit = restArguments(function(obj, keys) {
    var iteratee = keys[0], context;
    if (isFunction$1(iteratee)) {
      iteratee = negate(iteratee);
      if (keys.length > 1) context = keys[1];
    } else {
      keys = map(flatten$1(keys, false, false), String);
      iteratee = function(value, key) {
        return !contains(keys, key);
      };
    }
    return pick(obj, iteratee, context);
  });

  // Returns everything but the last entry of the array. Especially useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N.
  function initial(array, n, guard) {
    return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  }

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. The **guard** check allows it to work with `_.map`.
  function first(array, n, guard) {
    if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
    if (n == null || guard) return array[0];
    return initial(array, array.length - n);
  }

  // Returns everything but the first entry of the `array`. Especially useful on
  // the `arguments` object. Passing an **n** will return the rest N values in the
  // `array`.
  function rest(array, n, guard) {
    return slice.call(array, n == null || guard ? 1 : n);
  }

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array.
  function last(array, n, guard) {
    if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
    if (n == null || guard) return array[array.length - 1];
    return rest(array, Math.max(0, array.length - n));
  }

  // Trim out all falsy values from an array.
  function compact(array) {
    return filter(array, Boolean);
  }

  // Flatten out an array, either recursively (by default), or up to `depth`.
  // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
  function flatten(array, depth) {
    return flatten$1(array, depth, false);
  }

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  var difference = restArguments(function(array, rest) {
    rest = flatten$1(rest, true, true);
    return filter(array, function(value){
      return !contains(rest, value);
    });
  });

  // Return a version of the array that does not contain the specified value(s).
  var without = restArguments(function(array, otherArrays) {
    return difference(array, otherArrays);
  });

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // The faster algorithm will not work with an iteratee if the iteratee
  // is not a one-to-one function, so providing an iteratee will disable
  // the faster algorithm.
  function uniq(array, isSorted, iteratee, context) {
    if (!isBoolean(isSorted)) {
      context = iteratee;
      iteratee = isSorted;
      isSorted = false;
    }
    if (iteratee != null) iteratee = cb(iteratee, context);
    var result = [];
    var seen = [];
    for (var i = 0, length = getLength(array); i < length; i++) {
      var value = array[i],
          computed = iteratee ? iteratee(value, i, array) : value;
      if (isSorted && !iteratee) {
        if (!i || seen !== computed) result.push(value);
        seen = computed;
      } else if (iteratee) {
        if (!contains(seen, computed)) {
          seen.push(computed);
          result.push(value);
        }
      } else if (!contains(result, value)) {
        result.push(value);
      }
    }
    return result;
  }

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  var union = restArguments(function(arrays) {
    return uniq(flatten$1(arrays, true, true));
  });

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  function intersection(array) {
    var result = [];
    var argsLength = arguments.length;
    for (var i = 0, length = getLength(array); i < length; i++) {
      var item = array[i];
      if (contains(result, item)) continue;
      var j;
      for (j = 1; j < argsLength; j++) {
        if (!contains(arguments[j], item)) break;
      }
      if (j === argsLength) result.push(item);
    }
    return result;
  }

  // Complement of zip. Unzip accepts an array of arrays and groups
  // each array's elements on shared indices.
  function unzip(array) {
    var length = array && max(array, getLength).length || 0;
    var result = Array(length);

    for (var index = 0; index < length; index++) {
      result[index] = pluck(array, index);
    }
    return result;
  }

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  var zip = restArguments(unzip);

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values. Passing by pairs is the reverse of `_.pairs`.
  function object(list, values) {
    var result = {};
    for (var i = 0, length = getLength(list); i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  }

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](https://docs.python.org/library/functions.html#range).
  function range(start, stop, step) {
    if (stop == null) {
      stop = start || 0;
      start = 0;
    }
    if (!step) {
      step = stop < start ? -1 : 1;
    }

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var range = Array(length);

    for (var idx = 0; idx < length; idx++, start += step) {
      range[idx] = start;
    }

    return range;
  }

  // Chunk a single array into multiple arrays, each containing `count` or fewer
  // items.
  function chunk(array, count) {
    if (count == null || count < 1) return [];
    var result = [];
    var i = 0, length = array.length;
    while (i < length) {
      result.push(slice.call(array, i, i += count));
    }
    return result;
  }

  // Helper function to continue chaining intermediate results.
  function chainResult(instance, obj) {
    return instance._chain ? _$1(obj).chain() : obj;
  }

  // Add your own custom functions to the Underscore object.
  function mixin(obj) {
    each(functions(obj), function(name) {
      var func = _$1[name] = obj[name];
      _$1.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return chainResult(this, func.apply(_$1, args));
      };
    });
    return _$1;
  }

  // Add all mutator `Array` functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    _$1.prototype[name] = function() {
      var obj = this._wrapped;
      if (obj != null) {
        method.apply(obj, arguments);
        if ((name === 'shift' || name === 'splice') && obj.length === 0) {
          delete obj[0];
        }
      }
      return chainResult(this, obj);
    };
  });

  // Add all accessor `Array` functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    _$1.prototype[name] = function() {
      var obj = this._wrapped;
      if (obj != null) obj = method.apply(obj, arguments);
      return chainResult(this, obj);
    };
  });

  // Named Exports

  var allExports = {
    __proto__: null,
    VERSION: VERSION,
    restArguments: restArguments,
    isObject: isObject,
    isNull: isNull,
    isUndefined: isUndefined,
    isBoolean: isBoolean,
    isElement: isElement,
    isString: isString,
    isNumber: isNumber,
    isDate: isDate,
    isRegExp: isRegExp,
    isError: isError,
    isSymbol: isSymbol,
    isArrayBuffer: isArrayBuffer,
    isDataView: isDataView$1,
    isArray: isArray,
    isFunction: isFunction$1,
    isArguments: isArguments$1,
    isFinite: isFinite$1,
    isNaN: isNaN$1,
    isTypedArray: isTypedArray$1,
    isEmpty: isEmpty,
    isMatch: isMatch,
    isEqual: isEqual,
    isMap: isMap,
    isWeakMap: isWeakMap,
    isSet: isSet,
    isWeakSet: isWeakSet,
    keys: keys,
    allKeys: allKeys,
    values: values,
    pairs: pairs,
    invert: invert,
    functions: functions,
    methods: functions,
    extend: extend,
    extendOwn: extendOwn,
    assign: extendOwn,
    defaults: defaults,
    create: create,
    clone: clone,
    tap: tap,
    get: get,
    has: has,
    mapObject: mapObject,
    identity: identity,
    constant: constant,
    noop: noop,
    toPath: toPath$1,
    property: property,
    propertyOf: propertyOf,
    matcher: matcher,
    matches: matcher,
    times: times,
    random: random,
    now: now,
    escape: _escape,
    unescape: _unescape,
    templateSettings: templateSettings,
    template: template,
    result: result,
    uniqueId: uniqueId,
    chain: chain,
    iteratee: iteratee,
    partial: partial,
    bind: bind,
    bindAll: bindAll,
    memoize: memoize,
    delay: delay,
    defer: defer,
    throttle: throttle,
    debounce: debounce,
    wrap: wrap,
    negate: negate,
    compose: compose,
    after: after,
    before: before,
    once: once,
    findKey: findKey,
    findIndex: findIndex,
    findLastIndex: findLastIndex,
    sortedIndex: sortedIndex,
    indexOf: indexOf,
    lastIndexOf: lastIndexOf,
    find: find,
    detect: find,
    findWhere: findWhere,
    each: each,
    forEach: each,
    map: map,
    collect: map,
    reduce: reduce,
    foldl: reduce,
    inject: reduce,
    reduceRight: reduceRight,
    foldr: reduceRight,
    filter: filter,
    select: filter,
    reject: reject,
    every: every,
    all: every,
    some: some,
    any: some,
    contains: contains,
    includes: contains,
    include: contains,
    invoke: invoke,
    pluck: pluck,
    where: where,
    max: max,
    min: min,
    shuffle: shuffle,
    sample: sample,
    sortBy: sortBy,
    groupBy: groupBy,
    indexBy: indexBy,
    countBy: countBy,
    partition: partition,
    toArray: toArray,
    size: size,
    pick: pick,
    omit: omit,
    first: first,
    head: first,
    take: first,
    initial: initial,
    last: last,
    rest: rest,
    tail: rest,
    drop: rest,
    compact: compact,
    flatten: flatten,
    without: without,
    uniq: uniq,
    unique: uniq,
    union: union,
    intersection: intersection,
    difference: difference,
    unzip: unzip,
    transpose: unzip,
    zip: zip,
    object: object,
    range: range,
    chunk: chunk,
    mixin: mixin,
    'default': _$1
  };

  // Default Export

  // Add all of the Underscore functions to the wrapper object.
  var _ = mixin(allExports);
  // Legacy Node.js API.
  _._ = _;

  return _;

})));
//# sourceMappingURL=underscore-umd.js.map


/***/ })

}]);
//# sourceMappingURL=vendors-node_modules_css-loader_dist_runtime_api_js-node_modules_dagre_index_js-node_modules_-7114b2.12878c99a99b73c91b56.js.map